These examples show exact helper boundaries and implementation choices. They are reference code: review dependencies, permissions, and installed-tool contracts before adapting them.
Safety and completeness boundaries
- The fork template bypasses approvals and sandboxing. Review this explicitly before installing any hook; prompt interception is executable code, not just a prompt convention.
- The registry example only reads mappings. It neither registers sessions nor implements a screen-scraping fallback;
--allow-screenis an accepted compatibility argument. - The cmux helper receipt proves dispatch to a surface, not successful completion of the command. Verify target workspace, working directory, and resulting behavior.
- Hook logs may contain prompt text, local paths, session identifiers, and subprocess output. Keep runtime logs private and review retention/redaction.
- Test ambiguous prefixes, timeouts, and hook errors against the installed roster. Do not infer that every routing failure blocks or that a timeout means no pane was opened.
hooks/cmux-codex-session-registry.py.example
#!/usr/bin/env python3
"""Redacted cmux-to-Codex session registry contract.
This example documents the command surface used by zsh helpers such as
`_codex_cmux_current_session_id`. It is intentionally not a copy of a private
registry implementation.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
def registry_path() -> Path:
return Path.home() / ".codex" / "cmux-codex-sessions.json"
def load_registry(path: Path) -> dict[str, str]:
if not path.exists():
return {}
data = json.loads(path.read_text())
if not isinstance(data, dict):
raise ValueError("registry must be a JSON object")
return {str(key): str(value) for key, value in data.items()}
def main() -> int:
parser = argparse.ArgumentParser(description="Resolve cmux surface ids to Codex session ids.")
parser.add_argument("--registry-path", action="store_true", help="print the registry path")
parser.add_argument("--resolve-surface", help="surface id, for example surface:123")
parser.add_argument("--allow-screen", action="store_true", help="accepted for compatibility")
args = parser.parse_args()
path = registry_path()
if args.registry_path:
print(path)
return 0
if args.resolve_surface:
session_id = load_registry(path).get(args.resolve_surface)
if not session_id:
return 1
print(session_id)
return 0
parser.print_help(sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main())
hooks/cmux-run-surface.example
#!/bin/sh
# Example contract for opening a new focused cmux terminal pane and running a command.
# Review before installing as ~/.local/bin/cmux-run-surface.
set -eu
CMUX="${CMUX_BIN:-/Applications/cmux.app/Contents/Resources/bin/cmux}"
JQ="${JQ_BIN:-/usr/bin/jq}"
LOG="$HOME/Library/Logs/cmux-run-surface.log"
DIRECTION="right"
case "${1:-}" in
--below|--down)
DIRECTION="down"
shift
;;
--right)
shift
;;
esac
COMMAND_TEXT="${1:-}"
[ -n "$COMMAND_TEXT" ] || {
/bin/echo "Usage: cmux-run-surface [--below|--right] <command>" >&2
exit 64
}
log() { /bin/echo "[$(/bin/date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG"; }
[ -x "$CMUX" ] || { log "cmux CLI not found at $CMUX"; exit 1; }
[ -x "$JQ" ] || { log "jq not found at $JQ"; exit 1; }
cur="$("$CMUX" rpc workspace.current 2>>"$LOG")"
CWD="$(/bin/echo "$cur" | "$JQ" -r '.workspace.current_directory // empty')"
WORKSPACE_ID="$(/bin/echo "$cur" | "$JQ" -r '.workspace_id // .workspace.id // empty')"
WINDOW_ID="$(/bin/echo "$cur" | "$JQ" -r '.window_id // .window.id // empty')"
[ -n "$CWD" ] || { log "no current_directory in workspace.current: $cur"; exit 1; }
[ -n "$WORKSPACE_ID" ] || { log "no workspace id in workspace.current: $cur"; exit 1; }
[ -n "$WINDOW_ID" ] || { log "no window id in workspace.current: $cur"; exit 1; }
pane_output="$("$CMUX" rpc pane.create "{\"workspace_id\":\"$WORKSPACE_ID\",\"window_id\":\"$WINDOW_ID\",\"direction\":\"$DIRECTION\",\"type\":\"terminal\",\"focus\":true}" 2>>"$LOG")"
PANE_ID="$(/bin/echo "$pane_output" | "$JQ" -r '.pane_id // .pane.id // empty')"
PANE_REF="$(/bin/echo "$pane_output" | "$JQ" -r '.pane_ref // .pane.ref // empty')"
WORKSPACE_REF="$(/bin/echo "$pane_output" | "$JQ" -r '.workspace_ref // .workspace.ref // empty')"
WINDOW_REF="$(/bin/echo "$pane_output" | "$JQ" -r '.window_ref // .window.ref // empty')"
[ -n "$PANE_ID" ] || { log "no pane id in pane.create output: $pane_output"; exit 1; }
SURFACE=""
i=0
while [ "$i" -lt 20 ]; do
surfaces_output="$("$CMUX" rpc pane.surfaces "{\"pane_id\":\"$PANE_ID\",\"workspace_id\":\"$WORKSPACE_ID\",\"window_id\":\"$WINDOW_ID\"}" 2>>"$LOG")"
SURFACE="$(/bin/echo "$surfaces_output" | "$JQ" -r '.surfaces[]? | select((.type // "") == "terminal") | .ref // .id' | /usr/bin/head -n 1)"
[ -n "$SURFACE" ] && break
i=$((i + 1))
/bin/sleep 0.1
done
[ -n "$SURFACE" ] || { log "could not find terminal surface in pane: $PANE_ID"; exit 1; }
"$CMUX" send --workspace "$WORKSPACE_ID" --surface "$SURFACE" "$COMMAND_TEXT" 2>>"$LOG"
"$CMUX" send-key --workspace "$WORKSPACE_ID" --surface "$SURFACE" enter 2>>"$LOG"
# Stable receipt consumed by the Imp hook.
/bin/echo "OK surface=$SURFACE pane=${PANE_REF:-$PANE_ID} workspace=${WORKSPACE_REF:-$WORKSPACE_ID} window=${WINDOW_REF:-$WINDOW_ID}"
hooks/hooks.json.example
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "python3 \"$HOME/.codex/hooks/imp-user-prompt-submit.py\"",
"timeout": 5,
"statusMessage": "Routing imp prompt"
}
]
}
]
}
}
hooks/imp-user-prompt-submit.py.template
#!/usr/bin/env python3
"""Example UserPromptSubmit hook for dash-prefix Imp routing.
Install target after review:
~/.codex/hooks/imp-user-prompt-submit.py
"""
from __future__ import annotations
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
IMP_LINE_RE = re.compile(r"^\s{2}(imp-[a-z0-9][a-z0-9-]*)\s+(.+?)\s*$")
PROMPT_RE = re.compile(r"^\s*-([A-Za-z0-9][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$")
FORK_PROMPT_RE = re.compile(r"^\s*--([A-Za-z0-9][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$")
CMUX_RECEIPT_RE = re.compile(r"\b(surface|pane|workspace|window)[=:]([A-Za-z0-9_.:-]+)")
@dataclass(frozen=True)
class Imp:
command: str
description: str
executable_path: str = ""
@property
def name(self) -> str:
return self.command.removeprefix("imp-")
def log(event: dict[str, Any]) -> None:
try:
path = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser() / "logs" / "imp-user-prompt-submit.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(event, sort_keys=True) + "\n")
except Exception:
pass
def emit_continue(additional_context: str | None = None) -> None:
out: dict[str, Any] = {"continue": True, "suppressOutput": True}
if additional_context:
out["hookSpecificOutput"] = {
"hookEventName": "UserPromptSubmit",
"additionalContext": additional_context,
}
print(json.dumps(out, separators=(",", ":")))
def emit_block(reason: str) -> None:
print(
json.dumps(
{
"continue": True,
"decision": "block",
"reason": reason,
"suppressOutput": False,
},
separators=(",", ":"),
)
)
def read_payload() -> dict[str, Any]:
raw = sys.stdin.read()
if not raw.strip():
return {}
return json.loads(raw)
def read_imps() -> list[Imp]:
imp_palette = shutil.which("imp-")
if not imp_palette:
return []
result = subprocess.run(
[imp_palette],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
timeout=2,
)
if result.returncode != 0:
return []
imps: list[Imp] = []
for line in result.stdout.splitlines():
match = IMP_LINE_RE.match(line)
if not match:
continue
command = match.group(1)
imps.append(
Imp(
command=command,
description=match.group(2).strip(),
executable_path=shutil.which(command) or "",
)
)
return imps
def normalize_name(raw: str) -> str:
return raw.strip().lower().replace("_", "-").removeprefix("imp-")
def acronym(text: str) -> str:
return "".join(part[0] for part in re.split(r"[-\s]+", text) if part)
def is_subsequence(needle: str, haystack: str) -> bool:
pos = 0
for char in needle:
found = haystack.find(char, pos)
if found < 0:
return False
pos = found + 1
return True
def score_imp(query: str, imp: Imp) -> int:
name = imp.name
description = imp.description.lower()
words = set(re.findall(r"[a-z0-9]+", description))
if query == name or query == imp.command:
return 100
if name.startswith(query):
return 85
if query.startswith(name):
return 80
if query == acronym(name):
return 78
if query in name:
return 70
if query in words:
return 62
if query in description:
return 55
if len(query) >= 3 and is_subsequence(query, name):
return 48
return 0
def find_imp(raw_name: str, imps: list[Imp]) -> tuple[Imp | None, list[tuple[int, Imp]]]:
query = normalize_name(raw_name)
ranked = sorted(
((score_imp(query, imp), imp) for imp in imps),
key=lambda item: (-item[0], item[1].command),
)
ranked = [item for item in ranked if item[0] > 0]
if not ranked:
return None, []
best_score, best = ranked[0]
runner_up = ranked[1][0] if len(ranked) > 1 else 0
if best_score >= 80 or (best_score >= 55 and best_score - runner_up >= 12):
return best, ranked
return None, ranked
def block_reason(raw_name: str, ranked: list[tuple[int, Imp]]) -> str:
if ranked:
options = ", ".join(f"{imp.command} ({imp.description})" for _, imp in ranked[:5])
return (
f"I could not confidently map '-{raw_name}' to an imp. "
f"Did you mean one of these: {options}? "
"Please resubmit with the exact imp name, or ask whether to create a new imp with imp-create."
)
return (
f"I could not find an imp matching '-{raw_name}'. "
"Please be more specific, or ask whether to create a new imp with imp-create."
)
def normalized_single_dash_prompt(imp: Imp, task: str) -> str:
return f"-{imp.name} {task.strip()}".strip()
def fork_inner_command(session_id: str, single_dash_prompt: str) -> str:
return " ".join(
[
"codex",
"-c",
shlex.quote('shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"'),
"--dangerously-bypass-approvals-and-sandbox",
"fork",
shlex.quote(session_id),
"--",
shlex.quote(single_dash_prompt),
]
)
def run_fork(session_id: str, single_dash_prompt: str) -> subprocess.CompletedProcess[str]:
run_surface = str(Path.home() / ".local/bin/cmux-run-surface")
return subprocess.run(
[run_surface, fork_inner_command(session_id, single_dash_prompt)],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=4,
)
def parse_cmux_receipt(stdout: str) -> dict[str, str]:
receipt: dict[str, str] = {}
for line in stdout.splitlines():
if not line.startswith("OK "):
continue
for key, value in CMUX_RECEIPT_RE.findall(line):
receipt[key] = value
return receipt
def cmux_check_instructions(receipt: dict[str, str]) -> str:
workspace = receipt.get("workspace", "<workspace>")
surface = receipt.get("surface", "<surface>")
pane = receipt.get("pane", "<pane>")
return (
"Check this fork later with: "
f"cmux read-screen --workspace {workspace} --surface {surface} --scrollback --lines 80 ; "
f"cmux top --workspace {workspace} --processes --flat --format tsv ; "
f"cmux focus-pane --workspace {workspace} --pane {pane}"
)
def main() -> int:
try:
payload = read_payload()
prompt = str(payload.get("prompt") or "")
fork = False
match = FORK_PROMPT_RE.match(prompt)
if match:
fork = True
else:
match = PROMPT_RE.match(prompt)
if not match:
emit_continue()
return 0
raw_name = match.group(1)
task = (match.group(2) or "").strip()
if not task:
emit_block(f"Please include a task after '-{raw_name}', for example '-{raw_name} do the thing'.")
return 0
imp, ranked = find_imp(raw_name, read_imps())
if not imp:
emit_block(block_reason(raw_name, ranked))
return 0
executable = imp.executable_path or imp.command
cwd = str(payload.get("cwd") or "").strip()
if fork:
session_id = str(payload.get("session_id") or os.environ.get("CODEX_THREAD_ID") or "").strip()
if not session_id:
emit_block(f"Could not fork '-{imp.name}' because the hook payload did not include a Codex session id.")
return 0
single_dash_prompt = normalized_single_dash_prompt(imp, task)
result = run_fork(session_id, single_dash_prompt)
receipt = parse_cmux_receipt(result.stdout)
log(
{
"event": "fork_opened" if result.returncode == 0 else "fork_error",
"imp": imp.command,
"task": task,
"cwd": cwd,
"session_id": session_id,
"single_dash_prompt": single_dash_prompt,
"stdout": result.stdout,
"stderr": result.stderr,
"cmux": receipt,
}
)
if result.returncode != 0:
emit_block(f"Could not open a cmux fork for '-{imp.name}'. stderr: {result.stderr.strip() or '(none)'}")
return 0
emit_block(
"\n".join(
[
f"Opened a cmux fork for {imp.command} with: {single_dash_prompt}",
f"cmux workspace: {receipt.get('workspace', 'unknown')}",
f"cmux pane: {receipt.get('pane', 'unknown')}",
f"cmux surface: {receipt.get('surface', 'unknown')}",
f"cmux window: {receipt.get('window', 'unknown')}",
cmux_check_instructions(receipt),
]
)
)
return 0
emit_continue(
(
f"The user's prompt began with '-{raw_name}', which is shorthand for invoking {imp.command}.\n\n"
"The UserPromptSubmit hook has already discovered the imp from the command palette "
"and resolved its executable path. Do not run which, where, find, rg, or other discovery "
"commands to locate this imp.\n\n"
f"Resolved imp command: {imp.command}\n"
f"Resolved executable: {executable}\n"
f"imp description: {imp.description}\n"
f"Task text: {task}\n"
f"Current cwd: {cwd}\n\n"
"Let UserPromptSubmit complete and take this main-agent turn before invoking tools. "
"Use the current conversation context naturally, then invoke the resolved executable when appropriate."
)
)
return 0
except Exception as err:
log({"event": "error", "error": repr(err)})
emit_continue()
return 0
if __name__ == "__main__":
raise SystemExit(main())