aiterm-mcp 0.62.3 → 0.62.5

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/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.62.5] - 2026-11-01
11
+
12
+ ### Added
13
+ - Include the managed `launch_id` snapshot in structured `pty_list` results; older remote results without the field remain valid.
14
+
15
+ ### Fixed
16
+ - Reject psmux command errors after successful authentication and stop without resending partially delivered input.
17
+ - Keep input admission independent of unrelated activity-capture failures while retaining native ownership and readiness checks.
18
+ - Reject readiness or steer admission when a screen or transcript read finishes after a positive readiness deadline.
19
+ - Reject queued agent operations if the session was recreated while they waited, before they can act on the replacement launch.
20
+ - Keep Windows test temp directories until the preloaded runner finishes so another MSYS process cannot retain a deleted `/tmp` mount.
21
+ - Keep native Windows harness startup distinct from confirmed exit using a launch-bound shell return record, while retaining readiness deadlines and checks before input.
22
+ - Bind each new shell completion mark to its submission so a delayed earlier mark cannot complete a newer command or remove its pending mark.
23
+ - Recognize an explicitly configured native harness executable by its full process path, including renamed Windows binaries, instead of reporting it exited.
24
+ - Keep a read with an empty pending output stream unconfirmed instead of completing from a stale shell name; late output remains observable within the existing deadline.
25
+ - Avoid repeating native seat observation when selecting the Goal adapter; retain all adapter binding and readback checks.
26
+
27
+ ## [0.62.4] - 2026-11-01
28
+
29
+ ### Fixed
30
+ - Recognize the Codex `Fast` status footer after its header scrolls away, retaining dialog guards and keeping the footer outside Goal composer text.
31
+
10
32
  ## [0.62.3] - 2026-10-31
11
33
 
12
34
  ### Fixed
@@ -2947,7 +2969,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
2947
2969
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
2948
2970
  provenance.
2949
2971
 
2950
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.3...HEAD
2972
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.5...HEAD
2973
+ [0.62.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.4...v0.62.5
2974
+ [0.62.4]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.3...v0.62.4
2951
2975
  [0.62.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.2...v0.62.3
2952
2976
  [0.62.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.1...v0.62.2
2953
2977
  [0.62.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.0...v0.62.1
package/README.ja.md CHANGED
@@ -209,7 +209,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
209
209
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
210
210
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
211
211
 
212
- **状態:** 開発継続中 · 現行公開版 **v0.62.3** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
212
+ **状態:** 開発継続中 · 現行公開版 **v0.62.5** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
213
 
214
214
  ### 更新と巻き戻し
215
215
 
@@ -273,6 +273,8 @@ agent session宛ての`pty_send`は、任意の`preface`(本文の前に置く
273
273
 
274
274
  同じagent sessionへの`pty_send`が重なった時は、1本ずつ通す。後の1通は、前の1通を送り終えてから振り分け直すので、順に送った時と同じ結果になる(起動直後のClaude Codeへ重なった後の1通は`mode=agent_steer`で返る)。前の1通が起動直後の入力受付待ちなら、その分だけ返りが遅れる。待つ上限(POSIX 60秒、Windows 180秒)を越えた時は、打鍵前に`AGENT_SEND_BUSY`と「文字列は送信していません」を返す。送信の途中で終了したprocessのlockは、次の送信が片付けて進む。
275
275
 
276
+ 順番待ちのagent操作は、受付時の`launch_id`を保持する。待機中に同じ名前の席を作り直した時は、新しい席へ作用する前に`EXECUTION_STALE_GENERATION`で拒否する。
277
+
276
278
  `agent_launch`・`pty_send`(agent session宛て)は任意の`image`(画像ファイルの絶対パスの配列。png/jpg/jpeg/gif/webp)を受ける。aitermが本文末尾へ添付行を付け、どのharnessも自分のfile読取toolでそのpathを画像として開く。呼出し側はharness別の添付手順を覚えない。不正なpathは送信前に拒否する。
277
279
 
278
280
  `agent_launch`は任意の`write_scope`も受ける。Codex/Grokのread-onlyは`--sandbox read-only`、Cursorは公式`--mode ask`で実効化する。path説明は同等CLI引数がないためdeclaration-only。
@@ -531,6 +533,7 @@ sessionへ登録する名前の配列で、`pty_list({ env_keys: ["JOB_OWNER"] }
531
533
 
532
534
  `pty_observe({ session_id, cursor? })`は`aiterm.pty-observe-result.v1`で`exists`、`observed_at`、
533
535
  `state`(busy/idle/blocked/dead/missing/unknown)、`reason`、`pane_alive`、`harness_alive`を返す。
536
+ Windowsで新しく起動するClaude・Codex・Grok・Antigravityは、本人processが不在でも、同じ起動のCLIからshellへ戻った記録がなければ未確認を返す。送信は既存の準備待ちの期限を使い、貼付直前とEnter直前にも本人を確認する。旧版で起動したsessionの扱いは維持する。
534
537
  `pane_process`と`harness_process`は別のidentityで、`process_identity`はagentならharness、通常PTYなら
535
538
  一意な子process group leader、子がなければpaneを指す。identityは`pid`、`process_group_id`、
536
539
  `started_identity`、`argv_digest`を持ち、特定不能はnull。WindowsのPIDはnative PIDで、process groupはnull。
@@ -595,7 +598,7 @@ Claudeの相関済み承認は既存の`claude_approval`を使う。
595
598
  | `pty_read` | 出力を削減して読む(既定は増分) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
596
599
  | `pty_key` | 制御キーを送る | `session_id`, `key`(`C-c`/`Enter`/`Up`…) |
597
600
  | `pty_close` | 冪等に閉じ、`closed` / `already_closed`を返す | `session_id` |
598
- | `pty_list` | textと構造化したsession一覧、明示した非秘密環境変数の照会 | `env_keys?` |
601
+ | `pty_list` | textと構造化したsession一覧。管理対象の起動ID `launch_id` は一覧取得時の値で、通常PTYやmetadata不明時はnull、旧remote版は省略。操作前の最新の紐付け確認は引き続き必要。明示した非秘密環境変数も照会できる | `env_keys?` |
599
602
  | `pty_observe` | pane/harnessの生存、native process identity、状態と活動 | `session_id`, `cursor?` |
600
603
  | `agent_launch` | harnessとmodelを別軸で選ぶ正規agent起動入口 | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
601
604
  | `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
@@ -714,7 +717,7 @@ SSH先がPowerShellの場合、`mark:true`は現在の標準`PS ...>`プロン
714
717
 
715
718
  Windows nativeで現在のGit Bashプロンプトが折り返されている時は、実pane列数と一致する表示幅の連続行だけを接続して方言を補正する。過去の入力済みcommand・別prompt・未知の幅を根拠にBashへ切り替えず、通常送信とmark送信が同じruntimeの判定を使う。
716
719
 
717
- `pty_read({ wait: true })`は通常PTYを、process終了/`mark:true` sentinel/`until`一致/shell復帰を伴う出力静止/timeoutの5層で判定する。agent sessionは第6の正確な層を使い、Codexは通常rollout、Grokは通常session event、Claudeはlaunch相関Stop event、Cursorは通常agent transcriptの`turn_ended`を`aiterm-wait --cursor`が観測する。親はブロックもポーリングもしない。
720
+ `pty_read({ wait: true })`は通常PTYを、process終了/`mark:true` sentinel/`until`一致/shell復帰を伴う出力静止/timeoutの5層で判定する。静止による完了には読取り位置以後の新しい出力が必要で、空のログは締切まで未確認を保つ。新しい`mark`は送信IDを持ち、前のcommandの遅れた完了印で次の読取りを完了させない。旧版の処理中markは引き続き読める。IDを保存できなければ入力前に拒否する。agent sessionは第6の正確な層を使い、Codexは通常rollout、Grokは通常session event、Claudeはlaunch相関Stop event、Cursorは通常agent transcriptの`turn_ended`を`aiterm-wait --cursor`が観測する。親はブロックもポーリングもしない。
718
721
 
719
722
  ### Codex/Claude Code/Cursor親への回答自動配送
720
723
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.62.3** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.62.5** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -297,6 +297,8 @@ When the caller gives no `preface`, Aiterm adds one itself for a Claude Code ses
297
297
 
298
298
  Overlapping `pty_send` calls to the same agent session are handled one at a time. A later call picks its route only after the earlier one has been sent, so the result matches calls made in sequence (a call that overlaps the first send to a freshly started Claude Code session returns `mode=agent_steer`). It returns later by however long the earlier call waits for the session to accept input. If its turn does not come within the limit (60 seconds on POSIX, 180 seconds on Windows), Aiterm refuses before sending any text and returns `AGENT_SEND_BUSY` with an explicit unsent message. A lock left by a process that exited mid-send is cleared by the next send. `agent_configure` waits in the same line: a `pty_send` that arrives while a configuration change is in progress is sent after the change, so the turn runs with the new setting. A configuration change to a session whose turn is running does not hold the line while it waits for the turn to end, so steering still goes through. If its turn does not come within the same limit, `agent_configure` returns `AGENT_SEND_BUSY` with an explicit unchanged message.
299
299
 
300
+ Queued agent operations retain the original `launch_id`. If the session is recreated under the same name while they wait, they fail with `EXECUTION_STALE_GENERATION` before acting on the replacement.
301
+
300
302
  `agent_launch` and `pty_send` (to an agent session) accept an optional `image`: an array of absolute paths to image files (png/jpg/jpeg/gif/webp). Aiterm appends an attachment block to the prompt, and every harness opens the path with its own file-reading tool and sees the image; the caller never learns harness-specific attachment tricks. Invalid paths are rejected before anything is sent.
301
303
 
302
304
  `agent_launch` accepts an optional `write_scope`: either `"read-only"` or a human-readable description of writable paths. Codex/Grok use `--sandbox read-only`; Cursor uses its official read-only `--mode ask`. A path description remains declaration-only because these CLI launch surfaces provide no equivalent path allowlist flag.
@@ -568,6 +570,8 @@ are separate identities. `process_identity` selects the harness for agents, or t
568
570
  for an ordinary terminal, using the pane when no child leader exists. An identity contains `pid`, `process_group_id`,
569
571
  `started_identity`, and `argv_digest`; unresolved identities are null. Windows PIDs are native and its process-group field
570
572
  is null. Start identity uses POSIX `LC_ALL=C ps lstart` or Windows UTC ISO milliseconds; the argv digest is SHA-256 hex.
573
+ New managed Windows launches of Claude, Codex, Grok, and Antigravity keep missing native processes unknown until their launch shell records that the same CLI invocation returned. Pending input uses the existing readiness deadline; it is still checked before paste and Enter. Older launch metadata keeps its previous behavior.
574
+ Input admission uses fresh native ownership and its dedicated readiness screen; an unrelated activity-capture failure does not block it. Public `pty_observe` still requires the full activity observation.
571
575
 
572
576
  Pass `activity.cursor` into the next observation to obtain `output_changed` and `cpu_delta_seconds`; first observations and
573
577
  recreated panes return null differences. `cpu_seconds` is the current subtree's cumulative CPU. If a process disappeared
@@ -615,6 +619,7 @@ For Claude Code's first-run text-style menu, it confirms the item already select
615
619
  If the CLI then requests an account login method, the launch reports `vendor_onboarding_required`; complete that choice in the official interactive Claude Code CLI.
616
620
  The input-readiness wait is 30 seconds. Only when it expires while the agent has not drawn anything yet (a busy host), the launch
617
621
  waits up to 50 seconds from startup. If nothing is drawn by then, it still returns `initial_prompt=not_sent` and keeps the session.
622
+ Positive readiness deadlines are checked again after screen and transcript reads; a late ready or busy result cannot authorize input.
618
623
  A prompt-free launch without this option retains `startup.status="not_checked"`. `initial_prompt.status` distinguishes
619
624
  `not_requested`, `not_sent`, `submitted_unconfirmed`, and `started`. Failure responses retain structured session information.
620
625
  WindowsのCodexもhook確認を認識し、npm shim経由の起動を一つのharnessとして識別する。
@@ -635,7 +640,7 @@ continue to use `claude_approval`.
635
640
  | `pty_read` | Read output, token-reduced (incremental by default) | `session_id`, `wait`, `until`, `until_regex`, `timeout`, `screen`, `full`, `lines`, `line_range`, `raw`, `rtk`, `agent_transcript`, `operation_id` |
636
641
  | `pty_key` | Send a control key | `session_id`, `key` (`C-c`/`Enter`/`Up`…) |
637
642
  | `pty_close` | Close idempotently; return `closed` / `already_closed` | `session_id` |
638
- | `pty_list` | Text and structured session list (each agent session carries its harness conversation ID as `vendor_session_id`), with explicitly requested non-secret environment values | `env_keys?` |
643
+ | `pty_list` | Text and structured session list (managed sessions include snapshot `launch_id` and harness conversation ID `vendor_session_id`; `launch_id` is null for ordinary/unmanaged PTYs and may be absent on older remote versions, so callers retain fresh binding checks before operations), with explicitly requested non-secret environment values | `env_keys?` |
639
644
  | `pty_observe` | Pane/harness liveness, native process identity, state, and activity | `session_id`, `cursor?` |
640
645
  | `agent_launch` | Canonical agent launch; harness and model are independent | `harness`, `prompt?`, `model?`, `reasoning_effort?`, `fast?`, `cwd?`, `write_scope?`, `trust_project?`, `env_vars?`, `throughline_source_session?`, `throughline_supplement_file?` |
641
646
  | `agent_auth` | 公式CLIの認証を開始・確認・取消し、公式URL・device code・入力待ちを返す | `harness`, `action`, `session_id?`, `cwd?`, `env_vars?`, `relogin?`, `expected_binding?`, `response?` |
@@ -762,7 +767,7 @@ For PowerShell over SSH, `mark:true` recognizes the current standard `PS ...>` p
762
767
 
763
768
  On native Windows, a wrapped current Git Bash prompt is reconciled with the measured pane columns before choosing shell syntax. Only full-width continuation rows of the current empty prompt are joined; earlier commands, other prompts and unknown widths do not authorize a correction. Ordinary and marked sends use the same runtime decision.
764
769
 
765
- `pty_read({ wait: true })` decides "is the command done?" via five layers: process exit / a `mark:true` sentinel / an `until` match / output quiescence with shell return / timeout. `mark` emits the shell's exit status on POSIX shells and `0` (success) or `1` (failure) on PowerShell; fish/csh/tcsh are rejected before send because they do not share either status syntax. When `mark` or `until` is active, that requested evidence takes precedence and a momentarily quiet shell cannot complete the read as quiescent. Agent sessions add a sixth exact layer: Codex observes normal rollout `task_complete`; Grok observes normal session `turn_ended`; Claude observes its additive launch-correlated Stop event; Cursor observes `turn_ended(status:"success")` in the launch-bound normal agent transcript. `aiterm-wait --cursor` performs that harness-specific observation without the parent blocking or polling. Pre-send readiness failures are MCP errors, and late completion remains recoverable without resending.
770
+ `pty_read({ wait: true })` decides "is the command done?" via five layers: process exit / a `mark:true` sentinel / an `until` match / output quiescence with shell return / timeout. Quiescence requires new output after the read cursor; an empty stream stays unconfirmed until its deadline. Each new `mark` carries a submission ID, so an older command's late sentinel cannot complete a newer read; legacy pending marks remain readable. If its ID cannot be saved, the command is refused before input. `mark` emits the shell's exit status on POSIX shells and `0` (success) or `1` (failure) on PowerShell; fish/csh/tcsh are rejected before send because they do not share either status syntax. When `mark` or `until` is active, that requested evidence takes precedence and a momentarily quiet shell cannot complete the read as quiescent. Agent sessions add a sixth exact layer: Codex observes normal rollout `task_complete`; Grok observes normal session `turn_ended`; Claude observes its additive launch-correlated Stop event; Cursor observes `turn_ended(status:"success")` in the launch-bound normal agent transcript. `aiterm-wait --cursor` performs that harness-specific observation without the parent blocking or polling. Pre-send readiness failures are MCP errors, and late completion remains recoverable without resending.
766
771
 
767
772
  ### Completion push for parent agents (`aiterm-wait`)
768
773
 
@@ -263,7 +263,7 @@ export function runThroughlineHandoffContext(bin, sessionId, supplementFile = nu
263
263
  });
264
264
  }
265
265
  /** Owned Windows agent launch: PowerShell uses argv, without interactive MSYS input. */
266
- export function windowsAgentLaunchLine(cwd, env, argv) {
266
+ export function windowsAgentLaunchLine(cwd, env, argv, exited) {
267
267
  const psq = (value) => `'${value.replace(/'/g, "''")}'`;
268
268
  const parts = [];
269
269
  if (cwd)
@@ -274,7 +274,8 @@ export function windowsAgentLaunchLine(cwd, env, argv) {
274
274
  parts.push(`$env:${name}=${psq(value)}`);
275
275
  }
276
276
  parts.push(`& ${argv.map(psq).join(" ")}`);
277
- return parts.join("; ");
277
+ const command = parts.join("; ");
278
+ return exited ? `try { ${command} } finally { [IO.File]::WriteAllText(${psq(exited.file)}, ${psq(exited.launch_id)}) }` : command;
278
279
  }
279
280
  /**
280
281
  * Keep accepted shebang wrappers in the same pane, as for control commands.
@@ -125,21 +125,23 @@ export async function waitAgentTuiReadyImpl(kind, sample, sleepFn, opts = {}) {
125
125
  let readyStreak = 0;
126
126
  let settledStreak = 0;
127
127
  let lastScreen = "";
128
+ // Synchronous screen/identity and transcript reads can return after the deadline.
129
+ const inTime = () => timeoutMs === 0 || now() < deadline;
128
130
  for (;;) {
129
131
  lastScreen = sample();
130
132
  samples++;
131
133
  if (kind === "grok")
132
134
  assertGrokSandboxNotRejected(lastScreen);
133
135
  if (opts.selectSteer?.(lastScreen))
134
- return { ready: false, samples, lastScreen, steer: true };
136
+ return { ready: false, samples, lastScreen, ...(inTime() ? { steer: true } : {}) };
135
137
  if (isAgentTuiIdleReady(kind, lastScreen)) {
136
138
  readyStreak++;
137
139
  if (readyStreak >= stableSamples)
138
- return { ready: true, samples, lastScreen };
140
+ return { ready: inTime(), samples, lastScreen };
139
141
  if (opts.turnSettled?.()) {
140
142
  settledStreak++;
141
143
  if (settledStreak >= settledSamples)
142
- return { ready: true, samples, lastScreen };
144
+ return { ready: inTime(), samples, lastScreen };
143
145
  }
144
146
  else if (settledStreak > 0) {
145
147
  // 記録の上でturnが始まった。短い間隔で数えた分を、11回の確かめへ持ち越さない。
package/dist/core.js CHANGED
@@ -351,6 +351,7 @@ function cleanupAgentState(name) {
351
351
  const p = path.join(dir, f);
352
352
  try {
353
353
  if (f.endsWith(".agent.json") ||
354
+ f.endsWith(".launch-exited") ||
354
355
  f.endsWith(".events.jsonl") ||
355
356
  f.endsWith(".wait.lock") ||
356
357
  f.endsWith(".claude-settings.json") ||
@@ -388,7 +389,7 @@ function offsetpath(name) {
388
389
  function lastcmdpath(name) {
389
390
  return path.join(SOCKDIR, name + ".lastcmd");
390
391
  }
391
- // mark:true 送信中フラグ。存在すれば waitCompletion が sentinel 完了検出(MARK_DONE_RE)を有効化する。
392
+ // mark:trueの送信ID。旧producerの"1"もpending flagとして読み取る。
392
393
  function markpath(name) {
393
394
  return path.join(SOCKDIR, name + ".mark");
394
395
  }
@@ -581,7 +582,15 @@ async function waitCompletion(name, untilStr, untilRegex, timeout) {
581
582
  }
582
583
  // mark:true 送信中なら sentinel 完了検出を有効化する。エコー(rc=%d)でなく実出力(rc=<数字>)だけに
583
584
  // 一致する数字アンカー MARK_DONE_RE を使うため、until のようにエコー部分一致で早期誤完了しない(B1)。
584
- const markActive = fs.existsSync(markpath(name));
585
+ let markId = null;
586
+ try {
587
+ markId = fs.readFileSync(markpath(name), "utf8").trim();
588
+ }
589
+ catch { /* no pending mark */ }
590
+ const markActive = markId !== null;
591
+ // shortcut: legacy "1" lacks correlation; retire the fallback after legacy pending commands are gone.
592
+ const markDone = markId === "1" ? MARK_DONE_RE : /^[0-9a-f]{32}$/.test(markId ?? "")
593
+ ? new RegExp(`${MARK_DONE_RE.source} id=${markId}(?:\\r?\\n|$)`) : null;
585
594
  for (;;) {
586
595
  let size = 0;
587
596
  try {
@@ -615,9 +624,10 @@ async function waitCompletion(name, untilStr, untilRegex, timeout) {
615
624
  }
616
625
  }
617
626
  // mark を until より先に判定(sentinel は確証つき完了。until はユーザ指定でエコー誤爆余地あり)。
618
- if (markActive && MARK_DONE_RE.test(neu)) {
627
+ if (markActive && markDone?.test(neu)) {
619
628
  try {
620
- fs.unlinkSync(markpath(name)); // 同一 sentinel での再発火を防ぐ
629
+ if (fs.readFileSync(markpath(name), "utf8").trim() === markId)
630
+ fs.unlinkSync(markpath(name));
621
631
  }
622
632
  catch {
623
633
  /* noop */
@@ -647,11 +657,12 @@ async function waitCompletion(name, untilStr, untilRegex, timeout) {
647
657
  if (safeStatSize(logpath(name)) !== size) {
648
658
  stable = 0;
649
659
  }
650
- else if (!until && !markActive && SHELLS.has(fg)) {
660
+ else if (!until && !markActive && SHELLS.has(fg) && size > start) {
661
+ // A native pipe may stay empty before the submitted input runs.
651
662
  await settlePaneLog(logpath(name), POLL);
652
663
  return [true, "quiescent"]; // 出力静止 ∧ シェル復帰 = 確証つき完了
653
664
  }
654
- else if (!until && !markActive && fg !== "") {
665
+ else if (!until && !markActive && fg !== "" && !SHELLS.has(fg)) {
655
666
  // ネスト中(前面が ssh/docker/REPL 等でシェル集合外)は quiescence の「シェル復帰」条件を
656
667
  // 原理的に満たせない。until も mark も無ければこれ以上待っても確証は増えない(until/dead/
657
668
  // quiescent/mark のいずれも発火し得ない)ので、出力静止時点で「未確定」のまま早期返却する。
@@ -886,8 +897,9 @@ export function send(name, text, o = {}) {
886
897
  writeLastcmd(name, o.launchShell ? atomicShellMultiline(text, o.launchShell) : text);
887
898
  if (o.rtk)
888
899
  text = rtkRewrite(text);
889
- if (o.mark)
890
- text = appendMarkSentinel(text, fg);
900
+ const markId = o.mark ? randomBytes(16).toString("hex") : null;
901
+ if (markId !== null)
902
+ text = appendMarkSentinel(text, fg, markId);
891
903
  assertSendTextSize(text, o.rtk || o.mark ? "変換後の送信文字列" : "送信文字列");
892
904
  const reportedText = text;
893
905
  // Agent composer paste is literal text even if native foreground metadata
@@ -900,10 +912,10 @@ export function send(name, text, o = {}) {
900
912
  });
901
913
  if (o.mark) {
902
914
  try {
903
- fs.writeFileSync(markpath(name), "1"); // waitCompletion に sentinel 完了検出を有効化させる
915
+ fs.writeFileSync(markpath(name), markId);
904
916
  }
905
917
  catch {
906
- /* noop(フラグ書けなくても until/quiescence 経路は生きる) */
918
+ throw new AitermError("完了印の送信IDを保存できません。文字列は送信していません。", 2);
907
919
  }
908
920
  }
909
921
  else {
@@ -1491,13 +1503,12 @@ export function selectHarnessProcesses(meta, rows, subtree) {
1491
1503
  .replace(/\.exe$/i, "").replace(/^-/, "").toLowerCase();
1492
1504
  const command = row.command.replace(/\\/g, "/").replace(/\.exe(?=["\s]|$)/gi, "").replace(/"/g, "");
1493
1505
  const tokens = row.command.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];
1494
- // `sh <script>` だけでなく、Windowsの `cmd.exe /c <launcher>.cmd` のように起動した実行ファイルが
1495
- // 2番目以降に来る形もある(Cursor公式installerは .cmd → .ps1 → node と中継する)。
1506
+ // native本体の先頭tokenと、sh/cmd経由で2番目以降に来るlauncherの両方を照合する。
1496
1507
  const launched = meta.agent_executable?.replace(/\\/g, "/");
1497
1508
  const sameFile = (value) => /^[A-Za-z]:\//.test(launched) ? value.toLowerCase() === launched.toLowerCase() : value === launched;
1498
- const launchedScript = launched !== undefined
1499
- && tokens.slice(1).some(token => sameFile(token.replace(/^["']|["']$/g, "").replace(/\\/g, "/")));
1500
- return launchedScript || (!SHELLS.has(executable) && executable !== "pwsh" && AGENT_COMMAND_PATTERNS[meta.kind].test(command));
1509
+ const launchedProcess = launched !== undefined
1510
+ && tokens.some(token => sameFile(token.replace(/^["']|["']$/g, "").replace(/\\/g, "/")));
1511
+ return launchedProcess || (!SHELLS.has(executable) && executable !== "pwsh" && AGENT_COMMAND_PATTERNS[meta.kind].test(command));
1501
1512
  };
1502
1513
  // WindowsのMSYS execでnative親子関係が切れる場合も、launch固有引数で相関する。
1503
1514
  const correlated = rows.filter(row => matches(row) && row.command.includes(meta.launch_id));
@@ -1574,9 +1585,21 @@ export function postStartupProcessCount(kind, activityRows, rows, startup, shape
1574
1585
  }
1575
1586
  return added.size;
1576
1587
  }
1577
- export function observeSession(name, cursor) {
1588
+ /** Native absence before the owned launcher returns does not prove CLI exit. */
1589
+ export function absentHarnessAlive(meta, platform = process.platform) {
1590
+ if (platform === "win32" && meta.windows_launch_exit_tracked === true) {
1591
+ try {
1592
+ return fs.readFileSync(agentMetadataPath(meta.aiterm_session, meta.launch_id) + ".launch-exited", "utf8") === meta.launch_id ? false : null;
1593
+ }
1594
+ catch {
1595
+ return null;
1596
+ }
1597
+ }
1598
+ return platform === "win32" && meta.kind === "cursor" ? null : false;
1599
+ }
1600
+ // Input admission needs the same native ownership proof, without activity capture or child-delivery scans.
1601
+ function observeSessionNative(name) {
1578
1602
  assertSessionName(name);
1579
- const previous = cursor === undefined ? null : decodeActivityCursor(cursor, name);
1580
1603
  const listed = listSessionsResult().sessions.find(session => session.session_id === name);
1581
1604
  const result = {
1582
1605
  schema: "aiterm.pty-observe-result.v1", session_id: name, observed_at: new Date().toISOString(),
@@ -1588,7 +1611,7 @@ export function observeSession(name, cursor) {
1588
1611
  post_startup_process_count: null },
1589
1612
  };
1590
1613
  if (!listed)
1591
- return result;
1614
+ return { result, native: null };
1592
1615
  const pane = tmux("display-message", "-p", "-t", name, "#{pane_pid}\t#{pane_dead}");
1593
1616
  if (pane.code !== 0)
1594
1617
  throw new AitermError("paneの生存情報を取得できません", 2);
@@ -1603,7 +1626,7 @@ export function observeSession(name, cursor) {
1603
1626
  result.state = "dead";
1604
1627
  result.reason = "pane_dead";
1605
1628
  result.harness_alive = meta ? false : null;
1606
- return result;
1629
+ return { result, native: null };
1607
1630
  }
1608
1631
  const rows = readRuntimeProcesses();
1609
1632
  const root = rows.find(row => row.pid === panePid);
@@ -1611,7 +1634,7 @@ export function observeSession(name, cursor) {
1611
1634
  result.state = "unknown";
1612
1635
  result.reason = root ? "ordinary_pty" : "native_pane_process_unresolved";
1613
1636
  if (!root)
1614
- return result;
1637
+ return { result, native: null };
1615
1638
  result.pane_process = processIdentity(root);
1616
1639
  const subtree = processSubtree(rows, root.pid);
1617
1640
  const candidates = meta ? selectHarnessProcesses(meta, rows, subtree) : [];
@@ -1619,13 +1642,14 @@ export function observeSession(name, cursor) {
1619
1642
  if (meta) {
1620
1643
  result.harness_process = agent ? processIdentity(agent) : null;
1621
1644
  // Cursorにはlaunch固有argvがない。Windowsの切れた親子関係だけで死亡を断定しない。
1622
- result.harness_alive = candidates.length ? true : isWin && meta.kind === "cursor" ? null : false;
1645
+ result.harness_alive = candidates.length ? true : absentHarnessAlive(meta);
1623
1646
  if (result.harness_alive === false) {
1624
1647
  result.state = "dead";
1625
1648
  result.reason = "harness_exited";
1626
1649
  }
1627
1650
  else if (result.harness_alive === null)
1628
- result.reason = "harness_process_unresolved";
1651
+ result.reason = isWin && meta.windows_launch_exit_tracked
1652
+ ? "harness_start_unconfirmed" : "harness_process_unresolved";
1629
1653
  else if (!agent)
1630
1654
  result.reason = "harness_process_ambiguous";
1631
1655
  result.process_identity = result.harness_process;
@@ -1636,6 +1660,15 @@ export function observeSession(name, cursor) {
1636
1660
  if (leaders.length > 1)
1637
1661
  result.reason = "process_identity_ambiguous";
1638
1662
  }
1663
+ return { result, native: { rows, root, subtree, meta, agent } };
1664
+ }
1665
+ export function observeSession(name, cursor) {
1666
+ assertSessionName(name);
1667
+ const previous = cursor === undefined ? null : decodeActivityCursor(cursor, name);
1668
+ const { result, native } = observeSessionNative(name);
1669
+ if (!native)
1670
+ return result;
1671
+ const { rows, root, subtree, meta, agent } = native;
1639
1672
  const captured = tmux("capture-pane", "-p", "-J", "-t", name, "-S", "-200");
1640
1673
  if (captured.code !== 0)
1641
1674
  throw new AitermError("paneの活動観測を取得できません", 2);
@@ -1822,6 +1855,7 @@ export function listSessionsResult(envKeys = [], runTmux = tmux) {
1822
1855
  const meta = tryLoadAgentMetadata(name);
1823
1856
  sessions.push({ session_id: name, current_command: normalizePaneCommand(command), attached: Number(attached) > 0,
1824
1857
  width: Number(width), height: Number(height), harness: meta ? agentHarness(meta.kind) : null,
1858
+ launch_id: meta?.launch_id ?? null,
1825
1859
  vendor_session_id: meta?.vendor_session_id ?? null, environment });
1826
1860
  }
1827
1861
  return { schema: "aiterm.pty-list-result.v1", observed_at: new Date().toISOString(), sessions };
@@ -2865,6 +2899,7 @@ async function acquireAgentSendFileLock(name, deadline, waitMs, untouched = AGEN
2865
2899
  }
2866
2900
  }
2867
2901
  async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
2902
+ const launchId = tryLoadAgentMetadata(name)?.launch_id;
2868
2903
  const waitMs = agentSendLockWaitMs;
2869
2904
  const deadline = performance.now() + waitMs;
2870
2905
  const previous = agentSendQueues.get(name) ?? Promise.resolve();
@@ -2893,6 +2928,8 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT) {
2893
2928
  const release = await acquireAgentSendFileLock(name, deadline, waitMs, untouched);
2894
2929
  agentSendHeld.add(name);
2895
2930
  try {
2931
+ if (tryLoadAgentMetadata(name)?.launch_id !== launchId)
2932
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
2896
2933
  return await run();
2897
2934
  }
2898
2935
  finally {
@@ -3014,7 +3051,10 @@ function loadAgentMetadata(name) {
3014
3051
  const parsedNative = m.execution_native === undefined ? null : executionNativeBindingSchema.safeParse(m.execution_native);
3015
3052
  if (parsedNative && !parsedNative.success)
3016
3053
  throw new AitermError("agent native bindingが不正です", 2);
3054
+ if (m.windows_launch_exit_tracked !== undefined && m.windows_launch_exit_tracked !== true)
3055
+ throw new AitermError("Windows launch exit metadataが不正です", 2);
3017
3056
  const executableFields = {
3057
+ ...(m.windows_launch_exit_tracked === true ? { windows_launch_exit_tracked: true } : {}),
3018
3058
  ...(m.agent_executable === undefined ? {} : { agent_executable: m.agent_executable }),
3019
3059
  ...(parsedNative?.success ? { execution_native: parsedNative.data } : {}),
3020
3060
  };
@@ -3928,7 +3968,7 @@ function agentTurnSettled(meta) {
3928
3968
  return false;
3929
3969
  }
3930
3970
  async function waitAgentTuiReady(name, meta, timeoutMs = AGENT_TUI_READY_TIMEOUT_MS, o = {}) {
3931
- const result = await waitAgentTuiReadyImpl(meta.kind, () => { o.checkInput?.(); return captureScreen(name, AGENT_TUI_READY_LINES); }, sleep, { timeoutMs, codexRateLimitRecovery: o.codexRateLimitRecovery, selectSteer: o.selectSteer,
3971
+ const result = await waitAgentTuiReadyImpl(meta.kind, () => o.checkInput?.() === false ? "" : captureScreen(name, AGENT_TUI_READY_LINES), sleep, { timeoutMs, codexRateLimitRecovery: o.codexRateLimitRecovery, selectSteer: o.selectSteer,
3932
3972
  launchLine: agentLaunchLines.get(name), ...(o.settledTurn ? { turnSettled: () => agentTurnSettled(meta) } : {}) });
3933
3973
  if (result.ready)
3934
3974
  agentLaunchLines.delete(name);
@@ -4324,8 +4364,7 @@ async function recoverCodexRateLimitModelSwitch(name, meta) {
4324
4364
  }
4325
4365
  /** ready待機中に現れたCodex利用上限modalも、同じ一時keep復旧へ戻す。 */
4326
4366
  async function waitAgentTuiReadyAfterCodexRateLimitRecovery(name, meta, timeoutMs, o = {}) {
4327
- o.checkInput?.();
4328
- let codexRateLimitModelSwitch = await recoverCodexRateLimitModelSwitch(name, meta);
4367
+ let codexRateLimitModelSwitch = o.checkInput?.() === false ? false : await recoverCodexRateLimitModelSwitch(name, meta);
4329
4368
  // 上限のmodalを閉じた直後は、画面が落ち着くのを11回の確かめで待つ。
4330
4369
  let ready = await waitAgentTuiReady(name, meta, timeoutMs, codexRateLimitModelSwitch ? { ...o, settledTurn: false, codexRateLimitRecovery: true } : o);
4331
4370
  if (!ready.ready && !ready.steer && !codexRateLimitModelSwitch) {
@@ -5500,16 +5539,25 @@ export async function agentGoal(input, origin = "automatic") {
5500
5539
  if (input.action !== "inspect")
5501
5540
  assertExecutionContext(input.session_id);
5502
5541
  const resolve = () => {
5503
- const generation = observeSessionGeneration(input.session_id);
5504
5542
  const meta = tryLoadAgentMetadata(input.session_id);
5505
- if (!generation.exists || generation.launch_id !== input.launch_id || meta?.launch_id !== input.launch_id)
5543
+ if (meta?.launch_id !== input.launch_id)
5544
+ return null;
5545
+ // Goal binding needs a live native process, not screen/CPU/activity collection.
5546
+ const pane = tmux("display-message", "-p", "-t", `=${input.session_id}:`, "#{pane_pid}\t#{pane_dead}");
5547
+ if (pane.code !== 0)
5548
+ return null;
5549
+ const fields = pane.stdout.trim().split("\t"), pid = Number(fields[0]);
5550
+ if (fields.length !== 2 || !Number.isSafeInteger(pid) || pid < 1 || fields[1] !== "0")
5551
+ return null;
5552
+ const rows = readRuntimeProcesses();
5553
+ if (!rows.some(row => row.pid === pid))
5506
5554
  return null;
5507
- const observed = observeSession(input.session_id);
5508
- if (observed.launch_id !== input.launch_id || observed.harness_alive !== true || observed.harness_process === null)
5555
+ const candidates = selectHarnessProcesses(meta, rows, processSubtree(rows, pid));
5556
+ if (candidates.length !== 1 || tryLoadAgentMetadata(input.session_id)?.launch_id !== input.launch_id)
5509
5557
  return null;
5510
5558
  return { session_id: input.session_id, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
5511
5559
  vendor_session_id: meta.vendor_session_id, codex_home: meta.codex_home, grok_home: meta.grok_home, cwd: meta.cwd ?? process.cwd(), executable: meta.agent_executable,
5512
- native_process: observed.harness_process };
5560
+ native_process: processIdentity(candidates[0]) };
5513
5561
  };
5514
5562
  const goalUi = (target) => {
5515
5563
  let inputStarted = false;
@@ -5652,13 +5700,14 @@ export async function agentGoal(input, origin = "automatic") {
5652
5700
  };
5653
5701
  return { ui, rows: () => { const text = read('updates.jsonl', true); return text === null ? [] : text.split('\n').filter(line => line.trim()).map(line => JSON.parse(line)); }, state: () => { const text = read('goal/state.json', true); return text === null ? null : JSON.parse(text); } };
5654
5702
  };
5655
- if (resolve()?.harness === 'grok-cli')
5703
+ const harness = resolve()?.harness;
5704
+ if (harness === 'grok-cli')
5656
5705
  return withAgentSendLock(input.session_id, () => manageGrokAgentGoal(input, { resolve,
5657
5706
  read: target => readFreshGrokGoal(target.vendor_session_id, grokPort(target)),
5658
5707
  canClear: target => grokGoalClearReady(grokPort(target).ui),
5659
5708
  clear: (target, before) => clearGrokGoal(target.vendor_session_id, before, grokPort(target)),
5660
5709
  }, origin));
5661
- if (resolve()?.harness === "claude-code")
5710
+ if (harness === "claude-code")
5662
5711
  return withAgentSendLock(input.session_id, () => manageClaudeAgentGoal(input, { resolve,
5663
5712
  read: target => readClaudeGoalDialog(target.vendor_session_id, goalUi(target), () => {
5664
5713
  const meta = tryLoadAgentMetadata(input.session_id);
@@ -6194,7 +6243,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6194
6243
  if (meta.kind !== "claude" || claudeColdStart) {
6195
6244
  // 上限のpanelを閉じた直後(Grok)は、画面が落ち着くのを11回の確かめで待つ。
6196
6245
  const recovery = await waitAgentTuiReadyAfterCodexRateLimitRecovery(name, meta, o.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS, { settledTurn: !limitDialog,
6197
- ...(pendingSend ? { checkInput: () => assertAgentSendHarness(name, meta),
6246
+ ...(pendingSend ? { checkInput: () => assertAgentSendHarness(name, meta, false, true),
6198
6247
  selectSteer: (screen) => agentPaneObservation(meta.kind, screen).state === "busy"
6199
6248
  && agentSendTurnRunning(meta, screen) } : {}) });
6200
6249
  codexRateLimitModelSwitch = recovery.codexRateLimitModelSwitch;
@@ -6384,7 +6433,7 @@ export async function sendAgentMessage(name, text, o = {}) {
6384
6433
  }
6385
6434
  async function sendAgentMessageInLock(name, text, o) {
6386
6435
  const meta = loadAgentMetadata(name);
6387
- assertAgentSendHarness(name, meta);
6436
+ assertAgentSendHarness(name, meta, false, true);
6388
6437
  // 前面回復は busy 判定より先(bash 前面のままだと画面の実行中マーカーを読んでも打鍵が届かない)。
6389
6438
  const paneInputRecovery = await ensureAgentOwnsPaneInput(name, meta.kind);
6390
6439
  if (meta.kind === "claude")
@@ -6402,15 +6451,17 @@ async function sendAgentMessageInLock(name, text, o) {
6402
6451
  // The same generation and existing process must still own this pending input.
6403
6452
  // Unknown native process observations remain unknown; only proven exit is a
6404
6453
  // death refusal. This check runs before waiting and inside each input admission.
6405
- function assertAgentSendHarness(name, meta, inputStarted = false) {
6406
- const current = observeSession(name);
6454
+ function assertAgentSendHarness(name, meta, inputStarted = false, waiting = false) {
6455
+ const current = observeSessionNative(name).result;
6407
6456
  if (current.exists && current.launch_id !== meta.launch_id)
6408
6457
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
6409
- if (!current.exists || current.harness_alive === false) {
6458
+ const starting = current.reason === "harness_start_unconfirmed";
6459
+ if (!current.exists || current.harness_alive === false || (starting && !waiting)) {
6410
6460
  throw new AitermError((inputStarted ? `agent session '${name}' の ${agentLabel(meta.kind)} への入力完了を確認できません。本文を再送しないでください。`
6411
6461
  : `agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`) +
6412
6462
  `\nstate=${current.state} reason=${current.reason}`, 2);
6413
6463
  }
6464
+ return !starting;
6414
6465
  }
6415
6466
  function agentSendTurnRunning(meta, screen) {
6416
6467
  // Claude's operation marker survives tool work without a busy indicator.
@@ -6885,6 +6936,9 @@ function prepareAgentLaunch(kind, opts = {}) {
6885
6936
  if (hasExecutionCreationScope())
6886
6937
  meta.execution_native = executionCreatedNativeBinding(sid);
6887
6938
  meta.agent_executable = bin;
6939
+ // Cursor retains its existing unresolved native-process contract.
6940
+ if (isWin && kind !== "cursor")
6941
+ meta.windows_launch_exit_tracked = true;
6888
6942
  // 席は通常の速度で始まる(Claude Code・Codexは起動の引数で明示する)。fast版のmodel IDで起こした時だけtrue。
6889
6943
  meta.fast = opts.fast_state === true;
6890
6944
  meta.model = opts.base_model !== undefined ? opts.base_model : model;
@@ -6909,7 +6963,7 @@ function prepareAgentLaunch(kind, opts = {}) {
6909
6963
  : grokAgentArgv(kind, bin, model, effort, prompt, meta);
6910
6964
  full = windowsAgentLaunchLine(cwd, [
6911
6965
  ...(meta?.kind === "grok" ? grokEnvEntries(meta) : []), ...agentEnvEntries(meta, sid, envVars),
6912
- ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")));
6966
+ ], windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), meta ? { file: agentMetadataPath(sid, meta.launch_id) + ".launch-exited", launch_id: meta.launch_id } : undefined);
6913
6967
  }
6914
6968
  else {
6915
6969
  const cmd = buildAgentCmd(kind, binForCmd, model, effort, opts.prompt ?? null, meta, cursorFast);
@@ -28,7 +28,7 @@ export function codexGoalUiState(raw) {
28
28
  const end = body.findIndex(line => {
29
29
  const value = plain(line);
30
30
  return line.some(c => c.decorated && c.text.trim())
31
- && (/^\s*\? for shortcuts|^\s*⚠\s*\d+ warnings|^\s*\S+\s+(?:default|minimal|low|medium|high|xhigh|ultra)\s*·\s/u.test(value));
31
+ && (/^\s*\? for shortcuts|^\s*⚠\s*\d+ warnings|^\s*\S+\s+(?:default|minimal|low|medium|high|xhigh|ultra)(?:[ \t]+[Ff]ast)?\s*·\s/u.test(value));
32
32
  });
33
33
  const content = (end < 0 ? body : body.slice(0, end));
34
34
  const cells = content.flat().filter(c => c.text.trim());
@@ -818,7 +818,7 @@ export function codexTuiReady(screen) {
818
818
  // 起動直後は製品header、長寿命sessionでは常駐footerがCodex TUIの識別子になる。
819
819
  // capture-paneは直近45行だけなので、会話が進むとheaderは正常に画面外へ流れる。表示名の空白は行内で受ける。
820
820
  const codexFrontend = screen.includes("OpenAI Codex")
821
- || /^[ \t]*\S[^\r\n]*?[ \t]+(?:default|low|medium|high|xhigh|max|ultra)(?:[ \t]+fast)?[ \t]+·[ \t]+\S[^\r\n]*\r?$/m.test(screen);
821
+ || /^[ \t]*\S[^\r\n]*?[ \t]+(?:default|low|medium|high|xhigh|max|ultra)(?:[ \t]+[Ff]ast)?[ \t]+·[ \t]+\S[^\r\n]*\r?$/m.test(screen);
822
822
  return codexFrontend && new RegExp(CODEX_COMPOSER_LINE).test(screen);
823
823
  }
824
824
  // 0.155までは文章のfooter、0.157からは「enter select · esc back」のようなkey hint行になった。
@@ -1297,7 +1297,7 @@ export function codexServiceTierNotices(screen) {
1297
1297
  * 出ていない時はnull: 通常の速度か、足元に段を出さない構成(独自のprovider等)かを、画面からは区別できない。
1298
1298
  */
1299
1299
  export function codexFooterShowsFast(screen) {
1300
- return screen.split("\n").slice(-6).some((line) => /^\s*\S+\s+(?:default|none|minimal|low|medium|high|xhigh|max|ultra)\s+fast\s+·\s/.test(line)) ? true : null;
1300
+ return screen.split("\n").slice(-6).some((line) => /^\s*\S+\s+(?:default|none|minimal|low|medium|high|xhigh|max|ultra)\s+[Ff]ast\s+·\s/.test(line)) ? true : null;
1301
1301
  }
1302
1302
  /** 入力欄へ `/fast` と打った時に、命令の候補として `/fast` が出ているか(出ていない時にEnterを押すと、文として送られる)。 */
1303
1303
  export function codexFastCommandOffered(screen) {
package/dist/index.js CHANGED
@@ -708,6 +708,7 @@ export function createAitermServer(options = {}) {
708
708
  session_id: z.string(), current_command: z.string(), attached: z.boolean(),
709
709
  width: z.number(), height: z.number(),
710
710
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).nullable(),
711
+ launch_id: z.string().nullable().optional().describe("一覧取得時のmanaged起動ID。通常PTYやmetadata不明時はnull、旧remote版は省略。操作時のfresh binding検証の代わりにはしない"),
711
712
  // 0.58.3より前の現地(remote)は返さないので、無い事も受ける。
712
713
  vendor_session_id: z.string().nullable().optional().describe("agent sessionのharness側の会話ID。Claude CodeとGrokは起動時に--session-idで渡した値(席の中で会話を移した後は追わない)、" +
713
714
  "CodexとCursorは分かった後の値。通常PTYと、まだ分からない席はnull"),
@@ -51,11 +51,14 @@ async function sendCommand(port, key, command, expectedResponse) {
51
51
  response += chunk.toString("utf8");
52
52
  });
53
53
  socket.on("end", () => {
54
- if (response.split(/\r?\n/).includes("OK") &&
55
- (expectedResponse == null || response.includes(expectedResponse)))
54
+ const authenticated = /^OK\r?\n/.exec(response);
55
+ if (!authenticated)
56
+ finish(new Error(`psmux authentication failed: ${response.trim() || "empty response"}`));
57
+ // AUTH is acknowledged before the command is read; only its separate reply can satisfy the command.
58
+ else if (response.slice(authenticated[0].length).trim() === (expectedResponse ?? ""))
56
59
  finish();
57
60
  else
58
- finish(new Error(`psmux authentication failed: ${response.trim() || "empty response"}`));
61
+ finish(new Error("psmux command response was not accepted; input may be partial, do not resend"));
59
62
  });
60
63
  socket.on("error", (error) => finish(error));
61
64
  });
@@ -662,16 +662,17 @@ export function adaptShellSubmission(name, text, options = {}) {
662
662
  return text;
663
663
  return atomicShellMultiline(text, options.shell || paneShellForSubmission(name));
664
664
  }
665
- export function appendMarkSentinel(text, foreground) {
665
+ export function appendMarkSentinel(text, foreground, id) {
666
666
  // 複数行入力の末尾はheredoc/here-string終端になり得るため、独立した次行へ置く。
667
667
  const separator = text.includes("\n") ? "\n" : "; ";
668
+ const suffix = id === undefined ? "" : ` id=${id}`;
668
669
  if (POWERSHELL_COMMANDS.has(foreground)) {
669
670
  // command echoに完成済みrc=<数字>を含めない。{0}を実行時formatして早期誤完了を防ぐ。
670
671
  return text + separator +
671
- "if ($?) { [Console]::WriteLine([Environment]::NewLine + ('<<<AITERM_DONE rc={0}>>>' -f 0)) }" +
672
- " else { [Console]::WriteLine([Environment]::NewLine + ('<<<AITERM_DONE rc={0}>>>' -f 1)) }";
672
+ `if ($?) { [Console]::WriteLine([Environment]::NewLine + ('<<<AITERM_DONE rc={0}>>>${suffix}' -f 0)) }` +
673
+ ` else { [Console]::WriteLine([Environment]::NewLine + ('<<<AITERM_DONE rc={0}>>>${suffix}' -f 1)) }`;
673
674
  }
674
- return text + separator + `printf '\\n<<<AITERM_DONE rc=%d>>>\\n' "$?"`;
675
+ return text + separator + `printf '\\n<<<AITERM_DONE rc=%d>>>${suffix}\\n' "$?"`;
675
676
  }
676
677
  // Windows の fs.Stats.mode は POSIX permission bit を持たず、常に 666/777 相当を報告する
677
678
  // (NTFS ACL は別体系)。既知制約の明示的受容として、Windows では group/other bit 検証を
package/docs/DESIGN.md CHANGED
@@ -86,7 +86,9 @@ agent入力欄への`bracketedPaste`は、制御文字の除去後も本文の
86
86
 
87
87
  `pty_read`は制御文字除去、反復圧縮、head+tail、command別reducerでcontext量を減らす。
88
88
  完了はprocess exit、shell sentinel、literal/regex `until`、shell復帰を伴うquiescence、timeoutを区別する。
89
+ 新しいmarkは送信IDを完了印と待機fileへ結び、旧commandの印を次の完了へ使わない。旧producerのpending flagは読取り互換を保ち、旧readの完了で新しい待機fileを消さない。ID保存失敗は入力前拒否。
89
90
  要求されたsentinel/untilを静止判定より優先し、nested shellで証拠がない状態を完了へ丸めない。
91
+ 静止による完了は読取りcursor以後の新しい出力を必要とし、native pipeが初回出力前に空のままでもshell名だけで完了へ進めない。
90
92
  sentinelの方言は端末runtimeが実効shellから決める。SSH先の現在の標準PowerShell promptを
91
93
  検出した場合は、Aiterm hostのOSに関係なくPowerShell構文を使う。過去のpromptでは切り替えない。
92
94
 
@@ -142,6 +144,7 @@ psmuxは切断の合図なしでsessionを止めるので、そのままでは
142
144
 
143
145
  `pty_observe`は存在、pane/harnessの生存、画面状態と理由、native process identityを分ける。
144
146
  PIDは開始識別子・argv digestと組にし、paneとharnessを同一視しない。特定できないidentityはnull。
147
+ 新しいWindows managed launch(Cursorを除く)はmetadataのwindows_launch_exit_trackedを立て、所有PowerShellのfinallyが`.agent.json.launch-exited`へ同launch IDを記録する。候補不在で記録が欠測・不一致ならharness_alive:null/reason:harness_start_unconfirmed、同IDがあればfalse/harness_exited。存在する本人候補は従来どおり優先する。準備待ち中は未確認を空sampleとして既deadlineで再観測し、native入力直前の未確認は拒否する。close/killAllは同sessionの終了記録も削除する。旧metadataとCursorのnative未解決は従来の判定を維持する。
145
148
  同じlaunchに属するnpm shimとnative本体は、中間の非候補processも含めた祖先関係から一つの起動として扱う。
146
149
  祖先を共有しない候補は別々に残し、複数候補を一つと推測しない。
147
150
  POSIXの停止状態はOSのprocess表から取得し、SIGSTOP中は残画面より優先して`blocked/harness_stopped`を返す。
@@ -196,6 +199,7 @@ Claude Codeはtool処理中に画面の実行中表示が消え、Stop hookの
196
199
  それ以外は新しいturnとしてdispatchする。
197
200
  振り分けから送り終えるまでの間には、起動直後の入力受付待ちなどの待ちが挟まる。同じsessionへの送信(`pty_send`、`claude_turn issue`、起動時prompt)は1本ずつ通し、
198
201
  重なった後の1通は前の1通が終わってから振り分け直す。同じprocessの中は着いた順の待ち行列、別のprocessの間はsocketの置き場の`<name>.agent-send.lock`で排他する。
202
+ この共通lockへ並ぶ時点の`launch_id`を保持し、取得後に同じ起動か確かめる。待機中の同名再作成では`EXECUTION_STALE_GENERATION`で拒否し、新しい席へ送信・設定変更・Goal操作を移さない。
199
203
  通常の`pty_send`は、本文未発行の入力受付待ちに生存busyが見えた時、同じrequest・送信lock内で既存steerを選ぶ。起動・設定の待ちはsteerへ変えない。
200
204
  送信前、準備中の観測、貼付とEnterの各native受付内で元launchとharness生存を再確認する。確定した死亡は30秒待たずに断り、貼付後の死亡は作用可能性を保持する(ADR 0134)。
201
205
  待つ上限は、起動から最初の描画を待つ上限と貼り付けの上限の和で、越えたら`AGENT_SEND_BUSY`で未送信を返す。判断の記録はADR 0088(`docs/adr/0088-one-agent-send-per-session.md`)。
@@ -208,6 +212,8 @@ Cursorのsubmitはadapterがextended keyboard protocolのEnterへ変換し、呼
208
212
  Codex・Grok・Cursorの席は、新しいturnを送るたびに入力受付を確かめる。起動の途中の入力欄を採らないよう、500msおきに11回続けて
209
213
  入力待ちを読む(ADR 0014)。席のharnessが自分の記録で「この起動でturnを1つ終えていて、次のturnを始めていない」と示している時は、
210
214
  100msおきに2回で通す(ADR 0097)。記録の上でturnが動いている間は、画面が入力待ちに見えても11回の確かめを通る。
215
+ 正の入力待ち期限は画面・履歴の読取が返った後にも照合し、期限後に返ったready/busyで入力やsteerを許可しない。
216
+ 入力の生存確認は公開observeと同じnative世代・本人の読取を共用し、不要な200行の活動captureや子配送集計は要求しない。専用45行の入力画面判定は保持し、公開observeは従来どおり活動観測まで行う。
211
217
  Codexの入力待ちは、入力欄の行(`›`、古い描画の`>`)がある時だけ読む。起動の見出しの`>_`は入力欄ではない。足元の警告をF2で開いた
212
218
  警告の画面は、入力欄の場所に出て鍵を受けるので、応答の要る画面と同じに数え、`pty_send`は打鍵の前に断る。Aitermは閉じない(ADR 0107)。
213
219
 
package/docs/RELEASE.md CHANGED
@@ -10,13 +10,18 @@ Aitermのreleaseはこのrepositoryが所有する。`.github/workflows/product-
10
10
  LinuxとWindowsを選ぶ。共通変更が混ざっても対象OSを落とさない。試験は依存graphから選び、依存を確定できない変更だけ全テストへ広げる。
11
11
  - 版番号だけの変更はJSONの実差分で識別し、Linuxでbuildと配布metadata・pack・文書確認を行う。依存や実行設定の変更は省略しない。
12
12
  文書だけなら文書検査、実装と文書の混在なら関連試験と文書検査を行う。
13
- - 週1回の定期実行(月曜 03:00 JST)と手動実行は、指定された環境で全テストを回す。定期実行の対象は3環境である。
13
+ - 手動実行の`test_files`へ既存試験fileのJSON配列を渡すと、指定OSでその試験だけを実行する。空欄は従来の全試験。
14
+ 選択実行のjob名は`selected`で、同headの全試験成功の再利用対象にしない。
15
+ - 週1回の定期実行(月曜 03:00 JST)と`test_files`未指定の手動実行は、指定された環境で全テストを回す。定期実行の対象は3環境である。
14
16
  - pushは、同じcommitの全テスト(手動実行か定期実行)がもう通っている環境を流さない。枝で手動実行を通してからmainへ早送りすると、
15
17
  mainのpushは変更分類と関門だけで終わる。通っている環境が一部の時は、残りの環境だけを流す。GitHubへ聞けない時は、選んだ環境を全部流す。
16
18
  同じcommitのpush・pull requestの成功は、試験を絞っている事があるので数えない(ADR 0115)。
17
19
  - tag push: 所有確認と、tagged commitが`origin/main`の祖先であることの確認だけを行い、npmへprovenance付きで
18
20
  publishする。同じcommitのmain CIの結果は待たない。
19
21
 
22
+ Windows試験の失敗時は、同じjob内で`test-failure-snapshots/`をhead/環境/attempt別artifactへ保存する(7日保持)。
23
+ 次のcheckout後もこの原本を回収できる。snapshotの無い失敗は詳細logを正本とし、artifact未取得を受入済みにしない。
24
+
20
25
  ## Producerとconsumerを公開前に揃える時
21
26
 
22
27
  Steerの未公開release sourceは` scripts/fixtures/steer-release-source.json `の固定commitと通常npm tgzで指定する。
@@ -29,7 +34,7 @@ Steerの未公開release sourceは` scripts/fixtures/steer-release-source.json `
29
34
  ## Release手順
30
35
 
31
36
  1. 変更に直結するfocused testを手元で通す。full regressionは手元で回さず、CIに任せる。
32
- 個別試験も`node --import ./test/seat-env.mjs --test ...`で起動する。稼働中の席の保存場所を試験へ継承しない。
37
+ 個別試験も`node scripts/run-seat-tests.mjs --test ...`で起動する。稼働中の席の保存場所を試験へ継承しない。
33
38
  2. `CHANGELOG.md`の`## [Unreleased]`へ内容を書き、mainへcommitしてpushする。
34
39
  3環境の全テストを先に通しておく時は、枝をpushして手動実行(`gh workflow run ci.yml --ref <枝> -f environment=all -f comparison_base=<前の公開commit>`)を
35
40
  1回流し、通ったcommitをそのままmainへ早送りする。Windowsの全テストは1回で済む。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.62.3",
3
+ "version": "0.62.5",
4
4
  "mcpName": "io.github.kitepon/aiterm-mcp",
5
5
  "description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [
@@ -66,10 +66,10 @@
66
66
  "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",
67
67
  "verify:release-commit": "node scripts/verify-release-commit.mjs",
68
68
  "release": "node scripts/release.mjs",
69
- "test:docs": "node --import ./test/seat-env.mjs --test test/repository-contract.test.mjs",
69
+ "test:docs": "node scripts/run-seat-tests.mjs --test test/repository-contract.test.mjs",
70
70
  "prepublishOnly": "npm run verify:release-commit && npm run build",
71
71
  "start": "node dist/index.js",
72
- "test": "npm run build && node --import ./test/seat-env.mjs --test test/seat-env.test.mjs && node --import ./test/seat-env.mjs --test scripts/verify-release-commit.test.mjs test/*.test.mjs",
72
+ "test": "npm run build && node scripts/run-seat-tests.mjs --test test/seat-env.test.mjs && node scripts/run-seat-tests.mjs --test scripts/verify-release-commit.test.mjs test/*.test.mjs",
73
73
  "ci:dependencies": "node scripts/install-ci-dependencies.mjs"
74
74
  },
75
75
  "dependencies": {