aiterm-mcp 0.63.11 → 0.63.13

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,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.13] - 2026-11-07
11
+
12
+ - Report current parent activity for Claude Code, Grok, Cursor and Antigravity through existing seat-turn metadata. Live original-pane observations retain opaque managed span identity/start through unchanged waits and absorbed input; unsupported tracking fields remain null. Settled native parent completion returns idle, ambiguous evidence remains unavailable. Codex tracking and waiters are unchanged.
13
+
14
+ ## [0.63.12] - 2026-11-07
15
+
16
+ - Remove filesystem input locks and the legacy socket/log-directory readiness predicate from managed-agent send and fresh-launch admission. Keep process-local order, current launch/native identity and stable TUI readiness checks. Independent local MCP and remote callers now serialize the same agent seat themselves; ordinary PTY/shell and standalone auth/approval file exclusion remain unchanged.
17
+ - Distinguish pre-input native absence (`AGENT_INPUT_TARGET_UNAVAILABLE`) from an actual TUI readiness refusal (`AGENT_INPUT_NOT_READY`) in error text. Public schemas/options are unchanged; these labels do not retrospectively identify older generic failures or prove vendor acceptance.
18
+
10
19
  ## [0.63.11] - 2026-11-06
11
20
 
12
21
  - Let any MCP client opt into existing host-controller routing with the initialize experimental capability `io.github.kitepon/aiterm-mcp/host-controller: {}`. The exact `bellteam` client name remains a backward-compatible alias; undeclared clients retain ordinary direct routing.
@@ -3058,7 +3067,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3058
3067
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3059
3068
  provenance.
3060
3069
 
3061
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.11...HEAD
3070
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.13...HEAD
3071
+ [0.63.13]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.12...v0.63.13
3072
+ [0.63.12]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.11...v0.63.12
3062
3073
  [0.63.11]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.10...v0.63.11
3063
3074
  [0.63.10]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.9...v0.63.10
3064
3075
  [0.63.9]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.8...v0.63.9
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.63.11** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.63.13** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
@@ -786,7 +786,7 @@ agent_launch({ "harness": "codex-cli", "remote": { "host": "rabbit" }, "cwd": "/
786
786
 
787
787
  `pty_send` はコマンドやpromptの意味を判定せず、指定された本文を端末へ送る。既定ではESC・ブラケットペースト終端などをサニタイズし、`pty_read`も制御文字を無害化して返す(`raw: true`はそのまま扱う)。コマンドの許可・拒否はshell、接続先、起動したharnessが所有する。
788
788
 
789
- 1回の `pty_send` が受理する本文はUTF-8で最大64KiB。同一sessionへの送信はaiterm processをまたいで直列化し、chunk同士の混線を防ぐ。全OSで長いPTY入力の欠落を避けるためplatformのmultiplexerへUTF-8境界を壊さない256-byte単位でpasteし、chunk間に10msのdrain間隔を置く。POSIX shellまたはPowerShellが前面にいる時のsanitize済み複数行は、改行を含まない単一入力へ符号化する。POSIXは`eval`、PowerShellはUTF-8のBase64を復元したscriptblockのdot-sourceを使い、変数と作業場所を現在のshellに保つ。shellがscript全体を所有してから先頭行を実行するため、途中で起動したpager/REPLが後続行を対話キーとして奪わない。単一行、`raw:true`、非shell前面は従来どおり直接PTYへpasteする。agent dispatchは本文全体を`ESC[200~/201~`で1回だけ包み、包んだ全体を同じchunkで流す。agent TUIには1回の貼り付けに見えるので画像pathが貼り付けの間で切れず、chunk投入中のキー解釈による語中文字化け・submit取り落としも抑える。途中chunkが失敗した場合は部分送信済みであることを明示し、自動でEnterを押さない。送信processの異常終了でlockが残った場合は送信前にfail-closedする。`pty_list`で対象sessionを確認し、`pty_close`で閉じてから同じsession IDを作り直す。公開の一括停止toolは存在しない。 POSIXの明示native execution構成では、unknown sendになった対象1席も`pty_close`で閉じて再作成できる。元requestはunknownのまま保持し、再送しない。発行中の操作、管理close自体のunknown、native identityが不明な席は引き続き拒否する。
789
+ 1回の `pty_send` が受理する本文はUTF-8で最大64KiB。Managed-agent callers serialize operations for the same seat across independent local MCP and remote clients. Aiterm keeps process-local ordering/native ownership; agent input has no filesystem send-lock or legacy directory readiness prerequisite. Ordinary PTY/shell and standalone auth/approval retain existing file exclusion.全OSで長いPTY入力の欠落を避けるためplatformのmultiplexerへUTF-8境界を壊さない256-byte単位でpasteし、chunk間に10msのdrain間隔を置く。POSIX shellまたはPowerShellが前面にいる時のsanitize済み複数行は、改行を含まない単一入力へ符号化する。POSIXは`eval`、PowerShellはUTF-8のBase64を復元したscriptblockのdot-sourceを使い、変数と作業場所を現在のshellに保つ。shellがscript全体を所有してから先頭行を実行するため、途中で起動したpager/REPLが後続行を対話キーとして奪わない。単一行、`raw:true`、非shell前面は従来どおり直接PTYへpasteする。agent dispatchは本文全体を`ESC[200~/201~`で1回だけ包み、包んだ全体を同じchunkで流す。agent TUIには1回の貼り付けに見えるので画像pathが貼り付けの間で切れず、chunk投入中のキー解釈による語中文字化け・submit取り落としも抑える。途中chunkが失敗した場合は部分送信済みであることを明示し、自動でEnterを押さない。For ordinary PTY/shell input, a lock left by a terminated sender still fails closed.`pty_list`で対象sessionを確認し、`pty_close`で閉じてから同じsession IDを作り直す。公開の一括停止toolは存在しない。 POSIXの明示native execution構成では、unknown sendになった対象1席も`pty_close`で閉じて再作成できる。元requestはunknownのまま保持し、再送しない。発行中の操作、管理close自体のunknown、native identityが不明な席は引き続き拒否する。
790
790
 
791
791
  BellTeamのmodel・effort・fast変更も、既存session世代に結合したnative管理要求で受け付ける。途中で世代・受付枠・停止状態が変われば、それ以降の打鍵を止める。途中まで変更した結果は作用不明のまま保持し、自動でやり直さない。
792
792
 
@@ -893,4 +893,6 @@ Grok 1.0.70のLinux読取は公式active_sessions.jsonのPID・開始tick・cwd
893
893
 
894
894
  ### Host-controller clients
895
895
 
896
+ Controller-only `pty_list` metadata `aiterm/seat_turns` reports all five harnesses. Codex retains real turn tracking; the other four use an opaque Aiterm-managed observed parent-work-span ID and first captured live-work time, with `event_cursor`, `interim_from` and `wait_process` explicitly null. Each read observes the original live parent pane. Positive settled parent terminal is `{state:"idle"}`; missing/ambiguous evidence is `null`. Observation-only rows provide neither non-Codex wait/interim support nor historical native UUID certification.
897
+
896
898
  Any MCP client can opt into the existing host-orchestration routing by declaring `capabilities.experimental["io.github.kitepon/aiterm-mcp/host-controller"] = {}` during initialize. This is routing identity, not authentication; source, generation, native identity and effect guards still apply. Clients without that declaration stay on the ordinary direct path. The exact client name `bellteam` remains a backward-compatible alias. A declared controller requests interim/follow metadata with `_meta["aiterm/caller"]` equal to its initialized client name (blank/missing name: `MCP client`); the old `BellTeam` marker is also preserved for compatibility. See [function map and data flow](https://github.com/kitepon/aiterm-mcp/blob/main/docs/architecture/host-controller.md). BellTeam's own caller can adopt the capability later; that migration is separate from this release.
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.63.11** · 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.63.13** · 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
 
@@ -844,7 +844,7 @@ Ordinary delivery and parent-return hooks do not acquire or wait for the shared
844
844
 
845
845
  `pty_send` does not interpret command or prompt meaning; it delivers the requested text to the terminal. By default it sanitizes ESC and bracketed-paste terminators, while `pty_read` neutralizes control characters in returned output (`raw: true` keeps them unchanged). The shell, remote endpoint, or launched harness owns command authorization.
846
846
 
847
- Each `pty_send` accepts at most 64 KiB of UTF-8 text. Sends to the same session are serialized across aiterm processes so chunks cannot interleave. Every OS pastes through its multiplexer in UTF-8-safe 256-byte chunks with a 10 ms drain interval; macOS, Linux, and WSL2 have all demonstrated silent middle/trailing loss when a long input is pushed without that boundary. Sanitized multiline text sent while a POSIX shell or PowerShell is in the foreground is encoded as one newline-free input (`eval` for POSIX shells; a dot-sourced, UTF-8 Base64-decoded scriptblock for PowerShell): the shell receives the complete script before it runs the first line, so a pager or REPL started mid-script cannot consume later lines as interactive keystrokes. Single-line input, `raw:true`, and non-shell frontends remain direct PTY pastes. Agent dispatches additionally wrap the whole text once in `ESC[200~/201~` and stream the wrapped text in the same chunks, so the agent TUI sees one paste (an image path is never split across pastes), hardening prompt injection against mid-word key-interpretation corruption and dropped submits. If a later chunk fails, aiterm reports the partial-send state and does not press Enter automatically. A lock left by a terminated sender fails closed before sending; use `pty_list` to confirm the affected session, close it with `pty_close`, then recreate the same session ID. There is no public kill-all tool.
847
+ Each `pty_send` accepts at most 64 KiB of UTF-8 text. Managed-agent callers must serialize operations for the same seat across independent local MCP and remote clients. Aiterm retains process-local ordering/native ownership, but agent input no longer acquires filesystem send locks or treats the legacy socket/log directory as readiness. Ordinary PTY/shell and standalone auth/approval still use their existing file exclusion. Every OS pastes through its multiplexer in UTF-8-safe 256-byte chunks with a 10 ms drain interval; macOS, Linux, and WSL2 have all demonstrated silent middle/trailing loss when a long input is pushed without that boundary. Sanitized multiline text sent while a POSIX shell or PowerShell is in the foreground is encoded as one newline-free input (`eval` for POSIX shells; a dot-sourced, UTF-8 Base64-decoded scriptblock for PowerShell): the shell receives the complete script before it runs the first line, so a pager or REPL started mid-script cannot consume later lines as interactive keystrokes. Single-line input, `raw:true`, and non-shell frontends remain direct PTY pastes. Agent dispatches additionally wrap the whole text once in `ESC[200~/201~` and stream the wrapped text in the same chunks, so the agent TUI sees one paste (an image path is never split across pastes), hardening prompt injection against mid-word key-interpretation corruption and dropped submits. If a later chunk fails, aiterm reports the partial-send state and does not press Enter automatically. For ordinary PTY/shell input, a lock left by a terminated sender fails closed before sending; use `pty_list` to confirm the affected session, close it with `pty_close`, then recreate the same session ID. There is no public kill-all tool.
848
848
 
849
849
  ## A human can watch
850
850
 
@@ -960,4 +960,6 @@ The Linux Grok 1.0.70 inspector binds the native current-session registry to the
960
960
 
961
961
  ### Host-controller clients
962
962
 
963
+ Controller-only `pty_list` metadata `aiterm/seat_turns` reports all five harnesses. Codex retains its real turn tracking; the other four use an opaque Aiterm-managed observed parent-work-span ID, first captured live-work time, and explicit null `event_cursor`, `interim_from`, `wait_process`. Each observation reads the original live parent pane; long unchanged waits keep identity when native occupancy remains visible. A positive settled parent terminal is `{state:"idle"}`; missing or ambiguous evidence is `null`. These observation-only rows do not provide non-Codex wait/interim support or certify historical native turn UUIDs.
964
+
963
965
  Any MCP client can opt into the existing host-orchestration routing by declaring `capabilities.experimental["io.github.kitepon/aiterm-mcp/host-controller"] = {}` during initialize. This is routing identity, not authentication; source, generation, native identity and effect guards still apply. Clients without that declaration stay on the ordinary direct path. The exact client name `bellteam` remains a backward-compatible alias. A declared controller requests interim/follow metadata with `_meta["aiterm/caller"]` equal to its initialized client name (blank/missing name: `MCP client`); the old `BellTeam` marker is also preserved for compatibility. See [function map and data flow](https://github.com/kitepon/aiterm-mcp/blob/main/docs/architecture/host-controller.md). BellTeam's own caller can adopt the capability later; that migration is separate from this release.
@@ -1,9 +1,9 @@
1
1
  import { antigravityPaneObservation } from "./harnesses/antigravity.js";
2
2
  import { AitermError } from "./errors.js";
3
- import { grokTuiReady, grokTuiBusy, grokPaneObservation, grokLaunchBlockingDialog, assertGrokSandboxNotRejected, GROK_COMPOSER_MARKER_RE } from "./harnesses/grok.js";
3
+ import { grokPromptAwaitingAccept, grokTuiReady, grokTuiBusy, grokPaneObservation, grokLaunchBlockingDialog, assertGrokSandboxNotRejected, GROK_COMPOSER_MARKER_RE } from "./harnesses/grok.js";
4
4
  import { codexTuiReady, codexTuiBusy, codexPaneObservation, codexRateLimitModelSwitchDialog, CODEX_COMPOSER_MARKER_RE } from "./harnesses/codex.js";
5
5
  import { claudeTuiReady, claudeTuiBusy, claudePaneObservation, claudeLoginMethodMenu, claudeStartupAction, CLAUDE_COMPOSER_MARKER_RE } from "./harnesses/claude.js";
6
- import { cursorTuiReady, cursorTuiBusy, cursorPaneObservation, CURSOR_COMPOSER_CONTENT_MARKER_RE } from "./harnesses/cursor.js";
6
+ import { cursorPromptHooksRunning, cursorTuiReady, cursorTuiBusy, cursorPaneObservation, CURSOR_COMPOSER_CONTENT_MARKER_RE } from "./harnesses/cursor.js";
7
7
  const AGENT_DONE_SETTLE_MIN_MS = 250;
8
8
  const AGENT_DONE_SCREEN_SETTLE_POLL_MS = 100;
9
9
  const AGENT_DONE_SCREEN_SETTLE_MAX_POLLS = 5;
@@ -298,3 +298,63 @@ export function __testSetAgentTuiReadyStableSamples(value) {
298
298
  }
299
299
  agentTuiReadyStableSamplesTestOverride = value;
300
300
  }
301
+ /** Only the current native composer/progress/footer can establish occupancy. */
302
+ // shortcut: pane snapshots cannot certify hidden native turn boundaries, use a continuous native lifecycle when that distinction is required.
303
+ export function parentPaneEvidence(kind, screen) {
304
+ const lines = screen.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trimEnd().split(/\r?\n/);
305
+ if (kind === "codex")
306
+ return "unknown";
307
+ if (agentPaneObservation(kind, lines.slice(-32).join("\n")).state === "blocked")
308
+ return "unknown";
309
+ let marker = -1;
310
+ const composer = kind === "claude" ? /^\s*❯(?:\s|$)/u
311
+ : kind === "grok" ? /^\s*│\s*[❯>](?:\s|$)/u
312
+ : kind === "cursor" ? /^\s*(?:→|->|>)(?:\s|$)/u : /^\s*>\s*$/u;
313
+ for (let i = lines.length - 1; i >= 0; i--)
314
+ if (composer.test(lines[i])) {
315
+ marker = i;
316
+ break;
317
+ }
318
+ if (marker < 0)
319
+ return "unknown";
320
+ let start = marker;
321
+ if (kind === "claude") {
322
+ if (marker < 1 || !/^\s*─{8,}\s*$/u.test(lines[marker - 1]))
323
+ return "unknown";
324
+ start = marker - 2;
325
+ while (start > 0 && (!lines[start].trim() || /^\s/u.test(lines[start])))
326
+ start--;
327
+ }
328
+ else if (kind === "grok" || kind === "antigravity") {
329
+ start = marker - 1;
330
+ while (start > 0 && (!lines[start].trim() || /^[╭─\s]+$/u.test(lines[start])))
331
+ start--;
332
+ }
333
+ const current = lines.slice(Math.max(0, start)).join("\n");
334
+ if (kind === "grok" && grokPromptAwaitingAccept(current))
335
+ return "unknown";
336
+ if (kind === "cursor" && cursorPromptHooksRunning(screen))
337
+ return "unknown";
338
+ if (kind === "claude" && /running UserPromptSubmit hook/u.test(current))
339
+ return "unknown";
340
+ const observed = agentPaneObservation(kind, current);
341
+ if (observed.state === "blocked" || observed.state === "unknown")
342
+ return "unknown";
343
+ if (kind === "claude" && observed.state === "idle"
344
+ && !/^[·✢✳✶✻✽*∗] [^…\n]+ for \d[^…\n]*$/mu.test(current))
345
+ return "unknown";
346
+ if (kind === "cursor") {
347
+ if (/^\s*ctrl\+c to stop\s*$/imu.test(lines.slice(marker + 1).join("\n")))
348
+ return "busy";
349
+ if (observed.state === "busy")
350
+ return "unknown";
351
+ }
352
+ if (kind === "grok" && observed.state === "busy"
353
+ && !/^\s*(?:[│┃]\s*)?(?:Waiting for response|Responding(?:…|\.\.\.)).*$/mu.test(current))
354
+ return "unknown";
355
+ if (kind === "antigravity" && observed.state === "busy"
356
+ && !/^\s*(?:[^\p{L}\p{N}\s]{1,3}\s+)?(?:Generating|Working)(?:…|\.\.\.).*$/mu.test(current)
357
+ && !/^\s*esc to interrupt\s*$/imu.test(lines.slice(marker + 1).join("\n")))
358
+ return "unknown";
359
+ return observed.state === "busy" ? "busy" : "ready";
360
+ }
package/dist/core.js CHANGED
@@ -8,9 +8,10 @@ import { loadAgentMetadata, tryLoadAgentMetadata } from "./agent-metadata-reader
8
8
  import { nativePaneTarget } from "./native-session.js";
9
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
10
  import { inspectIdleSettings, inspectCodexResumeSettings, codexRecoveryComposer } from "./harnesses/idle-settings.js";
11
- import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
11
+ import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, parentPaneEvidence, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
12
12
  export { launchEchoIsLastOnScreen, __testSetAgentTuiReadyStableSamples } from "./agent-screen-observation.js";
13
13
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
14
+ import { withManagedSpan, observeManagedSpan } from "./managed-seat-turn.js";
14
15
  /**
15
16
  * core — CLI/MCP が共有する端末操作とharness進行(Node/TS 版)。
16
17
  *
@@ -45,7 +46,7 @@ import { withExecutionInterruptEffectScope, bindExecutionNativeTarget, beforeExe
45
46
  import { ExecutionError } from "./execution-wire.js";
46
47
  import { readExecutionParentProcess } from "./execution-parent-process.js";
47
48
  import { isCursorMcpClient } from "aiterm-steer-delivery";
48
- import { antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
49
+ import { antigravityBinding, antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
49
50
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
50
51
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
51
52
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
@@ -63,7 +64,7 @@ import { isDeepStrictEqual } from "node:util";
63
64
  import { grokAuthPlan, grokAuthStatus, grokAuthPane, GROK_MODEL_DEFAULTS, realGrokHome, resolveAndValidateGrokAuth, assertGrokModelAvailable, grokModelChoices, grokModelFromFooter, grokFooterModelName, grokModelDefaultsFromBody, restoreGrokModelDefaults, grokEventsTranscript, grokSessionDirectory, latestGrokCompletion, grokTurnSettled, observeGrokDone, buildGrokAgentCmd, grokAgentArgv, grokLaunchNote, grokEnvTokens, grokEnvEntries, grokTuiReady, grokPaneObservation, GROK_INTERRUPT_KEY, grokRateLimitDialog, grokPromptAwaitingAccept, grokUnacceptedPromptRestored, grokStartupAction, grokFooterHasConfiguration, grokTranscriptText, createGrokAgentMetadata, } from "./harnesses/grok.js";
64
65
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, codexWorkingResumeConfiguration, captureCodexRecoveryProof, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRootTranscript, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
65
66
  import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, claudeFailureCategory, } from "./harnesses/claude.js";
66
- import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
67
+ import { cursorAuthPlan, cursorAuthStatus, cursorAuthPane, bindCursorTranscriptSession, cursorTurnBoundary, latestCursorCompletion, cursorTranscript, cursorTranscriptSessionId, observeCursorDone, cursorTranscriptText, assertCursorAuthenticationReady, assertCursorModelAvailable, cursorModelChoices, cursorModelIsFastVariant, cursorFastParameter, cursorHeaderShowsFast, cursorPickerView, cursorEffortSelected, cursorParameterRows, cursorUserConfigPath, CURSOR_DEFAULT_MODEL_KEYS, realCursorHome, buildCursorAgentCmd, cursorAgentArgv, cursorPromptWithLineage, createCursorAgentMetadata, cursorLaunchNote, cursorEffortNavigation, cursorTuiReady, cursorPaneObservation, CURSOR_INTERRUPT_KEY, cursorPromptHooksRunning, cursorUsageLimit, CURSOR_SUBMIT_SEQUENCE, validateCursorModelEffort, } from "./harnesses/cursor.js";
67
68
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
68
69
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
69
70
  import { resolveAgentBin, resolveThroughlineBin, runThroughlineHandoffContext, isWindowsNativeExecutable, isUsableAgentExecutableFile, agentBinForPaneShell, resolveWinPaneShell, windowsAgentArgv, windowsAgentLaunchLine } from "./agent-resolver.js";
@@ -101,7 +102,6 @@ const SESSION_SEND_LOCK_POLL_MS = 25;
101
102
  // 同じagent sessionへの送信が重なった時に、前の1通を待つ上限(ADR 0088)。
102
103
  // 起動から最初の描画を待つ上限と、貼り付けの上限の和。前の1通が正常に進んでいる間は待ち切れる長さにする。
103
104
  const AGENT_SEND_LOCK_WAIT_MS = AGENT_TUI_FIRST_DRAW_TIMEOUT_MS + SESSION_SEND_LOCK_WAIT_MS;
104
- const AGENT_SEND_LOCK_POLL_MS = 50;
105
105
  const PASTE_MARKERS_RE = /\x1b\[20[01]~/g;
106
106
  // よく使う制御キーの別名(tmux のキー名へ)
107
107
  const KEYMAP = {
@@ -391,7 +391,7 @@ function cleanupAgentState(name) {
391
391
  f.endsWith(".steers.jsonl") ||
392
392
  f.endsWith(".auth.json"))
393
393
  fs.unlinkSync(p);
394
- else if (f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".home") || f.endsWith(".resume-restore.d")) {
394
+ else if (f.endsWith(".seat-span.d") || f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".home") || f.endsWith(".resume-restore.d")) {
395
395
  fs.rmSync(p, { recursive: true, force: true });
396
396
  }
397
397
  }
@@ -829,7 +829,7 @@ export function send(name, text, o = {}) {
829
829
  `正しく展開されません。until で完了パターンを指定してください。`, 2);
830
830
  }
831
831
  }
832
- const releaseSendLock = acquireSessionSendFileLock(name);
832
+ const releaseSendLock = isAgentSession(name) ? () => { } : acquireSessionSendFileLock(name);
833
833
  try {
834
834
  // managed Claudeの通常送信は、lastcmd/mark/PTYのどれにも触れる前に拒否する。
835
835
  // 拒否した呼び出しが古いmarkを消したり偽のmarkを残すと、後続readが存在しない
@@ -3101,7 +3101,7 @@ function acquireSessionSendFileLock(name) {
3101
3101
  // ── 同じagent sessionへの送信を1本ずつ通す(ADR 0088) ────
3102
3102
  // 振り分け(差し込みか新しいturnか)から送り終えるまでの間に、入力受付待ちなどの待ちが挟まる。
3103
3103
  // その間に次の1通が同じ状態を読むと、Claudeはturnの印の取り合いで後の1通が断られ、他のharnessは同じ入力欄へ2回貼る。
3104
- // 同じprocessの中は着いた順の待ち行列、別のprocessの間はfileで排他し、後の1通は前の1通が終わってから振り分け直す。
3104
+ // Process-local order/ownership remains; independent MCP/remote clients serialize the same managed seat themselves.
3105
3105
  const agentSendQueues = new Map();
3106
3106
  const agentSendHeld = new Set();
3107
3107
  const agentSendOwner = new AsyncLocalStorage();
@@ -3213,48 +3213,6 @@ function agentSendBusyError(name, pid, waitMs, untouched = AGENT_SEND_UNSENT) {
3213
3213
  return new AitermError(`AGENT_SEND_BUSY: agent session '${name}' は${pid != null ? `別プロセス(pid ${pid})` : "先に受け付けた送信"}の処理中です。` +
3214
3214
  `${waitMs}ms待っても順番が来ませんでした。${untouched}`, 2);
3215
3215
  }
3216
- async function acquireAgentSendFileLock(name, deadline, waitMs, untouched = AGENT_SEND_UNSENT) {
3217
- const p = agentSendLockPath(name);
3218
- let checkedOwner = null;
3219
- let checkedOwnerReplaced = false;
3220
- for (;;) {
3221
- let token;
3222
- try {
3223
- token = tryCreateOwnedLock(p);
3224
- }
3225
- catch (e) {
3226
- // socketの置き場が無ければ、守る相手のsessionにも届かない。lockを取らずに進め、送信側の今まで通りの断りを返す。
3227
- if (e.code === "ENOENT")
3228
- return () => { };
3229
- throw e;
3230
- }
3231
- if (token !== null)
3232
- return () => releaseOwnedLock(p, token);
3233
- const probe = probeAgentSendLock(name);
3234
- let dead = !probe.live;
3235
- let replacedToken = null;
3236
- // 生きて見える持ち主は、初めて見た時に1回、本人かを確かめる。結果は覚え、待つ間にOSへ照会し直さない。
3237
- if (!dead && probe.pid != null) {
3238
- const owner = `${probe.pid}@${probe.at}`;
3239
- if (owner !== checkedOwner) {
3240
- checkedOwner = owner;
3241
- checkedOwnerReplaced = agentSendLockOwnerReplaced(probe);
3242
- }
3243
- if (checkedOwnerReplaced) {
3244
- dead = true;
3245
- replacedToken = probe.token ?? null;
3246
- }
3247
- }
3248
- if (dead && reapDeadAgentSendLock(name, replacedToken) === "stuck") {
3249
- throw new AitermError(`agent session '${name}' に、終了した送信のlockを片付ける途中で残った印があります。` +
3250
- `自動回収は並行送信の混線を招くため行いません。文字列は送信していません。` +
3251
- `pty_listで対象を確認し、pty_closeでsessionを閉じてから同じIDで再作成してください`, 2);
3252
- }
3253
- if (performance.now() >= deadline)
3254
- throw agentSendBusyError(name, dead ? null : probe.pid, waitMs, untouched);
3255
- await sleep(AGENT_SEND_LOCK_POLL_MS);
3256
- }
3257
- }
3258
3216
  function withAgentNativeOperation(name, mutates, body) {
3259
3217
  assertSessionName(name);
3260
3218
  if (!isAgentSession(name))
@@ -3273,9 +3231,6 @@ function withAgentNativeOperation(name, mutates, body) {
3273
3231
  };
3274
3232
  if (!mutates || owns)
3275
3233
  return execute();
3276
- const token = tryCreateOwnedLock(agentSendLockPath(name));
3277
- if (!token)
3278
- throw unavailable();
3279
3234
  const mine = Symbol(name);
3280
3235
  agentSendHeld.add(name);
3281
3236
  activeAgentSendOwner.set(name, mine);
@@ -3285,13 +3240,11 @@ function withAgentNativeOperation(name, mutates, body) {
3285
3240
  finally {
3286
3241
  activeAgentSendOwner.delete(name);
3287
3242
  agentSendHeld.delete(name);
3288
- releaseOwnedLock(agentSendLockPath(name), token);
3289
3243
  }
3290
3244
  }
3291
3245
  async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinResume = true) {
3292
3246
  const launchId = tryLoadAgentMetadata(name)?.launch_id;
3293
3247
  const waitMs = agentSendLockWaitMs;
3294
- const deadline = performance.now() + waitMs;
3295
3248
  const previous = agentSendQueues.get(name) ?? Promise.resolve();
3296
3249
  let leave;
3297
3250
  const mine = new Promise((resolve) => {
@@ -3315,7 +3268,6 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinRe
3315
3268
  clearTimeout(timer);
3316
3269
  if (!myTurn)
3317
3270
  throw agentSendBusyError(name, null, waitMs, untouched);
3318
- const release = await acquireAgentSendFileLock(name, deadline, waitMs, untouched);
3319
3271
  const mine = Symbol(name);
3320
3272
  agentSendHeld.add(name);
3321
3273
  activeAgentSendOwner.set(name, mine);
@@ -3328,8 +3280,6 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinRe
3328
3280
  return await agentSendOwner.run(mine, async () => {
3329
3281
  const meta = pinResume ? tryLoadAgentMetadata(name) : null;
3330
3282
  if (meta && !readAgentLifecycle(meta)) {
3331
- if (!fs.existsSync(SOCKDIR) && !meta.resumed_from)
3332
- throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`, 2);
3333
3283
  const uncertain = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "復帰対象のnativeを確認できません。本文は送信していません。", name, meta.launch_id);
3334
3284
  let failed;
3335
3285
  try {
@@ -3365,7 +3315,6 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinRe
3365
3315
  finally {
3366
3316
  activeAgentSendOwner.delete(name);
3367
3317
  agentSendHeld.delete(name);
3368
- release();
3369
3318
  }
3370
3319
  }
3371
3320
  finally {
@@ -3730,12 +3679,12 @@ export function readSessionInterimWords(name, after, from = null) {
3730
3679
  return readInterimWords(loadAgentMetadata(name), after, from);
3731
3680
  }
3732
3681
  /**
3733
- * BellTeamのため(ADR 0122): agent sessionの、記録の上の今の番。画面は読まない。
3734
- * BellTeamは、自分の送信で始めていない番(Aitermの子の結果が始めた番など)を、ここで見つけて追う。
3735
- * 動いている番のwait_processは、その番の終わりで返る。
3682
+ * Existing caller-only seat metadata. Codex keeps native tracking; other four
3683
+ * read current original-pane activity, with observation identity and no waiter.
3736
3684
  */
3737
3685
  export function readSeatTurns(sessionIds) {
3738
3686
  const seats = [];
3687
+ const observedAt = new Map();
3739
3688
  for (const name of sessionIds) {
3740
3689
  const meta = tryLoadAgentMetadata(name);
3741
3690
  if (!meta)
@@ -3743,14 +3692,100 @@ export function readSeatTurns(sessionIds) {
3743
3692
  let turn = null;
3744
3693
  try {
3745
3694
  const state = agentDormantState(meta);
3746
- turn = state ? (state === "hibernated" && observeSession(name).state === "hibernated" ? { state: "idle" } : null) : codexSeatTurn(meta);
3695
+ turn = state ? (state === "hibernated" && observeSession(name).state === "hibernated" ? { state: "idle" } : null)
3696
+ : meta.kind === "codex" ? codexSeatTurn(meta) : readManagedSeatTurn(meta);
3747
3697
  }
3748
3698
  catch { /* 読めない席は、分からないまま返す */ }
3699
+ if (meta.kind !== "codex")
3700
+ observedAt.set(name, performance.now());
3749
3701
  seats.push({ session_id: name, launch_id: meta.launch_id, harness: agentHarness(meta.kind),
3750
- turn: turn?.state === "running" ? { ...turn, wait_process: agentWaitProcess(name, turn.event_cursor) } : turn });
3702
+ turn: turn?.state === "running" && turn.event_cursor !== null
3703
+ ? { ...turn, wait_process: agentWaitProcess(name, turn.event_cursor) } : turn });
3751
3704
  }
3705
+ for (const seat of seats)
3706
+ if (seat.harness !== "codex-cli"
3707
+ && performance.now() - observedAt.get(seat.session_id) >= 15_000)
3708
+ seat.turn = null;
3752
3709
  return { schema: "aiterm.seat-turns.v1", seats };
3753
3710
  }
3711
+ function managedSeatConversation(meta) {
3712
+ if (meta.kind === "antigravity") {
3713
+ const bound = antigravityBinding(meta);
3714
+ return bound && (!meta.vendor_session_id || meta.vendor_session_id === bound.conversation_id) ? bound.conversation_id : null;
3715
+ }
3716
+ if (meta.kind === "cursor") {
3717
+ const file = cursorTranscript(meta);
3718
+ const id = file ? cursorTranscriptSessionId(file) : null;
3719
+ return id && (!meta.vendor_session_id || meta.vendor_session_id === id) ? id : null;
3720
+ }
3721
+ return meta.vendor_session_id;
3722
+ }
3723
+ function managedSeatTerminal(meta) {
3724
+ const file = meta.kind === "cursor" ? cursorTranscript(meta) : meta.kind === "grok" ? grokEventsTranscript(meta) : meta.event_file;
3725
+ if (!file)
3726
+ return null;
3727
+ try {
3728
+ const before = fs.statSync(file);
3729
+ if (!before.isFile() || before.size === 0 || readFileRange(file, before.size - 1, before.size).toString() !== "\n")
3730
+ return null;
3731
+ const done = latestAgentDoneEvent(meta);
3732
+ let identity = done ? { ...done, at: null } : null;
3733
+ if (done && (meta.kind === "claude" || meta.kind === "antigravity")) {
3734
+ identity = null;
3735
+ const tail = readFileRange(file, Math.max(0, before.size - AGENT_EVENT_TAIL_BYTES), before.size).toString("utf8");
3736
+ for (const line of tail.split("\n")) {
3737
+ try {
3738
+ const raw = JSON.parse(line), parsed = parseAgentDoneEvent(line, meta);
3739
+ if (parsed.event && typeof raw.at === "string" && Number.isFinite(Date.parse(raw.at)))
3740
+ identity = line;
3741
+ }
3742
+ catch { /* An incomplete/unrelated record is not a positive terminal. */ }
3743
+ }
3744
+ }
3745
+ const after = fs.statSync(file);
3746
+ if (!done || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
3747
+ || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
3748
+ return null;
3749
+ // Cursor/Grok adapters supply read-time `at`; it is not a lifecycle boundary.
3750
+ return identity ? createHash("sha256").update(JSON.stringify(identity)).digest("hex") : null;
3751
+ }
3752
+ catch {
3753
+ return null;
3754
+ }
3755
+ }
3756
+ function readManagedSeatTurn(meta) {
3757
+ const started = performance.now();
3758
+ const result = withManagedSpan(meta, file => {
3759
+ const conversation = managedSeatConversation(meta);
3760
+ if (!conversation)
3761
+ return null;
3762
+ const proof = readAgentResumeNative(meta);
3763
+ if (proof)
3764
+ verifyAgentResumeNative(meta, proof);
3765
+ const before = observeSessionNative(meta.aiterm_session);
3766
+ const live = before.result;
3767
+ if (live.pane_alive !== true || live.harness_alive !== true || !live.pane_process || !live.harness_process
3768
+ || before.native?.agent?.stopped === true || live.launch_id !== meta.launch_id)
3769
+ return null;
3770
+ const captured = tmux("capture-pane", "-p", "-J", "-t", proof ? nativePaneTarget(proof) : meta.aiterm_session);
3771
+ if (captured.code !== 0)
3772
+ return null;
3773
+ const evidence = parentPaneEvidence(meta.kind, captured.stdout);
3774
+ const terminal = managedSeatTerminal(meta);
3775
+ const observedAfter = observeSessionNative(meta.aiterm_session), after = observedAfter.result;
3776
+ if (proof)
3777
+ verifyAgentResumeNative(meta, proof);
3778
+ if (after.pane_alive !== true || after.harness_alive !== true || observedAfter.native?.agent?.stopped === true
3779
+ || !isDeepStrictEqual(after.pane_process, live.pane_process) || !isDeepStrictEqual(after.harness_process, live.harness_process)
3780
+ || !isDeepStrictEqual(loadAgentMetadata(meta.aiterm_session), meta)
3781
+ || managedSeatConversation(meta) !== conversation || agentDormantState(meta) !== null
3782
+ || performance.now() - started >= 15_000)
3783
+ return null;
3784
+ const binding = JSON.stringify([meta.aiterm_session, meta.launch_id, meta.kind, conversation, proof, live.pane_process, live.harness_process]);
3785
+ return observeManagedSpan(file, binding, evidence, terminal, new Date().toISOString());
3786
+ });
3787
+ return performance.now() - started < 15_000 ? result : null;
3788
+ }
3754
3789
  /** agent harness の構造化 transcript から直近完了ターンの最終回答と相関情報を読む。 */
3755
3790
  export async function readAgentTranscriptResult(name, o = {}) {
3756
3791
  const meta = loadAgentMetadata(name);
@@ -6860,7 +6895,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6860
6895
  }
6861
6896
  // 待たずに断るのは、応答が要る既知の画面(承認・確認のmodal)の時。どの画面で断ったかを残す。
6862
6897
  const state = agentPaneObservation(meta.kind, ready.lastScreen);
6863
- throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。` +
6898
+ throw new AitermError(`AGENT_INPUT_NOT_READY: agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。` +
6864
6899
  "少し後で pty_read(screen:true) を確認し、TUI が起動済みなら再度 pty_send してください。" +
6865
6900
  `\nstate=${state.state} reason=${state.reason}`, 2);
6866
6901
  }
@@ -7062,7 +7097,7 @@ function assertAgentSendHarness(name, meta, inputStarted = false, waiting = fals
7062
7097
  const starting = current.reason === "harness_start_unconfirmed";
7063
7098
  if (!current.exists || current.harness_alive === false || (starting && !waiting)) {
7064
7099
  throw new AitermError((inputStarted ? `agent session '${name}' の ${agentLabel(meta.kind)} への入力完了を確認できません。本文を再送しないでください。`
7065
- : `agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`) +
7100
+ : `AGENT_INPUT_TARGET_UNAVAILABLE: agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`) +
7066
7101
  `\nstate=${current.state} reason=${current.reason}`, 2);
7067
7102
  }
7068
7103
  return !starting;
@@ -7691,10 +7726,7 @@ function prepareAgentLaunch(kind, opts = {}) {
7691
7726
  throw new AitermError("AGENT_RESUME_UNCONFIRMED: 作成したnative本人性を取得できません。", 2);
7692
7727
  initialNative = { ...receipt, server_started_identity: server, pane_started_identity: pane };
7693
7728
  try {
7694
- const token = tryCreateOwnedLock(agentSendLockPath(receipt.session_id));
7695
- if (!token)
7696
- throw agentSendBusyError(receipt.session_id, null, 0);
7697
- initialAdmission = { name: receipt.session_id, token };
7729
+ initialAdmission = { name: receipt.session_id };
7698
7730
  agentSendHeld.add(receipt.session_id);
7699
7731
  // The old launch may have entered hibernation after the public precheck.
7700
7732
  assertNoDormantSession(receipt.session_id);
@@ -7717,9 +7749,8 @@ function prepareAgentLaunch(kind, opts = {}) {
7717
7749
  }
7718
7750
  finally {
7719
7751
  if (initialAdmission) {
7720
- const { name, token } = initialAdmission;
7752
+ const { name } = initialAdmission;
7721
7753
  agentSendHeld.delete(name);
7722
- releaseOwnedLock(agentSendLockPath(name), token);
7723
7754
  }
7724
7755
  }
7725
7756
  };
@@ -0,0 +1,106 @@
1
+ import * as fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ import { z } from "zod";
5
+ import { agentMetadataPath, writeJson0600 } from "./agent-shared.js";
6
+ import { readProcessIdentities, observeExecutionActor } from "./process-runtime.js";
7
+ const stamp = z.string().refine(value => Number.isFinite(Date.parse(value)));
8
+ const spanSchema = z.object({ turn_id: z.string().regex(/^managed:[a-f0-9]{32}$/), started_at: stamp }).strict();
9
+ const recordSchema = z.object({ binding: z.string().min(1), span: spanSchema.nullable(), terminal: z.string().nullable(),
10
+ ready: z.object({ since: stamp, terminal: z.string() }).strict().nullable() }).strict();
11
+ const ownerSchema = z.object({ pid: z.number().int().positive(), started_identity: stamp, token: z.string() }).strict();
12
+ export const managedSpanDirectory = (meta) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, ".seat-span.d");
13
+ /** Same callback owns live capture and the short identity transaction. Never waits or sends input. */
14
+ export function withManagedSpan(meta, capture) {
15
+ const directory = managedSpanDirectory(meta);
16
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
17
+ const actor = readProcessIdentities([process.pid]).find(row => row.pid === process.pid);
18
+ if (!actor?.started_identity)
19
+ return null;
20
+ const owner = ownerSchema.parse({ ...actor, token: randomBytes(16).toString("hex") });
21
+ const lock = path.join(directory, "lock"), candidate = path.join(directory, `claim-${owner.token}`);
22
+ fs.mkdirSync(candidate, { mode: 0o700 });
23
+ let acquired = false;
24
+ try {
25
+ writeJson0600(path.join(candidate, "owner.json"), owner);
26
+ try {
27
+ fs.renameSync(candidate, lock);
28
+ acquired = true;
29
+ }
30
+ catch (error) {
31
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "EACCES"].includes(error.code ?? ""))
32
+ throw error;
33
+ const before = fs.lstatSync(lock, { bigint: true });
34
+ const prior = ownerSchema.parse(JSON.parse(fs.readFileSync(path.join(lock, "owner.json"), "utf8")));
35
+ const dead = () => {
36
+ const observed = observeExecutionActor(prior.pid);
37
+ return observed.state === "absent" || observed.state === "present" && observed.actor.started_identity !== prior.started_identity;
38
+ };
39
+ if (!dead())
40
+ return null;
41
+ const after = fs.lstatSync(lock, { bigint: true });
42
+ if (before.dev !== after.dev || before.ino !== after.ino || !dead())
43
+ return null;
44
+ // Retain this nonempty destination: a competing reap cannot move a later owner's lock over it.
45
+ fs.renameSync(lock, path.join(directory, `retired-${before.dev}-${before.ino}`));
46
+ fs.renameSync(candidate, lock);
47
+ acquired = true;
48
+ }
49
+ return capture(path.join(directory, "span.json"));
50
+ }
51
+ finally {
52
+ if (acquired) {
53
+ const current = ownerSchema.parse(JSON.parse(fs.readFileSync(path.join(lock, "owner.json"), "utf8")));
54
+ if (current.token === owner.token) {
55
+ fs.unlinkSync(path.join(lock, "owner.json"));
56
+ fs.rmdirSync(lock);
57
+ }
58
+ }
59
+ else
60
+ fs.rmSync(candidate, { recursive: true, force: true });
61
+ }
62
+ }
63
+ /** Persistence keeps identity only; evidence must come from a new validated native read. */
64
+ export function observeManagedSpan(file, binding, evidence, terminal, at) {
65
+ stamp.parse(at);
66
+ let record = null;
67
+ try {
68
+ record = recordSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
69
+ }
70
+ catch (error) {
71
+ if (error.code !== "ENOENT" && (evidence !== "ready" || !terminal))
72
+ return null;
73
+ }
74
+ if (record?.binding !== binding)
75
+ record = null;
76
+ if (evidence === "unknown")
77
+ return null;
78
+ if (evidence === "busy") {
79
+ if (!record?.span) {
80
+ record = { binding, span: { turn_id: `managed:${randomBytes(16).toString("hex")}`, started_at: at }, terminal, ready: null };
81
+ writeJson0600(file, record);
82
+ }
83
+ else if (record.ready) {
84
+ record.ready = null;
85
+ writeJson0600(file, record);
86
+ }
87
+ return { state: "running", ...record.span, event_cursor: null, interim_from: null, wait_process: null };
88
+ }
89
+ if (!terminal || record?.span && terminal === record.terminal)
90
+ return null;
91
+ if (!record)
92
+ record = { binding, span: null, terminal, ready: null };
93
+ if (!record.ready || record.ready.terminal !== terminal || Date.parse(at) < Date.parse(record.ready.since)) {
94
+ record.ready = { since: at, terminal };
95
+ writeJson0600(file, record);
96
+ return null;
97
+ }
98
+ if (Date.parse(at) - Date.parse(record.ready.since) < 250)
99
+ return null;
100
+ if (record.span) {
101
+ record.span = null;
102
+ record.terminal = terminal;
103
+ writeJson0600(file, record);
104
+ }
105
+ return { state: "idle" };
106
+ }
package/docs/DESIGN.md CHANGED
@@ -589,3 +589,6 @@ Grok clear uses the existing host-origin contract and only a fresh UserPaused/Id
589
589
  Claude resume preserves the original CLAUDE_CONFIG_DIR selector (including unset) separately from its resolved path; incomplete old selectors remain unavailable. Security notes block startup even when an older shell marker remains above them.
590
590
 
591
591
  Factory diagnostics keep the v1 default projection and the separate parent-hook text. Optional format v2 adds fixed PTY reason codes and the 5000ms subprocess budget. Native resolution and the single scoped listing consume one deadline; unknown/permission/timeout failures do not prove absence. This uses ordinary native reads and no execution graph, PTY creation or credentials. The subprocess budget is not a hard real-time bound on OS filesystem calls or the complete diagnostics response.
592
+
593
+
594
+ A-1 all-five managed current activity: [function/DFD and state ownership](https://github.com/kitepon/aiterm-mcp/blob/main/docs/architecture/observation-results.md). Current original-pane evidence authorizes every non-Codex read; saved span identity is not freshness. Codex tracking remains unchanged.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.63.11",
3
+ "version": "0.63.13",
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": [