typeclaw 0.48.12 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,243 +0,0 @@
1
- # Tmux driving — full reference
2
-
3
- Deep dive for driving `claude` (interactive) through tmux. Read it when the main `SKILL.md` workflow hits an edge case: a hung session, a missing JSONL, an unexpected ANSI burst, a "tmux says session exists but claude isn't responsive" situation.
4
-
5
- ## Why tmux
6
-
7
- The agent process has no TTY. `claude` (interactive) is a TUI that uses raw terminal modes — it reads stdin one byte at a time with echo off, draws with ANSI escapes, and refuses to start if stdin/stdout aren't terminals. Piping into `claude` (`echo "prompt" | claude`) doesn't work; the CLI detects the absence of a TTY and either falls back to `-p` semantics (no plan mode) or fails outright.
8
-
9
- `tmux` solves this by spawning the process with a pty allocated by tmux itself. You then drive the pty via `send-keys` (write) and `capture-pane` (read). The process believes it's running interactively because, from its file descriptor's point of view, it is.
10
-
11
- ## Why `/tmp/cc-<id>` and not `workspace/cc-<id>`
12
-
13
- The cwd of the spawned `claude` process must be the git worktree at `/tmp/cc-<id>/`, not the agent folder's `workspace/`. Three reasons:
14
-
15
- 1. **Worktree-vs-scratch:** the `cc-<id>` directory is a real git checkout managed by `git worktree`, with refs in `/agent/.git/worktrees/cc-<id>/`. Putting it under `workspace/` would mean the agent folder contains a worktree of itself, which works mechanically but is recursive and confusing.
16
- 2. **The global SessionStart and Stop hooks write their per-session files into cwd.** Both hook scripts read `$PWD` (the literal cwd Claude Code was invoked with) and write into it: SessionStart writes `.session-id` containing the UUID; Stop writes `sentinel-<uuid>.json` and `.done-<uuid>`. `$PWD` resolves to the worktree because `tmux new-session -c /tmp/cc-<id>` sets claude's cwd there. If cwd is the wrong place, the files land somewhere the polling loop isn't watching and the loop times out at its budget. (The hook config itself is global at `~/.claude/settings.json`, not per-worktree — see `references/stop-hook.md` for the architectural context. The hooks deliberately do NOT use Claude Code's `$CLAUDE_PROJECT_DIR` env var, which resolves to the git root of cwd — inside a worktree that's the main repo, not the worktree path; the dockerfile constant block in `src/init/dockerfile.ts` carries the rationale.)
17
- 3. **The worktree IS the codebase.** Claude can read every file at `HEAD` directly — it doesn't need a separate scratch area.
18
-
19
- Auth has no in-container scratch directory at all — the OAuth `setup-token` flow runs on the user's machine, not in tmux here. See `references/auth-flow.md`.
20
-
21
- ## Spawning the session
22
-
23
- The canonical spawn (per `SKILL.md`):
24
-
25
- ```sh
26
- tmux new-session -d -s cc-<task-id> -c /tmp/cc-<task-id> claude
27
- ```
28
-
29
- Flags worth knowing:
30
-
31
- - `-d` — detached. The session runs in the background; your shell doesn't attach.
32
- - `-s cc-<task-id>` — explicit session name. Required. Without `-s`, tmux picks `0`, `1`, … and a sibling delegation will clobber yours.
33
- - `-c /tmp/cc-<task-id>` — start directory. Must be the worktree path. The global Stop hook at `~/.claude/settings.json` always fires regardless of cwd, but the hook script writes its sentinel to `$PWD`; if cwd is wrong, the sentinel lands somewhere your polling loop isn't watching.
34
- - `claude` — the command. Just `claude`, not `claude -p`. The interactive TUI is the whole point.
35
-
36
- Common mistake: forgetting `-c` and getting cwd `/agent` by default. The Stop hook still fires (it's global), but `sentinel.json` + `.done` end up under `/agent/`, your polling loop watches `/tmp/cc-<id>/`, and the loop times out at its wall-clock budget. Worse: claude in `/agent` operates on the live working tree instead of the worktree.
37
-
38
- ## The init wait
39
-
40
- `claude` prints a banner, performs auth verification, and renders its input box. This takes ~2–3 seconds on a warm cache, up to ~8s on cold start. You must wait for the input box to render (and clear any startup dialogs) before sending the first prompt, otherwise `send-keys` writes to a pane that isn't accepting input yet and your keystrokes are lost.
41
-
42
- The skill body's flow uses dialog-polling rather than a fixed sleep: every 500ms, `tmux capture-pane -t cc-<id> -p -S -15` and check for the input box (Unicode box-drawing `╭` / `╰` at column 0 of bottom rows) OR a known dialog (API key confirmation / workspace trust). Clear dialogs as they appear, exit the loop when the input box is visible. Give up after ~10s and surface to the user.
43
-
44
- `.session-id` cannot be used as a readiness signal: per anthropics/claude-code#11519, SessionStart is SKIPPED while workspace trust is pending. The dialog-polling loop is the only reliable signal here.
45
-
46
- ## Sending input
47
-
48
- ```sh
49
- tmux send-keys -t cc-<id> "<text>" Enter
50
- ```
51
-
52
- Notes:
53
-
54
- - **Quote carefully.** The text is interpreted by tmux's send-keys before reaching the pty. Embedded `"` and `\` need escaping. For complex prompts, write the prompt to a file and use `tmux load-buffer + paste-buffer` instead of `send-keys`:
55
-
56
- ```sh
57
- echo "<prompt>" > prompt.txt
58
- tmux load-buffer -t cc-<id> prompt.txt
59
- tmux paste-buffer -t cc-<id>
60
- tmux send-keys -t cc-<id> Enter
61
- ```
62
-
63
- - **`Enter` is the literal key name**, not the text "Enter". Other useful key names: `Escape`, `Tab`, `BSpace`, `Up`, `Down`, `C-c` (Ctrl+C), `C-d` (Ctrl+D for EOF).
64
-
65
- - **Multi-line prompts**: send the body, then `Enter`. Claude Code's input box treats `Enter` as submit, so newlines in your text become submitted lines (not multi-line input). If you need a genuinely multi-line prompt, use the paste-buffer flow above with embedded newlines.
66
-
67
- ## Discovering `cc_session_id` and polling for `.done-<session_id>`
68
-
69
- The skill workflow does NOT pre-fetch the session UUID from `.session-id` — per anthropics/claude-code#11519, SessionStart is suppressed while workspace trust is pending, so `.session-id` may never appear before the first prompt. Instead, the operator discovers the UUID from the **newest unprocessed** Stop sentinel.
70
-
71
- ### Polling is edge-triggered, not level-triggered
72
-
73
- A subtle correctness rule: never poll on "the current `.done-<sid>` appears." That's level-triggered and breaks when (a) an old `.done` still exists from the previous turn and (b) a new one with a different UUID appears (compaction). Instead:
74
-
75
- 1. **Track which sentinels you've already processed** (by UUID).
76
- 2. **On every poll, enumerate ALL `.done-*` files**, ignore the ones you've already processed, and pick the **newest by mtime** of what remains.
77
- 3. **Prefer real UUIDs over `malformed`**: if the newest unprocessed file is a real UUID, take it; if only `.done-malformed` remains, bail with a diagnostic.
78
- 4. **After processing**, remove the specific `.done-<uuid>` you read — don't `rm .done-*`, that wipes an in-flight new sentinel.
79
-
80
- This shape handles three cases uniformly:
81
-
82
- - **First turn**: no processed set; the only file is the new sentinel.
83
- - **Normal turn N→N+1**: the new sentinel arrives, the old one was removed last iteration; pick the new one.
84
- - **Compact mid-delegation**: a `.done-<newuuid>` appears while `.done-<oldsid>` may or may not have been cleaned; pick newest, update `cc_session_id`.
85
-
86
- ### Phase 1 — first-turn discovery (after the first prompt is sent)
87
-
88
- ```sh
89
- budget=600 # 10 minutes in seconds for the first turn
90
- elapsed=0
91
- processed="" # space-separated list of UUIDs we've already consumed
92
- cc_session_id=""
93
- while [ -z "$cc_session_id" ]; do
94
- # Newest unprocessed real .done-<uuid> wins.
95
- # ls -t sorts by mtime (newest first). Restrict to .done-<uuid> shape via case below.
96
- newest=""
97
- for f in $(ls -t /tmp/cc-<id>/.done-* 2>/dev/null); do
98
- [ -f "$f" ] || continue
99
- uuid="${f##*/.done-}"
100
- case " $processed " in *" $uuid "*) continue ;; esac
101
- if [ "$uuid" = "malformed" ]; then
102
- # Only honor malformed if there's nothing real to pick. Keep scanning;
103
- # if we don't see a real UUID first, fall through to the malformed-only case.
104
- malformed_fallback="$f"
105
- continue
106
- fi
107
- newest="$f"
108
- cc_session_id="$uuid"
109
- break
110
- done
111
- if [ -n "$cc_session_id" ]; then break; fi
112
- if [ -n "${malformed_fallback:-}" ]; then
113
- echo "Stop hook fired but couldn't extract a UUID-shape session_id"
114
- exit 1
115
- fi
116
- if [ "$elapsed" -ge "$budget" ]; then
117
- echo "Timeout reached — first Stop never fired"
118
- break
119
- fi
120
- if ! tmux has-session -t cc-<id> 2>/dev/null; then
121
- echo "tmux session died unexpectedly"
122
- break
123
- fi
124
- sleep 0.5
125
- elapsed=$((elapsed + 1))
126
- done
127
- ```
128
-
129
- (Fast-path optimization: if `/tmp/cc-<id>/.session-id` already exists when phase 1 starts — meaning trust was somehow already accepted before this session started — read it and skip the glob. The skill body explains why this rarely wins on first delegations.)
130
-
131
- ### Phase 2 — per-turn polling (turns 2 onward, after sending another prompt)
132
-
133
- ```sh
134
- budget=600
135
- elapsed=0
136
- # `processed` carries over from phase 1 — add the just-consumed UUID before entering phase 2.
137
- processed="$processed $cc_session_id"
138
- new_sid=""
139
- while [ -z "$new_sid" ]; do
140
- for f in $(ls -t /tmp/cc-<id>/.done-* 2>/dev/null); do
141
- [ -f "$f" ] || continue
142
- uuid="${f##*/.done-}"
143
- case " $processed " in *" $uuid "*) continue ;; esac
144
- if [ "$uuid" = "malformed" ]; then
145
- echo "Stop hook fired but couldn't extract a UUID-shape session_id"
146
- exit 1
147
- fi
148
- new_sid="$uuid"
149
- break
150
- done
151
- if [ -n "$new_sid" ]; then break; fi
152
- if [ "$elapsed" -ge "$budget" ]; then echo "Timeout reached"; break; fi
153
- if ! tmux has-session -t cc-<id> 2>/dev/null; then echo "tmux session died unexpectedly"; break; fi
154
- sleep 0.5
155
- elapsed=$((elapsed + 1))
156
- done
157
-
158
- if [ "$new_sid" != "$cc_session_id" ]; then
159
- echo "Detected session_id rotation (compact #29094): ${cc_session_id} → ${new_sid}"
160
- cc_session_id="$new_sid"
161
- fi
162
- # Read sentinel for this turn:
163
- cat "/tmp/cc-<id>/sentinel-${cc_session_id}.json"
164
- # After deciding what to do next, remove ONLY this turn's marker (not a glob):
165
- rm -f "/tmp/cc-<id>/.done-${cc_session_id}"
166
- ```
167
-
168
- In your actual loop, translate to your tool calls. The shell snippets are illustrative.
169
-
170
- ### Why edge-triggered, not level-triggered
171
-
172
- The previous version of this snippet was level-triggered (`while [ ! -f .done-${cc_session_id} ]`), which has two failure modes:
173
-
174
- - **Compact rotation while the old marker still exists**: if the operator hasn't yet `rm`'d `.done-<old>` when claude compacts and fires Stop with `.done-<new>`, the level-triggered predicate is FALSE (old still exists), the inner rotation-check loop never runs, and the operator never notices the new UUID. The new sentinel sits unread; the operator's next `rm .done-<old>` removes the stale marker; the polling loop now blocks forever waiting for `.done-<old>` to reappear.
175
- - **First-turn discovery picking the wrong file**: `for f in .done-*` iterates in shell glob order (lexicographic). If two `.done-*` exist (operator crashed mid-cleanup of a prior turn, or compact fired immediately), the lower-UUID-prefix file wins. Newest-by-mtime is causally correct; shell-glob order is not.
176
-
177
- If `/tmp/cc-<id>/sentinel-malformed.json` or `/tmp/cc-<id>/.done-malformed` appears AND no real UUID file appears, a hook fired but session_id extraction failed (malformed JSON, missing field, or a future upstream schema change). Read `sentinel-malformed.json` to diagnose and surface to the user — this is not a recoverable state from the operator's side.
178
-
179
- ### Why 500ms cadence
180
-
181
- - Faster polling (50–100ms) wastes CPU and is invisible to the user; the user's perception starts caring around 1s.
182
- - Slower polling (2s+) adds visible latency to the multi-turn loop — every Stop adds up to 2s of pure wait.
183
- - 500ms is the sweet spot: invisible latency, minimal CPU, plenty of headroom for short turns.
184
-
185
- ### Session-died recovery
186
-
187
- `tmux has-session` returns non-zero when the session is gone. Three reasons:
188
-
189
- 1. **Claude crashed**: assertion failure, OOM, segfault. `capture-pane` before tmux GC'd the session would show a stack trace. After GC, the session is just gone; you can't recover the pane content.
190
- 2. **Auth failed**: `claude` exited cleanly with "API key invalid" or similar. Pane would have shown the error briefly before the process exited.
191
- 3. **User killed it externally**: someone ran `tmux kill-session -t cc-<id>` outside your control.
192
-
193
- Recovery: surface to the user with whatever you have — `git diff main..cc-<id>` (which still works because the branch exists), `sentinel.json` from any prior turn, the JSONL if it exists. Then clean up: `git worktree remove --force /tmp/cc-<id>` + `git branch -D cc-<id>`. Ask whether to retry.
194
-
195
- ## Capturing the pane (fallback path)
196
-
197
- When the JSONL is missing or you need to see what the TUI showed:
198
-
199
- ```sh
200
- tmux capture-pane -t cc-<id> -p -S - -E -
201
- ```
202
-
203
- Flags:
204
-
205
- - `-p` — print to stdout (default is to copy to a tmux buffer).
206
- - `-S -` — start from the beginning of the scrollback.
207
- - `-E -` — end at the current line.
208
- - Without `-S -E`, you only capture the visible pane (rows × cols), losing everything that scrolled off.
209
-
210
- The captured content includes ANSI escape codes by default. Pass `-e` to preserve them explicitly (rarely useful) or omit and strip via a regex after capture: `s/\x1b\[[0-9;]*[a-zA-Z]//g`.
211
-
212
- ### ANSI gotchas
213
-
214
- - **Progress spinners redraw the same line.** Capture-pane shows the final state of each cell, so spinners look harmless. But mid-capture, if claude is actively redrawing, you may catch a partial frame. Re-capture after `Stop` for a stable view.
215
- - **Box-drawing characters** for the input box and message frames are Unicode (`╭ ╮ ╰ ╯ │ ─`). They render fine in modern terminals but mangle in some text post-processing. If you're showing pane content to the user via TypeClaw's TUI, just preserve as-is — Bun's stdout handles UTF-8.
216
- - **Color codes**: standard 8-color (`\x1b[31m` etc.) and 256-color (`\x1b[38;5;Nm`). The strip regex above handles both.
217
-
218
- ## Cleaning up
219
-
220
- ```sh
221
- tmux send-keys -t cc-<id> "/exit" Enter
222
- sleep 1
223
- tmux kill-session -t cc-<id> 2>/dev/null || true
224
- git -C /agent worktree remove --force /tmp/cc-<id>
225
- git -C /agent branch -D cc-<id>
226
- ```
227
-
228
- - `/exit` is Claude Code's built-in exit command. Cleaner than `C-c` — it lets the CLI flush the JSONL and close cleanly.
229
- - `sleep 1` gives the CLI time to flush. Skip it and you may lose the last few JSONL lines.
230
- - `kill-session ... || true` because the session may have already exited cleanly after `/exit`.
231
- - `worktree remove --force` because the working tree has un-cherry-picked changes (claude's edits + the sentinel + the hook). `--force` is correct here because we're explicitly discarding.
232
- - `branch -D` to delete the throwaway branch. `-D` (capital) because `cc-<id>` is unmerged into anything you care about.
233
-
234
- ## Things you must not do in tmux driving
235
-
236
- - **Do not omit `-s <name>` on `new-session`.** Anonymous sessions race across delegations.
237
- - **Do not omit `-c /tmp/cc-<id>` on `new-session`.** The global Stop hook writes its sentinel into `$PWD`; wrong cwd means the sentinel lands somewhere your polling loop isn't watching. Worse: claude in `/agent` operates on the live working tree instead of the worktree.
238
- - **Do not skip the init wait.** Sending input before the TUI is ready loses the input silently.
239
- - **Do not use `send-keys` with raw user-supplied strings without escaping.** Tmux's send-keys is mildly shell-like; embedded special chars get interpreted. Use `load-buffer + paste-buffer` for anything untrusted or complex.
240
- - **Do not poll `capture-pane` as your primary done-signal.** Use the sentinel. `capture-pane` is for content retrieval, not lifecycle.
241
- - **Do not kill the session with `C-c` if you can avoid it.** `/exit` is cleaner — it gives Claude Code time to flush the JSONL.
242
- - **Do not assume `tmux has-session` returning success means claude is responsive.** A session can exist while claude is wedged. Pair with a wall-clock budget.
243
- - **Do not `rm -rf /tmp/cc-<id>` instead of `git worktree remove`.** Pure rm leaves orphan refs in `/agent/.git/worktrees/cc-<id>/` and a dangling branch. The next delegation with the same id will fail with "branch already exists".
@@ -1,92 +0,0 @@
1
- # Stop hook — schema and gotchas (Codex CLI)
2
-
3
- Deep dive for the `Stop` lifecycle hook that powers the done-signal. Read it when the basic hook in `SKILL.md` isn't enough — when the transcript looks stale, the sentinel is malformed, or you need to extract intermediate tool calls from the JSONL.
4
-
5
- ## What fires when
6
-
7
- Codex CLI ships a hook system that closely mirrors Claude Code's. Events relevant to delegation:
8
-
9
- - **`Stop`** — fires every time the main agent finishes responding. Per-turn, not per-session. A 5-turn conversation fires `Stop` five times. The "task is done" signal is just "the latest Stop, where codex's message looks like a result not a question" — that's the multi-turn decision loop in `SKILL.md`.
10
- - **`SessionStart`** — fires once when the session begins. The pre-baked `typeclaw-cx-session-start-hook` uses this to write `$PWD/.session-id` so the operator learns the session UUID before any Stop fires.
11
- - **`SubagentStop`** — fires when a Codex subagent (Task tool invocation, plan-mode subagents) finishes. Sub-agents are codex spawning codex. You don't typically need to handle this — the parent's `Stop` fires after its subagents are done. Configure it only if you want progress signals during a subagent-heavy turn.
12
-
13
- Other hooks that Codex CLI supports (`PreToolUse`, `PostToolUse`, `PermissionRequest`, `UserPromptSubmit`, `PreCompact`, `PostCompact`, etc.) are out of scope for this skill — they're useful for progress logging, command auditing, or session bookkeeping, but they're not the done-signal.
14
-
15
- ## Stop event JSON schema
16
-
17
- The hook command receives a single JSON object on stdin. Fields observed in current Codex CLI (subject to upstream churn — the docs page is at `developers.openai.com/codex/hooks`):
18
-
19
- ```jsonc
20
- {
21
- "session_id": "abc123…",
22
- "transcript_path": "/root/.codex/sessions/abc123.jsonl",
23
- "cwd": "/tmp/cx-foo",
24
- "model": "gpt-5.5",
25
- "hook_event_name": "Stop",
26
- "last_assistant_message": "…",
27
- "turn_id": "tu_xyz",
28
- }
29
- ```
30
-
31
- Fields you actually use:
32
-
33
- - **`last_assistant_message`** — your primary capture for the multi-turn decision loop. Read this from `sentinel.json`, classify (question / permission / result / spurious), act.
34
- - **`transcript_path`** — points at the JSONL with the full conversation. Useful when `last_assistant_message` isn't enough.
35
- - **`cwd`** — sanity check. If this isn't `/tmp/cx-<id>`, something is wrong with your tmux spawn (likely missing `-c`).
36
- - **`session_id`** — useful for logging or if you want to correlate with the JSONL filename. Already extracted into the sentinel filename by the hook.
37
- - **`turn_id`** — Codex-specific (no equivalent in Claude Code's payload). Useful for correlating a Stop event with the specific assistant turn in the JSONL.
38
-
39
- Fields you ignore:
40
-
41
- - `model`, `hook_event_name` — fixed-per-session metadata; not useful for lifecycle decisions.
42
-
43
- ## The transcript JSONL
44
-
45
- `transcript_path` points at a JSONL file with one JSON object per line. Codex's JSONL is similar in shape to Claude Code's but the type tags differ. Per OpenAI's docs, expect events of the form:
46
-
47
- - **`{ "type": "thread.started", "thread_id": "..." }`** — session boot.
48
- - **`{ "type": "turn.started" }`** — a new agent turn.
49
- - **`{ "type": "turn.completed", "usage": { ... } }`** — turn ended.
50
- - **`{ "type": "item.started", "item": { "type": "agent_message" | "tool_call" | ..., ... } }`** — a content/tool item began.
51
- - **`{ "type": "item.completed", "item": { "id": "...", "type": "agent_message", "text": "..." } }`** — a content item finished.
52
- - **`{ "type": "error", ... }`** — an error item.
53
-
54
- To extract codex's final text answer when `last_assistant_message` isn't enough:
55
-
56
- ```sh
57
- jq -r 'select(.type == "item.completed") | .item | select(.type == "agent_message") | .text' "$transcript_path"
58
- ```
59
-
60
- The exact field names and item types may drift between Codex versions — confirm against `developers.openai.com/codex/noninteractive` (which documents the JSONL schema for `codex exec --json`, the same event types).
61
-
62
- ## Documented race conditions
63
-
64
- Race conditions in Codex CLI's hook system aren't as well-documented as Claude Code's (which has a richer GitHub-issues catalog). The hook's own design — temp-file-then-rename for atomic sentinel writes, `.done` touch after the rename, per-session filenames — already defends against the main classes of race the Claude Code hook surfaces in #15813, #20612, etc. Treat these as defense-in-depth:
65
-
66
- 1. **Stale transcript on Stop**: the hook payload's `last_assistant_message` field carries the same content the JSONL eventually flushes, so prefer it over a re-read of `transcript_path` immediately on hook fire. Wait 1–2 seconds before reading the JSONL if you need it.
67
- 2. **Missing transcript file**: rare in observed practice, but possible during heavy concurrent invocations. Mitigation: capture `last_assistant_message` on every Stop and accumulate it yourself if you need the full history.
68
- 3. **Token-count drift**: Codex's `turn.completed` usage field has been observed to underreport `output_tokens` in some streaming edge cases (similar to Claude Code's #27361). Don't rely on JSONL token counts for cost calculations; the OpenAI dashboard is the authoritative source.
69
-
70
- ## Permission prompts vs Stop
71
-
72
- Codex CLI's default `approval_policy` is `on-request`: the model asks for permission before each tool with side effects, and the user (you, via tmux) answers. **Permission prompts do not fire `Stop`** — when codex is waiting for a "Allow this command?" yes/no, the turn isn't over.
73
-
74
- - **Permission prompt appears** → no `Stop`, no `.done`, you keep polling.
75
- - **You answer the prompt** (via `tmux send-keys "y" Enter`) → codex continues, eventually finishes its turn → `Stop` fires.
76
-
77
- The multi-turn loop's classification looks for content-level questions (questions codex wrote as part of its response), not permission-tool prompts. Permission prompts only appear in the pane, not in `last_assistant_message`.
78
-
79
- If you need to detect permission prompts (to auto-answer them), `capture-pane` is the only signal. Look for the literal yes/no UI affordance. This is risky to automate. Default behavior in this skill: pause polling for the sentinel, look at the pane after the budget elapses without a `.done`, and if there's a permission prompt sitting there, surface to the user rather than auto-answering.
80
-
81
- **Alternative — bypass permissions for vetted automation.** If you want codex to run without per-tool prompts (because the worktree is sandboxed and you've vetted the task), pass `--ask-for-approval never --sandbox workspace-write` to `codex` on spawn. This is the Codex equivalent of "give the agent unattended tool access for this delegation"; use sparingly and only when the worktree's worst-case blast radius is bounded.
82
-
83
- ## Things you must not do with the Stop hook
84
-
85
- - **Do not write a per-worktree `~/.codex/hooks.json` from operator code.** The hook is pre-baked into the image at build time (see `src/init/dockerfile.ts`, constants `TYPECLAW_CX_STOP_HOOK_PATH` and `TYPECLAW_CX_GLOBAL_HOOKS`) precisely so the operator subagent never has to construct that JSON itself. The shape is identical to Claude Code's `settings.json` hooks block (deliberately — same nesting, same exec-form via `args: []`), but Codex's parser silently ignores unknown keys the same way Claude's does. Wrong-shape configs disable the done-signal and burn the polling loop's wall-clock budget. If you ever find yourself wanting to write a per-worktree hooks file, **stop** — either the global hook isn't installed (verify with the `jq` check in `SKILL.md`'s "The Stop hook" section) or you're trying to customize behavior the skill's flow doesn't anticipate. In the former case, bail to the user; in the latter, the right answer is a code change to `src/init/dockerfile.ts`, not a runtime JSON write.
86
- - **Do not edit the in-Dockerfile hook config in a way that bypasses `JSON.stringify` + the regression test.** `TYPECLAW_CX_GLOBAL_HOOKS` in `src/init/dockerfile.ts` is constructed via `JSON.stringify` so any structural drift fails `dockerfile.test.ts`'s `JSON.parse` regression test, not the docker build or (worse) the first failed delegation.
87
- - **Do not set the Stop matcher to anything other than `"*"`.** The matcher filters by hook tool name; for `Stop`, there's no tool — `"*"` is the canonical "fire on every Stop". Other values may silently never match.
88
- - **Do not put long-running commands in the hook.** The hook runs synchronously on the Codex CLI main loop; a slow hook blocks the user's next prompt. Write the payload + touch a flag + exit. Anything heavier belongs in your polling loop, not the hook.
89
- - **Do not skip the temp-file rename pattern.** Writing `sentinel.json` directly with `>` lets readers see partial JSON if they poll mid-write. Always temp-then-rename. The pre-baked hook script already does this — don't replace it with a per-worktree variant.
90
- - **Do not delete `transcript_path` from inside the hook.** The path is shared with `SessionEnd` and other lifecycle events; deleting it breaks downstream hooks.
91
- - **Do not log the full hook payload to a place you don't control.** It contains `last_assistant_message`, which can contain anything codex said — including code, secrets the user pasted, or private context. Sentinel is fine (it's in `/tmp/`); piping to a shared log is not.
92
- - **Do not assume the JSONL event-type names are identical to Claude Code's.** They're shaped similarly but differ (`item.completed` vs `assistant`/`content[].type`). When extracting content from the JSONL, write Codex-specific `jq` filters; don't reuse Claude Code's.
@@ -1,239 +0,0 @@
1
- # Tmux driving — full reference (Codex CLI)
2
-
3
- Deep dive for driving `codex` (interactive) through tmux. Read it when the main `SKILL.md` workflow hits an edge case: a hung session, a missing JSONL, an unexpected ANSI burst, a "tmux says session exists but codex isn't responsive" situation.
4
-
5
- The shape of this reference is intentionally a mirror of `typeclaw-claude-code`'s `references/tmux-driving.md`. The differences are noted inline; everything not flagged is the same.
6
-
7
- ## Why tmux
8
-
9
- The agent process has no TTY. `codex` (interactive) is a TUI built on `ratatui` + `crossterm` that uses raw terminal modes — it reads stdin one byte at a time with echo off, draws with ANSI escapes, and refuses to start sensibly if stdin/stdout aren't terminals. Piping into `codex` doesn't work; the CLI detects the absence of a TTY and either falls back to non-interactive semantics or fails outright.
10
-
11
- `tmux` solves this by spawning the process with a pty allocated by tmux itself. You then drive the pty via `send-keys` (write) and `capture-pane` (read).
12
-
13
- ## Why `/tmp/cx-<id>` and not `workspace/cx-<id>`
14
-
15
- Same reasoning as Claude Code's `cc-<id>`:
16
-
17
- 1. **Worktree-vs-scratch:** the `cx-<id>` directory is a real git checkout managed by `git worktree`, with refs in `/agent/.git/worktrees/cx-<id>/`. Putting it under `workspace/` would mean the agent folder contains a worktree of itself, which works mechanically but is recursive and confusing.
18
- 2. **The global SessionStart and Stop hooks write their per-session files into cwd.** Both hook scripts read `$PWD` (the literal cwd Codex CLI was invoked with) and write into it: SessionStart writes `.session-id` containing the UUID; Stop writes `sentinel-<uuid>.json` and `.done-<uuid>`. `$PWD` resolves to the worktree because `tmux new-session -c /tmp/cx-<id>` sets codex's cwd there.
19
- 3. **The worktree IS the codebase.** Codex can read every file at `HEAD` directly — it doesn't need a separate scratch area.
20
-
21
- The `cx-` prefix (vs Claude Code's `cc-`) keeps the two CLIs' worktrees, branches, and tmux sessions in parallel namespaces. An agent running both can delegate concurrently without collision; `git worktree list` shows both kinds clearly; `tmux ls` is unambiguous.
22
-
23
- ## Spawning the session
24
-
25
- The canonical spawn (per `SKILL.md`):
26
-
27
- ```sh
28
- tmux new-session -d -s cx-<task-id> -c /tmp/cx-<task-id> codex
29
- ```
30
-
31
- Flags worth knowing:
32
-
33
- - `-d` — detached. The session runs in the background; your shell doesn't attach.
34
- - `-s cx-<task-id>` — explicit session name. Required. Without `-s`, tmux picks `0`, `1`, … and a sibling delegation will clobber yours.
35
- - `-c /tmp/cx-<task-id>` — start directory. Must be the worktree path. The global Stop hook at `~/.codex/hooks.json` always fires regardless of cwd, but the hook script writes its sentinel to `$PWD`; if cwd is wrong, the sentinel lands somewhere your polling loop isn't watching.
36
- - `codex` — the command. Just `codex`, not `codex exec`. The interactive TUI is the whole point.
37
-
38
- Common mistakes:
39
-
40
- - Forgetting `-c` and getting cwd `/agent` by default. The Stop hook still fires (it's global), but `sentinel.json` + `.done` end up under `/agent/`, your polling loop watches `/tmp/cx-<id>/`, and the loop times out at its wall-clock budget. Worse: codex in `/agent` operates on the live working tree instead of the worktree.
41
- - Passing flags Codex CLI doesn't recognize. Codex is a Rust binary with a strict clap parser — unknown flags fail at startup, not silently.
42
-
43
- ### Alternate-screen vs inline mode
44
-
45
- Codex CLI's TUI defaults to **alternate-screen mode** (the same mode `vim` uses) — it takes over the entire terminal and restores the previous screen on exit. This means `tmux capture-pane -S -` only captures what's currently visible, not the full conversation history.
46
-
47
- For our workflow this is fine: we use the Stop sentinel as the done-signal, not pane-content parsing. But if you ever need to capture the full TUI history (e.g. for a post-mortem when the JSONL is missing), spawn codex with `--no-alt-screen`:
48
-
49
- ```sh
50
- tmux new-session -d -s cx-<id> -c /tmp/cx-<id> codex --no-alt-screen
51
- ```
52
-
53
- `--no-alt-screen` runs the TUI inline, preserving terminal scrollback. The trade-off is that the rendering is slightly less stable (the TUI's redraws collide with normal scrollback flow), but `capture-pane -S -` will then see the full history.
54
-
55
- Default to alternate-screen mode (no flag); reach for `--no-alt-screen` only when you genuinely need scrollback capture for debugging.
56
-
57
- ## The init wait
58
-
59
- `codex` prints a brief Welcome animation, then renders its TUI. The animation takes ~1 second; after that the input composer appears immediately if no dialogs fire, or one or more dialog modals appear in sequence. You must wait for the input composer (and clear any dialogs) before sending the first prompt.
60
-
61
- The skill body's flow uses dialog-polling rather than a fixed sleep: every 500ms, `tmux capture-pane -t cx-<id> -p -S -15` and check for the input composer (bottom-of-pane prompt indicator) OR a known dialog (Auth picker / TrustDirectory / hook trust). Clear dialogs as they appear, exit the loop when the input composer is visible. Give up after ~10s and surface to the user.
62
-
63
- Unlike Claude Code, Codex's `.session-id` IS a reliable readiness signal in most cases: Codex's SessionStart hook does NOT get suppressed while the TrustDirectory dialog is pending (different upstream architecture than Claude Code's #11519 issue). The fast path — read `.session-id` after ~1 second — usually wins. But the dialog-polling loop is still required to clear TrustDirectory before sending the first prompt; otherwise the prompt is interpreted as a dialog answer.
64
-
65
- ## Sending input
66
-
67
- ```sh
68
- tmux send-keys -t cx-<id> "<text>" Enter
69
- ```
70
-
71
- Notes:
72
-
73
- - **Quote carefully.** The text is interpreted by tmux's send-keys before reaching the pty. Embedded `"` and `\` need escaping. For complex prompts, write the prompt to a file and use `tmux load-buffer + paste-buffer` instead of `send-keys`:
74
-
75
- ```sh
76
- echo "<prompt>" > prompt.txt
77
- tmux load-buffer -t cx-<id> prompt.txt
78
- tmux paste-buffer -t cx-<id>
79
- tmux send-keys -t cx-<id> Enter
80
- ```
81
-
82
- - **Bracketed paste is enabled** by default in Codex's TUI (`EnableBracketedPaste` in `tui.rs`), so `paste-buffer` content arrives intact even with newlines.
83
-
84
- - **`Enter` is the literal key name**, not the text "Enter". Other useful key names: `Escape`, `Tab`, `BSpace`, `Up`, `Down`, `C-c` (Ctrl+C), `C-d` (Ctrl+D for EOF). Codex's composer also honors `Ctrl-M` as submit (configurable per `tui.keymap.composer.submit` in `~/.codex/config.toml`, but our flow assumes the default).
85
-
86
- - **Multi-line prompts**: send the body, then `Enter`. Codex's composer treats Enter as submit by default, so newlines in your text become submitted lines. For genuinely multi-line input, use the paste-buffer flow above — bracketed paste passes the newlines through to the composer's input buffer without submitting until you press Enter explicitly.
87
-
88
- ## Discovering `cx_session_id` and polling for `.done-<session_id>`
89
-
90
- Same edge-triggered polling pattern as Claude Code. Track which sentinels you've already processed by UUID; on every poll, enumerate ALL `.done-*` files, ignore the ones you've already processed, and pick the **newest by mtime** of what remains.
91
-
92
- ### Phase 1 — first-turn discovery
93
-
94
- Fast path: after spawning codex and waiting ~1s, check `/tmp/cx-<id>/.session-id`. If it exists and contains a real UUID, that's `cx_session_id`. Otherwise fall through to the same first-turn polling as Claude Code (translate to your tool calls; the shell snippet is illustrative):
95
-
96
- ```sh
97
- budget=600
98
- elapsed=0
99
- processed=""
100
- cx_session_id=""
101
- # Fast path
102
- if [ -f /tmp/cx-<id>/.session-id ]; then
103
- candidate="$(cat /tmp/cx-<id>/.session-id 2>/dev/null)"
104
- case "$candidate" in
105
- [0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]-*) cx_session_id="$candidate" ;;
106
- malformed) echo "SessionStart fired but session_id was bad" ; exit 1 ;;
107
- esac
108
- fi
109
- # Discovery path (fallback or wait for the first Stop)
110
- while [ -z "$cx_session_id" ]; do
111
- newest=""
112
- for f in $(ls -t /tmp/cx-<id>/.done-* 2>/dev/null); do
113
- [ -f "$f" ] || continue
114
- uuid="${f##*/.done-}"
115
- case " $processed " in *" $uuid "*) continue ;; esac
116
- if [ "$uuid" = "malformed" ]; then
117
- malformed_fallback="$f"
118
- continue
119
- fi
120
- newest="$f"
121
- cx_session_id="$uuid"
122
- break
123
- done
124
- if [ -n "$cx_session_id" ]; then break; fi
125
- if [ -n "${malformed_fallback:-}" ]; then
126
- echo "Stop hook fired but couldn't extract a UUID-shape session_id"
127
- exit 1
128
- fi
129
- if [ "$elapsed" -ge "$budget" ]; then echo "Timeout reached"; break; fi
130
- if ! tmux has-session -t cx-<id> 2>/dev/null; then echo "tmux session died"; break; fi
131
- sleep 0.5
132
- elapsed=$((elapsed + 1))
133
- done
134
- ```
135
-
136
- ### Phase 2 — per-turn polling (turns 2 onward)
137
-
138
- Same shape as Claude Code's phase 2. `processed` carries over from phase 1; add the just-consumed UUID before entering phase 2. On every iteration, glob `.done-*`, pick newest unprocessed real-UUID, update `cx_session_id` if it differs (rotation), read the sentinel, `rm` ONLY the specific `.done-<uuid>` you processed.
139
-
140
- ```sh
141
- budget=600
142
- elapsed=0
143
- processed="$processed $cx_session_id"
144
- new_sid=""
145
- while [ -z "$new_sid" ]; do
146
- for f in $(ls -t /tmp/cx-<id>/.done-* 2>/dev/null); do
147
- [ -f "$f" ] || continue
148
- uuid="${f##*/.done-}"
149
- case " $processed " in *" $uuid "*) continue ;; esac
150
- if [ "$uuid" = "malformed" ]; then echo "bad session_id"; exit 1; fi
151
- new_sid="$uuid"
152
- break
153
- done
154
- if [ -n "$new_sid" ]; then break; fi
155
- if [ "$elapsed" -ge "$budget" ]; then echo "Timeout"; break; fi
156
- if ! tmux has-session -t cx-<id> 2>/dev/null; then echo "tmux died"; break; fi
157
- sleep 0.5
158
- elapsed=$((elapsed + 1))
159
- done
160
-
161
- if [ "$new_sid" != "$cx_session_id" ]; then
162
- echo "Detected session_id rotation: ${cx_session_id} → ${new_sid}"
163
- cx_session_id="$new_sid"
164
- fi
165
- cat "/tmp/cx-<id>/sentinel-${cx_session_id}.json"
166
- rm -f "/tmp/cx-<id>/.done-${cx_session_id}"
167
- ```
168
-
169
- ### Why edge-triggered, not level-triggered
170
-
171
- Same reasoning as Claude Code. Level-triggered polling on a fixed `.done-<sid>` filename breaks on session rotation and on the "old marker still exists when new one arrives" race. Newest-by-mtime + processed-set is the only correct pattern.
172
-
173
- ### Why 500ms cadence
174
-
175
- - Faster polling (50–100ms) wastes CPU and is invisible to the user.
176
- - Slower polling (2s+) adds visible latency.
177
- - 500ms is the sweet spot — same calibration as Claude Code, same reasoning.
178
-
179
- ### Session-died recovery
180
-
181
- `tmux has-session` returns non-zero when the session is gone. Three reasons:
182
-
183
- 1. **Codex crashed**: panic, segfault. `capture-pane` before tmux GC'd would show the panic message.
184
- 2. **Auth failed**: `codex` exited cleanly with "Unauthorized" or similar. Pane would have shown the error briefly.
185
- 3. **User killed it externally**: someone ran `tmux kill-session -t cx-<id>` outside your control.
186
-
187
- Recovery: surface to the user with whatever you have — `git diff main..cx-<id>` (which still works because the branch exists), `sentinel.json` from any prior turn, the JSONL if it exists. Then clean up: `git worktree remove --force /tmp/cx-<id>` + `git branch -D cx-<id>`. Ask whether to retry.
188
-
189
- ## Capturing the pane (fallback path)
190
-
191
- When the JSONL is missing or you need to see what the TUI showed:
192
-
193
- ```sh
194
- tmux capture-pane -t cx-<id> -p -S - -E -
195
- ```
196
-
197
- Flags:
198
-
199
- - `-p` — print to stdout.
200
- - `-S -` — start from the beginning of the scrollback.
201
- - `-E -` — end at the current line.
202
-
203
- If codex was spawned in alternate-screen mode (the default), `-S -` only captures the current screen. For full history, spawn with `--no-alt-screen`.
204
-
205
- ### ANSI gotchas
206
-
207
- - **Codex uses crossterm + ratatui** with bracketed paste, focus tracking, and keyboard enhancement modes enabled. Captures will contain ANSI escapes for color, cursor positioning, and bracketed-paste markers (`\x1b[200~` / `\x1b[201~`).
208
- - **Progress indicators** in Codex's tool-use UI redraw in place. Captures show the final state of each cell.
209
- - **Box-drawing characters** for input frames are Unicode (`╭ ╮ ╰ ╯ │ ─`). Preserve as UTF-8.
210
- - **Color codes**: standard 8-color and 256-color. Strip with `s/\x1b\[[0-9;]*[a-zA-Z]//g` if you need plain text.
211
-
212
- ## Cleaning up
213
-
214
- ```sh
215
- tmux send-keys -t cx-<id> "/exit" Enter
216
- sleep 1
217
- tmux kill-session -t cx-<id> 2>/dev/null || true
218
- git -C /agent worktree remove --force /tmp/cx-<id>
219
- git -C /agent branch -D cx-<id>
220
- ```
221
-
222
- - `/exit` is Codex CLI's built-in exit command. Cleaner than `C-c` — it lets the CLI flush the JSONL and close cleanly.
223
- - `sleep 1` gives the CLI time to flush. Skip it and you may lose the last few JSONL lines.
224
- - `kill-session ... || true` because the session may have already exited cleanly after `/exit`.
225
- - `worktree remove --force` because the working tree has un-cherry-picked changes. `--force` is correct here because we're explicitly discarding.
226
- - `branch -D` to delete the throwaway branch.
227
-
228
- ## Things you must not do in tmux driving
229
-
230
- - **Do not omit `-s <name>` on `new-session`.** Anonymous sessions race across delegations.
231
- - **Do not omit `-c /tmp/cx-<id>` on `new-session`.** The global Stop hook writes its sentinel into `$PWD`; wrong cwd means the sentinel lands somewhere your polling loop isn't watching. Worse: codex in `/agent` operates on the live working tree instead of the worktree.
232
- - **Do not skip the init wait.** Sending input before the TUI is ready loses the input silently — or worse, the input lands inside a dialog modal and gets interpreted as a yes/no answer.
233
- - **Do not use `send-keys` with raw user-supplied strings without escaping.** Tmux's send-keys is mildly shell-like; embedded special chars get interpreted. Use `load-buffer + paste-buffer` for anything untrusted or complex.
234
- - **Do not poll `capture-pane` as your primary done-signal.** Use the sentinel. `capture-pane` is for content retrieval, not lifecycle.
235
- - **Do not kill the session with `C-c` if you can avoid it.** `/exit` is cleaner.
236
- - **Do not assume `tmux has-session` returning success means codex is responsive.** A session can exist while codex is wedged. Pair with a wall-clock budget.
237
- - **Do not `rm -rf /tmp/cx-<id>` instead of `git worktree remove`.** Pure rm leaves orphan refs and a dangling branch.
238
- - **Do not mix `cx-` and `cc-` prefixes within one delegation.** They're parallel namespaces by design — Codex sessions use `cx-`, Claude Code sessions use `cc-`. Cross-using leaves orphans in both worktree lists.
239
- - **Do not pass `codex --no-alt-screen` reflexively.** Alternate-screen mode is the default for good reason (cleaner TUI rendering). Reach for the flag only when you need full-scrollback capture for debugging.