aiterm-mcp 0.62.6 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -218,6 +218,14 @@ function issueEffect(scope) {
218
218
  }
219
219
  }
220
220
  export function hasExecutionCreationScope() { return !!scopes.getStore()?.creation; }
221
+ /** The mounted graph has no native resume transition; never manufacture a creation frame. */
222
+ export function assertExecutionResumeSupported() {
223
+ const scope = scopes.getStore();
224
+ if (scope)
225
+ refuse(scope, "EXECUTION_UNSUPPORTED");
226
+ if (required)
227
+ throw new ExecutionError("EXECUTION_UNSUPPORTED");
228
+ }
221
229
  export function prepareExecutionCreation() {
222
230
  const scope = scopes.getStore();
223
231
  if (!scope)
@@ -150,7 +150,7 @@ const CLAUDE_ULTRACODE_NOTE = "Claude Codeの--effortが受け付けるsession
150
150
  * (SDKの公開型 SDKControlRequest/SDKControlInitializeResponse)の応答にある models を読む。
151
151
  * promptは送らず、sessionを保存せず、利用者のhookとMCP serverを起動しない。
152
152
  */
153
- export async function claudeModelChoices(bin, cwd) {
153
+ export async function claudeModelChoices(bin, cwd, env = process.env) {
154
154
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aiterm-claude-models-"));
155
155
  try {
156
156
  const settings = path.join(dir, "settings.json");
@@ -167,7 +167,7 @@ export async function claudeModelChoices(bin, cwd) {
167
167
  "--no-session-persistence", "--strict-mcp-config", "--settings", settings,
168
168
  ], {
169
169
  cwd,
170
- env: process.env,
170
+ env,
171
171
  input: JSON.stringify(request) + "\n",
172
172
  until: requestId,
173
173
  timeout: CLAUDE_MODELS_TIMEOUT_MS,
@@ -319,6 +319,14 @@ export function claudeAgentArgv(bin, model, effort, prompt, meta) {
319
319
  parts.push(prompt); // 初手プロンプト(任意)
320
320
  return parts;
321
321
  }
322
+ /** Resume exactly the saved conversation; the caller submits its body only after readiness. */
323
+ export function claudeResumeArgv(bin, model, effort, meta) {
324
+ if (meta.kind !== "claude" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id))
325
+ throw new AitermError("AGENT_RESUME_UNSUPPORTED: Claudeの保存会話IDを確認できません。", 2);
326
+ const argv = claudeAgentArgv(bin, model, effort, null, meta);
327
+ argv[argv.indexOf("--session-id")] = "--resume";
328
+ return argv;
329
+ }
322
330
  export function buildClaudeAgentCmd(bin, model, effort, prompt, meta) {
323
331
  const argv = claudeAgentArgv(bin, model, effort, prompt, meta);
324
332
  const values = new Set(["--setting-sources", "--settings", "--session-id", "--append-system-prompt", "--model", "--effort"]);
@@ -339,10 +347,16 @@ function claudeComposerBox(screen) {
339
347
  marker--;
340
348
  return marker > 0 && rule.test(lines[marker - 1]) && lines.slice(marker + 1).some(line => rule.test(line));
341
349
  }
350
+ function claudeSecurityNotes(screen) {
351
+ const lines = screen.split(/\r?\n/u);
352
+ const lastMarker = lines.map(line => /^\s*❯/u.test(line)).lastIndexOf(true);
353
+ return lines.slice(lastMarker + 1).some(line => /^\s*Security notes:\s*$/.test(line))
354
+ && /Press (?:Enter|Return) to continue/u.test(lines.slice(lastMarker + 1).join("\n"));
355
+ }
342
356
  export function claudeTuiReady(screen) {
343
357
  if (!screen.includes("Claude Code") && !claudeComposerBox(screen))
344
358
  return false;
345
- if (claudeLoginMethodMenu(screen))
359
+ if (claudeLoginMethodMenu(screen) || claudeSecurityNotes(screen))
346
360
  return false;
347
361
  const lastMarker = screen.split(/\r?\n/u).filter((line) => /^\s*❯/u.test(line)).at(-1)?.trim();
348
362
  if (!lastMarker)
@@ -406,7 +420,7 @@ function claudeInterruptHint(screen) {
406
420
  }
407
421
  export function claudePaneObservation(screen) {
408
422
  const tail = screen.split("\n").slice(-32).join("\n");
409
- if (claudeLoginMethodMenu(screen))
423
+ if (claudeLoginMethodMenu(screen) || claudeSecurityNotes(screen))
410
424
  return { state: "blocked", reason: "vendor_onboarding_required" };
411
425
  if (/Do you want to proceed\?/.test(tail) && /(?:^|\n)\s*[❯>]?\s*\d+\.\s+(?:Yes|No)\s*$/m.test(tail))
412
426
  return { state: "blocked", reason: "tool_approval" };
@@ -618,6 +632,7 @@ export function createClaudeAgentMetadata(name, cwd, initialPrompt, launchOperat
618
632
  ...agentLineageFields(lineageContext),
619
633
  node_platform: process.platform,
620
634
  claude_settings: claudeSettings,
635
+ claude_home: path.resolve(cwd ?? process.cwd(), claudeConfigDir()),
621
636
  result_file: resultFile,
622
637
  };
623
638
  writeAgentMetadata(meta);
@@ -639,7 +654,7 @@ export function claudeProjectSlug(cwd) {
639
654
  export function claudeSessionTranscriptPath(meta) {
640
655
  if (meta.kind !== "claude" || !meta.vendor_session_id)
641
656
  return null;
642
- return path.join(claudeConfigDir(), "projects", claudeProjectSlug(meta.cwd ?? process.cwd()), `${meta.vendor_session_id}.jsonl`);
657
+ return path.join(meta.claude_home ?? claudeConfigDir(), "projects", claudeProjectSlug(meta.cwd ?? process.cwd()), `${meta.vendor_session_id}.jsonl`);
643
658
  }
644
659
  export function claudeApiErrorFromLine(line) {
645
660
  if (!line.trim())
@@ -5,13 +5,15 @@ import { authUrl, authUserCode } from "../agent-auth.js";
5
5
  import * as fs from "node:fs";
6
6
  import * as os from "node:os";
7
7
  import * as path from "node:path";
8
- import { randomBytes } from "node:crypto";
8
+ import { randomBytes, createHash } from "node:crypto";
9
+ import { z } from "zod";
9
10
  import { AitermError } from "../errors.js";
10
11
  import { spawnAgentControlCommand } from "../agent-resolver.js";
11
12
  import * as steer from "aiterm-steer-delivery";
12
13
  import { AITERM_PROFILE } from "../steer-profile.js";
13
14
  import { catalogInvalid, catalogUnavailable, checkedCatalog } from "../model-catalog.js";
14
- import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
15
+ import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, writeJson0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
16
+ import { readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
15
17
  export function realCodexHome() {
16
18
  return process.env.CODEX_HOME || path.join(process.env.HOME ?? os.homedir(), ".codex");
17
19
  }
@@ -241,7 +243,14 @@ function codexLaunchOthersFor(launchId) {
241
243
  export function codexBoundTranscript(meta) {
242
244
  if (meta.kind !== "codex" || !meta.codex_home || !meta.vendor_session_id)
243
245
  return null;
244
- return findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
246
+ const origin = codexResumedProof(meta);
247
+ if (origin?.session_id === meta.vendor_session_id)
248
+ return origin.file;
249
+ const file = findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
250
+ if (origin && (!file || codexTranscriptSessionId(file) !== meta.vendor_session_id
251
+ || codexLaunchVerdict(file, meta).verdict !== "match" || codexLaunchVerdict(file, meta).forked))
252
+ throw resumeProofUnavailable();
253
+ return file;
245
254
  }
246
255
  /**
247
256
  * 結び付けた会話より後に書かれた、この起動の別の会話のroot rollout。無ければnull(ADR 0105)。
@@ -286,6 +295,8 @@ function codexSwitchedTranscript(meta, bound) {
286
295
  if (mtime <= latestMtime)
287
296
  continue;
288
297
  let own = memo.get(file);
298
+ if (meta.resumed_from && own === true)
299
+ own = undefined;
289
300
  if (own === undefined) {
290
301
  const { verdict, forked } = codexLaunchVerdict(file, meta);
291
302
  if (verdict === "undecided")
@@ -302,10 +313,12 @@ function codexSwitchedTranscript(meta, bound) {
302
313
  }
303
314
  /** この起動の、今の会話のroot rollout。結び付けた会話から、同じprocessの新しい会話へ移っていれば、新しい方。 */
304
315
  export function codexRootTranscript(meta) {
316
+ if (meta.resumed_from !== undefined && !meta.vendor_session_id)
317
+ throw resumeProofUnavailable();
305
318
  if (meta.kind !== "codex" || !meta.codex_home)
306
319
  return null;
307
320
  if (meta.vendor_session_id) {
308
- const bound = findLatestCodexTranscript(meta.codex_home, meta.vendor_session_id);
321
+ const bound = codexBoundTranscript(meta);
309
322
  return bound ? codexSwitchedTranscript(meta, bound) ?? bound : null;
310
323
  }
311
324
  if (meta.hook_route === "shared_codex_home") {
@@ -354,6 +367,8 @@ export function codexCompletionEvent(meta, harnessSessionId, record) {
354
367
  typeof record?.payload?.turn_id !== "string" ||
355
368
  !record.payload.turn_id)
356
369
  return null;
370
+ if (record.payload.turn_id === codexResumeTurnId(meta, harnessSessionId))
371
+ return null;
357
372
  return {
358
373
  type: "agent_done",
359
374
  vendor: "codex",
@@ -441,6 +456,17 @@ function codexLatestTurnBoundary(meta, reach) {
441
456
  }
442
457
  if (!transcript)
443
458
  return null;
459
+ const floor = codexResumeCursor(meta, transcript);
460
+ if (floor > 0) {
461
+ const origin = codexResumedProof(meta);
462
+ const minimum = Math.max(floor, reach === "tail" ? safeStatSize(transcript) - AGENT_TURN_BOUNDARY_TAIL_BYTES : 0);
463
+ return scanLinesNewestFirst(transcript, (line, offset) => {
464
+ if (offset < minimum)
465
+ return null;
466
+ const value = codexTurnBoundaryLine(line);
467
+ return value?.turn_id === origin.last_turn_id ? undefined : value;
468
+ }, AGENT_TURN_BOUNDARY_TAIL_BYTES) ?? null;
469
+ }
444
470
  if (reach === "whole")
445
471
  return scanLinesNewestFirst(transcript, codexTurnBoundaryLine, AGENT_TURN_BOUNDARY_TAIL_BYTES) ?? null;
446
472
  const lines = readTailLinesNewestFirst(transcript, AGENT_TURN_BOUNDARY_TAIL_BYTES);
@@ -463,6 +489,7 @@ export function codexInterruptionRecord(meta) {
463
489
  if (meta.kind !== "codex" || meta.hook_route !== "shared_codex_home" || !meta.codex_home)
464
490
  return null;
465
491
  try {
492
+ const origin = codexResumedProof(meta);
466
493
  // The ordinary browser skips unreadable directories. Such a partial list
467
494
  // cannot establish a unique native endpoint for interruption evidence.
468
495
  const listStrict = () => {
@@ -519,6 +546,11 @@ export function codexInterruptionRecord(meta) {
519
546
  return null;
520
547
  };
521
548
  for (const file of files) {
549
+ if (origin?.file === file) {
550
+ if (origin.session_id === meta.vendor_session_id)
551
+ matches.push(file);
552
+ continue;
553
+ }
522
554
  const verdict = codexLaunchVerdict(file, meta);
523
555
  if (verdict.verdict === "undecided")
524
556
  return null; // no guessing around partial endpoint evidence
@@ -527,11 +559,15 @@ export function codexInterruptionRecord(meta) {
527
559
  }
528
560
  if (matches.length !== 1)
529
561
  return null;
530
- const file = matches[0], before = fs.statSync(file), session = header(file);
562
+ const file = matches[0], before = fs.statSync(file), session = origin?.file === file ? origin.session_id : header(file);
531
563
  if (!session || !before.isFile())
532
564
  return null;
533
565
  const boundary = scanLinesNewestFirst(file, (line, offset) => {
566
+ if (origin?.file === file && offset < origin.cursor)
567
+ return null;
534
568
  const value = codexTurnBoundaryLine(line);
569
+ if (origin?.file === file && value?.turn_id === origin.last_turn_id)
570
+ return undefined;
535
571
  return value ? { ...value, event_cursor: offset } : value;
536
572
  }, AGENT_TURN_BOUNDARY_TAIL_BYTES);
537
573
  const after = fs.statSync(file);
@@ -546,6 +582,8 @@ export function codexInterruptionRecord(meta) {
546
582
  if (JSON.stringify(last) !== JSON.stringify(files))
547
583
  return null;
548
584
  for (const candidate of last) {
585
+ if (origin?.file === candidate)
586
+ continue;
549
587
  const verdict = codexLaunchVerdict(candidate, meta);
550
588
  if (verdict.verdict === "undecided" || (verdict.verdict === "match" && !verdict.forked && candidate !== file))
551
589
  return null;
@@ -574,6 +612,11 @@ export function codexTurnSettled(meta) {
574
612
  // 見たのはEscで止めた時の形だけ。他の理由(別のturnへの置き換え等)は、次のturnが続くかも知れないので数えない。
575
613
  return boundary?.type === "turn_aborted" && boundary.reason === "interrupted";
576
614
  }
615
+ /** An idle reaper must not borrow a previous reply's clock after a later interrupted turn. */
616
+ export function codexCompletedTurnId(meta) {
617
+ const boundary = codexLatestTurnBoundary(meta, "tail");
618
+ return boundary?.type === "task_complete" && typeof boundary.turn_id === "string" && boundary.turn_id ? boundary.turn_id : null;
619
+ }
577
620
  /**
578
621
  * この起動のroot rolloutの上で動いているturnのID。末尾から見て最初の境界がtask_startedの時だけ返す。
579
622
  * rolloutが無い、この起動に結び付かない、書いている途中、境界が1つも無い時はnull(分からない時は「動いている」と数えない)。
@@ -590,6 +633,18 @@ export function latestCodexCompletion(meta, readTranscriptLines) {
590
633
  if (!transcript)
591
634
  return null;
592
635
  const harnessSessionId = codexRolloutSessionId(meta, transcript);
636
+ const floor = codexResumeCursor(meta, transcript);
637
+ if (floor > 0)
638
+ return scanLinesNewestFirst(transcript, (line, offset) => {
639
+ if (offset < floor)
640
+ return null;
641
+ try {
642
+ return codexCompletionEvent(meta, harnessSessionId, JSON.parse(line)) ?? undefined;
643
+ }
644
+ catch {
645
+ return undefined;
646
+ }
647
+ }, AGENT_TURN_BOUNDARY_TAIL_BYTES) ?? null;
593
648
  let latest = null;
594
649
  for (const line of readTranscriptLines(transcript)) {
595
650
  if (!line.trim())
@@ -608,7 +663,7 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
608
663
  // 読み位置(cursor)は、送った時に結び付いていた会話のrolloutの位置。結び付けが済んだ席は、そのrolloutから読み始める。
609
664
  const anchored = () => meta.vendor_session_id ? codexBoundTranscript(meta) : codexRootTranscript(meta);
610
665
  let transcript = anchored();
611
- let startOffset = requestedCursor ?? (transcript ? safeStatSize(transcript) : 0);
666
+ let startOffset = Math.max(requestedCursor ?? (transcript ? safeStatSize(transcript) : 0), transcript ? codexResumeCursor(meta, transcript) : 0);
612
667
  let cursor = startOffset;
613
668
  let carry = Buffer.alloc(0);
614
669
  let malformedEvents = 0;
@@ -641,6 +696,13 @@ export async function observeCodexDone(meta, timeout, requestedCursor, signal) {
641
696
  return observation("closed");
642
697
  let behind = false;
643
698
  transcript ??= anchored();
699
+ const floor = transcript ? codexResumeCursor(meta, transcript) : 0;
700
+ if (cursor < floor) {
701
+ cursor = startOffset = floor;
702
+ carry = Buffer.alloc(0);
703
+ initializedBoundary = false;
704
+ discardLeadingFragment = false;
705
+ }
644
706
  if (transcript && meta.vendor_session_id && cursor === startOffset && performance.now() >= switchCheckAt) {
645
707
  switchCheckAt = performance.now() + CODEX_SWITCH_CHECK_MS;
646
708
  let current = null;
@@ -769,6 +831,13 @@ export function codexAgentArgv(bin, model, effort, prompt, meta) {
769
831
  parts.push(prompt); // 初手プロンプト(任意)
770
832
  return parts;
771
833
  }
834
+ /** Explicit cwd avoids the vendor's directory-choice prompt during same-thread resume. */
835
+ export function codexResumeArgv(bin, model, effort, meta, cwd) {
836
+ if (meta.kind !== "codex" || !meta.vendor_session_id || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(meta.vendor_session_id)
837
+ || !path.isAbsolute(cwd) || cwd.includes("\0"))
838
+ throw new AitermError("AGENT_RESUME_UNSUPPORTED: Codexの保存会話IDとcwdを確認できません。", 2);
839
+ return [bin, "resume", meta.vendor_session_id, ...codexAgentArgv(bin, model, effort, null, meta).slice(1), "--cd", cwd];
840
+ }
772
841
  export function buildCodexAgentCmd(bin, model, effort, prompt, meta) {
773
842
  const argv = codexAgentArgv(bin, model, effort, prompt, meta);
774
843
  return argv.map((arg, index) => {
@@ -1063,7 +1132,10 @@ export function codexTranscriptText(meta, turnId, readTranscriptLines, transcrip
1063
1132
  const transcript = codexRootTranscript(meta);
1064
1133
  if (!transcript)
1065
1134
  transcriptUnavailable();
1066
- const lines = readTranscriptLines(transcript);
1135
+ const floor = codexResumeCursor(meta, transcript);
1136
+ if (turnId !== null && turnId === codexResumeTurnId(meta, meta.vendor_session_id))
1137
+ transcriptUnavailable();
1138
+ const lines = floor > 0 ? readFileRange(transcript, floor, safeStatSize(transcript)).toString("utf8").split("\n") : readTranscriptLines(transcript);
1067
1139
  if (exactCompletion) {
1068
1140
  // 同じturnの本文だけを使う。完了event内の本文と、turn ID付きoutput_textの両形式を扱う。
1069
1141
  const matching = codexTurnAnswer();
@@ -1173,8 +1245,8 @@ const CODEX_MODELS_MAX_PAGES = 20;
1173
1245
  * 親配送と同じ接続(aiterm-steer-deliveryのwithCodexReceiver)で、threadもturnも作らない。
1174
1246
  * `codex debug models` も同じ内容を返すが、debug用の命令なので使わない。
1175
1247
  */
1176
- export async function codexModelChoices(bin, includeHidden) {
1177
- const parent = { thread_id: "00000000-0000-4000-8000-000000000000", codex_home: path.resolve(steer.realCodexHome()) };
1248
+ export async function codexModelChoices(bin, includeHidden, codexHome = steer.realCodexHome(), env = process.env) {
1249
+ const parent = { thread_id: "00000000-0000-4000-8000-000000000000", codex_home: path.resolve(codexHome) };
1178
1250
  let pages;
1179
1251
  try {
1180
1252
  pages = await steer.withCodexReceiver(AITERM_PROFILE, parent, async (request) => {
@@ -1190,7 +1262,7 @@ export async function codexModelChoices(bin, includeHidden) {
1190
1262
  cursor = result.nextCursor;
1191
1263
  }
1192
1264
  throw catalogInvalid("Codex", `model/listが${CODEX_MODELS_MAX_PAGES}ページを超えました`);
1193
- }, { executable: bin, timeout_ms: CODEX_MODELS_TIMEOUT_MS });
1265
+ }, { executable: bin, timeout_ms: CODEX_MODELS_TIMEOUT_MS, env });
1194
1266
  }
1195
1267
  catch (error) {
1196
1268
  if (error instanceof AitermError)
@@ -1363,3 +1435,91 @@ export function restoreCodexDefaultInFile(configPath, key, before) {
1363
1435
  }
1364
1436
  // The ordinary interactive cancel gesture; not a process termination signal.
1365
1437
  export const CODEX_INTERRUPT_KEY = "Escape";
1438
+ const codexResumeProofSchema = z.object({ schema: z.literal("aiterm.codex-resume-proof.v1"),
1439
+ launch_id: z.string().regex(/^[a-f0-9]{32}$/), session_id: z.string().uuid(),
1440
+ file: z.string().refine(value => path.isAbsolute(value)), device: z.string().regex(/^\d+$/), inode: z.string().regex(/^\d+$/),
1441
+ cursor: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
1442
+ prefix_bytes: z.number().int().positive().max(1024 * 1024), prefix_sha256: z.string().regex(/^[a-f0-9]{64}$/),
1443
+ last_turn_id: z.string().min(1).max(256),
1444
+ }).strict();
1445
+ const codexResumeProofPath = (meta) => agentMetadataPath(meta.aiterm_session, meta.launch_id).replace(/\.agent\.json$/, ".codex-resume.json");
1446
+ const resumeProofUnavailable = () => new AitermError("AGENT_RESUME_UNCONFIRMED: Codexの元の会話記録を確認できません。", 2);
1447
+ /** A resumed launch inherits a proven native root, never the old launch marker. */
1448
+ function codexResumedProof(meta) {
1449
+ if (meta.resumed_from === undefined)
1450
+ return null;
1451
+ try {
1452
+ if (!/^[a-f0-9]{32}$/.test(meta.resumed_from) || meta.resumed_from === meta.launch_id)
1453
+ throw resumeProofUnavailable();
1454
+ const file = agentMetadataPath(meta.aiterm_session, meta.resumed_from), stat = fs.lstatSync(file);
1455
+ if (!stat.isFile() || stat.size > 4 * 1024 * 1024)
1456
+ throw resumeProofUnavailable();
1457
+ const previous = JSON.parse(fs.readFileSync(file, "utf8"));
1458
+ if (previous.kind !== "codex" || previous.aiterm_session !== meta.aiterm_session || previous.launch_id !== meta.resumed_from
1459
+ || previous.codex_home !== meta.codex_home || previous.hook_route !== meta.hook_route
1460
+ || ["agent_role", "parent_session_id", "delegation_depth", "lineage", "delegation_allowed"].some(key => previous[key] !== meta[key]))
1461
+ throw resumeProofUnavailable();
1462
+ const life = readAgentLifecycle(previous), recipe = readAgentResumeRecipe(previous), proof = readCodexResumeProof(previous);
1463
+ if (life?.state !== "hibernated" || !recipe || recipe.kind !== "codex" || recipe.vendor_session_id !== previous.vendor_session_id
1464
+ || recipe.configuration_root !== meta.codex_home || life.recipe_digest !== agentResumeRecipeDigest(recipe)
1465
+ || life.resume_proof_digest !== codexResumeProofDigest(proof))
1466
+ throw resumeProofUnavailable();
1467
+ return proof;
1468
+ }
1469
+ catch {
1470
+ throw resumeProofUnavailable();
1471
+ }
1472
+ }
1473
+ /** Byte floor for this launch on its inherited history; a new /new root starts at zero. */
1474
+ export function codexResumeCursor(meta, transcript) {
1475
+ const origin = codexResumedProof(meta);
1476
+ return origin?.file === transcript ? origin.cursor : 0;
1477
+ }
1478
+ export function codexResumeTurnId(meta, sessionId) {
1479
+ const origin = codexResumedProof(meta);
1480
+ return origin?.session_id === sessionId ? origin.last_turn_id : null;
1481
+ }
1482
+ export function codexResumeProofDigest(proof) {
1483
+ return createHash("sha256").update(JSON.stringify(codexResumeProofSchema.parse(proof))).digest("hex");
1484
+ }
1485
+ export function readCodexResumeProof(meta) {
1486
+ try {
1487
+ const item = fs.lstatSync(codexResumeProofPath(meta));
1488
+ if (!item.isFile() || item.size > 4 * 1024 * 1024)
1489
+ throw resumeProofUnavailable();
1490
+ const proof = codexResumeProofSchema.parse(JSON.parse(fs.readFileSync(codexResumeProofPath(meta), "utf8")));
1491
+ const relative = path.relative(path.join(meta.codex_home, "sessions"), proof.file), stat = fs.lstatSync(proof.file, { bigint: true });
1492
+ if (meta.kind !== "codex" || proof.launch_id !== meta.launch_id || proof.session_id !== meta.vendor_session_id
1493
+ || !stat.isFile() || path.isAbsolute(relative) || relative.startsWith("..") || stat.dev.toString() !== proof.device || stat.ino.toString() !== proof.inode
1494
+ || stat.size < BigInt(proof.cursor) || stat.size < BigInt(proof.prefix_bytes)
1495
+ || createHash("sha256").update(readFileRange(proof.file, 0, proof.prefix_bytes)).digest("hex") !== proof.prefix_sha256)
1496
+ throw resumeProofUnavailable();
1497
+ return proof;
1498
+ }
1499
+ catch {
1500
+ throw resumeProofUnavailable();
1501
+ }
1502
+ }
1503
+ /** Pin a unique, completed native root before stopping; a cached vendor ID alone is insufficient. */
1504
+ export function captureCodexResumeProof(meta) {
1505
+ try {
1506
+ const evidence = codexInterruptionRecord(meta), file = codexRootTranscript(meta);
1507
+ if (!evidence || !file || evidence.boundary.type !== "task_complete" || evidence.session_id !== meta.vendor_session_id)
1508
+ throw resumeProofUnavailable();
1509
+ const before = fs.statSync(file, { bigint: true }), bytes = Math.min(Number(before.size), 1024 * 1024);
1510
+ if (before.size > BigInt(Number.MAX_SAFE_INTEGER) || Number(before.dev) !== evidence.file.device || Number(before.ino) !== evidence.file.inode)
1511
+ throw resumeProofUnavailable();
1512
+ const digest = createHash("sha256").update(readFileRange(file, 0, bytes)).digest("hex"), after = fs.statSync(file, { bigint: true });
1513
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs
1514
+ || before.ctimeNs !== after.ctimeNs)
1515
+ throw resumeProofUnavailable();
1516
+ const proof = codexResumeProofSchema.parse({ schema: "aiterm.codex-resume-proof.v1", launch_id: meta.launch_id,
1517
+ session_id: evidence.session_id, file, device: before.dev.toString(), inode: before.ino.toString(), cursor: Number(before.size),
1518
+ prefix_bytes: bytes, prefix_sha256: digest, last_turn_id: evidence.boundary.turn_id });
1519
+ writeJson0600(codexResumeProofPath(meta), proof);
1520
+ return readCodexResumeProof(meta);
1521
+ }
1522
+ catch {
1523
+ throw resumeProofUnavailable();
1524
+ }
1525
+ }
@@ -0,0 +1,109 @@
1
+ import { claudeModelPicker, claudeModelPickerRow } from './claude.js';
2
+ import { sleep } from '../agent-shared.js';
3
+ export function codexSettingsPreview(screen) {
4
+ const lines = screen.split(/\r?\n/);
5
+ let head = lines.length - 1;
6
+ while (head >= 0 && !/^\s*Configure Status Line\s*$/.test(lines[head]))
7
+ head--;
8
+ if (head < 0)
9
+ return null;
10
+ const footer = lines.findIndex((line, i) => i > head && /space toggle.*enter save.*esc cancel/.test(line));
11
+ if (footer < 0 || lines.slice(footer + 1).some(line => line.trim()))
12
+ return null;
13
+ const rows = lines.slice(head + 1, footer - 1).flatMap(line => {
14
+ const match = /^\s*(›\s*)?\[([x ])\]\s+([a-z][a-z0-9-]*)\s{2,}\S/.exec(line);
15
+ return match ? [{ id: match[3], checked: match[2] === 'x', cursor: !!match[1] }] : [];
16
+ });
17
+ return { rows, preview: lines[footer - 1].trim() };
18
+ }
19
+ export function codexPreviewMatchesSettings(preview, expected) {
20
+ const match = /^(\S+) (none|minimal|low|medium|high|xhigh|max|ultra)( Fast)? · (Standard|Fast|Fast off)$/.exec(preview);
21
+ return !!match && !!expected.model && match[1].toLowerCase() === expected.model.toLowerCase()
22
+ && match[2] === expected.reasoning_effort && !!match[3] === (match[4] === 'Fast')
23
+ && (match[4] === 'Fast') === expected.fast;
24
+ }
25
+ function claudeFastMenu(screen) {
26
+ return /(?:^|\n)\s*↯ Fast mode\s*\n/.test(screen) && /(?:^|\n)\s*Esc to cancel\s*$/.test(screen);
27
+ }
28
+ async function until(read) {
29
+ const deadline = performance.now() + 1500;
30
+ do {
31
+ const value = read();
32
+ if (value !== null)
33
+ return value;
34
+ await sleep(75);
35
+ } while (performance.now() < deadline);
36
+ return null;
37
+ }
38
+ /** Preview only: Enter is used to open a command, never to save a selection. */
39
+ export async function inspectIdleSettings(kind, expected, ui) {
40
+ if (!expected.model || !expected.reasoning_effort || !['claude', 'codex'].includes(kind))
41
+ return false;
42
+ if (kind === 'claude' && !/^claude-[a-z]+-\d+(?:-\d{1,2})?$/.test(expected.model))
43
+ return false;
44
+ const inMenu = (screen) => kind === 'codex' ? codexSettingsPreview(screen) !== null
45
+ : (claudeModelPicker(screen) !== null && /Esc to cancel\s*$/.test(screen)) || claudeFastMenu(screen);
46
+ const close = async () => {
47
+ for (let i = 0; i < 3 && inMenu(ui.screen()); i++) {
48
+ ui.key('Escape');
49
+ await until(() => !inMenu(ui.screen()) ? true : null);
50
+ }
51
+ return !inMenu(ui.screen()) && await ui.ready();
52
+ };
53
+ let matched = false;
54
+ try {
55
+ if (kind === 'codex') {
56
+ await ui.command('/statusline');
57
+ if (!await until(() => codexSettingsPreview(ui.screen())))
58
+ return false;
59
+ let query = '';
60
+ const select = async (id, checked) => {
61
+ if (query.length)
62
+ ui.key(...Array(query.length).fill('BSpace'));
63
+ ui.text(id);
64
+ query = id;
65
+ const row = () => {
66
+ const menu = codexSettingsPreview(ui.screen());
67
+ return menu?.rows.length === 1 && menu.rows[0].id === id && menu.rows[0].cursor ? menu.rows[0] : null;
68
+ };
69
+ const before = await until(row);
70
+ if (!before)
71
+ return false;
72
+ if (before.checked !== checked) {
73
+ ui.key('Space');
74
+ if (!await until(() => row()?.checked === checked ? true : null))
75
+ return false;
76
+ }
77
+ return true;
78
+ };
79
+ // These default items otherwise clip the native settings at narrow widths.
80
+ for (const [id, checked] of [['current-dir', false], ['thread-name', false], ['model-with-reasoning', true], ['fast-mode', true]])
81
+ if (!await select(id, checked))
82
+ return false;
83
+ const preview = codexSettingsPreview(ui.screen());
84
+ matched = !!preview && codexPreviewMatchesSettings(preview.preview, expected);
85
+ }
86
+ else {
87
+ await ui.command('/model');
88
+ const menu = await until(() => claudeModelPicker(ui.screen()));
89
+ if (!menu)
90
+ return false;
91
+ const current = menu.rows.filter(row => row.current);
92
+ const requested = claudeModelPickerRow(menu.rows, expected.model);
93
+ if (current.length !== 1 || !current[0].cursor || requested !== current[0] || menu.effort !== expected.reasoning_effort)
94
+ return false;
95
+ if (!await close())
96
+ return false;
97
+ await ui.command('/fast');
98
+ if (!await until(() => claudeFastMenu(ui.screen()) ? true : null))
99
+ return false;
100
+ // Other account/menu layouts remain unknown until their native receipt is accepted.
101
+ matched = !expected.fast && /^\s*Fast mode requires usage credits · \/usage-credits to turn them on\s*$/m.test(ui.screen());
102
+ }
103
+ }
104
+ finally {
105
+ if (!await close())
106
+ matched = false;
107
+ }
108
+ return matched;
109
+ }
package/dist/index.js CHANGED
@@ -722,6 +722,7 @@ export function createAitermServer(options = {}) {
722
722
  },
723
723
  }, async ({ env_keys }, extra) => {
724
724
  try {
725
+ await core.maintainAgentIdleClocks();
725
726
  const result = core.listSessionsResult(env_keys);
726
727
  return { ...ok(core.listSessions(result)), structuredContent: { ...result }, ...seatTurnsMeta(result.sessions, extra._meta) };
727
728
  }
@@ -754,7 +755,7 @@ export function createAitermServer(options = {}) {
754
755
  outputSchema: {
755
756
  schema: z.literal("aiterm.pty-observe-result.v1"), session_id: z.string(), observed_at: z.string(),
756
757
  exists: z.boolean(), harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]).nullable(),
757
- launch_id: z.string().nullable(), state: z.enum(["busy", "idle", "blocked", "dead", "missing", "unknown"]),
758
+ launch_id: z.string().nullable(), state: z.enum(["busy", "idle", "blocked", "dead", "missing", "unknown", "hibernated"]),
758
759
  reason: z.string(), pane_alive: z.boolean().nullable(), harness_alive: z.boolean().nullable(),
759
760
  pane_process: nativeProcessIdentitySchema.nullable(), harness_process: nativeProcessIdentitySchema.nullable(),
760
761
  process_identity: nativeProcessIdentitySchema.nullable(),
@@ -1131,6 +1132,7 @@ export function createAitermServer(options = {}) {
1131
1132
  if (!supportsWriteScope && write_scope !== undefined) {
1132
1133
  throw new core.AitermError("claude-code harnessはwrite_scopeに対応していません。指定を外してください", 2);
1133
1134
  }
1135
+ await core.maintainAgentIdleClocks();
1134
1136
  const initialPrompt = image && image.length > 0 ? core.attachImages(prompt ?? "", image) : prompt ?? undefined;
1135
1137
  if (initialPrompt || throughline_source_session)
1136
1138
  delivery = await deliveryForRequest(extra);
@@ -14,7 +14,7 @@ import * as path from "node:path";
14
14
  import { AitermError } from "./errors.js";
15
15
  import { agentHarness, agentsDir, assertSessionName, LAUNCH_ID_RE, readFileRange, safeStatSize, writeJson0600, } from "./agent-shared.js";
16
16
  import { claudeSessionTranscriptPath } from "./harnesses/claude.js";
17
- import { codexBoundTranscript, codexRootTranscript, codexTurnError, codexTurnErrorLine } from "./harnesses/codex.js";
17
+ import { codexBoundTranscript, codexRootTranscript, codexResumeCursor, codexResumeTurnId, codexTurnError, codexTurnErrorLine } from "./harnesses/codex.js";
18
18
  import { grokSessionDirectory } from "./harnesses/grok.js";
19
19
  import { cursorTranscript } from "./harnesses/cursor.js";
20
20
  /** BellTeamが要求の_metaへ入れる呼び手の印。値が "BellTeam" の時だけ合間の言葉を返す。 */
@@ -282,6 +282,21 @@ export function interimFromNow(meta, eventCursor) {
282
282
  return { event_cursor: eventCursor, unit: "byte", boundary: file ? safeStatSize(file) : 0 };
283
283
  }
284
284
  /** 渡された位置より後に書かれた合間の言葉。位置の単位がharnessと合わない時は、言葉なし。 */
285
+ function codexLinesFrom(meta, boundary) {
286
+ const file = meta.vendor_session_id ? codexBoundTranscript(meta) : codexRootTranscript(meta);
287
+ const retiredTurn = codexResumeTurnId(meta, meta.vendor_session_id);
288
+ return readLines(file, file ? Math.max(boundary, codexResumeCursor(meta, file)) : boundary).filter(line => {
289
+ if (!retiredTurn)
290
+ return true;
291
+ try {
292
+ const payload = JSON.parse(line)?.payload;
293
+ return payload?.turn_id !== retiredTurn && payload?.internal_chat_message_metadata_passthrough?.turn_id !== retiredTurn;
294
+ }
295
+ catch {
296
+ return false;
297
+ }
298
+ });
299
+ }
285
300
  function interimWordsFrom(meta, from) {
286
301
  if (meta.kind === "grok")
287
302
  return from.unit === "user" ? grokInterimWords(readLines(grokChatHistory(meta)), from.boundary) : [];
@@ -290,7 +305,7 @@ function interimWordsFrom(meta, from) {
290
305
  if (meta.kind === "claude")
291
306
  return claudeInterimWords(readLines(claudeSessionTranscriptPath(meta), from.boundary));
292
307
  if (meta.kind === "codex")
293
- return codexInterimWords(readLines(meta.vendor_session_id ? codexBoundTranscript(meta) : codexRootTranscript(meta), from.boundary));
308
+ return codexInterimWords(codexLinesFrom(meta, from.boundary));
294
309
  // 位置より後の行だけを渡すので、user発話の数では絞らない。
295
310
  return meta.kind === "cursor" ? cursorInterimWords(readLines(cursorTranscript(meta), from.boundary), -1) : [];
296
311
  }
@@ -322,7 +337,7 @@ export function readInterimWords(meta, after, from = null) {
322
337
  found = claudeInterimWords(readLines(claudeSessionTranscriptPath(meta), boundary));
323
338
  // 境界は、送った時に結び付いていた会話のrolloutの位置。会話の切り替えは追わない(ADR 0105)。
324
339
  else if (meta.kind === "codex")
325
- found = codexInterimWords(readLines(meta.vendor_session_id ? codexBoundTranscript(meta) : codexRootTranscript(meta), boundary));
340
+ found = codexInterimWords(codexLinesFrom(meta, boundary));
326
341
  else if (meta.kind === "grok")
327
342
  found = grokInterimWords(readLines(grokChatHistory(meta)), boundary);
328
343
  else if (meta.kind === "cursor")
@@ -0,0 +1,22 @@
1
+ export function parseNativeSessionReceipt(receipt, platform = process.platform) {
2
+ const separator = platform === "win32" ? "[ \\t]" : "\\t";
3
+ const match = new RegExp(`^(\\$\\d+)${separator}([A-Za-z0-9_-]{1,64})${separator}([1-9][0-9]*)${separator}(%\\d+)${separator}([1-9][0-9]*)\\r?\\n?$`).exec(receipt);
4
+ if (!match || !Number.isSafeInteger(Number(match[3])) || !Number.isSafeInteger(Number(match[5])))
5
+ throw new Error("native_session_receipt_unconfirmed");
6
+ return { native_id: match[1], session_id: match[2], server_pid: Number(match[3]), pane_id: match[4], pane_pid: Number(match[5]) };
7
+ }
8
+ export function nativePaneTarget(target, platform = process.platform) {
9
+ // Qualify psmux panes by session; $ID routing under -L duplicates the namespace prefix.
10
+ return platform === "win32" ? `${target.session_id}:.${target.pane_id}` : target.pane_id;
11
+ }
12
+ export function nativeSessionTarget(target, platform = process.platform) {
13
+ // psmux kill-session compares the raw name; a trailing colon silently misses.
14
+ return platform === "win32" ? `=${target.session_id}` : target.native_id;
15
+ }
16
+ export function nativeSessionCondition(target, allowExitedPane = false) {
17
+ const pane = `#{==:#{pane_pid},${target.pane_pid}}`;
18
+ return [...[["pid", target.server_pid], ["session_id", target.native_id], ["session_name", target.session_id],
19
+ ["pane_id", target.pane_id]].map(([key, value]) => `#{==:#{${key}},${value}}`),
20
+ allowExitedPane ? `#{||:${pane},#{&&:#{==:#{pane_dead},1},#{==:#{pane_pid},}}}` : pane]
21
+ .reduce((left, right) => `#{&&:${left},${right}}`);
22
+ }