aiterm-mcp 0.20.3 → 0.21.3

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.
package/README.ja.md CHANGED
@@ -91,12 +91,16 @@ claude mcp add --scope user --transport stdio aiterm -- npx -y aiterm-mcp
91
91
  host統合は、kitepon.devの製品開発を支える内部基盤
92
92
  [dotagents](https://github.com/kitepon-rgb/dotagents)が担当します。
93
93
 
94
- **言葉でなく実測で:** このリポジトリ自身の 203 テストで、`pty_read` はコンテキストに載るトークンを生ログの **約 7.1 分の 1** に減らす。しかも pass/fail の判定は畳んでも残る。→ [組み込みシェルツールとの使い分け](#組み込みシェルツールとの使い分け)
94
+ **言葉でなく実測で:** 記録済み203テストのベンチマークでは、`pty_read` はコンテキストに載るトークンを生ログの **約 7.1 分の 1** に減らす。しかも pass/fail の判定は畳んでも残る。→ [組み込みシェルツールとの使い分け](#組み込みシェルツールとの使い分け)
95
95
 
96
96
  13 ツール: 6 つの **PTY ツール**(`pty_open` / `pty_send` / `pty_read` / `pty_key` / `pty_close` / `pty_list`)で 1 本の永続端末を開き・操作し・読む。加えて 4 つの **エージェント起動ツール**(`claude_agent` / `codex_agent` / `grok_agent` / `composer_agent`)が別のコーディングエージェントの TUI を新しい端末の中に起動し、`claude_turn`がdurable caller向けの構造化issue/recoveryを、`claude_approval`がmanaged Claudeの相関済み承認UI中継を、`diagnostics`が安全なfactory readinessを返す。バックエンドは **tmux** なので、MCP サーバや AI クライアントが再起動してもセッションは生き残る。
97
97
 
98
- **v0.20.3では、壊れた認証から複数のmanaged Claude/Fable sessionが同時にloginへ流れる問題を修理。**
99
- 新規Claude起動はPTY作成前にvendor所有の共有認証を検証し、正常な認証は複数sessionから並行・反復利用できる。
98
+ **v0.21.3ではCodexの完了経路からStop hookを撤去。** Codexの完了通知と最終回答の帰属は、
99
+ root rollout transcriptへ永続化される`task_complete.turn_id`をdispatch byte境界以後から観測する。
100
+ hookの実行ファイルが壊れたり消えたりしても`aiterm-wait`は座礁しない。v0.21.0では外部agent launcherへ
101
+ 明示的な`write_scope`能力宣言を追加し、v0.21.3で指定したscopeと実効性がstructured launch receiptへ
102
+ 確実に残るよう修正した。v0.20.3では、壊れた認証から複数のmanaged Claude/Fable
103
+ sessionが同時にloginへ流れる問題を修理し、新規Claude起動はPTY作成前にvendor所有の共有認証を検証する。
100
104
  v0.20では、待たずに一度だけ観測する
101
105
  `aiterm-wait --timeout 0` の未完了を、実際に待って終わらなかった`timeout`と区別し、
102
106
  `running`(exit 5)で返すようにしました。v0.19系では相関済みmanaged Claude approval中継を追加し、
@@ -133,11 +137,15 @@ pty_read(id, { wait: true }) → 削減済みの出力を読む(完了
133
137
 
134
138
  ### 2. その端末の中に他のコーディングエージェントを起動する — オーケストレーションの旗艦
135
139
 
136
- 同じ primitive が別エージェントの TUI を宿す。4 つの起動ツールが、Claude/Codex/Grok/Composer の対話 TUI を新しい永続端末の中に起動し、`session_id` を返す。既存の人間向けtextに加えて`aiterm.agent-launch-result.v1` structured receiptも返すため、durable callerは表示文字列を解析せずsession handleを取得できる。以後は同じ `pty_read` / `pty_send` で継続操作する。**起動は常に managed**(aiterm 所有の Stop hook 付き)で、agent session への `pty_send` は非ブロックの **dispatch** になり `event_cursor` 入り receipt を即返す。完了通知は `aiterm-wait --session <id> --cursor <event_cursor>` をホストのバックグラウンドタスクとして実行し、exit 時に receipt の `outcome` で判定する(exit 0=done / 3=timeout=未完了・既定600秒 / 4=closed。親はブロックもポーリングもしない)。起動時 `prompt` を渡した launch は structured receipt にコピペ可能な `wait_command` と `event_cursor`、そして `submit_residue` 観測を含む(true=prompt が composer に未 submit で残存している疑い=案内に従い画面確認から復旧 / false=残存観測せず・成立の保証ではない / null=対象外)。dispatch receipt にも同じ観測が付く。durable machine callerは`claude_turn({ action:"issue"|"recover", session_id, operation_id, ... })`を使い、人間向けerror文字列を解析せず`accepted`/`pending`/`completed`/`unknown`を判定できる。recoveryは再送せず、検証済み完了だけがexact `raw_output`を持つ。通常の`pty_send`/`pty_read`は対話callerと人間向けに維持する。`C-c`後もmarkerを保持し、Stopが来なければsessionをcloseする。`claude_agent` と `codex_agent` の初回 `prompt` は ready gate 経由で送信して待たずに返る(Grok/Composer は argv 渡し)。手動でキー操作したい場合は `pty_open` で素の端末を開き vendor CLI を自分で起動する。
140
+ 同じ primitive が別エージェントの TUI を宿す。4 つの起動ツールが、Claude/Codex/Grok/Composer の対話 TUI を新しい永続端末の中に起動し、`session_id` を返す。既存の人間向けtextに加えて`aiterm.agent-launch-result.v1` structured receiptも返すため、durable callerは表示文字列を解析せずsession handleを取得できる。以後は同じ `pty_read` / `pty_send` で継続操作する。**起動は常に managed**で、Codexはroot rollout transcriptの`task_complete`、Claude/Grokは隔離されたmanaged Stop hookを完了正本に使う。agent session への `pty_send` は非ブロックの **dispatch** になり `event_cursor` 入り receipt を即返す。完了通知は `aiterm-wait --session <id> --cursor <event_cursor>` をホストのバックグラウンドタスクとして実行し、exit 時に receipt の `outcome` で判定する(exit 0=done / 3=timeout=未完了・既定600秒 / 4=closed。親はブロックもポーリングもしない)。起動時 `prompt` を渡した launch は structured receipt にコピペ可能な `wait_command` と `event_cursor`、そして `submit_residue` 観測を含む(true=prompt が composer に未 submit で残存している疑い=案内に従い画面確認から復旧 / false=残存観測せず・成立の保証ではない / null=対象外)。dispatch receipt にも同じ観測が付く。durable machine callerは`claude_turn({ action:"issue"|"recover", session_id, operation_id, ... })`を使い、人間向けerror文字列を解析せず`accepted`/`pending`/`completed`/`unknown`を判定できる。recoveryは再送せず、検証済み完了だけがexact `raw_output`を持つ。通常の`pty_send`/`pty_read`は対話callerと人間向けに維持する。`C-c`後もClaude markerを保持し、Stopが来なければsessionをcloseする。`claude_agent` と `codex_agent` の初回 `prompt` は ready gate 経由で送信して待たずに返る(Grok/Composer は argv 渡し)。手動でキー操作したい場合は `pty_open` で素の端末を開き vendor CLI を自分で起動する。
141
+
142
+ `codex_agent`・`grok_agent`・`composer_agent`は任意の`write_scope`(`"read-only"`または書込み許可パスの説明)も受ける。指定値はlaunch receipt・session metadata・`pty_list`へ保存する。Codexの`write_scope:"read-only"`だけは実効能力壁であり、aitermがCLIの`--sandbox read-only`を付ける。Grok/Composerには対応する対話起動sandboxがなく、Codexにもパス説明をallowlistへ変換するフラグがないため、それらは強制済みと偽らず`write_scope_enforcement:"declaration_only_unsupported"`を返す。`write_scope`を省略した起動は従来どおりである。
137
143
 
138
144
  ```text
139
145
  codex_agent({ session_name: "codex1", cwd: "/repo",
140
- prompt: "port test/legacy.py to vitest" })
146
+ prompt: "port test/legacy.py to vitest",
147
+ model: "gpt-5.6-sol", reasoning_effort: "high",
148
+ write_scope: "test/ only; no commit" })
141
149
  → { session_id: "codex1", … } # Codex が永続端末で稼働開始
142
150
  pty_read("codex1", { screen: true }) → 何をしているか読む(トークン削減)
143
151
  pty_send("codex1", "also fix the imports it broke") # 非ブロックdispatch=event_cursor入りreceipt
@@ -150,9 +158,9 @@ $ aiterm-wait --session codex1 --cursor <event_cursor> # exit 0=done / 3=timeo
150
158
  | ツール | 起動するもの | 主な引数 |
151
159
  | --- | --- | --- |
152
160
  | `claude_agent` | Claude Code CLI(Anthropic) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?` |
153
- | `codex_agent` | Codex CLI(OpenAI・端末設定/CLI既定、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`/`ultra`), `cwd?`, `session_name?` |
154
- | `grok_agent` | Grok Build(xAI、既定`grok-4.5`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?` |
155
- | `composer_agent` | Grok Build(xAI、既定`grok-composer-2.5-fast`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?` |
161
+ | `codex_agent` | Codex CLI(OpenAI・端末設定/CLI既定、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`/`ultra`), `cwd?`, `session_name?`, `write_scope?` |
162
+ | `grok_agent` | Grok Build(xAI、既定`grok-4.5`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?`, `write_scope?` |
163
+ | `composer_agent` | Grok Build(xAI、既定`grok-composer-2.5-fast`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?`, `write_scope?` |
156
164
 
157
165
  各ベンダーの CLI が導入・認証済みであること(`claude_agent` は `claude`、`codex_agent` は `codex`、Grok 系は `grok`)。バイナリは `CLAUDE_BIN` / `CODEX_BIN` / `GROK_BIN`、各既定path、`PATH` の順で解決する。CLI不在・不正なmodel/effort・実在しない`cwd`はsession作成前に失敗し、残骸を残さない。Claudeはさらに、PTY作成前に同じCLIの`auth status --json`が`loggedIn:true`を返すことを要求する。未認証・malformed・失敗exit・timeoutは残骸ゼロで失敗し、正常なvendor所有の共有認証は複数sessionから利用する。managed Claudeへのexact `/login`・`/logout`は通常dispatchとforce送信の双方で副作用前に拒否するため、認証は通常端末で一度だけ修理する。Claudeは通常settingsを継承しないlaunch専用settingsとStop hookを使い、本文なしeventとowner-only bounded resultを分離する。`pty_read({ agent_transcript:true })`はdigestとbyte数を検証したresultだけを返し、Claude private transcriptを読まない。後着resultは同じsessionからprompt再送なしで回収できる。managed Claudeのactive turn中はC-c以外の`pty_key`と素送信を拒否する。Claudeが`Do you want to proceed?`を表示したら、`claude_approval(action:"inspect", ...)`で画面digestを取得し、表示内容を判断してから、そのdigestと`approve_once`または`deny`を`respond`へ渡す。同じoperation・同じ画面が維持されている時だけ入力し、任意文字列や恒久許可選択肢は中継しない。中断は`C-c`、解除は`pty_close`。
158
166
 
@@ -352,17 +360,17 @@ consumer は `aiterm-runtime-errors snapshot` を読み、durable ingestion 後
352
360
  | ツール | 起動するもの | 主な引数 |
353
361
  | --- | --- | --- |
354
362
  | `claude_agent` | Claude Code CLI(Anthropic) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?` |
355
- | `codex_agent` | Codex CLI(OpenAI・端末設定/CLI既定、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`/`ultra`), `cwd?`, `session_name?` |
356
- | `grok_agent` | Grok Build(xAI、既定`grok-4.5`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?` |
357
- | `composer_agent` | Grok Build(xAI、既定`grok-composer-2.5-fast`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?` |
363
+ | `codex_agent` | Codex CLI(OpenAI・端末設定/CLI既定、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`/`ultra`), `cwd?`, `session_name?`, `write_scope?` |
364
+ | `grok_agent` | Grok Build(xAI、既定`grok-4.5`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?`, `write_scope?` |
365
+ | `composer_agent` | Grok Build(xAI、既定`grok-composer-2.5-fast`、`model?`で上書き) | `prompt?`, `model?`, `reasoning_effort?`は非対応(指定時は明示エラー), `cwd?`, `session_name?`, `write_scope?` |
358
366
 
359
367
  対応するCLI(`claude` / `codex` / `grok`)の導入・認証が必要。解決順は`CLAUDE_BIN` / `CODEX_BIN` / `GROK_BIN`、既定path、`PATH`。前提違反はsession作成前に明示失敗する。ClaudeはPTY作成前に構造化認証statusも検証し、managed session内の`/login`・`/logout`を拒否する。4 launcherすべてが同じ非ブロックdispatch契約を使い、Claude/Codexの初回promptはready gate経由で送信される。Claudeはisolated managed settingsとhook-captured resultを使い、private transcriptへ依存しない。Claude/Codex/Grok/Composerのlive smokeはすべてgreenであり、fixtureによる検証とは区別して記録する。
360
368
 
361
- エージェントの回答が画面 tailより長ければ、対話callerは`pty_read({ agent_transcript:true })`で再promptなしに全文回収する。Claudeはmanaged Stop hookがowner-only resultへ保存した本文をdigest/byte数で検証して返し、private transcriptを読まない。durable machine callerは`claude_turn`を使う。`issue`は一度だけ送信し、`recover`は決して再送せず、`pending`を破損やidentity不一致と区別する。検証済みの`completed`だけがexact `raw_output`を持ち、`unknown`は未dispatchと帰属不能を区別する。不一致・破損は成功statusへ丸めずtool errorのままにする。IDなしの対話turnも匿名markerで直列化するため、現在Stop待ちの間に古い回答を返さない。CodexはStop hookの`turn_id`で構造化transcriptへjoinし、Grok/Composerは最後の実user行より後ろのassistant行を採る。不在・非agent・抽出不能は明示エラー。
369
+ エージェントの回答が画面 tailより長ければ、対話callerは`pty_read({ agent_transcript:true })`で再promptなしに全文回収する。Claudeはmanaged Stop hookがowner-only resultへ保存した本文をdigest/byte数で検証して返し、private transcriptを読まない。durable machine callerは`claude_turn`を使う。`issue`は一度だけ送信し、`recover`は決して再送せず、`pending`を破損やidentity不一致と区別する。検証済みの`completed`だけがexact `raw_output`を持ち、`unknown`は未dispatchと帰属不能を区別する。不一致・破損は成功statusへ丸めずtool errorのままにする。IDなしの対話turnも匿名markerで直列化するため、現在Stop待ちの間に古い回答を返さない。Codexはroot rollout transcriptの`task_complete.turn_id`で完了と最終回答を同じturnへ帰属し、Grok/Composerは最後の実user行より後ろのassistant行を採る。不在・非agent・抽出不能は明示エラー。
362
370
 
363
371
  ### 完了検出(5 層)
364
372
 
365
- `pty_read({ wait: true })` は、プロセス終了 / `mark:true` sentinel の自動検出(後述)/ `until` 一致(**既定はリテラル部分一致**、`until_regex: true` で正規表現)/ 出力静止 ∧ シェル復帰(quiescence)/ timeout の 5 層で「コマンドが終わったか」を判定する。ネスト中(SSH・コンテナ・REPL・起動したエージェントの TUI の中)はシェル復帰判定が効かないので、`until` で内側プロンプトを指定するか、`mark: true` で送れば `pty_read({ wait: true })` が sentinel を自動検出する(until 不要・ネストでも効く)——全画面のエージェント TUI なら、出力が落ち着いた時点で `{ screen: true }` を読む。agent session は第6の正確な層を使う: vendor Stop hook が完了 event を書き、`pty_send` dispatch が返した `event_cursor` 境界から `aiterm-wait --cursor` が完了を観測する(親はブロックもポーリングもしない)。`pty_send` の送信前 ready 失敗は MCP エラー、launcher の初回 prompt ready 失敗は `initial_prompt=not_sent` を返す。agent session の通常 `pty_read` には `agent_event_seen=true completion_attribution=none` のような補助 metadata が付くことがあるが、古い hook event を `is_complete=True` に昇格しない。完結した hook JSONL 行が壊れていた場合は、`aiterm-wait` receipt の `malformed_events` に数えられる。ターンは完了したが端末 screen/log が flush 窓内で安定しなかった場合は、`agent_done_but_screen_unstable` が付く。
373
+ `pty_read({ wait: true })` は、プロセス終了 / `mark:true` sentinel の自動検出(後述)/ `until` 一致(**既定はリテラル部分一致**、`until_regex: true` で正規表現)/ 出力静止 ∧ シェル復帰(quiescence)/ timeout の 5 層で「コマンドが終わったか」を判定する。ネスト中(SSH・コンテナ・REPL・起動したエージェントの TUI の中)はシェル復帰判定が効かないので、`until` で内側プロンプトを指定するか、`mark: true` で送れば `pty_read({ wait: true })` が sentinel を自動検出する(until 不要・ネストでも効く)——全画面のエージェント TUI なら、出力が落ち着いた時点で `{ screen: true }` を読む。agent session は第6の正確な層を使う: Codexは`pty_send` dispatchが返したtranscript byte境界以後の`task_complete`を、Claude/Grokはevent-file境界以後のmanaged hook eventを`aiterm-wait --cursor`が観測する(親はブロックもポーリングもしない)。`pty_send` の送信前 ready 失敗は MCP エラー、launcher の初回 prompt ready 失敗は `initial_prompt=not_sent` を返す。完結した構造化JSONL行が壊れていた場合は、`aiterm-wait` receipt の `malformed_events` に数えられる。
366
374
 
367
375
  ### トークン削減
368
376
 
package/README.md CHANGED
@@ -91,12 +91,19 @@ execution lane. Cross-product installation and host integration are handled by
91
91
  [dotagents](https://github.com/kitepon-rgb/dotagents), the internal development
92
92
  toolchain behind kitepon.dev's products.
93
93
 
94
- **Measured, not claimed:** on this repo's own 203-test suite, a `pty_read` puts **~7.1× fewer tokens** in your context than the raw log — and the pass/fail verdict survives the fold. → [When to reach for it vs. the built-in shell](#when-to-reach-for-it-vs-the-built-in-shell)
94
+ **Measured, not claimed:** in the recorded 203-test benchmark, a `pty_read` puts **~7.1× fewer tokens** in your context than the raw log — and the pass/fail verdict survives the fold. → [When to reach for it vs. the built-in shell](#when-to-reach-for-it-vs-the-built-in-shell)
95
95
 
96
96
  Thirteen tools: six **PTY tools** — `pty_open` / `pty_send` / `pty_read` / `pty_key` / `pty_close` / `pty_list` — to open, drive, and read one persistent terminal, four **agent launchers** — `claude_agent` / `codex_agent` / `grok_agent` / `composer_agent` — that each start another coding agent's TUI inside a fresh one, `claude_turn` for durable structured issue/recovery, `claude_approval` for correlated managed-Claude approval prompts, and `diagnostics` for safe factory readiness. The backend is **tmux**, so sessions survive even if the MCP server or the AI client restarts.
97
97
 
98
- **v0.20.3 prevents concurrent managed Claude/Fable sessions from turning one broken
99
- login into many competing login flows.** Every new Claude launch verifies the
98
+ **v0.21.3 removes Codex Stop hooks from the completion path.** Codex completion and
99
+ final-message attribution now come from the root rollout transcript's durable
100
+ `task_complete.turn_id`, observed after the dispatch byte boundary. A broken or stale
101
+ hook executable can no longer strand `aiterm-wait`. v0.21.0 added explicit
102
+ `write_scope` declarations for external-agent launchers; v0.21.3 also fixes their
103
+ structured launch receipts so a supplied scope and its enforcement status are retained.
104
+ v0.20.3 prevents concurrent
105
+ managed Claude/Fable sessions from turning one broken login into many competing login
106
+ flows. Every new Claude launch verifies the
100
107
  vendor-owned shared credential store before creating a PTY, while healthy credentials
101
108
  remain reusable across concurrent and repeated sessions. The v0.20 line also distinguishes
102
109
  a non-blocking `aiterm-wait --timeout 0` observation (`running`, exit 5) from a real timed-out
@@ -124,7 +131,7 @@ A lot of 2026's agent tooling is converging on orchestration: a lead model deleg
124
131
 
125
132
  aiterm predates Build Week, so the event work is kept visible in dated commits. During the submission window (July 14–16, 2026), I extended it with safe serialized delivery for long PTY input, correlated operation IDs and bounded result recovery, machine-readable launch and idempotent close receipts, and a hardened readiness gate that prevents prompts from disappearing during TUI startup redraws. The public comparison from the pre-event release is [`v0.12.2...main`](https://github.com/kitepon-rgb/aiterm-mcp/compare/v0.12.2...main).
126
133
 
127
- I used **Codex with GPT-5.6** as an engineering collaborator: it inspected the implementation, challenged the API and recovery contracts, generated focused regression cases, and helped verify race, security, timeout, and malformed-event paths. I reviewed the diffs and test evidence and retained the final product and architecture decisions. The result is a 262-test regression suite covering normal operation as well as failure and recovery behavior.
134
+ I used **Codex with GPT-5.6** as an engineering collaborator: it inspected the implementation, challenged the API and recovery contracts, generated focused regression cases, and helped verify race, security, timeout, and malformed-event paths. I reviewed the diffs and test evidence and retained the final product and architecture decisions. At that Build Week checkpoint, the regression suite contained 262 tests covering normal operation as well as failure and recovery behavior; current release receipts live in the [CHANGELOG](CHANGELOG.md) and release ADRs.
128
135
 
129
136
  ## Two ways to use it
130
137
 
@@ -143,13 +150,17 @@ pty_read(id, { wait: true }) → read the token-reduced output, completion
143
150
 
144
151
  ### 2. Launch other coding agents into that terminal — the orchestration flagship
145
152
 
146
- The same primitive hosts another agent's TUI. Four launchers each start one vendor's interactive coding-agent TUI inside a fresh persistent terminal and return a `session_id`. Their existing human-readable text is accompanied by an `aiterm.agent-launch-result.v1` structured receipt, so durable callers never parse display text for the session handle; when the launch carries an initial `prompt`, the receipt also includes the `event_cursor`, a ready-made `wait_command` for the completion waiter, and a `submit_residue` observation (`true` = the prompt is likely still sitting unsubmitted in the composer — the hint explains recovery; `false` = no residue observed, not a proof of submission; `null` = not applicable). From there you drive it with the same `pty_read` / `pty_send` you'd use on any shell: read its output token-reduced, send it the next step. (The TUIs are full-screen apps, so `pty_read({ screen: true })` gives you the rendered view.) Every launch is **managed**: aiterm installs its own Stop hook, so turn completion is a first-class event. Sending to an agent session is a non-blocking **dispatch** — the call returns immediately with an `event_cursor`, and completion arrives via [`aiterm-wait`](#completion-push-for-parent-agents-aiterm-wait). Durable machine callers use `claude_turn({ action: "issue" | "recover", session_id, operation_id, ... })`: it returns fixed `accepted` / `pending` / `completed` / `unknown` states without parsing human-facing errors, never resends during recovery, and includes exact `raw_output` only for a verified completion. The same operation ID is carried through the dispatch receipt, active marker, Stop event, and result. The ordinary `pty_send` / `pty_read` surface remains available for interactive callers and humans. `C-c` keeps the marker for a delayed Stop; if no Stop arrives, close the session. An initial `prompt` on `claude_agent`/`codex_agent` is submitted through the same ready gate and the launcher returns without waiting; on Grok/Composer it is passed on the CLI's argv. This needs the vendor's own CLI installed and authenticated — see [Requirements](#requirements).
153
+ The same primitive hosts another agent's TUI. Four launchers each start one vendor's interactive coding-agent TUI inside a fresh persistent terminal and return a `session_id`. Their existing human-readable text is accompanied by an `aiterm.agent-launch-result.v1` structured receipt, so durable callers never parse display text for the session handle; when the launch carries an initial `prompt`, the receipt also includes the `event_cursor`, a ready-made `wait_command` for the completion waiter, and a `submit_residue` observation (`true` = the prompt is likely still sitting unsubmitted in the composer — the hint explains recovery; `false` = no residue observed, not a proof of submission; `null` = not applicable). From there you drive it with the same `pty_read` / `pty_send` you'd use on any shell: read its output token-reduced, send it the next step. (The TUIs are full-screen apps, so `pty_read({ screen: true })` gives you the rendered view.) Every launch is **managed**: Codex completion comes from its own durable rollout transcript's `task_complete`; Claude and Grok use isolated managed Stop hooks. Sending to an agent session is a non-blocking **dispatch** — the call returns immediately with an `event_cursor`, and completion arrives via [`aiterm-wait`](#completion-push-for-parent-agents-aiterm-wait). Durable machine callers use `claude_turn({ action: "issue" | "recover", session_id, operation_id, ... })`: it returns fixed `accepted` / `pending` / `completed` / `unknown` states without parsing human-facing errors, never resends during recovery, and includes exact `raw_output` only for a verified completion. The same operation ID is carried through the dispatch receipt, active marker, Stop event, and result. The ordinary `pty_send` / `pty_read` surface remains available for interactive callers and humans. `C-c` keeps the marker for a delayed Claude Stop; if no Stop arrives, close the session. An initial `prompt` on `claude_agent`/`codex_agent` is submitted through the same ready gate and the launcher returns without waiting; on Grok/Composer it is passed on the CLI's argv. This needs the vendor's own CLI installed and authenticated — see [Requirements](#requirements).
154
+
155
+ `codex_agent`, `grok_agent`, and `composer_agent` also accept an optional `write_scope`: either `"read-only"` or a human-readable description of writable paths. A supplied value is retained in the launch receipt, session metadata, and `pty_list`. For Codex, `write_scope: "read-only"` is an effective boundary: aiterm adds the CLI's `--sandbox read-only` flag. Grok/Composer have no corresponding interactive-launch sandbox, and Codex has no path-description allowlist flag; those cases return `write_scope_enforcement: "declaration_only_unsupported"` rather than claiming enforcement. Omitting `write_scope` preserves prior behavior.
147
156
 
148
157
  For a managed Claude turn stopped at `Do you want to proceed?`, use `claude_approval(action: "inspect", ...)` to capture the active operation and SHA-256 screen digest, review the displayed command, then call `respond` with that exact digest and either `approve_once` or `deny`. The relay rechecks the operation and screen under the send lock, never exposes arbitrary input or permanent approval, keeps the active marker intact, and records a prompt-free owner-only receipt. `pty_send(force: true)` does not bypass this boundary.
149
158
 
150
159
  ```text
151
160
  codex_agent({ session_name: "codex1", cwd: "/repo",
152
- prompt: "port test/legacy.py to vitest" })
161
+ prompt: "port test/legacy.py to vitest",
162
+ model: "gpt-5.6-sol", reasoning_effort: "high",
163
+ write_scope: "test/ only; no commit" })
153
164
  → { session_id: "codex1", … } # Codex now live in a persistent terminal
154
165
  pty_read("codex1", { screen: true }) → read what it's doing (token-reduced)
155
166
  pty_send("codex1", "also fix the imports it broke")
@@ -163,13 +174,13 @@ One call per model, so the tool name itself tells you which model you get:
163
174
  | Tool | Launches | Key args |
164
175
  | --- | --- | --- |
165
176
  | `claude_agent` | Claude Code CLI (Anthropic) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `launch_operation_id?` |
166
- | `codex_agent` | Codex CLI (OpenAI; terminal config/CLI default unless overridden) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`/`ultra`; ultra enables proactive automatic delegation), `cwd?`, `session_name?` |
167
- | `grok_agent` | Grok Build, model `grok-4.5` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error; Grok CLI `--effort` is headless-only), `cwd?`, `session_name?` |
168
- | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error), `cwd?`, `session_name?` |
177
+ | `codex_agent` | Codex CLI (OpenAI; terminal config/CLI default unless overridden) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`/`ultra`; ultra enables proactive automatic delegation), `cwd?`, `session_name?`, `write_scope?` |
178
+ | `grok_agent` | Grok Build, model `grok-4.5` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error; Grok CLI `--effort` is headless-only), `cwd?`, `session_name?`, `write_scope?` |
179
+ | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error), `cwd?`, `session_name?`, `write_scope?` |
169
180
 
170
181
  The vendor CLI must be installed and authenticated (`claude` for `claude_agent`; `codex` for `codex_agent`; `grok` for both Grok tools). aiterm resolves the binary via `CLAUDE_BIN` / `CODEX_BIN` / `GROK_BIN`, then `~/.local/bin/claude` / `~/.local/bin/codex` / `~/.grok/bin/grok`, then `PATH`. Prerequisites are checked **before** a session exists: empty `model` values and unsupported effort values are rejected up front; a missing CLI binary or a nonexistent `cwd` fails for all four. Before creating a Claude session, aiterm also requires a successful structured `claude auth status --json` result with `loggedIn: true`; unavailable, malformed, or failed authentication leaves **zero leftover session**. Claude sessions share the vendor-owned credential store rather than copying credentials per launch, so multiple sessions can reuse one healthy login. Managed Claude rejects exact `/login` and `/logout` dispatches, including forced sends: repair authentication once in a normal terminal, then relaunch any stale unauthenticated sessions. Claude and Codex launchers forward `model` and `reasoning_effort` through their vendor CLI's public flags; Grok/Composer reject `reasoning_effort` because it is headless-only. Pass an absolute path for `cwd` — `~` is not expanded. Durable callers can make a promptless Claude launch exactly replayable by passing an explicit `session_name` and a `launch_operation_id` formatted as `sha256:<64 lowercase hex>`. Repeating the identical launch returns the same structured session receipt without starting the CLI twice; a different correlation ID or launch argument for that session fails explicitly. Claude uses launch-local managed settings containing only aiterm's Stop hook: normal user/project/local hooks are not inherited, the hook event contains no answer body, and the bounded owner-only result is returned by `pty_read({ agent_transcript:true })` without reading Claude's private transcript. A late result remains recoverable from the same session without re-sending the prompt. While a managed Claude turn is active, raw sends and non-interrupt keys are rejected. If Claude displays `Do you want to proceed?`, call `claude_approval(action:"inspect", ...)`, decide from the visible prompt, then call `respond` with the returned digest and either `approve_once` or `deny`. The response is accepted only while the same operation and screen digest remain current; arbitrary text and persistent-allow choices are never relayed. Use `pty_key("C-c")` to interrupt and `pty_close` to abandon the session. For unconstrained manual key-by-key driving, open a plain `pty_open` session and start the vendor CLI yourself. Codex uses a managed `CODEX_HOME`; Grok/Composer isolate their managed homes and pass validated OAuth state through `GROK_AUTH_PATH`. Before the first unbound dispatch, aiterm waits for the vendor TUI's input prompt and fails before sending if it is not ready. Managed completion requires POSIX filesystem semantics (Linux, WSL2, macOS).
171
182
 
172
- The managed Codex home links authentication, privately snapshots `config.toml` and `agents/*.toml` custom-role definitions, and keeps sessions/caches isolated. A symlinked role definition is resolved into a regular-file snapshot rather than shared with the source home.
183
+ The managed Codex home links authentication, privately snapshots `config.toml` and `agents/*.toml` custom-role definitions, and keeps sessions/caches isolated. A symlinked role definition is resolved into a regular-file snapshot rather than shared with the source home. aiterm does not install a Codex Stop hook: the root rollout transcript is the completion source, so a missing hook executable cannot strand `aiterm-wait`.
173
184
 
174
185
  There is no hidden protocol between agents: a launched Claude, Codex, Grok, or Composer is another user-visible persistent terminal session. The MCP client drives that TUI with ordinary PTY operations, and a human can attach to watch or take over.
175
186
 
@@ -291,7 +302,7 @@ The second round-trip pays for itself once the output runs long, or the state ha
291
302
  | `find node_modules -type f` | ~500 tok¹ | ~456 tok | tokens tie; aiterm keeps head and tail + `line_range` |
292
303
  | `grep -rn "session" src/` | ~2,989 tok | ~1,096 tok | **aiterm** (~2.7×; long lines get clipped²) |
293
304
 
294
- On the repo's own 203-test suite the reduction is real and safe. The built-in tool drops the whole 223-line log — ~4,292 tokens — into context. aiterm folds its own capture of the run down to ~607:
305
+ In the recorded 203-test benchmark the reduction is real and safe. The built-in tool drops the whole 223-line log — ~4,292 tokens — into context. aiterm folds its own capture of the run down to ~607:
295
306
 
296
307
  ```text
297
308
  [aiterm demo: 51 行 / ~607 tok (raw 223 行 / ~4292 tok); 172 行 hidden] [is_complete=True via mark]
@@ -369,24 +380,24 @@ Each launcher starts a specific vendor's interactive coding-agent TUI inside a f
369
380
  | Tool | Launches | Key args |
370
381
  | --- | --- | --- |
371
382
  | `claude_agent` | Claude Code CLI (Anthropic) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `launch_operation_id?` |
372
- | `codex_agent` | Codex CLI (OpenAI; terminal config/CLI default unless overridden) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`/`ultra`; ultra enables proactive automatic delegation), `cwd?`, `session_name?` |
373
- | `grok_agent` | Grok Build, model `grok-4.5` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error; Grok CLI `--effort` is headless-only), `cwd?`, `session_name?` |
374
- | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error), `cwd?`, `session_name?` |
383
+ | `codex_agent` | Codex CLI (OpenAI; terminal config/CLI default unless overridden) | `prompt?`, `model?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`/`ultra`; ultra enables proactive automatic delegation), `cwd?`, `session_name?`, `write_scope?` |
384
+ | `grok_agent` | Grok Build, model `grok-4.5` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error; Grok CLI `--effort` is headless-only), `cwd?`, `session_name?`, `write_scope?` |
385
+ | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` by default (`model?` overrides) (xAI) | `prompt?`, `model?`, `reasoning_effort?` unsupported (an explicit value is an error), `cwd?`, `session_name?`, `write_scope?` |
375
386
 
376
387
  The vendor CLI must be installed and authenticated (`claude` for `claude_agent`; `codex` for `codex_agent`; `grok` for both Grok tools). Binary resolution uses `CLAUDE_BIN` / `CODEX_BIN` / `GROK_BIN`, then each documented default location, then `PATH`. Missing binaries, invalid model/effort values, and nonexistent `cwd` fail before a session is created. Claude additionally requires a structured healthy authentication status before any PTY exists, and managed Claude rejects `/login` and `/logout`; repair authentication once in a normal terminal. All four share the same non-blocking dispatch contract for follow-up turns; `claude_agent`/`codex_agent` submit an initial `prompt` through the ready gate. Claude uses isolated managed settings and a hook-captured bounded result rather than private transcript access. Claude, Codex, Grok, and Composer live smokes are green; fixture coverage remains a separate claim. Native Windows can launch agents but managed completion is not supported yet.
377
388
 
378
- When an agent's answer is longer than the on-screen tail (pane height ≈ 24 lines), callers recover it in full with `pty_read({ agent_transcript: true })`. It returns the most recently completed turn's final assistant message in plain text with no re-prompting. Claude reads the bounded owner-only result captured by the managed Stop hook and verifies its digest/byte count; it never reads Claude's private transcript. Durable machine callers should use `claude_turn`: `issue` sends once, `recover` never sends, `pending` is distinct from unsafe or malformed state, and only `completed` carries the exact verified `raw_output`. `unknown` distinguishes `operation_not_found` from a receipt whose result can no longer be attributed. Mismatch and corruption remain tool errors rather than being folded into a successful status. ID-less interactive Claude turns are still serialized by an anonymous marker, so an older answer is not returned while the current Stop is pending. Codex joins its structured transcript on the Stop hook `turn_id`; Grok/Composer take the assistant rows after the last real user row. A missing result/transcript, a non-agent session, or an unextractable message is an explicit error, never a silent empty.
389
+ When an agent's answer is longer than the on-screen tail (pane height ≈ 24 lines), callers recover it in full with `pty_read({ agent_transcript: true })`. It returns the most recently completed turn's final assistant message in plain text with no re-prompting. Claude reads the bounded owner-only result captured by the managed Stop hook and verifies its digest/byte count; it never reads Claude's private transcript. Durable machine callers should use `claude_turn`: `issue` sends once, `recover` never sends, `pending` is distinct from unsafe or malformed state, and only `completed` carries the exact verified `raw_output`. `unknown` distinguishes `operation_not_found` from a receipt whose result can no longer be attributed. Mismatch and corruption remain tool errors rather than being folded into a successful status. ID-less interactive Claude turns are still serialized by an anonymous marker, so an older answer is not returned while the current Stop is pending. Codex uses the root rollout transcript's `task_complete.turn_id` both for completion and final-message attribution; Grok/Composer take the assistant rows after the last real user row. A missing result/transcript, a non-agent session, or an unextractable message is an explicit error, never a silent empty.
379
390
 
380
391
  ### Completion detection (5 layers)
381
392
 
382
- `pty_read({ wait: true })` decides "is the command done?" via five layers: process exit / a `mark:true` sentinel (auto-detected — see below) / an `until` match (a literal substring by default; pass `until_regex: true` for a regex) / output is quiescent ∧ the shell is back (quiescence) / timeout. While nested (inside SSH, a container, a REPL, or a launched agent's TUI), the "shell is back" check cannot fire, so pass `until` with the inner prompt — or send with `mark: true` and `pty_read({ wait: true })` auto-detects the completion sentinel (no `until` needed, works nested too) — or, for a full-screen agent TUI, read `{ screen: true }` once its output settles. Agent sessions use the sixth, exact layer instead: the vendor Stop hook writes a completion event, `pty_send` dispatch returns the `event_cursor` boundary, and `aiterm-wait --cursor` observes the completion without the parent blocking or polling. Pre-send readiness failures are MCP errors for `pty_send`, while launch-time initial prompt readiness failures return the session with `initial_prompt=not_sent`. A late Claude completion remains recoverable from the same session with `pty_read({ agent_transcript:true })`, without resending. Normal `pty_read` on an agent session can append auxiliary metadata such as `agent_event_seen=true completion_attribution=none`, but a stale hook event is not promoted to `is_complete=True`. If a complete hook JSONL line is malformed, the `aiterm-wait` receipt counts it in `malformed_events` for diagnosis. If the turn is done but the terminal screen/log does not settle within the flush window, aiterm appends `agent_done_but_screen_unstable`.
393
+ `pty_read({ wait: true })` decides "is the command done?" via five layers: process exit / a `mark:true` sentinel (auto-detected — see below) / an `until` match (a literal substring by default; pass `until_regex: true` for a regex) / output is quiescent ∧ the shell is back (quiescence) / timeout. While nested (inside SSH, a container, a REPL, or a launched agent's TUI), the "shell is back" check cannot fire, so pass `until` with the inner prompt — or send with `mark: true` and `pty_read({ wait: true })` auto-detects the completion sentinel (no `until` needed, works nested too) — or, for a full-screen agent TUI, read `{ screen: true }` once its output settles. Agent sessions use a sixth exact layer: Codex observes `task_complete` after the dispatch's transcript byte boundary; Claude/Grok observe their managed hook event after the event-file boundary. `aiterm-wait --cursor` performs that vendor-specific observation without the parent blocking or polling. Pre-send readiness failures are MCP errors for `pty_send`, while launch-time initial prompt readiness failures return the session with `initial_prompt=not_sent`. A late completion remains recoverable from the same session with `pty_read({ agent_transcript:true })`, without resending. Malformed complete JSONL records are counted in `malformed_events` for diagnosis rather than treated as done.
383
394
 
384
395
  ### Completion push for parent agents (`aiterm-wait`)
385
396
 
386
397
  As of v0.16 a parent agent **never blocks** on aiterm — there is no wait parameter anywhere (v0.17 makes the waiter's exit codes mirror its outcome). The whole flow is dispatch + one universal waiter:
387
398
 
388
399
  1. Launch the child (`claude_agent` / `codex_agent` / ...; every launch is managed). Send a turn with plain `pty_send` (or `claude_turn issue` for durable Claude operations). The call passes the TUI ready gate, submits, and returns immediately with an `event_cursor` in its structured receipt — plus a `submit_residue` observation: `true` means the sent text still lingered in the composer after submit (likely stranded; inspect the screen before re-pressing Enter), `false` means no residue was observed (not a proof of submission), `null` means not applicable.
389
- 2. Run `aiterm-wait --session <id> --cursor <event_cursor> [--operation sha256:<64hex>] [--timeout <sec>]` (a launch with an initial `prompt` returns this command ready-made as `wait_command` in its structured receipt). It observes the vendor Stop-hook completion event as a **pure reader** and exits with a one-line `aiterm.agent-wait-result.v1` receipt. **Exit ≠ done**: the receipt's `outcome` is authoritative, and the exit code mirrors it — `0` = `done`, `3` = `timeout` (the turn is **not** finished; default `--timeout` is 600 s), `4` = `closed`, `1` = error. On `timeout` just re-run the waiter with the same cursor. The `--cursor` boundary makes it start-order independent: no completion can slip past even if the waiter starts late.
400
+ 2. Run `aiterm-wait --session <id> --cursor <event_cursor> [--operation sha256:<64hex>] [--timeout <sec>]` (a launch with an initial `prompt` returns this command ready-made as `wait_command` in its structured receipt). It observes the vendor completion source as a **pure reader**—Codex rollout `task_complete`, or a managed hook event for the other vendors—and exits with a one-line `aiterm.agent-wait-result.v1` receipt. **Exit ≠ done**: the receipt's `outcome` is authoritative, and the exit code mirrors it — `0` = `done`, `3` = `timeout` (the turn is **not** finished; default `--timeout` is 600 s), `4` = `closed`, `1` = error. On `timeout` just re-run the waiter with the same cursor. The `--cursor` boundary makes it start-order independent: no completion can slip past even if the waiter starts late.
390
401
  3. **The parent never runs the waiter in its own foreground.** Waiting is correct — but the waiter is a separate process, not the parent's turn. A harness that re-invokes its agent when a background task exits (Claude Code) runs the waiter **in the background** and gets woken with zero polling. So that this is not left to interpretation, aiterm reads `clientInfo.name` from the MCP `initialize` handshake and its receipts name the concrete invocation for the detected host — for Claude Code, literally `Bash(command: "aiterm-wait …", run_in_background: true)`. Unknown or undeclared hosts get the generic "start it as a process that does not block the parent's turn" wording; nothing else about the contract changes. Every receipt leads with the same rule: dispatch and let go, then go do something else or end the turn.
391
402
  4. Collect the result exactly as before: `pty_read(agent_transcript: true)`, or `claude_turn recover` for durable Claude operations. The waiter carries the signal, never the payload.
392
403
 
package/dist/core.js CHANGED
@@ -56,6 +56,7 @@ const AGENT_DONE_SCREEN_SETTLE_MIN_SAMPLES = 3;
56
56
  const AGENT_SUBMIT_DELAY_MS = 250;
57
57
  const AGENT_EVENT_MAX_BYTES = 1024 * 1024;
58
58
  const AGENT_EVENT_TAIL_BYTES = 64 * 1024;
59
+ const CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES = 16 * 1024 * 1024;
59
60
  const AGENT_METADATA_NEGATIVE_CACHE_TTL_MS = 2_000;
60
61
  const AGENT_TUI_READY_TIMEOUT_MS = 30_000;
61
62
  const AGENT_TUI_READY_POLL_MS = 500;
@@ -1230,6 +1231,7 @@ export function listSessions() {
1230
1231
  const agent = [
1231
1232
  `agent=${meta.kind}`,
1232
1233
  "agent_done=true",
1234
+ meta.write_scope === undefined ? null : `write_scope=${JSON.stringify(meta.write_scope)}`,
1233
1235
  meta.vendor_session_id ? `vendor_session_id=${meta.vendor_session_id}` : null,
1234
1236
  ]
1235
1237
  .filter(Boolean)
@@ -1377,15 +1379,18 @@ export function killAll() {
1377
1379
  const DEFAULT_AGENT_DONE_TIMEOUT = 600;
1378
1380
  const agentMetadataNegativeCache = new Map();
1379
1381
  let agentTuiReadyStableSamplesTestOverride = null;
1380
- function codexHookScriptPath() {
1381
- return path.join(path.dirname(fileURLToPath(import.meta.url)), "codex-stop-hook.js");
1382
- }
1383
1382
  function grokHookScriptPath() {
1384
1383
  return path.join(path.dirname(fileURLToPath(import.meta.url)), "grok-stop-hook.js");
1385
1384
  }
1386
1385
  function claudeHookScriptPath() {
1387
1386
  return path.join(path.dirname(fileURLToPath(import.meta.url)), "claude-stop-hook.js");
1388
1387
  }
1388
+ // process.execPath は Homebrew 等では Cellar の版付き実体を指す。長寿命 MCP server の起動後に
1389
+ // runtime が更新されるとその実体だけが消え、既に生成済みの hook が exit 127 になる。
1390
+ // hook は server と同じ継承 PATH から node を毎回解決し、安定した package script を実行する。
1391
+ function nodeHookCommand(hookScript) {
1392
+ return `${shq("node")} ${shq(hookScript)}`;
1393
+ }
1389
1394
  function safeStatSize(p) {
1390
1395
  try {
1391
1396
  return fs.statSync(p).size;
@@ -1513,7 +1518,7 @@ function readCodexConfigPins(configPath) {
1513
1518
  };
1514
1519
  return { model: pick("model"), effort: pick("model_reasoning_effort") };
1515
1520
  }
1516
- function managedCodexConfigSummary(configPath, hookTrustBypass) {
1521
+ function managedCodexConfigSummary(configPath) {
1517
1522
  let body;
1518
1523
  try {
1519
1524
  body = fs.readFileSync(configPath, "utf8");
@@ -1542,8 +1547,6 @@ function managedCodexConfigSummary(configPath, hookTrustBypass) {
1542
1547
  bits.push(`approval_policy=${approvalPolicy}`);
1543
1548
  if (sandboxMode)
1544
1549
  bits.push(`sandbox_mode=${sandboxMode}`);
1545
- if (hookTrustBypass)
1546
- bits.push("hook trust bypass 有効");
1547
1550
  return `managed config: ${bits.join(" / ")}`;
1548
1551
  }
1549
1552
  // Custom agent definitions are configuration, not mutable Codex state. Copy only direct
@@ -1625,27 +1628,9 @@ function createManagedCodexHome(name, launchId, overrides = {}) {
1625
1628
  fs.chmodSync(configDst, 0o600);
1626
1629
  }
1627
1630
  snapshotCodexAgentDefinitions(srcHome, managedHome);
1628
- const hookScript = codexHookScriptPath();
1629
- if (!fs.existsSync(hookScript)) {
1630
- throw new AitermError(`Codex Stop hook wrapper が見つかりません。npm run build を実行してください: ${hookScript}`, 2);
1631
- }
1632
- writeJson0600(path.join(managedHome, "hooks.json"), {
1633
- hooks: {
1634
- Stop: [
1635
- {
1636
- hooks: [
1637
- {
1638
- type: "command",
1639
- command: `${shq(process.execPath)} ${shq(hookScript)}`,
1640
- timeoutSec: 10,
1641
- async: false,
1642
- statusMessage: null,
1643
- },
1644
- ],
1645
- },
1646
- ],
1647
- },
1648
- });
1631
+ // Codex 自身の rollout transcript に task_complete が永続化されるため、完了検出用の
1632
+ // Stop hook は作らない。hook と transcript の二重正本、および hook failure の単一障害点を
1633
+ // ここでなくす。
1649
1634
  return managedHome;
1650
1635
  }
1651
1636
  function createManagedClaudeSettings(name, launchId) {
@@ -1661,7 +1646,7 @@ function createManagedClaudeSettings(name, launchId) {
1661
1646
  hooks: [
1662
1647
  {
1663
1648
  type: "command",
1664
- command: `${shq(process.execPath)} ${shq(hookScript)}`,
1649
+ command: nodeHookCommand(hookScript),
1665
1650
  timeout: 10,
1666
1651
  },
1667
1652
  ],
@@ -1774,7 +1759,7 @@ function createManagedGrokHome(name, launchId, authPath) {
1774
1759
  hooks: [
1775
1760
  {
1776
1761
  type: "command",
1777
- command: `${shq(process.execPath)} ${shq(hookScript)}`,
1762
+ command: nodeHookCommand(hookScript),
1778
1763
  timeout: 10,
1779
1764
  },
1780
1765
  ],
@@ -2261,7 +2246,7 @@ function createClaudeAgentMetadata(name, cwd, initialPrompt, launchOperationId,
2261
2246
  writeAgentMetadata(meta);
2262
2247
  return meta;
2263
2248
  }
2264
- function createCodexAgentMetadata(name, cwd, initialPrompt, overrides = {}) {
2249
+ function createCodexAgentMetadata(name, cwd, initialPrompt, overrides = {}, writeScope) {
2265
2250
  const launchId = randomBytes(16).toString("hex");
2266
2251
  const eventFile = agentEventPath(name, launchId);
2267
2252
  createEmpty0600NoFollow(eventFile);
@@ -2273,16 +2258,18 @@ function createCodexAgentMetadata(name, cwd, initialPrompt, overrides = {}) {
2273
2258
  event_file: eventFile,
2274
2259
  created_at: new Date().toISOString(),
2275
2260
  cwd,
2261
+ ...(writeScope === undefined ? {} : { write_scope: writeScope }),
2276
2262
  vendor_session_id: null,
2277
2263
  initial_prompt: initialPrompt,
2278
2264
  hook_route: "managed_codex_home",
2265
+ completion_route: "codex_transcript",
2279
2266
  node_platform: process.platform,
2280
2267
  codex_home: codexHome,
2281
2268
  };
2282
2269
  writeAgentMetadata(meta);
2283
2270
  return meta;
2284
2271
  }
2285
- function createGrokAgentMetadata(kind, name, cwd, initialPrompt, authPath) {
2272
+ function createGrokAgentMetadata(kind, name, cwd, initialPrompt, authPath, writeScope) {
2286
2273
  const launchId = randomBytes(16).toString("hex");
2287
2274
  const eventFile = agentEventPath(name, launchId);
2288
2275
  createEmpty0600NoFollow(eventFile);
@@ -2294,6 +2281,7 @@ function createGrokAgentMetadata(kind, name, cwd, initialPrompt, authPath) {
2294
2281
  event_file: eventFile,
2295
2282
  created_at: new Date().toISOString(),
2296
2283
  cwd,
2284
+ ...(writeScope === undefined ? {} : { write_scope: writeScope }),
2297
2285
  vendor_session_id: null,
2298
2286
  initial_prompt: initialPrompt,
2299
2287
  hook_route: "managed_grok_home",
@@ -2355,6 +2343,7 @@ function loadAgentMetadata(name) {
2355
2343
  event_file: expectedEvent,
2356
2344
  created_at: typeof m.created_at === "string" ? m.created_at : "",
2357
2345
  cwd: typeof m.cwd === "string" ? m.cwd : null,
2346
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
2358
2347
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
2359
2348
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
2360
2349
  launch_operation_id: launchOperationId,
@@ -2377,9 +2366,11 @@ function loadAgentMetadata(name) {
2377
2366
  event_file: expectedEvent,
2378
2367
  created_at: typeof m.created_at === "string" ? m.created_at : "",
2379
2368
  cwd: typeof m.cwd === "string" ? m.cwd : null,
2369
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
2380
2370
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
2381
2371
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
2382
2372
  hook_route: "managed_codex_home",
2373
+ ...(m.completion_route === "codex_transcript" ? { completion_route: "codex_transcript" } : {}),
2383
2374
  node_platform: process.platform,
2384
2375
  codex_home: expectedHome,
2385
2376
  };
@@ -2400,6 +2391,7 @@ function loadAgentMetadata(name) {
2400
2391
  event_file: expectedEvent,
2401
2392
  created_at: typeof m.created_at === "string" ? m.created_at : "",
2402
2393
  cwd: typeof m.cwd === "string" ? m.cwd : null,
2394
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
2403
2395
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
2404
2396
  initial_prompt: normalizeInitialPromptState(m.initial_prompt),
2405
2397
  hook_route: "managed_grok_home",
@@ -2502,6 +2494,15 @@ function bindAgentVendorSession(meta, ev) {
2502
2494
  function bindCompletedInitialPrompt(meta) {
2503
2495
  if (meta.initial_prompt !== "pending" && meta.initial_prompt !== "sent")
2504
2496
  return;
2497
+ if (meta.kind === "codex") {
2498
+ const done = latestCodexCompletion(meta);
2499
+ if (!done) {
2500
+ throw new AitermError(`agent session '${meta.aiterm_session}' は起動時 prompt の完了待ちです。${agentWaitGuide(meta.aiterm_session)}`, 2);
2501
+ }
2502
+ bindAgentVendorSession(meta, done);
2503
+ setInitialPromptState(meta, "done");
2504
+ return;
2505
+ }
2505
2506
  if (meta.vendor_session_id) {
2506
2507
  setInitialPromptState(meta, "done");
2507
2508
  return;
@@ -2534,6 +2535,8 @@ function tryLoadAgentMetadata(name) {
2534
2535
  }
2535
2536
  }
2536
2537
  function latestAgentDoneEvent(meta, expectedOperationId = null) {
2538
+ if (meta.kind === "codex")
2539
+ return latestCodexCompletion(meta);
2537
2540
  const size = safeStatSize(meta.event_file);
2538
2541
  if (size === 0)
2539
2542
  return null;
@@ -2588,6 +2591,14 @@ function completedClaudeOperationEvent(meta, operationId) {
2588
2591
  function recoverAgentVendorSession(meta) {
2589
2592
  if (meta.vendor_session_id)
2590
2593
  return;
2594
+ if (meta.kind === "codex") {
2595
+ const transcript = bindCodexTranscriptSession(meta);
2596
+ if (!transcript)
2597
+ return;
2598
+ if (meta.initial_prompt === "pending" && latestCodexCompletion(meta))
2599
+ setInitialPromptState(meta, "done");
2600
+ return;
2601
+ }
2591
2602
  const size = safeStatSize(meta.event_file);
2592
2603
  if (size === 0)
2593
2604
  return;
@@ -2641,6 +2652,116 @@ function findLatestCodexTranscript(codexHome, vendorSessionId) {
2641
2652
  visit(sessionsDir);
2642
2653
  return latestFile;
2643
2654
  }
2655
+ function listCodexTranscripts(codexHome) {
2656
+ const sessionsDir = path.join(codexHome, "sessions");
2657
+ const files = [];
2658
+ const visit = (dir) => {
2659
+ let entries;
2660
+ try {
2661
+ entries = fs.readdirSync(dir, { withFileTypes: true });
2662
+ }
2663
+ catch {
2664
+ return;
2665
+ }
2666
+ for (const entry of entries) {
2667
+ const file = path.join(dir, entry.name);
2668
+ if (entry.isDirectory())
2669
+ visit(file);
2670
+ else if (entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl"))
2671
+ files.push(file);
2672
+ }
2673
+ };
2674
+ visit(sessionsDir);
2675
+ // managed CODEX_HOME では root TUI の rollout が最初に作られる。後から同じ home に
2676
+ // sub-agent rollout が増えても root を取り違えないよう、未bind時は最古を選べる順にする。
2677
+ return files.sort();
2678
+ }
2679
+ function codexTranscriptSessionId(file) {
2680
+ const size = Math.min(safeStatSize(file), AGENT_EVENT_TAIL_BYTES);
2681
+ if (size === 0)
2682
+ return null;
2683
+ const text = readFileRange(file, 0, size).toString("utf8");
2684
+ for (const line of text.split("\n")) {
2685
+ if (!line.trim())
2686
+ continue;
2687
+ try {
2688
+ const record = JSON.parse(line);
2689
+ if (record?.type === "session_meta" && typeof record?.payload?.id === "string" && record.payload.id) {
2690
+ return record.payload.id;
2691
+ }
2692
+ }
2693
+ catch {
2694
+ // startup中の未完結行は後のpollで読み直す。
2695
+ }
2696
+ }
2697
+ return null;
2698
+ }
2699
+ function codexRootTranscript(meta) {
2700
+ if (meta.kind !== "codex" || !meta.codex_home)
2701
+ return null;
2702
+ if (meta.vendor_session_id)
2703
+ return findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
2704
+ return listCodexTranscripts(meta.codex_home)[0] ?? null;
2705
+ }
2706
+ function bindCodexTranscriptSession(meta) {
2707
+ const transcript = codexRootTranscript(meta);
2708
+ if (!transcript)
2709
+ return null;
2710
+ const vendorSessionId = codexTranscriptSessionId(transcript);
2711
+ if (vendorSessionId && !meta.vendor_session_id) {
2712
+ meta.vendor_session_id = vendorSessionId;
2713
+ writeAgentMetadata(meta);
2714
+ }
2715
+ return transcript;
2716
+ }
2717
+ function codexCompletionEvent(meta, vendorSessionId, record) {
2718
+ if (record?.type !== "event_msg" ||
2719
+ record?.payload?.type !== "task_complete" ||
2720
+ typeof record?.payload?.turn_id !== "string" ||
2721
+ !record.payload.turn_id)
2722
+ return null;
2723
+ return {
2724
+ type: "agent_done",
2725
+ vendor: "codex",
2726
+ aiterm_session: meta.aiterm_session,
2727
+ launch_id: meta.launch_id,
2728
+ vendor_session_id: vendorSessionId,
2729
+ turn_id: record.payload.turn_id,
2730
+ operation_id: null,
2731
+ reason: "Codex transcript task_complete",
2732
+ done_status: "turn_done",
2733
+ stop_hook_active: false,
2734
+ at: typeof record.timestamp === "string" ? record.timestamp : new Date().toISOString(),
2735
+ };
2736
+ }
2737
+ function latestCodexCompletion(meta) {
2738
+ const transcript = codexRootTranscript(meta);
2739
+ if (!transcript)
2740
+ return null;
2741
+ const vendorSessionId = meta.vendor_session_id ?? codexTranscriptSessionId(transcript);
2742
+ let latest = null;
2743
+ for (const line of readTranscriptLines(transcript)) {
2744
+ if (!line.trim())
2745
+ continue;
2746
+ try {
2747
+ latest = codexCompletionEvent(meta, vendorSessionId, JSON.parse(line)) ?? latest;
2748
+ }
2749
+ catch {
2750
+ // Codexが末尾を書込み中なら、その行は次の観測で完結してから読む。
2751
+ }
2752
+ }
2753
+ return latest;
2754
+ }
2755
+ function agentCompletionCursor(meta) {
2756
+ if (meta.kind !== "codex")
2757
+ return safeStatSize(meta.event_file);
2758
+ const transcript = bindCodexTranscriptSession(meta);
2759
+ if (meta.completion_route !== "codex_transcript") {
2760
+ meta.completion_route = "codex_transcript";
2761
+ writeAgentMetadata(meta);
2762
+ }
2763
+ return transcript ? safeStatSize(transcript) : 0;
2764
+ }
2644
2765
  function transcriptUnavailable() {
2645
2766
  throw new AitermError(`transcript がまだありません。ターン完了後に再取得してください。${agentWaitGuide()}`, 2);
2646
2767
  }
@@ -2921,9 +3042,83 @@ export function agentWaitGuide(session) {
2921
3042
  const cmd = `aiterm-wait --session ${session ?? "<session_id>"} --cursor 0`;
2922
3043
  return `完了通知は ${agentWaitLaunchForm(cmd)} で受ける(親はここで待たない・polling 不要)。receipt の outcome=done を確認してから再取得する。`;
2923
3044
  }
3045
+ async function observeCodexDone(meta, timeout, requestedCursor) {
3046
+ const metadataFile = agentMetadataPath(meta.aiterm_session, meta.launch_id);
3047
+ let transcript = codexRootTranscript(meta);
3048
+ const startOffset = requestedCursor ?? (transcript ? safeStatSize(transcript) : 0);
3049
+ let cursor = startOffset;
3050
+ let carry = "";
3051
+ let malformedEvents = 0;
3052
+ let discardLeadingFragment = false;
3053
+ let initializedBoundary = false;
3054
+ const deadline = performance.now() + timeout * 1000;
3055
+ const observation = (outcome, ev = null) => ({
3056
+ schema: "aiterm.agent-wait-result.v1",
3057
+ session_id: meta.aiterm_session,
3058
+ launch_id: meta.launch_id,
3059
+ vendor: "codex",
3060
+ outcome,
3061
+ operation_id: null,
3062
+ vendor_session_id: ev?.vendor_session_id ?? meta.vendor_session_id ?? null,
3063
+ turn_id: ev?.turn_id ?? null,
3064
+ malformed_events: malformedEvents,
3065
+ at: ev?.at ?? null,
3066
+ });
3067
+ for (;;) {
3068
+ if (!fs.existsSync(metadataFile))
3069
+ return observation("closed");
3070
+ transcript ??= codexRootTranscript(meta);
3071
+ if (transcript) {
3072
+ if (!initializedBoundary) {
3073
+ if (cursor > 0) {
3074
+ const previous = readFileRange(transcript, cursor - 1, cursor).toString("utf8");
3075
+ discardLeadingFragment = previous !== "\n";
3076
+ }
3077
+ initializedBoundary = true;
3078
+ }
3079
+ const size = safeStatSize(transcript);
3080
+ if (size < cursor) {
3081
+ throw new AitermError("Codex transcript が完了待機中に短くなりました。該当セッションを閉じて起動し直してください。", 2);
3082
+ }
3083
+ if (size - startOffset > CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES) {
3084
+ throw new AitermError("Codex transcript のturn増分が大きすぎます。該当セッションを閉じて起動し直してください。", 2);
3085
+ }
3086
+ if (size > cursor) {
3087
+ carry += readFileRange(transcript, cursor, size).toString("utf8");
3088
+ cursor = size;
3089
+ const parts = carry.split("\n");
3090
+ carry = parts.pop() ?? "";
3091
+ if (discardLeadingFragment && parts.length > 0) {
3092
+ parts.shift();
3093
+ discardLeadingFragment = false;
3094
+ }
3095
+ const vendorSessionId = meta.vendor_session_id ?? codexTranscriptSessionId(transcript);
3096
+ for (const line of parts) {
3097
+ if (!line.trim())
3098
+ continue;
3099
+ if (Buffer.byteLength(line, "utf8") > AGENT_EVENT_MAX_BYTES) {
3100
+ malformedEvents++;
3101
+ continue;
3102
+ }
3103
+ try {
3104
+ const done = codexCompletionEvent(meta, vendorSessionId, JSON.parse(line));
3105
+ if (done)
3106
+ return observation("done", done);
3107
+ }
3108
+ catch {
3109
+ malformedEvents++;
3110
+ }
3111
+ }
3112
+ }
3113
+ }
3114
+ if (performance.now() >= deadline)
3115
+ return observation(timeout === 0 ? "running" : "timeout");
3116
+ await sleep(AGENT_DONE_POLL_MS);
3117
+ }
3118
+ }
2924
3119
  // 外部waiterプロセス用の純リーダー観測。lock・PTY・metadata書込・dispatch状態には一切触れない。
2925
- // event fileのtail規律(未終端行保持・増分上限)はwaitAgentDoneEventと同一だが、
2926
- // vendor_session_idのbind永続化を行わない点だけ意図的に異なる(waiterは観測者であって所有者でない)。
3120
+ // Codexはrollout transcript、他vendorはevent fileを増分走査し、vendor_session_idのbind永続化を
3121
+ // 行わない(waiterは観測者であって所有者でない)。
2927
3122
  export async function observeAgentDone(name, o = {}) {
2928
3123
  const meta = loadAgentMetadata(name);
2929
3124
  const operationId = o.operation_id == null ? null : validateOperationId(o.operation_id);
@@ -2934,6 +3129,9 @@ export async function observeAgentDone(name, o = {}) {
2934
3129
  throw new AitermError("cursor は0以上の整数byte offsetで指定してください", 2);
2935
3130
  }
2936
3131
  const timeout = o.timeout ?? DEFAULT_AGENT_DONE_TIMEOUT;
3132
+ if (meta.kind === "codex" && meta.completion_route === "codex_transcript") {
3133
+ return observeCodexDone(meta, timeout, o.cursor);
3134
+ }
2937
3135
  const metadataFile = agentMetadataPath(meta.aiterm_session, meta.launch_id);
2938
3136
  // 境界の優先順: dispatch receipt の event_cursor(起動順序に依存しない)→ operation相関
2939
3137
  // (operation_idの一意性で先頭から全走査できる)→ waiter起動時EOF(waiter先行起動が前提)。
@@ -3197,7 +3395,7 @@ export async function sendInitialAgentPrompt(name, text, o = {}) {
3197
3395
  submit_residue: null,
3198
3396
  };
3199
3397
  }
3200
- const startOffset = safeStatSize(meta.event_file);
3398
+ const startOffset = agentCompletionCursor(meta);
3201
3399
  try {
3202
3400
  if (meta.kind === "claude") {
3203
3401
  prepareSendText(text, { raw: false, force: true });
@@ -3224,7 +3422,7 @@ export function isAgentSession(name) {
3224
3422
  return tryLoadAgentMetadata(name) !== null;
3225
3423
  }
3226
3424
  // v0.16.0: 親をブロックする wait 経路は廃止した。send は ready gate と submit 分離を内蔵した
3227
- // dispatch として即返り、event_cursor(送信直前の event file 境界)を receipt で返す。
3425
+ // dispatch として即返り、event_cursor(送信直前のvendor完了正本境界)を receipt で返す。
3228
3426
  // 完了通知は aiterm-wait(--cursor で境界を渡す)、回収は pty_read / claude_turn recover が担う。
3229
3427
  export async function dispatchAgentTurn(name, text, o = {}) {
3230
3428
  assertSessionName(name);
@@ -3235,14 +3433,16 @@ export async function dispatchAgentTurn(name, text, o = {}) {
3235
3433
  throw new AitermError("operation_id はClaude agent sessionだけで使用できます", 2);
3236
3434
  }
3237
3435
  bindCompletedInitialPrompt(meta);
3238
- if (!meta.vendor_session_id) {
3436
+ // Codexはbind済みのfollow-upでも毎回idleを確認してからtranscript境界を切る。同じcursorへ
3437
+ // 複数turnを帰属させる余地を作らない。他vendorの既存dispatch条件は変えない。
3438
+ if (meta.kind === "codex" || !meta.vendor_session_id) {
3239
3439
  const ready = await waitAgentTuiReady(name, meta, o.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS);
3240
3440
  if (!ready.ready) {
3241
3441
  throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。` +
3242
3442
  "少し後で pty_read(screen:true) を確認し、TUI が起動済みなら再度 pty_send してください。", 2);
3243
3443
  }
3244
3444
  }
3245
- const startOffset = safeStatSize(meta.event_file);
3445
+ const startOffset = agentCompletionCursor(meta);
3246
3446
  if (meta.kind === "claude") {
3247
3447
  // durable/anonymousを分岐する前に同じsend preflightを通す。拒否されるpromptの
3248
3448
  // receipt/active markerだけを残して、来ないStopを待つ状態を作らない。
@@ -3446,8 +3646,10 @@ function buildAgentCmd(kind, bin, model, effort, prompt, meta = null) {
3446
3646
  parts.push("--effort", shq(effort));
3447
3647
  }
3448
3648
  else if (kind === "codex") {
3449
- if (meta?.kind === "codex")
3450
- parts.push("--dangerously-bypass-hook-trust");
3649
+ // `codex --help` で確認した実在フラグ。read-only 宣言だけはCLI sandboxへ落とし、
3650
+ // launcher自身が実効能力壁を作る。パス説明はCodex CLIに同等のallowlist引数がないため宣言のまま残す。
3651
+ if (meta?.kind === "codex" && meta.write_scope === "read-only")
3652
+ parts.push("--sandbox", "read-only");
3451
3653
  // model/effort は CLI 引数で明示(config 継承より優先)。agent_done 時は managed home 側
3452
3654
  // config.toml も同値で上書き済み(applyCodexConfigOverrides)。
3453
3655
  if (model)
@@ -3516,12 +3718,17 @@ function agentLabel(kind) {
3516
3718
  // model_reasoning_effort)が対話子へ波及する構造のため、引数・端末config継承・CLI既定の
3517
3719
  // どれで起動したかを起動時点で可視化し、実効 effort=ultra は proactive 自動委譲 ON を警告する。
3518
3720
  function buildAgentLaunchNote(kind, model, effort, meta) {
3721
+ const writeScopeNote = meta?.write_scope === undefined
3722
+ ? ""
3723
+ : kind === "codex" && meta.write_scope === "read-only"
3724
+ ? `\n能力宣言: write_scope=${JSON.stringify(meta.write_scope)}。Codex CLIへ --sandbox read-only を付与し、書込みを実効禁止。`
3725
+ : `\n能力宣言: write_scope=${JSON.stringify(meta.write_scope)}。${kind === "grok" || kind === "composer" ? "このCLIには起動sandbox機構がないため" : "パス単位のsandbox allowlistに対応するCLI引数がないため"}宣言の記録のみ(構造的unsupported)。`;
3519
3726
  if (kind === "claude") {
3520
- return `起動設定: model=${model ?? "CLI既定"} effort=${effort ?? "CLI既定"}。`;
3727
+ return `起動設定: model=${model ?? "CLI既定"} effort=${effort ?? "CLI既定"}。${writeScopeNote}`;
3521
3728
  }
3522
3729
  if (kind !== "codex") {
3523
3730
  return (`起動設定: model=${model ?? GROK_MODEL_DEFAULTS[kind]}(${model ? "引数" : "ツール既定"})。` +
3524
- "reasoning effort は対話 TUI 非対応=未指定で起動。");
3731
+ "reasoning effort は対話 TUI 非対応=未指定で起動。" + writeScopeNote);
3525
3732
  }
3526
3733
  const configPath = meta?.kind === "codex" && meta.codex_home
3527
3734
  ? path.join(meta.codex_home, "config.toml")
@@ -3539,8 +3746,8 @@ function buildAgentLaunchNote(kind, model, effort, meta) {
3539
3746
  (effectiveEffort === "ultra"
3540
3747
  ? "⚠ effort=ultra は max 推論+proactive 自動委譲 ON(子エージェント自動生成・使用量急増に注意)。"
3541
3748
  : "");
3542
- const summary = meta?.kind === "codex" && meta.codex_home ? managedCodexConfigSummary(configPath, true) : "";
3543
- return summary ? `${launch}\n${summary}\n` : launch;
3749
+ const summary = meta?.kind === "codex" && meta.codex_home ? managedCodexConfigSummary(configPath) : "";
3750
+ return (summary ? `${launch}\n${summary}\n` : launch) + writeScopeNote;
3544
3751
  }
3545
3752
  function claudeLaunchRequestDigest({ sessionName, model, effort, cwd, agentDone, }) {
3546
3753
  const canonical = JSON.stringify({
@@ -3582,6 +3789,7 @@ export function openAgent(kind, opts = {}) {
3582
3789
  throw new AitermError("model が空文字です(省略するか有効なモデル名を指定してください)", 2);
3583
3790
  }
3584
3791
  const effort = opts.reasoning_effort ?? null;
3792
+ const writeScope = opts.write_scope;
3585
3793
  if (effort && kind === "claude" && !CLAUDE_EFFORTS.has(effort)) {
3586
3794
  throw new AitermError("Claude Code の reasoning_effort は low/medium/high/xhigh/max のいずれかです", 2);
3587
3795
  }
@@ -3690,8 +3898,8 @@ export function openAgent(kind, opts = {}) {
3690
3898
  ? kind === "claude"
3691
3899
  ? createClaudeAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", launchOperationId, launchRequestDigest)
3692
3900
  : kind === "codex"
3693
- ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort })
3694
- : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath)
3901
+ ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none", { model, effort }, writeScope)
3902
+ : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none", grokAuthPath, writeScope)
3695
3903
  : null;
3696
3904
  if (meta)
3697
3905
  agentMetadataNegativeCache.delete(sid);
@@ -3754,6 +3962,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
3754
3962
  prompt,
3755
3963
  agent_done: true,
3756
3964
  launch_operation_id: opts.launch_operation_id ?? null,
3965
+ write_scope: opts.write_scope,
3757
3966
  });
3758
3967
  // argv prompt(grok/composer)は composer を経由しないため submit 座礁観測の対象外。
3759
3968
  return [sid, hint, prompt ? 0 : null, null];
@@ -3766,6 +3975,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
3766
3975
  prompt: null,
3767
3976
  agent_done: true,
3768
3977
  launch_operation_id: opts.launch_operation_id ?? null,
3978
+ write_scope: opts.write_scope,
3769
3979
  });
3770
3980
  try {
3771
3981
  const initial = await sendInitialAgentPrompt(sid, prompt, {
package/dist/index.js CHANGED
@@ -420,6 +420,19 @@ const agentCompletionDesc = `起動して投げたら投げっぱなしでよい
420
420
  `結果回収は pty_read(agent_transcript:true)。`;
421
421
  function registerAgentTool(toolName, kind, desc) {
422
422
  const correlatedLaunchSchema = {};
423
+ const supportsWriteScope = kind === "codex" || kind === "grok" || kind === "composer";
424
+ const writeScopeInputSchema = supportsWriteScope
425
+ ? {
426
+ write_scope: z.string().min(1).optional().describe("能力宣言。read-only、または書込みを許可するパスの説明文字列。Codexのread-onlyだけはCLI sandboxで実効禁止する"),
427
+ }
428
+ : {};
429
+ const writeScopeOutputSchema = supportsWriteScope
430
+ ? {
431
+ // write_scope省略時は既存launch receiptを完全に保つため両fieldを出さない。
432
+ write_scope: z.string().optional(),
433
+ write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
434
+ }
435
+ : {};
423
436
  if (kind === "claude") {
424
437
  correlatedLaunchSchema.launch_operation_id = z
425
438
  .string()
@@ -437,6 +450,7 @@ function registerAgentTool(toolName, kind, desc) {
437
450
  reasoning_effort: z.string().nullish().describe(agentEffortDesc(kind)),
438
451
  cwd: z.string().nullish().describe("作業ディレクトリ(対象リポのルート等・任意)"),
439
452
  session_name: z.string().nullish().describe("セッション名(省略で自動採番)"),
453
+ ...writeScopeInputSchema,
440
454
  ...correlatedLaunchSchema,
441
455
  },
442
456
  outputSchema: {
@@ -451,8 +465,9 @@ function registerAgentTool(toolName, kind, desc) {
451
465
  // 初回prompt dispatch後のsubmit座礁観測(additive)。true=composerに残存を確認(submit未成立の疑い)/
452
466
  // false=残存を観測せず(submit成立の保証ではない)/ null=promptなし・argv prompt・判定不能。
453
467
  submit_residue: z.boolean().nullable(),
468
+ ...writeScopeOutputSchema,
454
469
  },
455
- }, async ({ prompt, model, reasoning_effort, cwd, session_name, launch_operation_id }) => {
470
+ }, async ({ prompt, model, reasoning_effort, cwd, session_name, launch_operation_id, write_scope }) => {
456
471
  try {
457
472
  const [sid, hint, eventCursor, submitResidue] = await core.openAgentWithInitialPrompt(kind, {
458
473
  prompt: prompt ?? undefined,
@@ -461,6 +476,7 @@ function registerAgentTool(toolName, kind, desc) {
461
476
  cwd: cwd ?? undefined,
462
477
  session_name: session_name ?? undefined,
463
478
  launch_operation_id: launch_operation_id ?? undefined,
479
+ ...(supportsWriteScope ? { write_scope } : {}),
464
480
  });
465
481
  const structured = {
466
482
  schema: "aiterm.agent-launch-result.v1",
@@ -470,6 +486,14 @@ function registerAgentTool(toolName, kind, desc) {
470
486
  event_cursor: eventCursor,
471
487
  wait_command: eventCursor === null ? null : `aiterm-wait --session ${sid} --cursor ${eventCursor}`,
472
488
  submit_residue: submitResidue,
489
+ ...(supportsWriteScope && write_scope !== undefined
490
+ ? {
491
+ write_scope,
492
+ write_scope_enforcement: kind === "codex" && write_scope === "read-only"
493
+ ? "enforced_read_only"
494
+ : "declaration_only_unsupported",
495
+ }
496
+ : {}),
473
497
  };
474
498
  return {
475
499
  content: [{ type: "text", text: `session_id: ${sid}\n${hint}` }],
@@ -487,6 +511,9 @@ registerAgentTool("claude_agent", "claude", "【Claude Code (Anthropic)】の対
487
511
  agentCompletionDesc +
488
512
  "Claude の durable turn は claude_turn でも回収できる。");
489
513
  registerAgentTool("codex_agent", "codex", "【Codex (OpenAI)】の対話エージェント TUI を永続端末に起動する。実装・レビュー・調査を対話で回す。" +
514
+ "委譲契約を使う完全な呼び出し例: " +
515
+ '`codex_agent({"prompt":"<依頼>","model":"gpt-5.6-sol","reasoning_effort":"high",' +
516
+ '"cwd":"/absolute/path/to/repo","write_scope":"read-only"})`。' +
490
517
  "turn は pty_send で送る(自動で非ブロック dispatch になる)。" +
491
518
  agentCompletionDesc +
492
519
  "model / reasoning_effort を引数で指定可" +
@@ -281,7 +281,7 @@ function validateState(value, maxRecords = 256) {
281
281
  records: typed.map((record) => projectRecord(record)),
282
282
  };
283
283
  }
284
- function processStartIdentity(pid, platform) {
284
+ function processStartIdentity(pid, platform, timeoutMs = 1000) {
285
285
  if (!Number.isInteger(pid) || pid < 1)
286
286
  return null;
287
287
  if (platform === "linux") {
@@ -298,7 +298,7 @@ function processStartIdentity(pid, platform) {
298
298
  if (platform === "win32") {
299
299
  const script = "$p=Get-Process -Id $env:AITERMMCP_PROCESS_ID -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks";
300
300
  const result = spawnSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
301
- encoding: "utf8", timeout: 1000, maxBuffer: 4096, windowsHide: true,
301
+ encoding: "utf8", timeout: timeoutMs, maxBuffer: 4096, windowsHide: true,
302
302
  env: { ...process.env, AITERMMCP_PROCESS_ID: String(pid) },
303
303
  });
304
304
  const value = result.status === 0 ? (result.stdout ?? "").trim() : "";
@@ -503,7 +503,8 @@ export class RuntimeErrorStore {
503
503
  || (info.mode & 0o777) !== 0o700)
504
504
  throw new Error("runtime error lock queue のowner/modeが不正です");
505
505
  }
506
- const startId = processStartIdentity(process.pid, this.platform);
506
+ const identityTimeoutMs = this.platform === "win32" ? this.windowsAclTimeoutMs : 1000;
507
+ const startId = processStartIdentity(process.pid, this.platform, identityTimeoutMs);
507
508
  if (!startId)
508
509
  throw new Error("process start identity を取得できません");
509
510
  const owner = { pid: process.pid, start_id: startId, token: randomBytes(16).toString("hex") };
@@ -548,7 +549,7 @@ export class RuntimeErrorStore {
548
549
  }
549
550
  if (name !== `choosing-${current.token}.json`)
550
551
  throw new Error("runtime error choosing entry が不正です");
551
- const identity = processStartIdentity(current.pid, this.platform);
552
+ const identity = processStartIdentity(current.pid, this.platform, identityTimeoutMs);
552
553
  const live = identity === current.start_id || (!identity && processExists(current.pid));
553
554
  if (live)
554
555
  hasLiveChoosing = true;
@@ -583,7 +584,7 @@ export class RuntimeErrorStore {
583
584
  }
584
585
  if (!name.endsWith(`-${current.token}.ticket`))
585
586
  throw new Error("runtime error lock ticket が不正です");
586
- const identity = processStartIdentity(current.pid, this.platform);
587
+ const identity = processStartIdentity(current.pid, this.platform, identityTimeoutMs);
587
588
  const live = identity === current.start_id || (!identity && processExists(current.pid));
588
589
  if (!live) {
589
590
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.20.3",
3
+ "version": "0.21.3",
4
4
  "mcpName": "io.github.kitepon-rgb/aiterm-mcp",
5
5
  "description": "Persistent tmux terminal MCP that lets Claude Code drive Codex CLI's interactive TUI, including slash commands and $imagegen. Also runs durable PTY sessions for SSH, containers, REPLs, and coding agents.",
6
6
  "keywords": [
@@ -52,11 +52,12 @@
52
52
  "node": ">=18"
53
53
  },
54
54
  "scripts": {
55
- "build": "tsc",
55
+ "build": "node scripts/clean-build.mjs && tsc",
56
56
  "mcpb:build": "npm run build && node scripts/build-mcpb.mjs && npm ci --omit=dev --ignore-scripts --no-audit --no-fund --prefix dist/mcpb-stage/server && npx --yes @anthropic-ai/mcpb@2.1.2 validate dist/mcpb-stage/manifest.json && npx --yes @anthropic-ai/mcpb@2.1.2 pack dist/mcpb-stage dist/aiterm-mcp.mcpb",
57
- "prepublishOnly": "npm run build",
57
+ "verify:release-commit": "node scripts/verify-release-commit.mjs",
58
+ "prepublishOnly": "npm run verify:release-commit && npm run build",
58
59
  "start": "node dist/index.js",
59
- "test": "npm run build && node --test test/*.test.mjs"
60
+ "test": "npm run build && node --test scripts/verify-release-commit.test.mjs test/*.test.mjs"
60
61
  },
61
62
  "dependencies": {
62
63
  "@modelcontextprotocol/sdk": "^1.29.0",
@@ -1,128 +0,0 @@
1
- #!/usr/bin/env node
2
- import * as fs from "node:fs";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- const LAUNCH_ID_RE = /^[0-9a-f]{32}$/;
6
- const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
7
- const MAX_STDIN_BYTES = 1024 * 1024;
8
- function fail(message) {
9
- process.stderr.write(`aiterm codex-stop-hook: ${message}\n`);
10
- process.stdout.write(JSON.stringify({ continue: false }) + "\n");
11
- process.exit(0);
12
- }
13
- function noop() {
14
- process.stdout.write(JSON.stringify({ continue: false }) + "\n");
15
- process.exit(0);
16
- }
17
- function hasAitermEnv() {
18
- return !!(process.env.AITERM_AGENT_KIND ||
19
- process.env.AITERM_SESSION_ID ||
20
- process.env.AITERM_AGENT_SESSION_ID ||
21
- process.env.AITERM_AGENT_LAUNCH_ID);
22
- }
23
- function uid() {
24
- if (typeof process.getuid !== "function")
25
- fail("POSIX getuid が使えません");
26
- return process.getuid();
27
- }
28
- function runtimeStateBase() {
29
- const xdg = process.env.XDG_RUNTIME_DIR;
30
- if (xdg) {
31
- try {
32
- if (fs.statSync(xdg).isDirectory())
33
- return xdg;
34
- }
35
- catch {
36
- /* XDG_RUNTIME_DIR が壊れている CI/非 login 環境では os.tmpdir() に戻す */
37
- }
38
- }
39
- return os.tmpdir();
40
- }
41
- function secureAgentsDir() {
42
- const root = path.join(runtimeStateBase(), `aiterm-mcp-${uid()}`);
43
- const agents = path.join(root, "agents");
44
- const rst = fs.lstatSync(root);
45
- if (!rst.isDirectory() || rst.isSymbolicLink() || rst.uid !== uid() || (rst.mode & 0o077) !== 0) {
46
- fail(`agent state root が安全ではありません: ${root}`);
47
- }
48
- const ast = fs.lstatSync(agents);
49
- if (!ast.isDirectory() || ast.isSymbolicLink() || ast.uid !== uid() || (ast.mode & 0o077) !== 0) {
50
- fail(`agent state dir が安全ではありません: ${agents}`);
51
- }
52
- return agents;
53
- }
54
- function str(v) {
55
- return typeof v === "string" ? v : null;
56
- }
57
- async function readStdin() {
58
- const chunks = [];
59
- let total = 0;
60
- for await (const chunk of process.stdin) {
61
- const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
62
- total += b.length;
63
- if (total > MAX_STDIN_BYTES)
64
- fail("payload が大きすぎます");
65
- chunks.push(b);
66
- }
67
- return Buffer.concat(chunks).toString("utf8");
68
- }
69
- function appendEvent(file, event) {
70
- const nofollow = fs.constants.O_NOFOLLOW ?? 0;
71
- const line = JSON.stringify(event) + "\n";
72
- if (Buffer.byteLength(line, "utf8") > 64 * 1024)
73
- fail("event line が大きすぎます");
74
- const fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_APPEND | fs.constants.O_WRONLY | nofollow, 0o600);
75
- try {
76
- const st = fs.fstatSync(fd);
77
- if (!st.isFile() || st.uid !== uid() || st.nlink !== 1 || (st.mode & 0o077) !== 0) {
78
- fail(`event file が安全ではありません: ${file}`);
79
- }
80
- const written = fs.writeSync(fd, line, undefined, "utf8");
81
- if (written < Buffer.byteLength(line, "utf8")) {
82
- fs.ftruncateSync(fd, st.size);
83
- fail(`event file への書込みが途中で終了しました: ${file}`);
84
- }
85
- }
86
- finally {
87
- fs.closeSync(fd);
88
- }
89
- }
90
- async function main() {
91
- if (!hasAitermEnv())
92
- noop();
93
- const kind = process.env.AITERM_AGENT_KIND;
94
- const session = process.env.AITERM_SESSION_ID || process.env.AITERM_AGENT_SESSION_ID || "";
95
- const launchId = process.env.AITERM_AGENT_LAUNCH_ID || "";
96
- if (kind !== "codex")
97
- fail(`AITERM_AGENT_KIND が codex ではありません: ${kind ?? ""}`);
98
- if (!SESSION_RE.test(session))
99
- fail(`session id が不正です: ${session}`);
100
- if (!LAUNCH_ID_RE.test(launchId))
101
- fail(`launch id が不正です: ${launchId}`);
102
- let payload = {};
103
- const input = await readStdin();
104
- if (input.trim()) {
105
- try {
106
- payload = JSON.parse(input);
107
- }
108
- catch {
109
- payload = {};
110
- }
111
- }
112
- const agents = secureAgentsDir();
113
- const eventFile = path.join(agents, `${session}.${launchId}.events.jsonl`);
114
- appendEvent(eventFile, {
115
- type: "agent_done",
116
- vendor: "codex",
117
- aiterm_session: session,
118
- launch_id: launchId,
119
- vendor_session_id: str(payload.session_id),
120
- turn_id: str(payload.turn_id),
121
- reason: str(payload.hook_event_name) ?? "Stop",
122
- done_status: "turn_done",
123
- stop_hook_active: !!payload.stop_hook_active,
124
- at: new Date().toISOString(),
125
- });
126
- process.stdout.write(JSON.stringify({ continue: false }) + "\n");
127
- }
128
- main().catch((e) => fail(e instanceof Error ? e.message : String(e)));