aiterm-mcp 0.9.0 → 0.10.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.
package/README.ja.md CHANGED
@@ -45,11 +45,11 @@ pty_read(id, { wait: true }) → 削減済みの出力を読む(完了
45
45
 
46
46
  ### 2. その端末の中に他のコーディングエージェントを起動する — オーケストレーションの旗艦
47
47
 
48
- 同じ primitive が別エージェントの TUI を宿す。3 つの起動ツールが、各ベンダーの対話型コーディングエージェント TUI を新しい永続端末の中に起動し、`session_id` を返す。以後はどのシェルとも同じ `pty_read` / `pty_send` で操作する——出力をトークン削減して読み、次の一手を送る。(TUI は全画面アプリなので `pty_read({ screen: true })` で描画済みの画面が得られる。)`agent_done: true` を付けると hook ベースのターン完了待ちが有効になり、`pty_send({ wait: "agent_done" })` が agent のターン終了後に返る。Codex/Grok/Composer は、各ベンダー CLI が認証済みなら実 smoke 済み。これはベンダー自身の CLI が導入・認証済みであることが必要——[要件](#要件)参照。
48
+ 同じ primitive が別エージェントの TUI を宿す。3 つの起動ツールが、各ベンダーの対話型コーディングエージェント TUI を新しい永続端末の中に起動し、`session_id` を返す。以後はどのシェルとも同じ `pty_read` / `pty_send` で操作する——出力をトークン削減して読み、次の一手を送る。(TUI は全画面アプリなので `pty_read({ screen: true })` で描画済みの画面が得られる。)`agent_done: true` を付けると hook ベースのターン完了待ちが有効になり、`pty_send({ wait: "agent_done" })` が agent のターン終了後に返る。`codex_agent` は起動時 `prompt` も待てる——`prompt`、`agent_done:true`、`wait:"agent_done"` を渡すと、まず TUI を起動し、入力欄の ready を待ってから初回 prompt を送り、その初回ターンの Stop hook 後に返る。Codex/Grok/Composer は、各ベンダー CLI が認証済みなら後続 `pty_send(wait:"agent_done")` は実 smoke 済み。Codex の初回 prompt wait も実 smoke 済み。Grok/Composer の初回 prompt wait は post-OAuth smoke が通るまで意図的に未公開。これはベンダー自身の CLI が導入・認証済みであることが必要——[要件](#要件)参照。
49
49
 
50
50
  ```text
51
51
  codex_agent({ session_name: "codex1", cwd: "/repo", agent_done: true,
52
- prompt: "port test/legacy.py to vitest" })
52
+ wait: "agent_done", prompt: "port test/legacy.py to vitest" })
53
53
  → { session_id: "codex1", … } # Codex が永続端末で稼働開始
54
54
  pty_read("codex1", { screen: true }) → 何をしているか読む(トークン削減)
55
55
  pty_send("codex1", "also fix the imports it broke", { wait: "agent_done" })
@@ -60,11 +60,11 @@ pty_send("codex1", "also fix the imports it broke", { wait: "agent_done" })
60
60
 
61
61
  | ツール | 起動するもの | 主な引数 |
62
62
  | --- | --- | --- |
63
- | `codex_agent` | Codex CLI(OpenAI・モデルは CLI の既定) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?` |
63
+ | `codex_agent` | Codex CLI(OpenAI・モデルは CLI の既定) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?`, `wait?`, `timeout?`, `screen?`, `lines?` |
64
64
  | `grok_agent` | Grok Build の `grok-build` モデル(xAI) | `prompt?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `agent_done?` |
65
65
  | `composer_agent` | Grok Build の `grok-composer-2.5-fast` モデル(xAI) | `grok_agent` と同じ |
66
66
 
67
- 各ベンダーの CLI が導入・認証済みであること(`codex_agent` は `codex`、Grok 系 2 つは `grok`)。バイナリは `CODEX_BIN` / `GROK_BIN` → `~/.local/bin/codex` / `~/.grok/bin/grok` → `PATH` の順で解決する。前提は **session を作る前に**検証する——`grok_agent` / `composer_agent` は範囲外の `reasoning_effort` を先に弾き(値集合は固定=`low`/`medium`/`high`/`xhigh`/`max`)、CLI バイナリ不在・実在しない `cwd` は 3 つとも失敗する。前提(`reasoning_effort`・バイナリ・`cwd`)で弾かれた起動は **session の残骸をゼロ**にして返し、起動キーストロークを送れなければ session を畳む。(その先でベンダー CLI が実際に立ち上がったか・認証できたかは aiterm は検証しない——`openAgent` は起動コマンドを送った時点で返る。起動できたかは session を読んで確認する。)(`codex_agent` は Codex の受理値が版で変わるため、`reasoning_effort` を検証せず config override〔`-c model_reasoning_effort=…`〕として Codex CLI へ渡す。)`cwd` は絶対パスで渡す——`~` は展開されない。`agent_done` は launch ごとの managed vendor home を使い、通常の hook file は書き換えない。Grok/Composer はさらに `GROK_HOME` と `HOME` を隔離し、compat hook/plugin 混入を抑える。一方で OAuth は通常 Grok home の `auth.json` と `auth.json.lock` をセットで共有し、複数セッション間で refresh lock が分裂しないようにする。初回の未 bind `pty_send({ wait: "agent_done" })` は、vendor TUI の入力欄が出るまで待ち、入力受付状態でなければ文字列を送らず送信前エラーにする。`agent_done` は `getuid`・安全な一時ファイル・hard link 検査など POSIX ファイルシステム前提を使うため、対応は Linux / WSL2 / macOS。Windows ネイティブでは core PTY と agent launcher は使えるが、`agent_done` はまだ未対応。
67
+ 各ベンダーの CLI が導入・認証済みであること(`codex_agent` は `codex`、Grok 系 2 つは `grok`)。バイナリは `CODEX_BIN` / `GROK_BIN` → `~/.local/bin/codex` / `~/.grok/bin/grok` → `PATH` の順で解決する。前提は **session を作る前に**検証する——`grok_agent` / `composer_agent` は範囲外の `reasoning_effort` を先に弾き(値集合は固定=`low`/`medium`/`high`/`xhigh`/`max`)、CLI バイナリ不在・実在しない `cwd` は 3 つとも失敗する。前提(`reasoning_effort`・バイナリ・`cwd`)で弾かれた起動は **session の残骸をゼロ**にして返し、起動キーストロークを送れなければ session を畳む。(初回 prompt wait を使わない場合、その先でベンダー CLI が実際に立ち上がったか・認証できたかは aiterm は検証しない——起動できたかは session を読んで確認する。)(`codex_agent` は Codex の受理値が版で変わるため、`reasoning_effort` を検証せず config override〔`-c model_reasoning_effort=…`〕として Codex CLI へ渡す。)`cwd` は絶対パスで渡す——`~` は展開されない。`agent_done` は launch ごとの managed vendor home を使い、通常の hook file は書き換えない。Codex は managed `CODEX_HOME` に `auth.json` だけを symlink し、`config.toml` はコピーする。Grok/Composer はさらに `GROK_HOME` と `HOME` を隔離し、compat hook/plugin 混入を抑える。一方で Grok OAuth は通常 Grok home の `auth.json` と `auth.json.lock` をセットで共有し、複数セッション間で refresh lock が分裂しないようにする。初回の未 bind `pty_send({ wait: "agent_done" })` は、vendor TUI の入力欄が出るまで待ち、入力受付状態でなければ文字列を送らず送信前エラーにする。`codex_agent` launcher の `wait:"agent_done"` も同じく `prompt` と `agent_done:true` が必須。TUI が入力欄 ready にならない場合は prompt を送らず、`initial_prompt=not_sent` として session を調査可能なまま残す。起動時 prompt が `pending`/`sent` の間は、混入防止のため通常 `pty_send` も拒否する。手動介入は `pty_key`、または意図的な `pty_send(..., force:true)` で行う。`agent_done` は `getuid`・安全な一時ファイル・hard link 検査など POSIX ファイルシステム前提を使うため、対応は Linux / WSL2 / macOS。Windows ネイティブでは core PTY と agent launcher は使えるが、`agent_done` はまだ未対応。
68
68
 
69
69
  **Claude launcher はあえて無い**し、エージェント間のプロトコルも無い: aiterm の役目は、あなたの Claude(や任意の MCP クライアント)が*他の*エージェントに手を伸ばして端末を操作できるようにすること。起動したエージェントは単なるもう 1 本の永続セッションなので、この README の他のすべて(トークン削減読取・完了検出・人の `attach` での監視/介入)がそのまま効く。
70
70
 
@@ -219,15 +219,15 @@ aiterm は同じ核心の洞察——端末を出会いの場にする——を
219
219
 
220
220
  | ツール | 起動するもの | 主な引数 |
221
221
  | --- | --- | --- |
222
- | `codex_agent` | Codex CLI(OpenAI・モデルは CLI の既定) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?` |
222
+ | `codex_agent` | Codex CLI(OpenAI・モデルは CLI の既定) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?`, `wait?`, `timeout?`, `screen?`, `lines?` |
223
223
  | `grok_agent` | Grok Build の `grok-build` モデル(xAI) | `prompt?`, `reasoning_effort?`(`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `agent_done?` |
224
224
  | `composer_agent` | Grok Build の `grok-composer-2.5-fast` モデル(xAI) | `grok_agent` と同じ |
225
225
 
226
- 各ベンダーの CLI が導入・認証済みであること(`codex_agent` は `codex`、Grok 系 2 つは `grok`)。バイナリは `CODEX_BIN` / `GROK_BIN` → `~/.local/bin/codex` / `~/.grok/bin/grok` → `PATH` の順で解決する。前提はセッション作成前に検証し(grok/composer は範囲外の `reasoning_effort` を弾く。CLI 不在・実在しない `cwd` は 3 つとも失敗)、起動に失敗してもセッションの残骸は残さない。詳細は [その端末の中に他のコーディングエージェントを起動する](#2-その端末の中に他のコーディングエージェントを起動する--オーケストレーションの旗艦)。`cwd` は絶対パスで渡す——`~` は展開されない。`agent_done` は hook-backed で、Codex/Grok/Composer は Linux/WSL2/macOS で実 smoke 済み。Windows ネイティブでは agent launcher は使えるが `agent_done` はまだ未対応。初回の未 bind agent send では `pty_send({ wait:"agent_done" })` が vendor TUI の入力欄を待ち、未 ready なら送信前エラーにする。Grok OAuth mode では hook/config 隔離は launch ごとに維持しつつ、通常 Grok home の `auth.json` と `auth.json.lock` をセットで共有する。OAuth auth 不在ならセッション残骸なしで失敗する。
226
+ 各ベンダーの CLI が導入・認証済みであること(`codex_agent` は `codex`、Grok 系 2 つは `grok`)。バイナリは `CODEX_BIN` / `GROK_BIN` → `~/.local/bin/codex` / `~/.grok/bin/grok` → `PATH` の順で解決する。前提はセッション作成前に検証し(grok/composer は範囲外の `reasoning_effort` を弾く。CLI 不在・実在しない `cwd` は 3 つとも失敗)、起動に失敗してもセッションの残骸は残さない。詳細は [その端末の中に他のコーディングエージェントを起動する](#2-その端末の中に他のコーディングエージェントを起動する--オーケストレーションの旗艦)。`cwd` は絶対パスで渡す——`~` は展開されない。`agent_done` は hook-backed で、Codex/Grok/Composer は Linux/WSL2/macOS の後続 `pty_send(wait:"agent_done")` で実 smoke 済み。Codex は launcher の `prompt + wait:"agent_done"` も実 smoke 済み。Windows ネイティブでは agent launcher は使えるが `agent_done` はまだ未対応。Codex の managed `CODEX_HOME` は `auth.json` だけを symlink し、`config.toml` をコピーし、`hooks.json` は aiterm が所有する。初回の未 bind agent send では `pty_send({ wait:"agent_done" })` が vendor TUI の入力欄を待ち、未 ready なら送信前エラーにする。`codex_agent` launcher の `wait:"agent_done"` は `prompt` と `agent_done:true` が必須で、TUI ready 後にだけ初回 prompt を送る。入力欄 ready にならない場合は prompt を送らず、`initial_prompt=not_sent` を返して session を残す。Grok OAuth mode では hook/config 隔離は launch ごとに維持しつつ、通常 Grok home の `auth.json` と `auth.json.lock` をセットで共有する。OAuth auth 不在ならセッション残骸なしで失敗する。
227
227
 
228
228
  ### 完了検出(5 層)
229
229
 
230
- `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_done:true` で起動したセッションは代わりに `pty_send({ wait:"agent_done" })` を使える。必要な場合はまず agent TUI の入力欄を待ち、その後 vendor Stop hook を待ってターン境界後の画面を返す。送信前 ready 失敗は MCP エラー、送信後 timeout は `is_complete=False via agent_timeout` で返り、成功扱いしない。完結した hook JSONL 行が壊れていた場合は、切り分け用に timeout suffix へ `malformed_events=N` が付く。ターンは完了したが端末 screen/log が flush 窓内で安定しなかった場合は、`agent_done_but_screen_unstable` が付く。
230
+ `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_done:true` で起動したセッションは代わりに `pty_send({ wait:"agent_done" })` を使える。必要な場合はまず agent TUI の入力欄を待ち、その後 vendor Stop hook を待ってターン境界後の画面を返す。`codex_agent` launcher の `wait:"agent_done"` は起動時 `prompt` に同じ待機を行う。`pty_send` の送信前 ready 失敗は MCP エラー、launcher の初回 prompt ready 失敗は `initial_prompt=not_sent` を返す。送信後 timeout は `is_complete=False via agent_timeout` で返り、成功扱いしない。agent session の通常 `pty_read` には `agent_event_seen=true completion_attribution=none` のような補助 metadata が付くことがあるが、古い hook event を `is_complete=True` に昇格しない。完結した hook JSONL 行が壊れていた場合は、切り分け用に timeout suffix へ `malformed_events=N` が付く。ターンは完了したが端末 screen/log が flush 窓内で安定しなかった場合は、`agent_done_but_screen_unstable` が付く。
231
231
 
232
232
  ### トークン削減
233
233
 
package/README.md CHANGED
@@ -45,11 +45,11 @@ pty_read(id, { wait: true }) → read the token-reduced output, completion
45
45
 
46
46
  ### 2. Launch other coding agents into that terminal — the orchestration flagship
47
47
 
48
- The same primitive hosts another agent's TUI. Three launchers each start one vendor's interactive coding-agent TUI inside a fresh persistent terminal and return a `session_id`. 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.) Agent launchers can also opt into hook-backed turn completion with `agent_done: true`, letting `pty_send({ wait: "agent_done" })` return after the agent turn ends. Codex/Grok/Composer all have passing live smokes when their vendor CLI is authenticated. This needs the vendor's own CLI installed and authenticated — see [Requirements](#requirements).
48
+ The same primitive hosts another agent's TUI. Three launchers each start one vendor's interactive coding-agent TUI inside a fresh persistent terminal and return a `session_id`. 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.) Agent launchers can also opt into hook-backed turn completion with `agent_done: true`, letting `pty_send({ wait: "agent_done" })` return after the agent turn ends. `codex_agent` can additionally wait for its initial `prompt`: pass `prompt`, `agent_done: true`, and `wait: "agent_done"`; aiterm starts the TUI first, waits until its input area is ready, submits the prompt, then returns after that first turn's Stop hook. Codex/Grok/Composer all have passing live smokes for follow-up `pty_send(wait:"agent_done")` when their vendor CLI is authenticated; Codex initial-prompt wait is also live-smoked. Grok/Composer initial-prompt wait is intentionally not exposed until the post-OAuth smoke passes. This needs the vendor's own CLI installed and authenticated — see [Requirements](#requirements).
49
49
 
50
50
  ```text
51
51
  codex_agent({ session_name: "codex1", cwd: "/repo", agent_done: true,
52
- prompt: "port test/legacy.py to vitest" })
52
+ wait: "agent_done", prompt: "port test/legacy.py to vitest" })
53
53
  → { session_id: "codex1", … } # Codex now live in a persistent terminal
54
54
  pty_read("codex1", { screen: true }) → read what it's doing (token-reduced)
55
55
  pty_send("codex1", "also fix the imports it broke", { wait: "agent_done" })
@@ -60,11 +60,11 @@ One call per model, so the tool name itself tells you which model you get:
60
60
 
61
61
  | Tool | Launches | Key args |
62
62
  | --- | --- | --- |
63
- | `codex_agent` | Codex CLI (OpenAI; the CLI's default model) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?` |
63
+ | `codex_agent` | Codex CLI (OpenAI; the CLI's default model) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?`, `wait?`, `timeout?`, `screen?`, `lines?` |
64
64
  | `grok_agent` | Grok Build, model `grok-build` (xAI) | `prompt?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `agent_done?` |
65
65
  | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` (xAI) | same as `grok_agent` |
66
66
 
67
- The vendor CLI must be installed and authenticated (`codex` for `codex_agent`; `grok` for both Grok tools). aiterm resolves the binary via `CODEX_BIN` / `GROK_BIN`, then `~/.local/bin/codex` / `~/.grok/bin/grok`, then `PATH`. Prerequisites are checked **before** a session exists: for `grok_agent` / `composer_agent` an out-of-range `reasoning_effort` is rejected up front (the value set is fixed — `low`/`medium`/`high`/`xhigh`/`max`); a missing CLI binary or a nonexistent `cwd` fails for all three. A rejected launch — bad `reasoning_effort`, an unresolvable binary, or a nonexistent `cwd` — leaves **zero leftover session** behind, and if the launch keystroke itself can't be delivered aiterm tears the session down. (aiterm does *not* then verify the vendor CLI actually started or authenticated — `openAgent` returns once the launch command is sent; read the session to confirm the agent came up.) (`codex_agent` forwards `reasoning_effort` to the Codex CLI as a config override — `-c model_reasoning_effort=…` — rather than validating it, since Codex's accepted values vary by version.) Pass an absolute path for `cwd` — `~` is not expanded. `agent_done` uses launch-local managed vendor homes and does not edit your normal hook files; Grok/Composer additionally isolate `GROK_HOME` and `HOME` to suppress compat hook/plugin contamination, while OAuth uses the normal Grok home's `auth.json` and `auth.json.lock` as a pair so refresh locking does not split across sessions. Before the first unbound `pty_send({ wait: "agent_done" })`, aiterm waits for the vendor TUI's input prompt and fails before sending if the prompt is not ready, avoiding dropped startup input. `agent_done` currently requires POSIX filesystem semantics (`getuid`, secure temp files, hard-link checks), so it is supported on Linux, WSL2, and macOS; native Windows can still use the core PTY tools and agent launchers without `agent_done`.
67
+ The vendor CLI must be installed and authenticated (`codex` for `codex_agent`; `grok` for both Grok tools). aiterm resolves the binary via `CODEX_BIN` / `GROK_BIN`, then `~/.local/bin/codex` / `~/.grok/bin/grok`, then `PATH`. Prerequisites are checked **before** a session exists: for `grok_agent` / `composer_agent` an out-of-range `reasoning_effort` is rejected up front (the value set is fixed — `low`/`medium`/`high`/`xhigh`/`max`); a missing CLI binary or a nonexistent `cwd` fails for all three. A rejected launch — bad `reasoning_effort`, an unresolvable binary, or a nonexistent `cwd` — leaves **zero leftover session** behind, and if the launch keystroke itself can't be delivered aiterm tears the session down. (Without an initial prompt wait, aiterm does *not* then verify the vendor CLI actually started or authenticated — read the session to confirm the agent came up.) (`codex_agent` forwards `reasoning_effort` to the Codex CLI as a config override — `-c model_reasoning_effort=…` — rather than validating it, since Codex's accepted values vary by version.) Pass an absolute path for `cwd` — `~` is not expanded. `agent_done` uses launch-local managed vendor homes and does not edit your normal hook files; Codex links only `auth.json` and copies `config.toml` into its managed `CODEX_HOME`, while Grok/Composer additionally isolate `GROK_HOME` and `HOME` to suppress compat hook/plugin contamination. Grok OAuth uses the normal Grok home's `auth.json` and `auth.json.lock` as a pair so refresh locking does not split across sessions. Before the first unbound `pty_send({ wait: "agent_done" })`, aiterm waits for the vendor TUI's input prompt and fails before sending if the prompt is not ready, avoiding dropped startup input. `codex_agent` launcher `wait:"agent_done"` has the same requirement and is only valid with both `prompt` and `agent_done:true`; if the TUI is not ready, the prompt is not sent and the session is left inspectable with `initial_prompt=not_sent`. While an initial prompt is still `pending`/`sent`, ordinary `pty_send` is rejected to prevent mixed input; manual takeover can still use `pty_key`, or `pty_send(..., force:true)` if you intentionally want to type into that live TUI. `agent_done` currently requires POSIX filesystem semantics (`getuid`, secure temp files, hard-link checks), so it is supported on Linux, WSL2, and macOS; native Windows can still use the core PTY tools and agent launchers without `agent_done`.
68
68
 
69
69
  There is deliberately **no Claude launcher**, and no protocol between the agents: aiterm's job is to let your Claude (or any MCP client) reach for *other* agents and drive their terminals. Because a launched agent is just another persistent session, everything else in this README applies to it: token-reduced reads, completion detection, and a human `attach` to watch or take over.
70
70
 
@@ -219,15 +219,15 @@ Each launcher starts a specific vendor's interactive coding-agent TUI inside a f
219
219
 
220
220
  | Tool | Launches | Key args |
221
221
  | --- | --- | --- |
222
- | `codex_agent` | Codex CLI (OpenAI; the CLI's default model) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?` |
222
+ | `codex_agent` | Codex CLI (OpenAI; the CLI's default model) | `prompt?`, `reasoning_effort?`, `cwd?`, `session_name?`, `agent_done?`, `wait?`, `timeout?`, `screen?`, `lines?` |
223
223
  | `grok_agent` | Grok Build, model `grok-build` (xAI) | `prompt?`, `reasoning_effort?` (`low`/`medium`/`high`/`xhigh`/`max`), `cwd?`, `session_name?`, `agent_done?` |
224
224
  | `composer_agent` | Grok Build, model `grok-composer-2.5-fast` (xAI) | same as `grok_agent` |
225
225
 
226
- The vendor CLI must be installed and authenticated (`codex` for `codex_agent`; `grok` for both Grok tools). aiterm resolves the binary via `CODEX_BIN` / `GROK_BIN`, then `~/.local/bin/codex` / `~/.grok/bin/grok`, then `PATH`. Prerequisites are validated before a session is created (grok/composer reject an out-of-range `reasoning_effort`; a missing CLI or a nonexistent `cwd` fails for all three), and a failed launch leaves no session behind. Full details under [Launch other coding agents into that terminal](#2-launch-other-coding-agents-into-that-terminal--the-orchestration-flagship). Pass an absolute path for `cwd` — `~` is not expanded. `agent_done` is hook-backed for agent launchers; Codex/Grok/Composer have passing live smokes on Linux/WSL2/macOS; native Windows can launch agents but `agent_done` is not supported yet. Before the first unbound agent send, `pty_send({ wait:"agent_done" })` waits for the vendor TUI input prompt and fails before sending if it is not ready. In Grok OAuth mode, aiterm keeps hook/config isolation per launch but shares both `auth.json` and `auth.json.lock` with the normal Grok home; missing OAuth auth fails without leaving a session behind.
226
+ The vendor CLI must be installed and authenticated (`codex` for `codex_agent`; `grok` for both Grok tools). aiterm resolves the binary via `CODEX_BIN` / `GROK_BIN`, then `~/.local/bin/codex` / `~/.grok/bin/grok`, then `PATH`. Prerequisites are validated before a session is created (grok/composer reject an out-of-range `reasoning_effort`; a missing CLI or a nonexistent `cwd` fails for all three), and a failed launch leaves no session behind. Full details under [Launch other coding agents into that terminal](#2-launch-other-coding-agents-into-that-terminal--the-orchestration-flagship). Pass an absolute path for `cwd` — `~` is not expanded. `agent_done` is hook-backed for agent launchers; Codex/Grok/Composer have passing live smokes on Linux/WSL2/macOS for follow-up `pty_send(wait:"agent_done")`, and Codex has a live smoke for launcher `prompt + wait:"agent_done"`. Native Windows can launch agents but `agent_done` is not supported yet. Codex managed `CODEX_HOME` links only `auth.json`, copies `config.toml`, and owns its own `hooks.json`. Before the first unbound agent send, `pty_send({ wait:"agent_done" })` waits for the vendor TUI input prompt and fails before sending if it is not ready. `codex_agent` launcher `wait:"agent_done"` requires `prompt` plus `agent_done:true`; it sends the initial prompt only after the TUI is ready, and returns `initial_prompt=not_sent` without sending if the TUI is blocked before input. In Grok OAuth mode, aiterm keeps hook/config isolation per launch but shares both `auth.json` and `auth.json.lock` with the normal Grok home; missing OAuth auth fails without leaving a session behind.
227
227
 
228
228
  ### Completion detection (5 layers)
229
229
 
230
- `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. Sessions launched with `agent_done:true` can instead use `pty_send({ wait:"agent_done" })`, which first waits for the agent TUI input prompt when needed, then waits for the vendor Stop hook and returns the screen after the turn boundary; pre-send readiness failures are MCP errors and timeouts after sending are reported as `is_complete=False via agent_timeout`, not as success. If a complete hook JSONL line is malformed, the timeout suffix includes `malformed_events=N` 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`.
230
+ `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. Sessions launched with `agent_done:true` can instead use `pty_send({ wait:"agent_done" })`, which first waits for the agent TUI input prompt when needed, then waits for the vendor Stop hook and returns the screen after the turn boundary; `codex_agent` launcher `wait:"agent_done"` does the same for the initial `prompt`. 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`; timeouts after sending are reported as `is_complete=False via agent_timeout`, not as success. 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 timeout suffix includes `malformed_events=N` 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`.
231
231
 
232
232
  ### Token reduction
233
233
 
package/dist/core.js CHANGED
@@ -711,6 +711,7 @@ export function send(name, text, o = {}) {
711
711
  const enter = o.enter ?? true;
712
712
  if (!sessionExists(name))
713
713
  throw new AitermError(`session '${name}' が無い(open してください)`, 2);
714
+ assertInitialPromptNotPendingForSend(name, !!o.force);
714
715
  if (!o.raw) {
715
716
  text = text.replace(PASTE_MARKERS_RE, "").replace(ANSI_RE, "").replace(CTRL_RE, "");
716
717
  }
@@ -812,7 +813,7 @@ export async function readOutput(name, o = {}) {
812
813
  if (o.raw)
813
814
  return rawTxt;
814
815
  const [body, meta] = reduceOutput(rawTxt, name, true);
815
- return body + "\n" + meta + (status ? completionSuffix(status) : "");
816
+ return body + "\n" + meta + agentReadMetadataSuffix(name, rawTxt) + (status ? completionSuffix(status) : "");
816
817
  }
817
818
  // ログ全体を毎回メモリに載せず、必要な範囲だけ fd で読む(B7)。size は statSync で取る。
818
819
  let size = 0;
@@ -892,17 +893,19 @@ export async function readOutput(name, o = {}) {
892
893
  const [reduced, rname] = rtk.reduce(cmd, framed);
893
894
  if (reduced !== null) {
894
895
  const meta = `[aiterm ${name}: rtk:${rname} 適用 / ~${estimateTokens(reduced)} tok (raw ~${estimateTokens(text)} tok)]`;
896
+ const agentMeta = agentReadMetadataSuffix(name);
895
897
  if (status)
896
- return reduced + "\n" + meta + completionSuffix(status);
897
- return reduced + "\n" + meta;
898
+ return reduced + "\n" + meta + agentMeta + completionSuffix(status);
899
+ return reduced + "\n" + meta + agentMeta;
898
900
  }
899
901
  }
900
902
  // reducer 非該当 → 汎用削減へフォールバック
901
903
  }
902
904
  const [body, meta] = reduceOutput(text, name, !o.range);
905
+ const agentMeta = agentReadMetadataSuffix(name);
903
906
  if (status)
904
- return body + "\n" + meta + completionSuffix(status);
905
- return body + "\n" + meta;
907
+ return body + "\n" + meta + agentMeta + completionSuffix(status);
908
+ return body + "\n" + meta + agentMeta;
906
909
  }
907
910
  export function listSessions() {
908
911
  const r = tmux("list-sessions", "-F", "#{session_name}\t#{pane_current_command}\t#{?session_attached,attached,detached}\t#{window_width}x#{window_height}");
@@ -975,6 +978,13 @@ export function killAll() {
975
978
  }
976
979
  const DEFAULT_AGENT_DONE_TIMEOUT = 600;
977
980
  const agentWaitLocks = new Set();
981
+ function normalizeAgentLauncherWait(v) {
982
+ if (v == null || v === "none")
983
+ return "none";
984
+ if (v === "agent_done")
985
+ return "agent_done";
986
+ throw new AitermError('wait は "none" または "agent_done" を指定してください', 2);
987
+ }
978
988
  function codexHookScriptPath() {
979
989
  return path.join(path.dirname(fileURLToPath(import.meta.url)), "codex-stop-hook.js");
980
990
  }
@@ -1054,32 +1064,31 @@ function createManagedCodexHome(name, launchId) {
1054
1064
  const managedHome = agentManagedCodexHomePath(name, launchId);
1055
1065
  fs.mkdirSync(managedHome, { recursive: false, mode: 0o700 });
1056
1066
  fs.chmodSync(managedHome, 0o700);
1057
- let authLinked = false;
1058
- for (const entry of fs.readdirSync(srcHome)) {
1059
- if (entry === "hooks.json" || entry.startsWith("hooks.json."))
1060
- continue;
1061
- const src = path.join(srcHome, entry);
1062
- const dst = path.join(managedHome, entry);
1063
- if (entry === "auth.json") {
1064
- const st = fs.statSync(src);
1065
- if (!st.isFile())
1066
- throw new AitermError(`Codex auth.json が通常ファイルではありません: ${src}`, 2);
1067
- fs.symlinkSync(src, dst);
1068
- authLinked = true;
1069
- }
1070
- else if (entry === "config.toml") {
1071
- const st = fs.statSync(src);
1072
- if (st.isFile()) {
1073
- fs.copyFileSync(src, dst);
1074
- fs.chmodSync(dst, 0o600);
1075
- }
1067
+ const authSrc = path.join(srcHome, "auth.json");
1068
+ try {
1069
+ const st = fs.statSync(authSrc);
1070
+ if (!st.isFile())
1071
+ throw new AitermError(`Codex auth.json が通常ファイルではありません: ${authSrc}`, 2);
1072
+ }
1073
+ catch (e) {
1074
+ if (e.code === "ENOENT") {
1075
+ throw new AitermError(`Codex auth.json が見つかりません。先に codex login が必要です: ${srcHome}`, 2);
1076
1076
  }
1077
- else {
1078
- fs.symlinkSync(src, dst);
1077
+ throw e;
1078
+ }
1079
+ fs.symlinkSync(authSrc, path.join(managedHome, "auth.json"));
1080
+ const configSrc = path.join(srcHome, "config.toml");
1081
+ try {
1082
+ const st = fs.statSync(configSrc);
1083
+ if (st.isFile()) {
1084
+ fs.copyFileSync(configSrc, path.join(managedHome, "config.toml"));
1085
+ fs.chmodSync(path.join(managedHome, "config.toml"), 0o600);
1079
1086
  }
1080
1087
  }
1081
- if (!authLinked)
1082
- throw new AitermError(`Codex auth.json が見つかりません。先に codex login が必要です: ${srcHome}`, 2);
1088
+ catch (e) {
1089
+ if (e.code !== "ENOENT")
1090
+ throw e;
1091
+ }
1083
1092
  const hookScript = codexHookScriptPath();
1084
1093
  if (!fs.existsSync(hookScript)) {
1085
1094
  throw new AitermError(`Codex Stop hook wrapper が見つかりません。npm run build を実行してください: ${hookScript}`, 2);
@@ -1243,6 +1252,25 @@ function createManagedGrokHome(name, launchId) {
1243
1252
  function writeAgentMetadata(meta) {
1244
1253
  writeJson0600(agentMetadataPath(meta.aiterm_session, meta.launch_id), meta);
1245
1254
  }
1255
+ function normalizeInitialPromptState(v) {
1256
+ if (v === true)
1257
+ return "pending";
1258
+ if (v === false || v == null)
1259
+ return "none";
1260
+ if (v === "none" ||
1261
+ v === "not_sent" ||
1262
+ v === "sent" ||
1263
+ v === "pending" ||
1264
+ v === "done" ||
1265
+ v === "failed") {
1266
+ return v;
1267
+ }
1268
+ return "none";
1269
+ }
1270
+ function setInitialPromptState(meta, state) {
1271
+ meta.initial_prompt = state;
1272
+ writeAgentMetadata(meta);
1273
+ }
1246
1274
  function acquireAgentWaitFileLock(meta) {
1247
1275
  const p = agentWaitLockPath(meta.aiterm_session, meta.launch_id);
1248
1276
  const nofollow = fs.constants.O_NOFOLLOW ?? 0;
@@ -1365,7 +1393,7 @@ function loadAgentMetadata(name) {
1365
1393
  created_at: typeof m.created_at === "string" ? m.created_at : "",
1366
1394
  cwd: typeof m.cwd === "string" ? m.cwd : null,
1367
1395
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
1368
- initial_prompt: m.initial_prompt === true,
1396
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
1369
1397
  hook_route: "managed_codex_home",
1370
1398
  node_platform: process.platform,
1371
1399
  codex_home: expectedHome,
@@ -1384,7 +1412,7 @@ function loadAgentMetadata(name) {
1384
1412
  created_at: typeof m.created_at === "string" ? m.created_at : "",
1385
1413
  cwd: typeof m.cwd === "string" ? m.cwd : null,
1386
1414
  vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
1387
- initial_prompt: m.initial_prompt === true,
1415
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
1388
1416
  hook_route: "managed_grok_home",
1389
1417
  node_platform: process.platform,
1390
1418
  grok_home: expectedGrokHome,
@@ -1462,8 +1490,12 @@ function bindAgentVendorSession(meta, ev) {
1462
1490
  }
1463
1491
  }
1464
1492
  function bindCompletedInitialPrompt(meta) {
1465
- if (!meta.initial_prompt || meta.vendor_session_id)
1493
+ if (meta.initial_prompt !== "pending" && meta.initial_prompt !== "sent")
1466
1494
  return;
1495
+ if (meta.vendor_session_id) {
1496
+ setInitialPromptState(meta, "done");
1497
+ return;
1498
+ }
1467
1499
  const size = safeStatSize(meta.event_file);
1468
1500
  if (size === 0) {
1469
1501
  throw new AitermError(`agent session '${meta.aiterm_session}' は起動時 prompt の完了待ちです。初回応答完了後に再度 pty_send(wait:"agent_done") してください。`, 2);
@@ -1481,8 +1513,69 @@ function bindCompletedInitialPrompt(meta) {
1481
1513
  throw new AitermError(`agent session '${meta.aiterm_session}' は起動時 prompt の完了 event をまだ確認できません。初回応答完了後に再度 pty_send(wait:"agent_done") してください。${malformed}${partial}`, 2);
1482
1514
  }
1483
1515
  bindAgentVendorSession(meta, scanned.event);
1484
- meta.initial_prompt = false;
1485
- writeAgentMetadata(meta);
1516
+ setInitialPromptState(meta, "done");
1517
+ }
1518
+ function tryLoadAgentMetadata(name) {
1519
+ try {
1520
+ return loadAgentMetadata(name);
1521
+ }
1522
+ catch {
1523
+ return null;
1524
+ }
1525
+ }
1526
+ function latestAgentDoneEvent(meta) {
1527
+ const size = safeStatSize(meta.event_file);
1528
+ if (size === 0 || size > AGENT_EVENT_MAX_BYTES)
1529
+ return null;
1530
+ const text = readFileRange(meta.event_file, 0, size).toString("utf8");
1531
+ let latest = null;
1532
+ for (const line of text.split("\n")) {
1533
+ if (!line.trim() || Buffer.byteLength(line, "utf8") > 64 * 1024)
1534
+ continue;
1535
+ const parsed = parseAgentDoneEvent(line, meta);
1536
+ if (parsed.event)
1537
+ latest = parsed.event;
1538
+ }
1539
+ return latest;
1540
+ }
1541
+ function inferAgentFrontend(name, meta, screen) {
1542
+ const fg = paneCurrentCommand(name);
1543
+ const view = screen ?? captureScreen(name, AGENT_TUI_READY_LINES);
1544
+ if (isAgentTuiReady(meta.kind, view))
1545
+ return "agent_tui";
1546
+ if (SHELLS.has(fg)) {
1547
+ if (/(^|\n)\s*>\s/.test(view))
1548
+ return "shell_continuation";
1549
+ return "shell";
1550
+ }
1551
+ return "unknown";
1552
+ }
1553
+ function agentReadMetadataSuffix(name, screen) {
1554
+ const meta = tryLoadAgentMetadata(name);
1555
+ if (!meta)
1556
+ return "";
1557
+ const ev = latestAgentDoneEvent(meta);
1558
+ const bits = [
1559
+ "agent",
1560
+ `vendor=${meta.kind}`,
1561
+ `initial_prompt=${meta.initial_prompt}`,
1562
+ `agent_event_seen=${ev ? "true" : "false"}`,
1563
+ "completion_attribution=none",
1564
+ ev?.turn_id ? `last_turn_id=${ev.turn_id}` : null,
1565
+ `frontend=${inferAgentFrontend(name, meta, screen)}`,
1566
+ ].filter(Boolean);
1567
+ return ` [${bits.join(" ")}]`;
1568
+ }
1569
+ function assertInitialPromptNotPendingForSend(name, force) {
1570
+ if (force)
1571
+ return;
1572
+ const meta = tryLoadAgentMetadata(name);
1573
+ if (!meta)
1574
+ return;
1575
+ if (meta.initial_prompt !== "pending" && meta.initial_prompt !== "sent")
1576
+ return;
1577
+ throw new AitermError(`agent session '${name}' は起動時 prompt の完了待ちです。通常 pty_send は混入防止のため送信しません。` +
1578
+ `完了後に pty_send(wait:"agent_done") するか、手動介入が必要な場合だけ force:true を明示してください。`, 2);
1486
1579
  }
1487
1580
  async function waitAgentDoneEvent(meta, startOffset, timeout) {
1488
1581
  const deadline = performance.now() + timeout * 1000;
@@ -1561,6 +1654,9 @@ async function waitAgentTuiReadyImpl(kind, sample, sleepFn, opts = {}) {
1561
1654
  async function waitAgentTuiReady(name, meta, timeoutMs = AGENT_TUI_READY_TIMEOUT_MS) {
1562
1655
  return waitAgentTuiReadyImpl(meta.kind, () => captureScreen(name, AGENT_TUI_READY_LINES), sleep, { timeoutMs });
1563
1656
  }
1657
+ async function waitAgentTuiReadyByKind(name, kind, timeoutMs = AGENT_TUI_READY_TIMEOUT_MS) {
1658
+ return waitAgentTuiReadyImpl(kind, () => captureScreen(name, AGENT_TUI_READY_LINES), sleep, { timeoutMs });
1659
+ }
1564
1660
  async function settleAgentDoneScreenImpl(sample, sleepFn, opts = {}) {
1565
1661
  const minDelayMs = opts.minDelayMs ?? AGENT_DONE_SETTLE_MIN_MS;
1566
1662
  const pollMs = opts.pollMs ?? AGENT_DONE_SCREEN_SETTLE_POLL_MS;
@@ -1617,6 +1713,76 @@ export async function __testWaitAgentTuiReady(kind, samples, opts = {}) {
1617
1713
  }, opts);
1618
1714
  return { ...result, sleeps };
1619
1715
  }
1716
+ async function sendAgentPromptText(name, text) {
1717
+ send(name, text, {
1718
+ enter: false,
1719
+ force: true,
1720
+ raw: false,
1721
+ mark: false,
1722
+ rtk: false,
1723
+ });
1724
+ await sleep(AGENT_SUBMIT_DELAY_MS);
1725
+ sendKey(name, "Enter");
1726
+ }
1727
+ export async function sendInitialAgentPrompt(name, text, o = {}) {
1728
+ assertSessionName(name);
1729
+ const waitMode = normalizeAgentLauncherWait(o.wait);
1730
+ const meta = loadAgentMetadata(name);
1731
+ if (agentWaitLocks.has(name))
1732
+ throw new AitermError(`agent session '${name}' は別の agent_done 待機中です`, 2);
1733
+ if (meta.initial_prompt === "done") {
1734
+ throw new AitermError(`agent session '${name}' の起動時 prompt は既に完了しています`, 2);
1735
+ }
1736
+ if (meta.initial_prompt === "pending" || meta.initial_prompt === "sent") {
1737
+ throw new AitermError(`agent session '${name}' は起動時 prompt の完了待ちです。初回応答完了後に再度操作してください。`, 2);
1738
+ }
1739
+ const releaseFileLock = acquireAgentWaitFileLock(meta);
1740
+ const timeout = o.timeout ?? DEFAULT_AGENT_DONE_TIMEOUT;
1741
+ const screen = o.screen ?? true;
1742
+ agentWaitLocks.add(name);
1743
+ try {
1744
+ setInitialPromptState(meta, "not_sent");
1745
+ const ready = await waitAgentTuiReady(name, meta, o.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS);
1746
+ if (!ready.ready) {
1747
+ return (`initial_prompt=not_sent vendor=${meta.kind} ready=false samples=${ready.samples}\n` +
1748
+ `agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。prompt は送信していません。`);
1749
+ }
1750
+ const startOffset = safeStatSize(meta.event_file);
1751
+ try {
1752
+ await sendAgentPromptText(name, text);
1753
+ setInitialPromptState(meta, "pending");
1754
+ }
1755
+ catch (e) {
1756
+ setInitialPromptState(meta, "failed");
1757
+ throw e;
1758
+ }
1759
+ if (waitMode === "none") {
1760
+ return (`initial_prompt=pending vendor=${meta.kind}\n` +
1761
+ `起動時 prompt を送信しました。完了後の follow-up は pty_send(wait:"agent_done") を使ってください。`);
1762
+ }
1763
+ const wait = await waitAgentDoneEvent(meta, startOffset, timeout);
1764
+ if (wait.event) {
1765
+ setInitialPromptState(meta, "done");
1766
+ }
1767
+ else {
1768
+ setInitialPromptState(meta, "pending");
1769
+ }
1770
+ const settled = wait.event
1771
+ ? await settleAgentDoneScreen(name, o.lines ?? 0)
1772
+ : { unstable: false, samples: 0 };
1773
+ const out = await readOutput(name, {
1774
+ screen,
1775
+ lines: o.lines ?? null,
1776
+ timeout: 0,
1777
+ });
1778
+ writeOffset(name, safeStatSize(logpath(name)));
1779
+ return out + agentDoneSuffix(wait, meta.kind) + (settled.unstable ? " [agent_done_but_screen_unstable]" : "");
1780
+ }
1781
+ finally {
1782
+ agentWaitLocks.delete(name);
1783
+ releaseFileLock();
1784
+ }
1785
+ }
1620
1786
  export async function sendAndWaitAgentDone(name, text, o = {}) {
1621
1787
  assertSessionName(name);
1622
1788
  if (o.enter === false)
@@ -1812,8 +1978,8 @@ export function openAgent(kind, opts = {}) {
1812
1978
  try {
1813
1979
  const meta = agentDone
1814
1980
  ? kind === "codex"
1815
- ? createCodexAgentMetadata(sid, cwd, !!opts.prompt)
1816
- : createGrokAgentMetadata(kind, sid, cwd, !!opts.prompt)
1981
+ ? createCodexAgentMetadata(sid, cwd, opts.prompt ? "pending" : "none")
1982
+ : createGrokAgentMetadata(kind, sid, cwd, opts.prompt ? "pending" : "none")
1817
1983
  : null;
1818
1984
  const cmd = buildAgentCmd(kind, binForCmd, effort, opts.prompt ?? null, meta);
1819
1985
  const envPrefix = agentEnvPrefix(meta, sid);
@@ -1842,3 +2008,60 @@ export function openAgent(kind, opts = {}) {
1842
2008
  `起動直後に増分 pty_read すると空/半描画になり得るので screen:true を使う。`,
1843
2009
  ];
1844
2010
  }
2011
+ async function sendInitialPromptWithoutAgentDone(name, kind, text, opts = {}) {
2012
+ const ready = await waitAgentTuiReadyByKind(name, kind, opts.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS);
2013
+ if (!ready.ready) {
2014
+ return (`initial_prompt=not_sent vendor=${kind} ready=false samples=${ready.samples}\n` +
2015
+ `agent session '${name}' の ${agentLabel(kind)} TUI が入力受付状態になりません。prompt は送信していません。`);
2016
+ }
2017
+ await sendAgentPromptText(name, text);
2018
+ return `initial_prompt=sent vendor=${kind}\n起動時 prompt を送信しました。完了待ちは通常の pty_read で行ってください。`;
2019
+ }
2020
+ export async function openAgentWithInitialPrompt(kind, opts = {}) {
2021
+ const waitMode = normalizeAgentLauncherWait(opts.wait);
2022
+ const prompt = opts.prompt ?? null;
2023
+ const agentDone = !!opts.agent_done;
2024
+ if (waitMode === "agent_done" && !prompt) {
2025
+ throw new AitermError('wait:"agent_done" は prompt 指定時だけ使えます', 2);
2026
+ }
2027
+ if (waitMode === "agent_done" && !agentDone) {
2028
+ throw new AitermError('wait:"agent_done" には agent_done:true が必要です', 2);
2029
+ }
2030
+ if (!prompt) {
2031
+ return openAgent(kind, opts);
2032
+ }
2033
+ if (kind !== "codex") {
2034
+ if (waitMode === "agent_done") {
2035
+ throw new AitermError(`${agentLabel(kind)} の起動時 prompt wait は未対応です。` +
2036
+ `agent_done:true で prompt なし起動後、TUI のログイン/ready を確認してから pty_send(wait:"agent_done") を使ってください。`, 2);
2037
+ }
2038
+ return openAgent(kind, opts);
2039
+ }
2040
+ const [sid, hint] = openAgent(kind, {
2041
+ session_name: opts.session_name ?? null,
2042
+ reasoning_effort: opts.reasoning_effort ?? null,
2043
+ cwd: opts.cwd ?? null,
2044
+ prompt: null,
2045
+ agent_done: agentDone,
2046
+ });
2047
+ try {
2048
+ const initial = agentDone
2049
+ ? await sendInitialAgentPrompt(sid, prompt, {
2050
+ wait: waitMode,
2051
+ timeout: opts.timeout ?? undefined,
2052
+ ready_timeout: opts.ready_timeout ?? undefined,
2053
+ screen: opts.screen ?? undefined,
2054
+ lines: opts.lines ?? null,
2055
+ })
2056
+ : await sendInitialPromptWithoutAgentDone(sid, kind, prompt, {
2057
+ ready_timeout: opts.ready_timeout ?? undefined,
2058
+ });
2059
+ return [sid, `${hint}\n${initial}`];
2060
+ }
2061
+ catch (e) {
2062
+ const code = e instanceof AitermError ? e.code : 1;
2063
+ const message = e instanceof Error ? e.message : String(e);
2064
+ throw new AitermError(`session_id: ${sid}\n` +
2065
+ `起動後の初回 prompt 処理で失敗しました。session は調査/復旧用に残しています。\n${message}`, code);
2066
+ }
2067
+ }
package/dist/index.js CHANGED
@@ -184,6 +184,16 @@ const agentEffortDesc = (grokLike) => "reasoning effort(思考レベル)。"
184
184
  (grokLike ? "low/medium/high/xhigh/max" : "low/medium/high 等") +
185
185
  "。省略時は CLI 既定。";
186
186
  function registerAgentTool(toolName, kind, desc, grokLike) {
187
+ const initialPromptWaitSchema = {};
188
+ if (kind === "codex") {
189
+ initialPromptWaitSchema.wait = z
190
+ .enum(["none", "agent_done"])
191
+ .default("none")
192
+ .describe("none=従来通り起動/初回prompt送信のみ。agent_done=起動時promptのStop hookまで待つ(agent_done:true必須)");
193
+ initialPromptWaitSchema.timeout = z.number().default(600).describe("wait:'agent_done' の最大待ち秒数");
194
+ initialPromptWaitSchema.screen = z.boolean().default(true).describe("wait:'agent_done' の返り値を描画済みスクリーンにする");
195
+ initialPromptWaitSchema.lines = z.number().int().nullish().describe("wait:'agent_done' で返す末尾 N 行");
196
+ }
187
197
  server.registerTool(toolName, {
188
198
  description: desc,
189
199
  inputSchema: {
@@ -199,15 +209,20 @@ function registerAgentTool(toolName, kind, desc, grokLike) {
199
209
  .boolean()
200
210
  .default(false)
201
211
  .describe("managed Stop hook を有効化し、pty_send(wait:'agent_done') を使えるようにする"),
212
+ ...initialPromptWaitSchema,
202
213
  },
203
- }, async ({ prompt, reasoning_effort, cwd, session_name, agent_done }) => {
214
+ }, async ({ prompt, reasoning_effort, cwd, session_name, agent_done, wait, timeout, screen, lines }) => {
204
215
  try {
205
- const [sid, hint] = core.openAgent(kind, {
216
+ const [sid, hint] = await core.openAgentWithInitialPrompt(kind, {
206
217
  prompt: prompt ?? undefined,
207
218
  reasoning_effort: reasoning_effort ?? undefined,
208
219
  cwd: cwd ?? undefined,
209
220
  session_name: session_name ?? undefined,
210
221
  agent_done: agent_done ?? false,
222
+ wait: wait ?? "none",
223
+ timeout,
224
+ screen,
225
+ lines,
211
226
  });
212
227
  return ok(`session_id: ${sid}\n${hint}`);
213
228
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "mcpName": "io.github.kitepon-rgb/aiterm-mcp",
5
5
  "description": "AI-driven persistent terminal as a local stdio MCP server (tmux-backed). Holds one local PTY; SSH and containers are just commands you send into it. Also launches interactive Codex/Grok/Composer agent TUIs in a persistent terminal. Token-reducing reads.",
6
6
  "keywords": [