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