aiterm-mcp 0.63.5 → 0.63.7

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.
@@ -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
@@ -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,6 +173,7 @@ 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 }] };
@@ -204,8 +206,8 @@ export function createAitermServer(options = {}) {
204
206
  * Factory 向けの read-only 診断。JSON の field は意図的に allowlist 制で、絶対 path、環境変数、
205
207
  * token、コマンド本文、PTY 出力、raw log、認証状態を公開しない。
206
208
  */
207
- async function factoryDiagnostics() {
208
- const ptyList = core.readOnlyPtyListDiagnostic();
209
+ async function factoryDiagnostics(format = "v1") {
210
+ const ptyList = core.readOnlyPtyListDiagnostic(undefined, format === "v2");
209
211
  const claude = core.harnessLauncherDiagnostic("claude");
210
212
  const codex = core.harnessLauncherDiagnostic("codex");
211
213
  const grok = core.harnessLauncherDiagnostic("grok");
@@ -214,11 +216,11 @@ export function createAitermServer(options = {}) {
214
216
  const runtimeErrors = await runtimeErrorStoreDiagnostic();
215
217
  const overall = ptyList.status === "unverified" || runtimeErrors.status === "unverified" ? "unverified" : "ready";
216
218
  return JSON.stringify({
217
- diagnostic_schema: "aiterm-mcp.factory-diagnostics.v1",
219
+ diagnostic_schema: format === "v2" ? "aiterm-mcp.factory-diagnostics.v2" : "aiterm-mcp.factory-diagnostics.v1",
218
220
  version: pkg.version,
219
221
  overall,
220
222
  mcp: { transport: "stdio", initialize: "ready", tool_call: "ready" },
221
- pty_list: { access: "read_only", ...ptyList },
223
+ pty_list: { access: "read_only", ...ptyList, ...(format === "v2" ? { timeout_ms: 5000 } : {}) },
222
224
  runtime_error_store: runtimeErrors,
223
225
  vendor_dependencies: {
224
226
  claude: {
@@ -326,40 +328,40 @@ export function createAitermServer(options = {}) {
326
328
  if (delivery)
327
329
  await remoteParentDelivery.beforeChange(key, true);
328
330
  if (delivery && structured.event_cursor !== null)
329
- await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor);
331
+ await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor, null, structured.input_id);
330
332
  }
331
333
  catch (e) {
332
334
  delivery?.failed(e);
333
335
  return fail(new Error(`別端末へのdispatchは済みましたが、回答配送を登録できませんでした: ${e instanceof Error ? e.message : String(e)}`));
334
336
  }
335
- const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor);
337
+ const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor, structured.input_id);
336
338
  return {
337
339
  content: [...result.content, remoteNote(target, result), { type: "text", text: deliveryIdLine(delivery).trim() || "completion=wait_process" }],
338
340
  structuredContent: { ...structured, wait_process: waited.wait_process, ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}) },
339
341
  };
340
342
  }
341
343
  /** 別端末の子の依頼を、この端末の親への配送に登録する。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 });
344
+ async function registerRemoteDelivery(delivery, target, sessionId, eventCursor, operationId = null, inputId) {
345
+ const probe = await observeRemoteAgentDone(target, sessionId, { cursor: eventCursor, operation_id: operationId, timeout: 0, input_id: inputId });
344
346
  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 });
347
+ event_cursor: eventCursor, operation_id: operationId, ...(inputId ? { input_id: inputId } : {}), remote: target });
346
348
  }
347
- async function remoteCompletionWait(delivery, target, sessionId, eventCursor) {
349
+ async function remoteCompletionWait(delivery, target, sessionId, eventCursor, inputId) {
348
350
  if (eventCursor === null)
349
351
  return { wait_process: null, wait_command: null };
350
352
  if (delivery)
351
353
  return { wait_process: delivery.wait_process(), wait_command: null };
352
- const waitProcess = await remoteWaitProcess(target, sessionId, eventCursor);
354
+ const waitProcess = await remoteWaitProcess(target, sessionId, eventCursor, inputId);
353
355
  return { wait_process: waitProcess, wait_command: `ssh ${remoteLabel(target)} aiterm-wait --session ${sessionId} --cursor ${eventCursor}` };
354
356
  }
355
357
  server.registerTool("diagnostics", {
356
358
  description: "Factory 向け read-only 診断。安全な状態語彙だけを機械可読 JSON で返す(PTY 内容・認証情報・path・環境値は返さない)。" +
357
359
  "2つ目のtextは親配送hook(Claude Code・Cursor)の登録状態で、caller_status が setup_required なら呼出元からのagent送信は拒否される。aiterm-setup を実行する。",
358
- inputSchema: {},
360
+ inputSchema: { format: z.enum(["v1", "v2"]).optional().describe("既定v1は既存の固定fieldを維持。v2はPTY診断の安全なreason_codeを含む。") },
359
361
  },
360
362
  // 1つ目は項目を固定したfactory向けの契約。親配送hookの状態は別のtextに分け、既存の読み手の形を変えない。
361
- async () => ({ content: [
362
- { type: "text", text: await factoryDiagnostics() },
363
+ async ({ format }) => ({ content: [
364
+ { type: "text", text: await factoryDiagnostics(format) },
363
365
  { type: "text", text: JSON.stringify(parentDeliveryDiagnostic(deliveryParentKind(server.server.getClientVersion()?.name))) },
364
366
  ] }));
365
367
  const DEFAULT_PTY_SHELL = process.platform === "win32" ? "pwsh" : "bash";
@@ -432,6 +434,7 @@ export function createAitermServer(options = {}) {
432
434
  mode: z.enum(["sent", "agent_dispatch", "agent_steer"]),
433
435
  session_id: z.string(),
434
436
  event_cursor: z.number().int().nullable(),
437
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
435
438
  wait_process: waitProcessOutputSchema,
436
439
  parent_delivery: parentDeliveryOutputSchema.optional(),
437
440
  launch_id: z.string().nullable(),
@@ -495,7 +498,7 @@ export function createAitermServer(options = {}) {
495
498
  ...(follow ? { _meta: { [STEER_RESULT_META_KEY]: { schema: "aiterm.steer-ref.v1", steer_id: follow.steer_id, interim_from: follow.interim_from } } } : {}),
496
499
  };
497
500
  }
498
- const waited = completionWait(delivery, receipt.session_id, receipt.event_cursor, receipt.launch_id);
501
+ const waited = completionWait(delivery, receipt.session_id, receipt.event_cursor, receipt.launch_id, receipt.input_id);
499
502
  return {
500
503
  content: [
501
504
  {
@@ -511,6 +514,7 @@ export function createAitermServer(options = {}) {
511
514
  mode: "agent_dispatch",
512
515
  session_id: receipt.session_id,
513
516
  event_cursor: receipt.event_cursor,
517
+ ...(receipt.input_id ? { input_id: receipt.input_id } : {}),
514
518
  wait_process: waited.wait_process,
515
519
  ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}),
516
520
  launch_id: receipt.launch_id,
@@ -1120,13 +1124,13 @@ export function createAitermServer(options = {}) {
1120
1124
  return { content: [...result.content, remoteNote(target, result)], isError: true };
1121
1125
  try {
1122
1126
  if (delivery && structured.event_cursor !== null)
1123
- await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor);
1127
+ await registerRemoteDelivery(delivery, target, structured.session_id, structured.event_cursor, null, structured.input_id);
1124
1128
  }
1125
1129
  catch (e) {
1126
1130
  delivery?.failed(e);
1127
1131
  return fail(new Error(`別端末でagentは起動しましたが、回答配送を登録できませんでした(session_id=${structured.session_id}): ${e instanceof Error ? e.message : String(e)}`));
1128
1132
  }
1129
- const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor);
1133
+ const waited = await remoteCompletionWait(delivery, target, structured.session_id, structured.event_cursor, structured.input_id);
1130
1134
  // 現地が開始未確認を誤りで返す版(0.54.0以前)でも、ここでは誤りにしない(ADR 0093)。案内が無ければ足す。
1131
1135
  const unconfirmed = core.launchStartUnconfirmed(structured);
1132
1136
  const noted = result.content.some(item => item.type === "text" && item.text.includes(core.INITIAL_PROMPT_UNCONFIRMED_MARK));
@@ -1152,6 +1156,7 @@ export function createAitermServer(options = {}) {
1152
1156
  const initialPrompt = image && image.length > 0 ? core.attachImages(prompt ?? "", image) : prompt ?? undefined;
1153
1157
  if (initialPrompt || throughline_source_session)
1154
1158
  delivery = await deliveryForRequest(extra);
1159
+ let inputId;
1155
1160
  const [sid, hint, eventCursor, submitResidue, initialDelivery, startup, fastState] = await core.openAgentWithInitialPrompt(kind, {
1156
1161
  prompt: initialPrompt,
1157
1162
  throughline_source_session,
@@ -1161,7 +1166,7 @@ export function createAitermServer(options = {}) {
1161
1166
  fast: fast ?? undefined,
1162
1167
  env_vars,
1163
1168
  trust_project,
1164
- before_send: delivery?.before_send,
1169
+ before_send: async (boundary) => { inputId = boundary.input_id; await delivery?.before_send(boundary); },
1165
1170
  cwd: cwd ?? undefined,
1166
1171
  session_name: session_name ?? undefined,
1167
1172
  launch_operation_id: launch_operation_id ?? undefined,
@@ -1174,7 +1179,8 @@ export function createAitermServer(options = {}) {
1174
1179
  session_id: sid,
1175
1180
  managed_completion: true,
1176
1181
  event_cursor: eventCursor,
1177
- ...completionWait(delivery, sid, eventCursor),
1182
+ ...completionWait(delivery, sid, eventCursor, undefined, inputId),
1183
+ ...(inputId ? { input_id: inputId } : {}),
1178
1184
  ...(delivery?.result() ? { parent_delivery: delivery.result() } : {}),
1179
1185
  submit_residue: submitResidue,
1180
1186
  initial_prompt: initialDelivery,
@@ -1275,6 +1281,7 @@ export function createAitermServer(options = {}) {
1275
1281
  // 起動時promptでturnが走っている時だけ非null。wait_processがmachine向けprocess境界、
1276
1282
  // wait_commandは人間向け互換表示。
1277
1283
  event_cursor: z.number().int().nullable(),
1284
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
1278
1285
  wait_process: waitProcessOutputSchema,
1279
1286
  wait_command: z.string().nullable(),
1280
1287
  parent_delivery: parentDeliveryOutputSchema.optional(),
@@ -1321,6 +1328,7 @@ export function createAitermServer(options = {}) {
1321
1328
  session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
1322
1329
  managed_completion: z.boolean(),
1323
1330
  event_cursor: z.number().int().nullable(),
1331
+ input_id: z.string().regex(/^[a-f0-9]{32}$/).optional(),
1324
1332
  wait_process: waitProcessOutputSchema,
1325
1333
  wait_command: z.string().nullable(),
1326
1334
  parent_delivery: parentDeliveryOutputSchema.optional(),
@@ -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);
@@ -156,10 +156,37 @@ export function psmuxVersionSupported(output) {
156
156
  }
157
157
  let winPsmuxOk = false;
158
158
  let winPsmuxVersion = null;
159
- export function ensureWinPsmux(observe = true) {
159
+ export const PTY_DIAGNOSTIC_TIMEOUT_MS = 5000;
160
+ export class PtyDiagnosticError extends Error {
161
+ reasonCode;
162
+ constructor(reasonCode) {
163
+ super("PTY diagnostic unavailable");
164
+ this.reasonCode = reasonCode;
165
+ }
166
+ }
167
+ function diagnosticSpawnOptions(deadline) {
168
+ if (deadline === undefined)
169
+ return {};
170
+ const remaining = Math.ceil(deadline - performance.now());
171
+ if (remaining <= 0)
172
+ throw new PtyDiagnosticError("timeout");
173
+ return { timeout: remaining, killSignal: "SIGKILL", maxBuffer: 1024 * 1024 };
174
+ }
175
+ function diagnosticSpawnFailure(result, deadline, dependency = false) {
176
+ if (deadline === undefined)
177
+ return;
178
+ const code = result.error?.code;
179
+ const reason = code === "ETIMEDOUT" ? "timeout" : code === "ENOBUFS" ? "output_limit"
180
+ : code === "EACCES" || code === "EPERM" ? "permission_denied" : code === "ENOENT" ? "dependency_unavailable"
181
+ : result.error ? "native_failure" : result.signal ? "signal" : dependency && result.status !== 0 ? "dependency_unavailable" : null;
182
+ if (reason)
183
+ throw new PtyDiagnosticError(reason);
184
+ }
185
+ export function ensureWinPsmux(observe = true, deadline) {
160
186
  if (winPsmuxOk)
161
187
  return;
162
- const r = spawnSync(psmuxBin(), ["-V"], { encoding: "utf8", timeout: 10000 });
188
+ const r = spawnSync(psmuxBin(), ["-V"], { encoding: "utf8", timeout: 10000, ...diagnosticSpawnOptions(deadline) });
189
+ diagnosticSpawnFailure(r, deadline, true);
163
190
  if (r.error) {
164
191
  const code = r.error.code;
165
192
  if (code === "ENOENT")
@@ -168,8 +195,11 @@ export function ensureWinPsmux(observe = true) {
168
195
  }
169
196
  if (r.status !== 0)
170
197
  ptyDependencyError("psmux -V が失敗しました。`psmux -V` が通るか確認してください。", observe);
171
- if (!psmuxVersionSupported(r.stdout ?? ""))
198
+ if (!psmuxVersionSupported(r.stdout ?? "")) {
199
+ if (deadline !== undefined)
200
+ throw new PtyDiagnosticError("dependency_unavailable");
172
201
  ptyDependencyError("psmux 3.3.8以上が必要です。winget upgrade --id marlocarlo.psmux --source winget で更新してください。", observe);
202
+ }
173
203
  winPsmuxVersion = /^psmux (\d+\.\d+\.\d+)(?:\s|$)/mu.exec(r.stdout ?? "")?.[1] ?? null;
174
204
  winPsmuxOk = true;
175
205
  }
@@ -304,18 +334,21 @@ function tmuxMissingMessage() {
304
334
  // 解決順: AITERM_TMUX(明示指定)→ PATH 上の tmux → Homebrew 既定パス。一度だけ実行しキャッシュする。
305
335
  // 見つからなければ tmuxMissingMessage で投げる(黙ってフォールバックせず、原因が見えるようにする)。
306
336
  let tmuxBin = null;
307
- export function resolveTmux(observe = true) {
337
+ export function resolveTmux(observe = true, deadline) {
308
338
  if (tmuxBin)
309
339
  return tmuxBin;
310
340
  const override = process.env.AITERM_TMUX;
311
341
  if (override) {
312
- const r = spawnSync(override, ["-V"], { encoding: "utf8", timeout: 5000 });
342
+ const r = spawnSync(override, ["-V"], { encoding: "utf8", timeout: 5000, ...diagnosticSpawnOptions(deadline) });
343
+ diagnosticSpawnFailure(r, deadline, true);
313
344
  if (!r.error && r.status === 0)
314
345
  return (tmuxBin = override);
315
346
  ptyDependencyError(`AITERM_TMUX に指定された tmux を起動できません: ${override}(\`${override} -V\` が通りません)`, observe);
316
347
  }
317
348
  // CLI/開発時は PATH 上の tmux をそのまま使う(最優先)。
318
- const onPath = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 5000 });
349
+ const onPath = spawnSync("tmux", ["-V"], { encoding: "utf8", timeout: 5000, ...diagnosticSpawnOptions(deadline) });
350
+ if (onPath.signal || ["ETIMEDOUT", "ENOBUFS"].includes(onPath.error?.code ?? ""))
351
+ diagnosticSpawnFailure(onPath, deadline);
319
352
  if (!onPath.error && onPath.status === 0)
320
353
  return (tmuxBin = "tmux");
321
354
  // GUI 起動などで PATH に Homebrew の bin が無い場合、既定の場所を探す。
@@ -323,13 +356,15 @@ export function resolveTmux(observe = true) {
323
356
  for (const cand of ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux"]) {
324
357
  try {
325
358
  fs.accessSync(cand, fs.constants.X_OK);
326
- console.error(`aiterm: tmux が PATH 上に無いため ${cand} を使用します`);
359
+ if (deadline === undefined)
360
+ console.error(`aiterm: tmux が PATH 上に無いため ${cand} を使用します`);
327
361
  return (tmuxBin = cand);
328
362
  }
329
363
  catch {
330
364
  /* 次の候補へ */
331
365
  }
332
366
  }
367
+ diagnosticSpawnFailure(onPath, deadline, true);
333
368
  ptyDependencyError(tmuxMissingMessage(), observe);
334
369
  }
335
370
  // tmux は locale が C/POSIX/未設定だと UTF-8 を扱えない: server は send-keys/paste のマルチバイト
@@ -352,7 +387,7 @@ export function tmuxCommandWithInput(observe, input, ...args) {
352
387
  }
353
388
  // session は、新しい session を作る呼び出しの時だけ渡す client の環境(POSIX のみ)。server を起こし得るのは
354
389
  // この呼び出しだけなので、空 config の指定と macOS の gui domain での起動もここに限る。
355
- function runTmux(observe, input, args, session) {
390
+ function runTmux(observe, input, args, session, deadline) {
356
391
  // Authorize the logical/native session before routing it to its pinned pane.
357
392
  args = nativeSessionArgs(guardTmuxExecution(args));
358
393
  args = nativeConditionalArgs(args);
@@ -360,19 +395,20 @@ function runTmux(observe, input, args, session) {
360
395
  // 頭打ちになり stdout が切れる/空になる。Python の subprocess.run は無制限だったので 64MiB へ広げる。
361
396
  // Windows は tmux CLI 互換の native psmux を -L namespace 隔離で叩く(WSL 非依存)。
362
397
  let r;
363
- const spawnOpts = { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, input, env: session ?? tmuxSpawnEnv() };
398
+ const spawnOpts = () => ({ encoding: "utf8", maxBuffer: 64 * 1024 * 1024, input, env: session ?? tmuxSpawnEnv(), ...diagnosticSpawnOptions(deadline) });
364
399
  if (isWin) {
365
- ensureWinPsmux(observe);
366
- r = spawnSync(psmuxBin(), ["-L", WIN_NS, ...args], spawnOpts);
400
+ ensureWinPsmux(observe, deadline);
401
+ r = spawnSync(psmuxBin(), ["-L", WIN_NS, ...args], spawnOpts());
367
402
  }
368
403
  else {
369
404
  // resolveTmux() は tmux を解決できなければ明確な AitermError を投げる(POSIX 版の事前確認)。
370
- const bin = resolveTmux(observe);
405
+ const bin = resolveTmux(observe, deadline);
371
406
  // -f は tmux 本体の引数で、server を起こす時にだけ読まれる(new-session の -f は別物で、config を指さない)。
372
407
  const argv = session ? ["-f", TMUX_EMPTY_CONFIG, "-S", SOCK, ...args] : ["-S", SOCK, ...args];
373
408
  r = (session && macGuiServerWanted(bin) && startTmuxInMacGui(bin, argv, session))
374
- || spawnSync(bin, argv, spawnOpts);
409
+ || spawnSync(bin, argv, spawnOpts());
375
410
  }
411
+ diagnosticSpawnFailure(r, deadline);
376
412
  // ENOBUFS(出力が 64MiB 超)を「code=1 の失敗」へ握り潰すと部分/空 stdout を正常扱いしてしまう。区別して投げる。
377
413
  // EXPECTED-FAILURE: 外部システム境界(tmux 出力過大)
378
414
  if (r.error && r.error.code === "ENOBUFS") {
@@ -391,6 +427,10 @@ function runTmux(observe, input, args, session) {
391
427
  verifyNativeTarget(native);
392
428
  return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
393
429
  }
430
+ /** One read-only probe; resolution and listing consume the same subprocess budget. */
431
+ export function readOnlyTmuxList() {
432
+ return runTmux(false, undefined, ["list-sessions", "-F", "#{session_name}"], undefined, performance.now() + PTY_DIAGNOSTIC_TIMEOUT_MS);
433
+ }
394
434
  // macOS の login keychain は GUI(Aqua)の security session からしか読めない。SSH 等から立てた
395
435
  // tmux server の pane では Claude Code・Cursor CLI がログイン済みでも未ログイン扱いになる。
396
436
  // server が無く、自分が Aqua の外にいて、同じ利用者が画面にログインしている時だけ、最初の