aiterm-mcp 0.63.6 → 0.63.8

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.8] - 2026-11-06
11
+
12
+ - Add optional local `agent_launch(require_existing_resume:true)` admission under the existing send lock. Missing, invalid or unsupported saved resume targets cannot fall through to fresh creation.
13
+ - Return typed resume-unavailable metadata without changing ordinary launch success receipts; capability-aware callers can avoid automatic fresh fallback.
14
+
15
+ ## [0.63.7] - 2026-11-03
16
+
17
+ - Preserve capacity, usage-limit and transient failure classifications through wait, steer and parent delivery without treating an error as permission to replay input. Claude dispatches retain an input ID and the pre-submit transcript boundary so failures written before the waiter starts are observed. Bound waiters reject another input's completion; legacy outcomes and exit codes are unchanged.
18
+
10
19
  ## [0.63.6] - 2026-11-03
11
20
 
12
21
  - Make the existing read-only diagnostics PTY probe finite and socket-exact: share a 5000 ms subprocess budget across backend resolution and one listing, and stop treating broad connection errors as absence. Opt-in `format:"v2"` adds safe PTY reason codes and the timeout budget; default v1 fields and the parent-hook text stay unchanged. No PTY warming or provider calls.
@@ -3032,7 +3041,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3032
3041
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3033
3042
  provenance.
3034
3043
 
3035
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.6...HEAD
3044
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.8...HEAD
3045
+ [0.63.8]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.7...v0.63.8
3046
+ [0.63.7]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.6...v0.63.7
3036
3047
  [0.63.6]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.5...v0.63.6
3037
3048
  [0.63.5]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.3...v0.63.5
3038
3049
  [0.63.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.2...v0.63.3
package/README.ja.md CHANGED
@@ -8,6 +8,12 @@
8
8
 
9
9
  # Aiterm
10
10
 
11
+ Codex・Claudeの失敗した番では、既存の待機結果へ`failure`を追加します。`category`は`capacity`/`rate_limited`/`transient`/`other`、`execution`は記録に作業があれば`started`、分からなければ`unknown`です。providerの拒否だけで、それ以前の道具が未実行だったとは判断しません。`terminal`は観測した番の終了だけを示し、`future_effects:"unknown"`は待ち行列・自動再試行・ほかの送信元の作用を未確認のまま残します。
12
+
13
+ Claudeの送信・初手つき起動の返りには`input_id`が付きます。返りの`wait_process`を保持するか、元のsession・launch・cursorと一緒に`aiterm-wait --input <id>`へ渡してください。APIエラー直後は匿名入力のcursorが同じになることがありますが、古い入力を次の番の成功へ結び直しません。送信前の会話記録の位置から読むため、待機開始前のAPIエラーも拾います。この境界はAitermの入力観測との対応であり、nativeによる本文受理の証明ではありません。旧記録や欠測を新しい証拠へ変換しません。
14
+
15
+ 分類は親配送の保存・返りにも残ります。Aitermは元本文を自動再送しません。呼出元は通常の停止・設定の条件を守り、残された会話や保存した引継ぎから未了の仕事を続けられます。
16
+
11
17
  [![CI](https://github.com/kitepon/aiterm-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/kitepon/aiterm-mcp/actions/workflows/ci.yml)
12
18
  [![npm](https://img.shields.io/npm/v/aiterm-mcp.svg)](https://www.npmjs.com/package/aiterm-mcp)
13
19
  [![週間ダウンロード](https://img.shields.io/npm/dw/aiterm-mcp.svg)](https://www.npmjs.com/package/aiterm-mcp)
@@ -209,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
209
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
210
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
211
217
 
212
- **状態:** 開発継続中 · 現行公開版 **v0.63.6** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.63.8** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
219
 
214
220
  ### 更新と巻き戻し
215
221
 
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.6** · 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.8** · 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
 
@@ -268,6 +268,10 @@ Cursorが誤りでturnを終えた時(記録の`turn_ended`が`status: "error"
268
268
 
269
269
  ## Two ways to use it
270
270
 
271
+ Failed Codex and Claude turns may add `failure` to the existing wait result. Its `category` is `capacity`, `rate_limited`, `transient` or `other`; `execution` reports observed work as `started` or leaves it `unknown`. A provider rejection never proves that earlier tools did not run. `terminal` refers only to the observed turn; `future_effects:"unknown"` preserves uncertainty about queued input, retries and other producers. No input is automatically replayed by Aiterm.
272
+
273
+ Claude dispatch and prompt-launch receipts include `input_id`. Keep the receipt's `wait_process`, or pass that ID to `aiterm-wait --input <id> --cursor <original cursor>` with the original session and launch. This prevents a later anonymous turn at the same event cursor from becoming the old request's result. Its saved transcript boundary also catches an API error written before the waiter starts. The failure boundary identifies the Aiterm input observation, not native input acceptance. Missing or legacy evidence is not upgraded. Parent receipts and notices preserve the classification. A caller can continue unfinished work from the retained conversation or saved handoff after applying its normal stop and configuration conditions; replaying the original message is a separate decision.
274
+
271
275
  Grok can finish its current turn while `pty_send` is submitting input. Aiterm correlates the newly appended full user message with the native turn number and returns `agent_dispatch` for a proven new turn, without sending again. `STEER_NOT_QUEUED` and `STEER_STILL_QUEUED` preserve `isError:true` and their existing text prefix; `structuredContent` adds `aiterm.agent-send-error.v1`, a string `code`, `outcome:"outcome_unknown"`, `effect:"possible"`, and the original session/launch. A Grok observation handle is returned only when its pre-input record was saved; unavailable handles are null. Do not resend unknown input. Its waiter remains pending until the input's native acceptance is proven and cannot use the preceding turn's completion. Cursor errors retain null recovery handles until native acceptance can be proven.
272
276
 
273
277
  ### 1. Drive SSH, containers, and REPLs in one persistent terminal — the primitive
@@ -12,7 +12,7 @@ import { AitermError, detectAgentRateLimit, observeAgentDone } from "./core.js";
12
12
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
13
13
  const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
14
14
  const STEER_RE = /^[0-9a-f]{16}$/;
15
- const USAGE = "usage: aiterm-wait --session <name> [--cursor <event_cursor>] [--operation sha256:<64hex>] [--timeout <sec>]" +
15
+ const USAGE = "usage: aiterm-wait --session <name> [--cursor <event_cursor>] [--input <32hex>] [--operation sha256:<64hex>] [--timeout <sec>]" +
16
16
  "(--timeout 0 は待たずに一度だけ観測する照会で、未完了は outcome=running / exit 5)";
17
17
  export function parseArgs(argv) {
18
18
  let session = null;
@@ -21,14 +21,20 @@ export function parseArgs(argv) {
21
21
  let cursor = null;
22
22
  let steer = null;
23
23
  let expectedLaunchId;
24
+ let inputId;
24
25
  for (let i = 0; i < argv.length; i++) {
25
26
  const a = argv[i];
26
- if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer" || a === "--launch") {
27
+ if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer" || a === "--launch" || a === "--input") {
27
28
  const v = argv[i + 1];
28
29
  if (v === undefined)
29
30
  throw new Error(`${a} に値がありません。${USAGE}`);
30
31
  i++;
31
- if (a === "--launch") {
32
+ if (a === "--input") {
33
+ if (inputId !== undefined || !/^[0-9a-f]{32}$/.test(v))
34
+ throw new Error(`--input が不正又は重複しています。${USAGE}`);
35
+ inputId = v;
36
+ }
37
+ else if (a === "--launch") {
32
38
  if (expectedLaunchId !== undefined || !/^[0-9a-f]{32}$/.test(v))
33
39
  throw new Error(`--launch が不正又は重複しています。${USAGE}`);
34
40
  expectedLaunchId = v;
@@ -79,7 +85,9 @@ export function parseArgs(argv) {
79
85
  throw new Error(`--session は必須です。${USAGE}`);
80
86
  if (steer !== null && operationId !== null)
81
87
  throw new Error(`--steer は --operation と併用できません。${USAGE}`);
82
- return { session, operationId, timeout: timeout ?? 600, cursor, steer, ...(expectedLaunchId ? { expectedLaunchId } : {}) };
88
+ if (inputId && (steer !== null || cursor === null))
89
+ throw new Error(`--input requires --cursor without --steer. ${USAGE}`);
90
+ return { session, operationId, timeout: timeout ?? 600, cursor, steer, ...(expectedLaunchId ? { expectedLaunchId } : {}), ...(inputId ? { inputId } : {}) };
83
91
  }
84
92
  function emit(value) {
85
93
  process.stdout.write(JSON.stringify(value) + "\n");
@@ -106,6 +114,7 @@ export async function main(argv) {
106
114
  cursor: cmd.cursor,
107
115
  steer: cmd.steer,
108
116
  expected_launch_id: cmd.expectedLaunchId,
117
+ input_id: cmd.inputId,
109
118
  });
110
119
  }
111
120
  catch (e) {
@@ -4,8 +4,22 @@ export function parseClaudeOperationMarker(value) {
4
4
  const legacy = keys === "operation_id,schema" && row.schema === "aiterm.claude-operation-marker.v1";
5
5
  const bound = keys === "event_cursor,operation_id,schema" && row.schema === "aiterm.claude-operation-marker.v2"
6
6
  && Number.isSafeInteger(row.event_cursor) && row.event_cursor >= 0;
7
- if ((!legacy && !bound) || (row.operation_id !== null
7
+ const captured = keys === "event_cursor,input_id,operation_id,schema,transcript" && row.schema === "aiterm.claude-operation-marker.v3"
8
+ && Number.isSafeInteger(row.event_cursor) && row.event_cursor >= 0
9
+ && typeof row.input_id === "string" && /^[a-f0-9]{32}$/.test(row.input_id);
10
+ if (captured && row.transcript !== null) {
11
+ const value = row.transcript;
12
+ if (!value || typeof value !== "object" || Array.isArray(value)
13
+ || Object.keys(value).sort().join(",") !== "cursor,device,inode,session_id"
14
+ || typeof value.session_id !== "string" || !/^[A-Za-z0-9_-]{1,256}$/.test(value.session_id)
15
+ || !Number.isSafeInteger(value.cursor) || value.cursor < 0
16
+ || ![value.device, value.inode].every(n => n === null || (typeof n === "string" && /^\d{1,30}$/.test(n)))
17
+ || ((value.device === null) !== (value.inode === null)) || (value.device === null && value.cursor !== 0))
18
+ throw new Error("Claude transcript boundaryが不正です");
19
+ }
20
+ if ((!legacy && !bound && !captured) || (row.operation_id !== null
8
21
  && (typeof row.operation_id !== "string" || !/^sha256:[0-9a-f]{64}$/.test(row.operation_id))))
9
22
  throw new Error("Claude operation markerが不正です");
10
- return { operationId: row.operation_id, eventCursor: bound ? row.event_cursor : null };
23
+ return { operationId: row.operation_id, eventCursor: bound || captured ? row.event_cursor : null,
24
+ ...(captured ? { inputId: row.input_id, transcript: row.transcript } : {}) };
11
25
  }
@@ -109,10 +109,10 @@ function readOperationMarker(file) {
109
109
  }
110
110
  const body = fs.readFileSync(fd, "utf8");
111
111
  const value = JSON.parse(body);
112
- // Reading/consuming the v2 reservation is compatibility only. Its cursor
113
- // is deliberately absent from agent_done/result and proves no interruption.
112
+ // v1/v2 remain readable. The v3 input ID correlates this reservation;
113
+ // none of these markers proves native interruption or a producer fence.
114
114
  const marker = parseClaudeOperationMarker(value);
115
- return { operationId: marker.operationId, dev: st.dev, ino: st.ino };
115
+ return { operationId: marker.operationId, ...(marker.inputId ? { inputId: marker.inputId } : {}), dev: st.dev, ino: st.ino };
116
116
  }
117
117
  catch (error) {
118
118
  fail(error instanceof Error ? error.message : String(error));
@@ -212,6 +212,7 @@ async function main() {
212
212
  operation_id: operationId,
213
213
  reason: "Stop",
214
214
  done_status: "turn_done",
215
+ ...(operationMarker?.inputId ? { input_id: operationMarker.inputId } : {}),
215
216
  stop_hook_active: !!payload.stop_hook_active,
216
217
  result_digest: resultDigest,
217
218
  result_bytes: resultBytes,
package/dist/core.js CHANGED
@@ -50,7 +50,7 @@ import { paneTokenHint } from "./harnesses/pane-tokens.js";
50
50
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
51
51
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
52
52
  import { liveNodeExecutable } from "./live-node.js";
53
- import { AitermError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
53
+ import { AitermError, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
54
54
  import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
55
55
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, } from "./agent-shared.js";
56
56
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
@@ -62,7 +62,7 @@ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefa
62
62
  import { isDeepStrictEqual } from "node:util";
63
63
  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
64
  import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, 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
- 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, } from "./harnesses/claude.js";
65
+ 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
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
67
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
68
68
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
@@ -1210,12 +1210,13 @@ function observeManagedClaudeInterruption(point) {
1210
1210
  };
1211
1211
  try {
1212
1212
  const before = { marker: identity(marker, false), receipt: receipt ? identity(receipt, true) : null };
1213
- if (!matchesClaudeInterruptionMarker(readClaudeOperationMarker(meta), point))
1213
+ const parsed = readClaudeOperationMarker(meta);
1214
+ if (!matchesClaudeInterruptionMarker(parsed, point))
1214
1215
  throw new ExecutionError("EXECUTION_UNSUPPORTED");
1215
1216
  const after = { marker: identity(marker, false), receipt: receipt ? identity(receipt, true) : null };
1216
1217
  if (!isDeepStrictEqual(before, after))
1217
1218
  throw new ExecutionError("EXECUTION_CONFLICT");
1218
- return after;
1219
+ return { ...after, protocol: parsed?.inputId ? "aiterm.claude-operation-marker.v3" : "aiterm.claude-operation-marker.v2" };
1219
1220
  }
1220
1221
  catch (error) {
1221
1222
  if (error instanceof ExecutionError)
@@ -1255,7 +1256,7 @@ function observeManagedClaudeInterruption(point) {
1255
1256
  return { ...common, schema: "aiterm.claude-anonymous-interruption-observation.v1",
1256
1257
  endpoint: { session_id: null, operation_marker: reference(after.files.marker), dispatch_receipt: null },
1257
1258
  native_boundary: { type: "anonymous_turn_reserved", event_cursor: point.boundary.event_cursor },
1258
- marker_protocol: "aiterm.claude-operation-marker.v2", loaded_hook: "unconfirmed" };
1259
+ marker_protocol: after.files.protocol, loaded_hook: "unconfirmed" };
1259
1260
  return { ...common, schema: "aiterm.claude-managed-interruption-observation.v1",
1260
1261
  endpoint: { session_id: null, operation_marker: reference(after.files.marker), dispatch_receipt: reference(after.files.receipt) },
1261
1262
  native_boundary: { type: "managed_operation_reserved", operation_id: operation } };
@@ -2652,18 +2653,40 @@ function runAgentApprovalInNative(options) {
2652
2653
  }
2653
2654
  const DEFAULT_AGENT_DONE_TIMEOUT = 600;
2654
2655
  const agentMetadataNegativeCache = new Map();
2655
- function writeClaudeOperationMarker(meta, operationId) {
2656
+ function writeClaudeOperationMarker(meta, operationId, eventCursor, inputId) {
2656
2657
  if (meta.kind !== "claude")
2657
2658
  throw new AitermError("operation_id はClaude agent sessionだけで使用できます", 2);
2658
2659
  const operation = operationId === null ? null : validateOperationId(operationId);
2659
- // Only the same private request frame can supply this anonymous reference.
2660
- // Unmounted/legacy execution keeps v1; never infer a cursor from file size.
2660
+ // Private interruption retains its original request frame; v3 also captures
2661
+ // the public dispatch observation, never native input acceptance.
2661
2662
  const captured = operation === null ? readExecutionSendBoundary(meta.aiterm_session) : null;
2662
2663
  if (captured && (!isDeepStrictEqual(captured.launch, { session_id: meta.aiterm_session, launch_id: meta.launch_id })
2663
2664
  || !captured.boundary || captured.boundary.operation_id !== null || captured.boundary.turn_id !== null
2664
2665
  || captured.boundary.steer_id !== null))
2665
2666
  throw new ExecutionError("EXECUTION_CONFLICT");
2666
- withExecutionPreparation(meta.aiterm_session, () => writeJson0600(agentClaudeOperationPath(meta.aiterm_session, meta.launch_id), captured ? {
2667
+ if (captured && eventCursor !== undefined && captured.boundary.event_cursor !== eventCursor)
2668
+ throw new ExecutionError("EXECUTION_CONFLICT");
2669
+ let transcript = null;
2670
+ const file = claudeSessionTranscriptPath(meta);
2671
+ if (eventCursor !== undefined && file && meta.vendor_session_id) {
2672
+ let stat;
2673
+ try {
2674
+ stat = fs.statSync(file, { bigint: true });
2675
+ }
2676
+ catch (error) {
2677
+ if (error.code !== "ENOENT")
2678
+ throw error;
2679
+ stat = null;
2680
+ }
2681
+ if (stat && !stat.isFile())
2682
+ throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: input boundary is not a file", 2);
2683
+ if (stat && !Number.isSafeInteger(Number(stat.size)))
2684
+ throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: input boundary is too large", 2);
2685
+ transcript = { session_id: meta.vendor_session_id, cursor: Number(stat?.size ?? 0), device: stat?.dev.toString() ?? null, inode: stat?.ino.toString() ?? null };
2686
+ }
2687
+ withExecutionPreparation(meta.aiterm_session, () => writeJson0600(agentClaudeOperationPath(meta.aiterm_session, meta.launch_id), eventCursor !== undefined ? {
2688
+ schema: "aiterm.claude-operation-marker.v3", operation_id: operation, event_cursor: eventCursor, input_id: inputId, transcript,
2689
+ } : captured ? {
2667
2690
  schema: "aiterm.claude-operation-marker.v2", operation_id: null, event_cursor: captured.boundary.event_cursor,
2668
2691
  } : { schema: "aiterm.claude-operation-marker.v1", operation_id: operation }));
2669
2692
  }
@@ -2704,7 +2727,7 @@ function readClaudeOperationMarker(meta) {
2704
2727
  fs.closeSync(fd);
2705
2728
  }
2706
2729
  }
2707
- function reserveClaudeOperation(meta, operationId) {
2730
+ function reserveClaudeOperation(meta, operationId, eventCursor, inputId) {
2708
2731
  const validated = validateOperationId(operationId);
2709
2732
  const active = readClaudeOperationMarker(meta);
2710
2733
  if (active?.operationId === validated) {
@@ -2726,7 +2749,7 @@ function reserveClaudeOperation(meta, operationId) {
2726
2749
  throw new AitermError(`operation ${validated} は既にdispatch済みです。再送しません。`, 2);
2727
2750
  }
2728
2751
  try {
2729
- writeClaudeOperationMarker(meta, validated);
2752
+ writeClaudeOperationMarker(meta, validated, eventCursor, inputId);
2730
2753
  }
2731
2754
  catch (error) {
2732
2755
  try {
@@ -2736,13 +2759,13 @@ function reserveClaudeOperation(meta, operationId) {
2736
2759
  throw error;
2737
2760
  }
2738
2761
  }
2739
- function reserveAnonymousClaudeTurn(meta) {
2762
+ function reserveAnonymousClaudeTurn(meta, eventCursor, inputId) {
2740
2763
  const active = readClaudeOperationMarker(meta);
2741
2764
  if (active) {
2742
2765
  throw new AitermError(`${active.operationId ? `operation ${active.operationId}` : "operation_idなしのClaude turn"} が未解決です。` +
2743
2766
  "Stop結果を回収するかsessionをcloseするまで次のturnを送れません。", 2);
2744
2767
  }
2745
- writeClaudeOperationMarker(meta, null);
2768
+ writeClaudeOperationMarker(meta, null, eventCursor, inputId);
2746
2769
  }
2747
2770
  function managedClaudeOperation(name) {
2748
2771
  let meta;
@@ -3431,6 +3454,7 @@ function parseAgentDoneEvent(line, meta) {
3431
3454
  vendor_session_id: typeof ev.vendor_session_id === "string" ? ev.vendor_session_id : null,
3432
3455
  turn_id: typeof ev.turn_id === "string" ? ev.turn_id : null,
3433
3456
  operation_id: typeof ev.operation_id === "string" && OPERATION_ID_RE.test(ev.operation_id) ? ev.operation_id : null,
3457
+ ...(typeof ev.input_id === "string" && /^[a-f0-9]{32}$/.test(ev.input_id) ? { input_id: ev.input_id } : {}),
3434
3458
  reason: typeof ev.reason === "string" ? ev.reason : "Stop",
3435
3459
  done_status: ev.done_status === "turn_error" ? "turn_error" : "turn_done",
3436
3460
  stop_hook_active: !!ev.stop_hook_active,
@@ -3441,7 +3465,7 @@ function parseAgentDoneEvent(line, meta) {
3441
3465
  malformed: false,
3442
3466
  };
3443
3467
  }
3444
- function scanAgentDoneLines(lines, meta, expectedOperationId = null) {
3468
+ function scanAgentDoneLines(lines, meta, expectedOperationId = null, expectedInputId) {
3445
3469
  let malformedEvents = 0;
3446
3470
  let candidate = null;
3447
3471
  for (const line of lines) {
@@ -3461,6 +3485,8 @@ function scanAgentDoneLines(lines, meta, expectedOperationId = null) {
3461
3485
  continue;
3462
3486
  if (expectedOperationId && ev.operation_id !== expectedOperationId)
3463
3487
  continue;
3488
+ if (expectedInputId && ev.input_id !== expectedInputId)
3489
+ continue;
3464
3490
  if (meta.vendor_session_id)
3465
3491
  return { event: ev, malformedEvents, ambiguousHarnessSession: false };
3466
3492
  if (candidate?.vendor_session_id &&
@@ -3905,6 +3931,7 @@ export function agentWaitProcess(session, cursor, runtime = {}, steer = null) {
3905
3931
  // 差し込みを取った番の終わりを待つ(ADR 0122)。
3906
3932
  ...(steer ? ["--steer", steer] : []),
3907
3933
  ...(runtime.launchId ? ["--launch", runtime.launchId] : []),
3934
+ ...(runtime.inputId ? ["--input", runtime.inputId] : []),
3908
3935
  ];
3909
3936
  return {
3910
3937
  executable,
@@ -4003,6 +4030,8 @@ export async function observeAgentDone(name, o = {}) {
4003
4030
  }
4004
4031
  async function observeAgentDoneInternal(name, o = {}) {
4005
4032
  const meta = loadAgentMetadata(name);
4033
+ if (o.input_id !== undefined && (!/^[a-f0-9]{32}$/.test(o.input_id) || meta.kind !== "claude" || o.steer != null))
4034
+ throw new AitermError("AGENT_WAIT_INPUT_INVALID: input_id requires a Claude dispatch boundary", 2);
4006
4035
  if (o.expected_launch_id && meta.launch_id !== o.expected_launch_id)
4007
4036
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
4008
4037
  const operationId = o.operation_id == null ? null : validateOperationId(o.operation_id);
@@ -4056,11 +4085,20 @@ async function observeAgentDoneInternal(name, o = {}) {
4056
4085
  let cursor = startOffset;
4057
4086
  let carry = "";
4058
4087
  let malformedEvents = 0;
4059
- // Claudeの会話記録はこの観測開始時点の末尾から先だけを読む。過去turnのAPIエラー行を今回の
4060
- // 終了と誤認しないため。dispatch直後に待機を始める親(receiptのwait_process)を前提にする。
4088
+ // New Claude input reservations retain the pre-submit transcript offset.
4089
+ // Legacy waits start at EOF and never acquire a missing input binding.
4061
4090
  const transcriptFile = claudeSessionTranscriptPath(meta);
4062
- let transcriptCursor = transcriptFile ? safeStatSize(transcriptFile) : 0;
4091
+ let marker = meta.kind === "claude" ? readClaudeOperationMarker(meta) : null;
4092
+ let capturedTranscript = marker?.transcript;
4093
+ let matchesBoundary = !!capturedTranscript && capturedTranscript.session_id === meta.vendor_session_id
4094
+ && marker.operationId === operationId && (o.cursor != null ? marker.eventCursor === o.cursor : operationId !== null);
4095
+ let transcriptCursor = matchesBoundary ? capturedTranscript.cursor : transcriptFile ? safeStatSize(transcriptFile) : 0;
4063
4096
  let transcriptCarry = "";
4097
+ let parentUuid = null;
4098
+ let sawUser = false;
4099
+ let sawExecution = false;
4100
+ let transcriptBound = matchesBoundary && (operationId !== null || (o.input_id !== undefined && marker?.inputId === o.input_id));
4101
+ let transcriptIdentity = capturedTranscript?.device === null ? null : capturedTranscript;
4064
4102
  // 利用上限の知らせは画面でしか分からない。画面を読むとtmuxを起動するので、完了の見回りより間隔を空ける。
4065
4103
  // 実被弾: 完了の見回り(100ms)のたびに読んでいて、待ち1本が1秒に約10回tmuxを起動していた(4本でコンテナのCPUが148%)。
4066
4104
  const rateLimitDue = pollGate(AGENT_RATE_LIMIT_POLL_MS);
@@ -4072,18 +4110,36 @@ async function observeAgentDoneInternal(name, o = {}) {
4072
4110
  harness: agentHarness(meta.kind),
4073
4111
  outcome,
4074
4112
  operation_id: ev?.operation_id ?? operationId,
4113
+ ...(o.input_id ? { input_id: o.input_id } : {}),
4075
4114
  vendor_session_id: ev?.vendor_session_id ?? meta.vendor_session_id ?? null,
4076
4115
  turn_id: ev?.turn_id ?? null,
4077
4116
  malformed_events: malformedEvents,
4078
4117
  at: ev?.at ?? apiError?.at ?? null,
4079
4118
  rate_limit: rateLimit,
4080
4119
  error: apiError?.text ?? null,
4081
- error_kind: null,
4120
+ error_kind: apiError?.status ? `http_${apiError.status}` : null,
4121
+ ...(apiError ? { failure: { category: claudeFailureCategory(apiError), execution: sawExecution ? "started" : "unknown",
4122
+ boundary: transcriptBound && sawUser && apiError.session_id === meta.vendor_session_id && parentUuid !== null && apiError.parent_uuid === parentUuid && apiError.uuid !== null ? {
4123
+ event_cursor: marker.eventCursor, operation_id: operationId, turn_id: null, input_id: marker.inputId
4124
+ } : null,
4125
+ terminal: transcriptBound && sawUser && apiError.session_id === meta.vendor_session_id && parentUuid !== null && apiError.parent_uuid === parentUuid && apiError.uuid !== null,
4126
+ future_effects: "unknown" } } : {}),
4082
4127
  });
4083
4128
  for (;;) {
4084
4129
  o.signal?.throwIfAborted();
4085
4130
  if (!fs.existsSync(metadataFile))
4086
4131
  return observation("closed");
4132
+ if (o.input_id && !marker) {
4133
+ marker = readClaudeOperationMarker(meta);
4134
+ capturedTranscript = marker?.transcript;
4135
+ matchesBoundary = !!capturedTranscript && capturedTranscript.session_id === meta.vendor_session_id
4136
+ && marker.operationId === operationId && marker.eventCursor === o.cursor && marker.inputId === o.input_id;
4137
+ if (matchesBoundary) {
4138
+ transcriptCursor = capturedTranscript.cursor;
4139
+ transcriptBound = true;
4140
+ transcriptIdentity = capturedTranscript.device === null ? null : capturedTranscript;
4141
+ }
4142
+ }
4087
4143
  const size = safeStatSize(meta.event_file);
4088
4144
  if (size < cursor) {
4089
4145
  cursor = 0;
@@ -4097,20 +4153,52 @@ async function observeAgentDoneInternal(name, o = {}) {
4097
4153
  cursor = size;
4098
4154
  const parts = carry.split("\n");
4099
4155
  carry = parts.pop() ?? "";
4100
- const scanned = scanAgentDoneLines(parts, meta, operationId);
4156
+ const scanned = scanAgentDoneLines(parts, meta, operationId, o.input_id);
4101
4157
  malformedEvents += scanned.malformedEvents;
4102
4158
  if (scanned.ambiguousHarnessSession) {
4103
4159
  throw new AitermError("agent event file に複数の vendor_session_id が混在しています。該当セッションを閉じて起動し直してください。", 2);
4104
4160
  }
4161
+ if (o.input_id && !scanned.event && parts.some(line => parseAgentDoneEvent(line, meta).event !== null))
4162
+ throw new AitermError("AGENT_WAIT_INPUT_CHANGED: completion belongs to another or unconfirmed input", 2);
4105
4163
  if (scanned.event)
4106
4164
  return scanned.event.done_status === "turn_error"
4107
4165
  ? { ...observation("error", scanned.event), error: `Antigravity execution ended: ${scanned.event.reason}`, error_kind: scanned.event.reason }
4108
4166
  : observation("done", scanned.event);
4109
4167
  }
4168
+ if (o.input_id) {
4169
+ const current = readClaudeOperationMarker(meta);
4170
+ if ((current && (current.inputId !== o.input_id || current.eventCursor !== o.cursor)) || (!current && marker)) {
4171
+ // Stop saves its event before consuming the marker; capture that event
4172
+ // if it arrived after this iteration's event-file read.
4173
+ if (safeStatSize(meta.event_file) > cursor)
4174
+ continue;
4175
+ throw new AitermError("AGENT_WAIT_INPUT_CHANGED: original input marker was replaced", 2);
4176
+ }
4177
+ if (!current) {
4178
+ if (performance.now() >= deadline)
4179
+ return observation(timeout === 0 ? "running" : "timeout");
4180
+ await sleep(AGENT_DONE_POLL_MS);
4181
+ continue;
4182
+ }
4183
+ }
4110
4184
  if (transcriptFile && fs.existsSync(transcriptFile)) {
4111
- const transcriptSize = safeStatSize(transcriptFile);
4185
+ const transcriptStat = fs.statSync(transcriptFile, { bigint: true });
4186
+ const transcriptSize = Number(transcriptStat.size);
4187
+ if (!transcriptStat.isFile() || !Number.isSafeInteger(transcriptSize))
4188
+ throw new AitermError("CLAUDE_TRANSCRIPT_INVALID: cannot read input boundary", 2);
4189
+ if (transcriptBound && transcriptIdentity
4190
+ && (transcriptStat.dev.toString() !== transcriptIdentity.device || transcriptStat.ino.toString() !== transcriptIdentity.inode)) {
4191
+ transcriptBound = false;
4192
+ parentUuid = null;
4193
+ transcriptCursor = transcriptSize;
4194
+ transcriptCarry = "";
4195
+ }
4196
+ if (transcriptBound && !transcriptIdentity)
4197
+ transcriptIdentity = { ...capturedTranscript, device: transcriptStat.dev.toString(), inode: transcriptStat.ino.toString() };
4112
4198
  if (transcriptSize < transcriptCursor) {
4113
- transcriptCursor = 0;
4199
+ transcriptBound = false;
4200
+ parentUuid = null;
4201
+ transcriptCursor = transcriptSize;
4114
4202
  transcriptCarry = "";
4115
4203
  }
4116
4204
  if (transcriptSize > transcriptCursor) {
@@ -4120,8 +4208,36 @@ async function observeAgentDoneInternal(name, o = {}) {
4120
4208
  transcriptCarry = lines.pop() ?? "";
4121
4209
  for (const line of lines) {
4122
4210
  const apiError = claudeApiErrorFromLine(line);
4123
- if (apiError)
4211
+ if (apiError && (apiError.session_id === null || apiError.session_id === meta.vendor_session_id))
4124
4212
  return observation("error", null, null, apiError);
4213
+ let record;
4214
+ try {
4215
+ record = JSON.parse(line);
4216
+ }
4217
+ catch {
4218
+ transcriptBound = false;
4219
+ continue;
4220
+ }
4221
+ if (record.isSidechain === true || (record.sessionId && record.sessionId !== meta.vendor_session_id))
4222
+ continue;
4223
+ if (record.type === "user" || record.type === "assistant") {
4224
+ if (typeof record.uuid !== "string" || (parentUuid !== null && record.parentUuid !== parentUuid))
4225
+ transcriptBound = false;
4226
+ if (!sawUser && record.type !== "user")
4227
+ transcriptBound = false;
4228
+ if (record.sessionId !== meta.vendor_session_id)
4229
+ transcriptBound = false;
4230
+ if (record.type === "user") {
4231
+ const content = record.message?.content;
4232
+ const toolResult = Array.isArray(content) && content.length > 0 && content.every((part) => part?.type === "tool_result");
4233
+ if (sawUser && !toolResult)
4234
+ transcriptBound = false;
4235
+ sawUser = true;
4236
+ }
4237
+ if (record.type === "assistant")
4238
+ sawExecution = true;
4239
+ parentUuid = typeof record.uuid === "string" ? record.uuid : null;
4240
+ }
4125
4241
  }
4126
4242
  }
4127
4243
  }
@@ -4131,7 +4247,8 @@ async function observeAgentDoneInternal(name, o = {}) {
4131
4247
  if (rateLimitDue()) {
4132
4248
  const limited = detectAgentRateLimit(meta.kind, meta.aiterm_session);
4133
4249
  if (limited)
4134
- return observation("rate_limited", null, limited);
4250
+ return { ...observation("rate_limited", null, limited), failure: { category: "rate_limited", execution: "unknown",
4251
+ boundary: null, terminal: false, future_effects: "unknown" } };
4135
4252
  }
4136
4253
  if (performance.now() >= deadline)
4137
4254
  return observation(timeout === 0 ? "running" : "timeout");
@@ -4424,16 +4541,17 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4424
4541
  await o.after_ready?.(name, meta);
4425
4542
  const promptText = meta.kind === "cursor" ? cursorPromptWithLineage(meta, text) : text;
4426
4543
  const startOffset = agentCompletionCursor(meta);
4544
+ const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
4427
4545
  try {
4428
4546
  prepareSendText(promptText, { raw: false });
4429
4547
  await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
4430
- harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: null });
4548
+ harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: null, ...(inputId ? { input_id: inputId } : {}) });
4431
4549
  captureExecutionSendBoundary({ launch: { session_id: name, launch_id: meta.launch_id }, boundary: {
4432
4550
  event_cursor: startOffset, operation_id: null, turn_id: null, steer_id: null
4433
4551
  } });
4434
4552
  if (meta.kind === "claude") {
4435
4553
  prepareSendText(text, { raw: false });
4436
- reserveAnonymousClaudeTurn(meta);
4554
+ reserveAnonymousClaudeTurn(meta, startOffset, inputId);
4437
4555
  }
4438
4556
  setInitialDelivery(meta, { status: "submitted_unconfirmed", reason: "dispatch_in_progress", turn_started: null }, startOffset);
4439
4557
  await sendAgentPromptText(name, promptText, meta.kind, meta);
@@ -4472,7 +4590,7 @@ async function sendInitialAgentPromptInLock(name, text, o) {
4472
4590
  setInitialPromptState(meta, "failed");
4473
4591
  throw new AitermError(userHookBlockedMessage(`initial_prompt=failed vendor=${meta.kind} harness=${agentHarness(meta.kind)}`, "起動時prompt", state.detail), 2);
4474
4592
  }
4475
- const completed = await observeAgentDone(name, { cursor: startOffset, timeout: 0 });
4593
+ const completed = await observeAgentDone(name, { cursor: startOffset, timeout: 0, input_id: inputId });
4476
4594
  if (completed.outcome === "done") {
4477
4595
  delivery = { status: "started", reason: "turn_completed", turn_started: true };
4478
4596
  break;
@@ -6710,8 +6828,9 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6710
6828
  ? `${subagentInstruction(meta)}\n\n${prefaced.body}`
6711
6829
  : prefaced.body;
6712
6830
  prepareSendText(dispatchText, { raw: o.raw });
6831
+ const inputId = meta.kind === "claude" ? randomBytes(16).toString("hex") : undefined;
6713
6832
  await o.before_send?.({ session_id: name, launch_id: meta.launch_id, vendor: meta.kind,
6714
- harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId });
6833
+ harness: agentHarness(meta.kind), event_cursor: startOffset, operation_id: operationId, ...(inputId ? { input_id: inputId } : {}) });
6715
6834
  await submitAgentComposerText(name, meta.kind, dispatchText, {
6716
6835
  inputMeta: meta,
6717
6836
  force: o.force, raw: o.raw, typedPreface: prefaced.typedPreface, preserveAgentOperation: meta.kind === "claude",
@@ -6727,10 +6846,10 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6727
6846
  // receipt/active markerだけを残して、来ないStopを待つ状態を作らない。
6728
6847
  prepareSendText(text, { raw: o.raw });
6729
6848
  if (operationId) {
6730
- reserveClaudeOperation(meta, operationId);
6849
+ reserveClaudeOperation(meta, operationId, startOffset, inputId);
6731
6850
  }
6732
6851
  else
6733
- reserveAnonymousClaudeTurn(meta);
6852
+ reserveAnonymousClaudeTurn(meta, startOffset, inputId);
6734
6853
  }
6735
6854
  },
6736
6855
  });
@@ -6749,6 +6868,7 @@ async function dispatchAgentTurnInLock(name, text, o, pendingSend) {
6749
6868
  harness: agentHarness(meta.kind),
6750
6869
  event_cursor: startOffset,
6751
6870
  operation_id: operationId,
6871
+ ...(inputId ? { input_id: inputId } : {}),
6752
6872
  submit_residue: residue.residue,
6753
6873
  pane_input_recovery: paneInputRecovery,
6754
6874
  };
@@ -7570,6 +7690,9 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7570
7690
  await withExecutionNativeAdmission(opts.session_name, () => assertExecutionContext(opts.session_name));
7571
7691
  else
7572
7692
  assertExecutionContext(opts.session_name);
7693
+ if (opts.require_existing_resume && (!opts.session_name || opts.prompt != null || opts.throughline_source_session != null
7694
+ || opts.throughline_supplement_file != null))
7695
+ throw new AitermError("require_existing_resume requires session_name and no prompt or Throughline fork", 2);
7573
7696
  const mission = opts.prompt ?? null;
7574
7697
  const sourceSessionId = opts.throughline_source_session ?? null;
7575
7698
  const supplementFile = opts.throughline_supplement_file ?? null;
@@ -7596,13 +7719,22 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7596
7719
  }
7597
7720
  if (opts.session_name) {
7598
7721
  assertSessionName(opts.session_name);
7599
- const name = opts.session_name, saved = tryLoadAgentMetadata(name);
7600
- if (saved && (readAgentLifecycle(saved) || agentDormantState(saved))) {
7722
+ const name = opts.session_name, saved = opts.require_existing_resume ? null : tryLoadAgentMetadata(name);
7723
+ if (opts.require_existing_resume || (saved && (readAgentLifecycle(saved) || agentDormantState(saved)))) {
7601
7724
  return withAgentSendLock(name, async () => {
7602
- const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
7603
- if (!isDeepStrictEqual(previous, saved) || (lifecycle?.state !== "hibernated" && !failedCodexResumeRecipe(previous)) || readAgentResumeAttempt(previous))
7604
- throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
7605
- const recipe = lifecycle ? confirmedAgentResumeRecipe(previous, lifecycle) : failedCodexResumeRecipe(previous);
7725
+ let previous, recipe;
7726
+ try {
7727
+ previous = loadAgentMetadata(name);
7728
+ const lifecycle = readAgentLifecycle(previous);
7729
+ if ((saved && !isDeepStrictEqual(previous, saved)) || (lifecycle?.state !== "hibernated" && !failedCodexResumeRecipe(previous)) || readAgentResumeAttempt(previous))
7730
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
7731
+ recipe = lifecycle ? confirmedAgentResumeRecipe(previous, lifecycle) : failedCodexResumeRecipe(previous);
7732
+ }
7733
+ catch (error) {
7734
+ if (opts.require_existing_resume)
7735
+ throw new AgentResumeUnavailableError(name);
7736
+ throw error;
7737
+ }
7606
7738
  if (kind !== previous.kind || sourceSessionId !== null
7607
7739
  || (opts.model != null && opts.model.trim() !== recipe.model)
7608
7740
  || (opts.reasoning_effort != null && opts.reasoning_effort.trim() !== recipe.reasoning_effort)
@@ -7610,7 +7742,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7610
7742
  || (opts.cwd != null && path.resolve(opts.cwd) !== recipe.cwd)
7611
7743
  || (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
7612
7744
  || (opts.env_vars !== undefined && !isDeepStrictEqual([...new Set(opts.env_vars)].sort(), Object.keys(recipe.environment).sort())))
7613
- throw new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
7745
+ throw opts.require_existing_resume ? new AgentResumeUnavailableError(name) : new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
7614
7746
  if (opts.launch_operation_id != null)
7615
7747
  requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
7616
7748
  cwd: opts.cwd ?? null, agentDone: true }));
package/dist/errors.js CHANGED
@@ -19,6 +19,16 @@ export class AgentAuthenticationPreflightError extends AitermError {
19
19
  this.name = "AgentAuthenticationPreflightError";
20
20
  }
21
21
  }
22
+ /** Admission refusal before the requested resume starts. */
23
+ export class AgentResumeUnavailableError extends AitermError {
24
+ resumeUnavailable;
25
+ constructor(sessionId) {
26
+ super("AGENT_RESUME_UNAVAILABLE: 保存した再開対象を確認できません。新規起動も本文送信もしていません。", 2);
27
+ this.resumeUnavailable = { schema: "aiterm.agent-resume-unavailable.v1",
28
+ code: "AGENT_RESUME_UNAVAILABLE", session_id: sessionId,
29
+ outcome: "unavailable", effect: "not_started", input: "not_sent" };
30
+ }
31
+ }
22
32
  /** Resume failures occur before the caller's body reaches the input path. */
23
33
  export class AgentResumeError extends AitermError {
24
34
  resumeFailure;
@@ -58,7 +58,7 @@ export const claudeAnonymousInterruptionObservationSchema = z.object({
58
58
  }).strict(),
59
59
  recorded_state: z.literal("unconfirmed"),
60
60
  native_boundary: z.object({ type: z.literal("anonymous_turn_reserved"), event_cursor: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) }).strict(),
61
- marker_protocol: z.literal("aiterm.claude-operation-marker.v2"), loaded_hook: z.literal("unconfirmed"),
61
+ marker_protocol: z.enum(["aiterm.claude-operation-marker.v2", "aiterm.claude-operation-marker.v3"]), loaded_hook: z.literal("unconfirmed"),
62
62
  invocation_fence: z.literal("unknown"), session_preserved: z.literal("unconfirmed"),
63
63
  }).strict().superRefine((value, context) => {
64
64
  const boundary = value.run.boundary;
@@ -666,7 +666,7 @@ export function claudeApiErrorFromLine(line) {
666
666
  catch {
667
667
  return null;
668
668
  }
669
- if (record?.type !== "assistant" || record?.isApiErrorMessage !== true)
669
+ if (record?.type !== "assistant" || record?.isApiErrorMessage !== true || record.isSidechain === true)
670
670
  return null;
671
671
  const content = record?.message?.content;
672
672
  const text = typeof content === "string"
@@ -678,8 +678,19 @@ export function claudeApiErrorFromLine(line) {
678
678
  return {
679
679
  text: text.trim() || (status != null ? `API Error: ${String(status)}` : "API Error"),
680
680
  at: typeof record?.timestamp === "string" ? record.timestamp : null,
681
+ status: Number.isInteger(status) && status >= 100 && status <= 599 ? status : null,
682
+ session_id: typeof record.sessionId === "string" ? record.sessionId : null,
683
+ uuid: typeof record.uuid === "string" ? record.uuid : null,
684
+ parent_uuid: typeof record.parentUuid === "string" ? record.parentUuid : null,
681
685
  };
682
686
  }
687
+ export function claudeFailureCategory(error) {
688
+ if (error.status === 429 || /^You've (?:reached your [^.\r\n]{1,80} limit\.|hit your (?:usage|session) limit\b)/i.test(error.text))
689
+ return "rate_limited";
690
+ if (error.status === 529)
691
+ return "capacity";
692
+ return error.status !== null && error.status >= 500 ? "transient" : "other";
693
+ }
683
694
  // Stopが発火しないエラー終了を、現在のturn開始後の会話記録だけから判定する。
684
695
  export function claudeApiErrorAfter(meta, startedAtMs) {
685
696
  const file = claudeSessionTranscriptPath(meta);
@@ -698,7 +709,7 @@ export function claudeApiErrorAfter(meta, startedAtMs) {
698
709
  lines.pop(); // 改行まで書かれた記録だけを扱う。
699
710
  for (const line of lines.reverse()) {
700
711
  const error = claudeApiErrorFromLine(line);
701
- if (error?.at && Date.parse(error.at) >= startedAtMs)
712
+ if (error?.at && (error.session_id === null || error.session_id === meta.vendor_session_id) && Date.parse(error.at) >= startedAtMs)
702
713
  return error;
703
714
  }
704
715
  return null;
@@ -418,6 +418,23 @@ export function codexUsageLimit(record) {
418
418
  const error = codexTurnError(record);
419
419
  return error?.info === "usage_limit_exceeded" ? error.message : null;
420
420
  }
421
+ export function codexFailureCategory(record) {
422
+ const error = codexTurnError(record);
423
+ if (!error)
424
+ return null;
425
+ if (error.info === "usage_limit_exceeded" || error.info === "rate_limit_exceeded")
426
+ return "rate_limited";
427
+ if (error.info === "server_overloaded"
428
+ || error.message === "Selected model is at capacity. Please try a different model.")
429
+ return "capacity";
430
+ const status = record.payload.error.codex_error_info?.http_connection_failed?.http_status_code;
431
+ if (status === 429)
432
+ return "rate_limited";
433
+ if (typeof status === "number" && status >= 400 && status < 500)
434
+ return "other";
435
+ return ["internal_server_error", "http_connection_failed", "response_stream_disconnected", "response_stream_connection_failed"].includes(error.info ?? "")
436
+ ? "transient" : "other";
437
+ }
421
438
  // 完了待ちが、会話の切り替えを確かめる間隔。送った文はすぐ記録へ書かれるので、普通のturnはここへ来ない。
422
439
  const CODEX_SWITCH_CHECK_MS = 3_000;
423
440
  // 完了待ちが、記録を1回に読む大きさ。
@@ -676,6 +693,7 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
676
693
  let cursor = startOffset;
677
694
  let carry = Buffer.alloc(0);
678
695
  let malformedEvents = 0;
696
+ let sawExecution = false;
679
697
  let discardLeadingFragment = false;
680
698
  let initializedBoundary = false;
681
699
  // 待ち始めてからrolloutが1行も増えない時、会話が切り替わっていないかを見る時刻(ADR 0105)。
@@ -784,6 +802,9 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
784
802
  }
785
803
  try {
786
804
  const record = JSON.parse(line);
805
+ if (record.type === "response_item" && (record.payload?.role === "assistant"
806
+ || ["function_call", "custom_tool_call", "local_shell_call", "reasoning"].includes(record.payload?.type)))
807
+ sawExecution = true;
787
808
  const done = codexCompletionEvent(meta, harnessSessionId, record);
788
809
  if (done && completedAfter !== null) {
789
810
  const at = Date.parse(record.timestamp);
@@ -794,12 +815,18 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
794
815
  // 上限の知らせはこのturnの終わりにだけ書かれる。画面やpane logの文字は、上限が明けた後も
795
816
  // 残り、道具の出力や依頼文にも現れるので見ない(2026-09-28)。
796
817
  const limited = codexUsageLimit(record);
818
+ const category = codexFailureCategory(record);
819
+ const failure = category ? { category, execution: sawExecution ? "started" : "unknown",
820
+ boundary: requestedCursor == null || completedAfter !== null ? null : {
821
+ event_cursor: requestedCursor, operation_id: null, turn_id: done.turn_id
822
+ },
823
+ terminal: true, future_effects: "unknown" } : undefined;
797
824
  if (limited)
798
- return observation("rate_limited", done, limited);
825
+ return { ...observation("rate_limited", done, limited), failure };
799
826
  // サービスの誤りや通信の失敗で終わったturnも、Codexはtask_completeを書く(errorつき、回答は無い)。
800
827
  // 完了として返すと、失敗が空の回答に見える。Claude CodeのAPIエラーと同じく、typedな終了として返す(ADR 0103)。
801
828
  const failed = codexTurnError(record);
802
- return failed ? observation("error", done, null, failed) : observation("done", done);
829
+ return failed ? { ...observation("error", done, null, failed), failure } : observation("done", done);
803
830
  }
804
831
  }
805
832
  catch {
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { remoteInputDescription, remoteInputSchema } from "./remote-contract.js";
3
3
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
4
4
  import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
5
- import { AitermError, AgentAuthenticationPreflightError, AgentResumeError } from "./errors.js";
5
+ import { AitermError, AgentAuthenticationPreflightError, AgentResumeUnavailableError, AgentResumeError } from "./errors.js";
6
6
  /**
7
7
  * aiterm-mcp — AI が握るローカル永続端末を stdio MCP サーバとして公開する(Node/TS 版)。
8
8
  *
@@ -29,6 +29,7 @@ import { fileURLToPath } from "node:url";
29
29
  import { ExecutionError, executionErrorResult } from "./execution-wire.js";
30
30
  import { attachExecutionControlRegistrar } from "./execution-tools.js";
31
31
  import { ParentDeliveryManager, deliveryKey } from "./parent-delivery.js";
32
+ import { failureObservationSchema } from "./parent-delivery-record.js";
32
33
  import { acceptRemote, callRemoteTool, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
33
34
  import { codexParentFromRequest } from "./codex-parent-receiver.js";
34
35
  import { claudeParentFromRequest, discardClaudeHookRequest } from "./claude-parent-receiver.js";
@@ -142,12 +143,12 @@ export function createAitermServer(options = {}) {
142
143
  const wait = delivery?.wait_process();
143
144
  return `\ndelivery_id=${id}` + (wait ? `\nwait_process(ターンを終える前に背景で起動): ${waitProcessCommandLine(wait)}` : "");
144
145
  }
145
- function completionWait(delivery, session, eventCursor, launchId) {
146
+ function completionWait(delivery, session, eventCursor, launchId, inputId) {
146
147
  if (eventCursor === null)
147
148
  return { wait_process: null, wait_command: null };
148
149
  if (delivery)
149
150
  return { wait_process: delivery.wait_process(), wait_command: null };
150
- return { wait_process: core.agentWaitProcess(session, eventCursor, { launchId }), wait_command: `aiterm-wait --session ${session} --cursor ${eventCursor}` };
151
+ return { wait_process: core.agentWaitProcess(session, eventCursor, { launchId, inputId }), wait_command: `aiterm-wait --session ${session} --cursor ${eventCursor}` + (inputId ? ` --input ${inputId}` : "") };
151
152
  }
152
153
  /**
153
154
  * dispatch 系の説明で共有する非ブロック規範。tool description は registerTool 時=initialize 前に
@@ -172,12 +173,16 @@ export function createAitermServer(options = {}) {
172
173
  delivery_id: z.string(), state: z.enum(["waiting", "ready", "sending", "submitted", "failed", "unknown"]),
173
174
  child_outcome: z.enum(["done", "closed", "rate_limited", "error"]).nullable(),
174
175
  child_turn_id: z.string().nullable(), queued_submission_id: z.string().nullable(), error_code: z.string().nullable(),
176
+ child_failure: failureObservationSchema.optional(), child_error_kind: z.string().nullable().optional(), child_vendor_session_id: z.string().nullable().optional(),
175
177
  });
176
178
  function ok(s) {
177
179
  return { content: [{ type: "text", text: s }] };
178
180
  }
179
181
  function fail(e) {
180
182
  const msg = e instanceof Error ? e.message : String(e);
183
+ if (e instanceof AgentResumeUnavailableError)
184
+ return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
185
+ _meta: { "aiterm/resume_unavailable": { ...e.resumeUnavailable } } };
181
186
  if (e instanceof AgentResumeError)
182
187
  return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
183
188
  structuredContent: { ...e.resumeFailure } };
@@ -326,30 +331,30 @@ export function createAitermServer(options = {}) {
326
331
  if (delivery)
327
332
  await remoteParentDelivery.beforeChange(key, true);
328
333
  if (delivery && structured.event_cursor !== null)
329
- await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor);
334
+ await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor, null, structured.input_id);
330
335
  }
331
336
  catch (e) {
332
337
  delivery?.failed(e);
333
338
  return fail(new Error(`別端末へのdispatchは済みましたが、回答配送を登録できませんでした: ${e instanceof Error ? e.message : String(e)}`));
334
339
  }
335
- const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor);
340
+ const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor, structured.input_id);
336
341
  return {
337
342
  content: [...result.content, remoteNote(target, result), { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }],
338
343
  structuredContent: { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) },
339
344
  };
340
345
  }
341
346
  /** 別端末の子の依頼を、この端末の親への配送に登録する。launch_idは現地の完了観測から取る。 */
342
- async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null) {
343
- const probe = await observeRemoteAgentDone(target, sessionId, { cursor: eventCursor, operation_id: operationId, timeout: 0 });
347
+ async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null, inputId) {
348
+ const probe = await observeRemoteAgentDone(target, sessionId, { cursor: eventCursor, operation_id: operationId, timeout: 0, input_id: inputId });
344
349
  await delivery.before_send({ session_id: sessionId, launch_id: probe.launch_id, vendor: probe.vendor, harness: probe.harness,
345
- event_cursor: eventCursor, operation_id: operationId, remote: target });
350
+ event_cursor: eventCursor, operation_id: operationId, ...(inputId ? { input_id: inputId } : {}), remote: target });
346
351
  }
347
- async function remoteCompletionWait(delivery, target, sessionId, eventCursor) {
352
+ async function remoteCompletionWait(delivery, target, sessionId, eventCursor, inputId) {
348
353
  if (eventCursor === null)
349
354
  return { wait_process: null, wait_command: null };
350
355
  if (delivery)
351
356
  return { wait_process: delivery.wait_process(), wait_command: null };
352
- const waitProcess = await remoteWaitProcess(target, sessionId, eventCursor);
357
+ const waitProcess = await remoteWaitProcess(target, sessionId, eventCursor, inputId);
353
358
  return { wait_process: waitProcess, wait_command: `ssh ${remoteLabel(target)} aiterm-wait --session ${sessionId} --cursor ${eventCursor}` };
354
359
  }
355
360
  server.registerTool("diagnostics", {
@@ -432,6 +437,7 @@ export function createAitermServer(options = {}) {
432
437
  mode: z.enum(["sent", "agent_dispatch", "agent_steer"]),
433
438
  session_id: z.string(),
434
439
  event_cursor: z.number().int().nullable(),
440
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
435
441
  wait_process: waitProcessOutputSchema,
436
442
  parent_delivery: parentDeliveryOutputSchema.optional(),
437
443
  launch_id: z.string().nullable(),
@@ -495,7 +501,7 @@ export function createAitermServer(options = {}) {
495
501
  ...(follow ? { _meta: { [STEER_RESULT_META_KEY]: { schema: "aiterm.steer-ref.v1", steer_id: follow.steer_id, interim_from: follow.interim_from } } } : {}),
496
502
  };
497
503
  }
498
- const waited = completionWait(delivery, receipt.session_id, receipt.event_cursor, receipt.launch_id);
504
+ const waited = completionWait(delivery, receipt.session_id, receipt.event_cursor, receipt.launch_id, receipt.input_id);
499
505
  return {
500
506
  content: [
501
507
  {
@@ -511,6 +517,7 @@ export function createAitermServer(options = {}) {
511
517
  mode: "agent_dispatch",
512
518
  session_id: receipt.session_id,
513
519
  event_cursor: receipt.event_cursor,
520
+ ...(receipt.input_id ? { input_id: receipt.input_id } : {}),
514
521
  wait_process: waited.wait_process,
515
522
  ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}),
516
523
  launch_id: receipt.launch_id,
@@ -1120,13 +1127,13 @@ export function createAitermServer(options = {}) {
1120
1127
  return { content: [...result.content, remoteNote(target, result)], isError: true };
1121
1128
  try {
1122
1129
  if (delivery && structured.event_cursor !== null)
1123
- await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor);
1130
+ await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor, null, structured.input_id);
1124
1131
  }
1125
1132
  catch (e) {
1126
1133
  delivery?.failed(e);
1127
1134
  return fail(new Error(`別端末でagentは起動しましたが、回答配送を登録できませんでした(session_id=${structured.session_id}): ${e instanceof Error ? e.message : String(e)}`));
1128
1135
  }
1129
- const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor);
1136
+ const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor, structured.input_id);
1130
1137
  // 現地が開始未確認を誤りで返す版(0.54.0以前)でも、ここでは誤りにしない(ADR 0093)。案内が無ければ足す。
1131
1138
  const unconfirmed = core.launchStartUnconfirmed(structured);
1132
1139
  const noted = result.content.some(item => item.type === "text" && item.text.includes(core.INITIAL_PROMPT_UNCONFIRMED_MARK));
@@ -1142,16 +1149,20 @@ export function createAitermServer(options = {}) {
1142
1149
  }
1143
1150
  async function launchAgent(kind, args, extra) {
1144
1151
  const supportsWriteScope = kind !== "claude";
1145
- const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project } = args;
1152
+ const { prompt, image, throughline_source_session, throughline_supplement_file, model, reasoning_effort, fast, env_vars, cwd, session_name, launch_operation_id, write_scope, trust_project, require_existing_resume } = args;
1146
1153
  let delivery = null;
1147
1154
  try {
1148
1155
  if (!supportsWriteScope && write_scope !== undefined) {
1149
1156
  throw new core.AitermError("claude-code harnessはwrite_scopeに対応していません。指定を外してください", 2);
1150
1157
  }
1151
- await core.maintainAgentIdleClocks();
1158
+ if (require_existing_resume && ((image?.length ?? 0) > 0 || prompt != null || throughline_source_session != null || throughline_supplement_file != null))
1159
+ throw new core.AitermError("require_existing_resume is promptless", 2);
1160
+ if (!require_existing_resume)
1161
+ await core.maintainAgentIdleClocks();
1152
1162
  const initialPrompt = image && image.length > 0 ? core.attachImages(prompt ?? "", image) : prompt ?? undefined;
1153
1163
  if (initialPrompt || throughline_source_session)
1154
1164
  delivery = await deliveryForRequest(extra);
1165
+ let inputId;
1155
1166
  const [sid, hint, eventCursor, submitResidue, initialDelivery, startup, fastState] = await core.openAgentWithInitialPrompt(kind, {
1156
1167
  prompt: initialPrompt,
1157
1168
  throughline_source_session,
@@ -1161,9 +1172,10 @@ export function createAitermServer(options = {}) {
1161
1172
  fast: fast ?? undefined,
1162
1173
  env_vars,
1163
1174
  trust_project,
1164
- before_send: delivery?.before_send,
1175
+ before_send: async (boundary) => { inputId = boundary.input_id; await delivery?.before_send(boundary); },
1165
1176
  cwd: cwd ?? undefined,
1166
1177
  session_name: session_name ?? undefined,
1178
+ require_existing_resume,
1167
1179
  launch_operation_id: launch_operation_id ?? undefined,
1168
1180
  ...(supportsWriteScope ? { write_scope } : {}),
1169
1181
  });
@@ -1174,7 +1186,8 @@ export function createAitermServer(options = {}) {
1174
1186
  session_id: sid,
1175
1187
  managed_completion: true,
1176
1188
  event_cursor: eventCursor,
1177
- ...completionWait(delivery, sid, eventCursor),
1189
+ ...completionWait(delivery, sid, eventCursor, undefined, inputId),
1190
+ ...(inputId ? { input_id: inputId } : {}),
1178
1191
  ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}),
1179
1192
  submit_residue: submitResidue,
1180
1193
  initial_prompt: initialDelivery,
@@ -1275,6 +1288,7 @@ export function createAitermServer(options = {}) {
1275
1288
  // 起動時promptでturnが走っている時だけ非null。wait_processがmachine向けprocess境界、
1276
1289
  // wait_commandは人間向け互換表示。
1277
1290
  event_cursor: z.number().int().nullable(),
1291
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
1278
1292
  wait_process: waitProcessOutputSchema,
1279
1293
  wait_command: z.string().nullable(),
1280
1294
  parent_delivery: parentDeliveryOutputSchema.optional(),
@@ -1294,6 +1308,7 @@ export function createAitermServer(options = {}) {
1294
1308
  "remoteを付けると、SSHで入った別端末のAitermで同じ起動を行い、完了は同じ形で親へ届く。" +
1295
1309
  agentEnvironmentDesc + agentCompletionDesc,
1296
1310
  inputSchema: {
1311
+ require_existing_resume: z.boolean().optional().describe("Resume an existing saved conversation only; missing or unsupported target never creates a new session. Requires session_name and no prompt; local-only."),
1297
1312
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).describe("agent loop・session・hook・transcript・認証を所有する実行基盤"),
1298
1313
  prompt: z.string().nullish().describe("起動時に渡す初手プロンプト(任意)。送信後は待たずに即返る"),
1299
1314
  image: z.array(z.string()).optional().describe("初手プロンプトへ添付する画像ファイルの絶対パス(png/jpg/jpeg/gif/webp)"),
@@ -1321,6 +1336,7 @@ export function createAitermServer(options = {}) {
1321
1336
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
1322
1337
  managed_completion: z.boolean(),
1323
1338
  event_cursor: z.number().int().nullable(),
1339
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
1324
1340
  wait_process: waitProcessOutputSchema,
1325
1341
  wait_command: z.string().nullable(),
1326
1342
  parent_delivery: parentDeliveryOutputSchema.optional(),
@@ -1331,6 +1347,10 @@ export function createAitermServer(options = {}) {
1331
1347
  write_scope_enforcement: z.enum(["enforced_read_only", "declaration_only_unsupported"]).optional(),
1332
1348
  },
1333
1349
  }, async ({ harness, remote, ...args }, extra) => {
1350
+ if (remote && args.require_existing_resume)
1351
+ return fail(typeof args.session_name === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(args.session_name)
1352
+ ? new AgentResumeUnavailableError(args.session_name)
1353
+ : new AitermError("require_existing_resume requires session_name", 2));
1334
1354
  if (!remote)
1335
1355
  return launchAgent(kindForHarness(harness), args, extra);
1336
1356
  try {
@@ -9,6 +9,13 @@ import { cursorParentSchema } from "./cursor-parent-receiver.js";
9
9
  import { executionRequestSchema } from "./execution-contract.js";
10
10
  import { parentSourceSchema } from "./execution-parent-source.js";
11
11
  import { executionActorSchema } from "./execution-inventory.js";
12
+ export const failureObservationSchema = z.object({
13
+ category: z.enum(["capacity", "rate_limited", "transient", "other"]),
14
+ execution: z.enum(["not_started", "started", "unknown"]),
15
+ boundary: z.object({ event_cursor: z.number().int().nonnegative(), operation_id: z.string().nullable(), turn_id: z.string().nullable(),
16
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional() }).strict().nullable(),
17
+ terminal: z.boolean(), future_effects: z.literal("unknown"),
18
+ }).strict();
12
19
  export const recordSchema = z.object({
13
20
  schema: z.literal("aiterm.parent-delivery.v1"),
14
21
  delivery_id: z.uuid(),
@@ -21,6 +28,7 @@ export const recordSchema = z.object({
21
28
  vendor: z.enum(["claude", "codex", "grok", "cursor", "antigravity"]),
22
29
  harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]),
23
30
  event_cursor: z.number().int().nonnegative(), operation_id: z.string().nullable(),
31
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
24
32
  // 別端末の子。remote用の保存場所にだけ書き、旧版のreaderへ渡さない。
25
33
  remote: remoteTargetSchema.optional(),
26
34
  }).strict(),
@@ -28,6 +36,9 @@ export const recordSchema = z.object({
28
36
  text: z.string().nullable(),
29
37
  child_outcome: z.enum(["done", "closed", "rate_limited", "error"]).nullable(),
30
38
  child_turn_id: z.string().nullable(),
39
+ child_error_kind: z.string().nullable().optional(),
40
+ child_vendor_session_id: z.string().nullable().optional(),
41
+ child_failure: failureObservationSchema.optional(),
31
42
  error: z.string().nullable(),
32
43
  queued_submission_id: z.string().nullable(),
33
44
  // Private references for this existing delivery, never a payload/retry queue.
@@ -35,6 +46,10 @@ export const recordSchema = z.object({
35
46
  execution: z.object({ request: executionRequestSchema, source_evidence: parentSourceSchema.optional(),
36
47
  origin_owner: executionActorSchema.optional() }).strict().optional(),
37
48
  }).strict().superRefine((record, context) => {
49
+ const failed = record.child_failure?.boundary;
50
+ if (failed && (failed.event_cursor !== record.boundary.event_cursor || failed.operation_id !== record.boundary.operation_id
51
+ || failed.turn_id !== record.child_turn_id || failed.input_id !== record.boundary.input_id))
52
+ context.addIssue({ code: "custom", message: "failure must match the original child boundary" });
38
53
  if (record.execution?.source_evidence && JSON.stringify(record.execution.request) !== JSON.stringify(record.execution.source_evidence.request))
39
54
  context.addIssue({ code: "custom", message: "parent delivery source request must match its original reference" });
40
55
  const execution = record.execution;
@@ -61,5 +76,7 @@ export function answerMessage(record) {
61
76
  return "Aitermの子エージェントからの実行結果です。子の回答として扱ってください。\n" +
62
77
  `delivery_id=${record.delivery_id}\nsession=${record.boundary.session_id}\nharness=${record.boundary.harness}\n` +
63
78
  `launch_id=${record.boundary.launch_id}\nturn_id=${record.child_turn_id ?? "unknown"}\n` +
64
- `outcome=${record.child_outcome}\n\n${record.text ?? ""}`;
79
+ `outcome=${record.child_outcome}\n` +
80
+ (record.child_failure ? `failure=${JSON.stringify(record.child_failure)}\nvendor_session_id=${record.child_vendor_session_id ?? "unknown"}\nerror_kind=${record.child_error_kind ?? "unknown"}\n` : "") +
81
+ `\n${record.text ?? ""}`;
65
82
  }
@@ -90,6 +90,8 @@ function receipt(record) {
90
90
  ? codexHookDeliveryState(record.parent.codex_home, record.parent.thread_id, record.delivery_id) : null;
91
91
  return { delivery_id: record.delivery_id, state: hookState ?? record.state, child_outcome: record.child_outcome,
92
92
  child_turn_id: record.child_turn_id, queued_submission_id: record.queued_submission_id,
93
+ ...(record.child_failure ? { child_failure: record.child_failure, child_error_kind: record.child_error_kind,
94
+ child_vendor_session_id: record.child_vendor_session_id } : {}),
93
95
  error_code: hookState === "unknown" ? "CODEX_HOOK_DELIVERY_UNCONFIRMED"
94
96
  : record.error ? /^[A-Z][A-Z0-9_]+(?=:)/.exec(record.error)?.[0] ?? "PARENT_DELIVERY_FAILED" : null };
95
97
  }
@@ -416,6 +418,7 @@ export class ParentDeliveryManager {
416
418
  try {
417
419
  const completion = await this.deps.observe(boundary.session_id, {
418
420
  cursor: boundary.event_cursor, operation_id: boundary.operation_id,
421
+ ...(boundary.input_id ? { input_id: boundary.input_id } : {}),
419
422
  timeout: Infinity, signal: job.controller.signal, ...(boundary.remote ? { remote: boundary.remote } : {}),
420
423
  });
421
424
  await this.capture(job, completion);
@@ -433,14 +436,23 @@ export class ParentDeliveryManager {
433
436
  if (job.record.state !== "waiting")
434
437
  return;
435
438
  job.capture = (async () => {
436
- if (completion.launch_id !== job.record.boundary.launch_id)
439
+ if (completion.launch_id !== job.record.boundary.launch_id || completion.session_id !== job.record.boundary.session_id)
437
440
  throw new AitermError("PARENT_DELIVERY_LAUNCH_CHANGED: 子のlaunchが置換されました", 2);
441
+ if (job.record.boundary.input_id && completion.input_id !== job.record.boundary.input_id)
442
+ throw new AitermError("PARENT_DELIVERY_INPUT_CHANGED: 完了は元の入力に対応していません", 2);
438
443
  // not_takenは差し込みを追う待ちだけが返す。親配送の待ちは差し込みを追わないので、来ない。
439
444
  if (completion.outcome === "running" || completion.outcome === "timeout" || completion.outcome === "not_taken")
440
445
  throw new AitermError("PARENT_DELIVERY_NOT_COMPLETED: 子の完了を確認できません", 2);
441
446
  const record = job.record;
447
+ if (completion.failure)
448
+ recordSchema.parse({ ...record, child_failure: completion.failure, child_turn_id: completion.turn_id });
442
449
  record.child_outcome = completion.outcome;
443
450
  record.child_turn_id = completion.turn_id;
451
+ if (completion.failure) {
452
+ record.child_failure = structuredClone(completion.failure);
453
+ record.child_error_kind = completion.error_kind ?? null;
454
+ record.child_vendor_session_id = completion.vendor_session_id;
455
+ }
444
456
  if (completion.outcome === "done") {
445
457
  const answer = await this.deps.answer(record.boundary.session_id, { completion, operation_id: completion.operation_id, raw: true,
446
458
  ...(record.boundary.remote ? { remote: record.boundary.remote } : {}) });
@@ -506,6 +518,7 @@ export class ParentDeliveryManager {
506
518
  continue;
507
519
  const boundary = job.record.boundary;
508
520
  const completion = await this.deps.observe(boundary.session_id, { cursor: boundary.event_cursor, operation_id: boundary.operation_id, timeout: 0,
521
+ ...(boundary.input_id ? { input_id: boundary.input_id } : {}),
509
522
  ...(boundary.remote ? { remote: boundary.remote } : {}) });
510
523
  if (completion.outcome !== "running" && completion.outcome !== "timeout") {
511
524
  await this.capture(job, completion);
package/dist/remote.js CHANGED
@@ -167,16 +167,20 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000) {
167
167
  }
168
168
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
169
169
  const OPERATION_RE = /^sha256:[0-9a-f]{64}$/;
170
- export function remoteWaitCommand(shell, session, cursor, operationId, timeout) {
170
+ export function remoteWaitCommand(shell, session, cursor, operationId, timeout, inputId) {
171
171
  if (!SESSION_RE.test(session))
172
172
  throw new AitermError("REMOTE_SESSION_INVALID: session名が不正です", 2);
173
173
  if (operationId !== null && !OPERATION_RE.test(operationId))
174
174
  throw new AitermError("REMOTE_OPERATION_INVALID: operation_idが不正です", 2);
175
+ if (inputId !== undefined && (!/^[a-f0-9]{32}$/.test(inputId) || cursor === null))
176
+ throw new AitermError("REMOTE_INPUT_INVALID: input_id requires its original cursor", 2);
175
177
  const parts = ["--session", session, "--timeout", String(timeout)];
176
178
  if (cursor !== null)
177
179
  parts.push("--cursor", String(cursor));
178
180
  if (operationId !== null)
179
181
  parts.push("--operation", operationId);
182
+ if (inputId !== undefined)
183
+ parts.push("--input", inputId);
180
184
  if (shell !== "posix")
181
185
  return `aiterm-wait ${parts.join(" ")}`;
182
186
  // npmのbinをPATHへ通さず aiterm-mcp だけリンクしている端末がある。見つからなければ同じpackageのCLIを使う。
@@ -184,9 +188,9 @@ export function remoteWaitCommand(shell, session, cursor, operationId, timeout)
184
188
  return posixCommand(`${resolve}; exec "$w" ${parts.join(" ")}`);
185
189
  }
186
190
  /** 親が別processで起動する完了待ち。ssh越しのaiterm-waitで、exit codeは現地のaiterm-waitをそのまま返す。 */
187
- export async function remoteWaitProcess(target, session, cursor) {
191
+ export async function remoteWaitProcess(target, session, cursor, inputId) {
188
192
  // 別processには鍵のパスフレーズを渡せない。ssh-agentか、張ってあるControlMasterの接続に相乗りする。
189
- const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600), { passphrase: false });
193
+ const { args } = sshInvocation(target, remoteWaitCommand(await remoteShell(target), session, cursor, null, 600, inputId), { passphrase: false });
190
194
  return { executable: "ssh", args, windows_start_process_argument_list: process.platform === "win32" ? windowsStartProcessArgumentList(args) : null };
191
195
  }
192
196
  function runSsh(target, command, signal) {
@@ -212,7 +216,7 @@ export async function observeRemoteAgentDone(target, session, options) {
212
216
  if (options.signal?.aborted)
213
217
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
214
218
  const remaining = infinite ? 86_400 : Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
215
- const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400));
219
+ const command = remoteWaitCommand(await remoteShell(target), session, options.cursor ?? null, options.operation_id ?? null, Math.min(remaining, 86_400), options.input_id);
216
220
  const { code, stdout, stderr } = await runSsh(target, command, options.signal);
217
221
  if (options.signal?.aborted)
218
222
  throw new AitermError("REMOTE_OBSERVE_ABORTED: 観測を停止しました", 2);
@@ -11,8 +11,8 @@ import * as path from "node:path";
11
11
  import { createHash, randomBytes } from "node:crypto";
12
12
  import { AitermError } from "./errors.js";
13
13
  import { AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_RATE_LIMIT_POLL_MS, AGENT_TURN_BOUNDARY_TAIL_BYTES, agentHarness, agentMetadataPath, agentsDir, assertSessionName, LAUNCH_ID_RE, readFileRange, safeStatSize, scanLinesNewestFirst, sleep, } from "./agent-shared.js";
14
- import { claudeApiErrorFromLine, claudeSessionTranscriptPath } from "./harnesses/claude.js";
15
- import { codexBoundTranscript, codexCompletionEvent, codexRolloutSessionId, codexRootTranscript, codexResumeCursor, codexResumeTurnId, codexRunningTurn, codexTranscriptSessionId, codexTurnError, codexTurnErrorLine, codexUsageLimit, } from "./harnesses/codex.js";
14
+ import { claudeApiErrorFromLine, claudeFailureCategory, claudeSessionTranscriptPath } from "./harnesses/claude.js";
15
+ import { codexBoundTranscript, codexCompletionEvent, codexRolloutSessionId, codexRootTranscript, codexResumeCursor, codexResumeTurnId, codexRunningTurn, codexTranscriptSessionId, codexTurnError, codexTurnErrorLine, codexUsageLimit, codexFailureCategory, } from "./harnesses/codex.js";
16
16
  import { interimFromToken, parseInterimFrom } from "./interim-words.js";
17
17
  import { grokEventsTranscript, grokSessionDirectory, grokUserPrompt } from "./harnesses/grok.js";
18
18
  /** 差し込みの返りの_metaで返すキー。 */
@@ -317,10 +317,12 @@ async function observeCodexSteerDone(meta, entry, timeoutSeconds, deps) {
317
317
  const observed = { ...baseObservation(meta), vendor_session_id: done.vendor_session_id ?? meta.vendor_session_id ?? null,
318
318
  turn_id: done.turn_id, malformed_events: malformedEvents, at: done.at, steer };
319
319
  const limited = codexUsageLimit(record);
320
+ const category = codexFailureCategory(record);
321
+ const failure = category ? { category, execution: "unknown", boundary: null, terminal: true, future_effects: "unknown" } : undefined;
320
322
  if (limited)
321
- return { ...observed, outcome: "rate_limited", rate_limit: limited };
323
+ return { ...observed, outcome: "rate_limited", rate_limit: limited, failure };
322
324
  const failed = codexTurnError(record);
323
- return failed ? { ...observed, outcome: "error", error: codexTurnErrorLine(failed), error_kind: failed.info } : { ...observed, outcome: "done" };
325
+ return failed ? { ...observed, outcome: "error", error: codexTurnErrorLine(failed), error_kind: failed.info, failure } : { ...observed, outcome: "done" };
324
326
  };
325
327
  const pending = (outcome) => ({ ...baseObservation(meta), outcome, malformed_events: malformedEvents, steer: taken?.fate ?? fate("unknown") });
326
328
  for (;;) {
@@ -510,8 +512,11 @@ async function observeClaudeSteerDone(meta, entry, timeoutSeconds, deps) {
510
512
  continue;
511
513
  // Stopが来ない終わり方(APIエラー)は、今までの待ちと同じく、誤りとして返す。
512
514
  const failed = claudeApiErrorFromLine(line);
513
- if (failed)
514
- return { ...observed("error", null, taken), at: failed.at, error: failed.text };
515
+ if (failed && (failed.session_id === null || failed.session_id === meta.vendor_session_id))
516
+ return {
517
+ ...observed("error", null, taken), at: failed.at, error: failed.text, error_kind: failed.status ? `http_${failed.status}` : null,
518
+ failure: { category: claudeFailureCategory(failed), execution: "unknown", boundary: null, terminal: false, future_effects: "unknown" }
519
+ };
515
520
  const text = claudeTextBlocks(parsed.message?.content);
516
521
  const at = stamp ? Date.parse(stamp) : NaN;
517
522
  answers.set(createHash("sha256").update(text, "utf8").digest("hex"), Number.isFinite(at) ? at : -Infinity);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.63.6",
3
+ "version": "0.63.8",
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": [