aiterm-mcp 0.63.1 → 0.63.3

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/dist/core.js CHANGED
@@ -1,6 +1,13 @@
1
+ import { recordAgentResumeFailure, safeResumeReadiness } from "./agent-resume-diagnostic.js";
2
+ import { configureClaudeForSessionOnly } from "./harnesses/claude-configure.js";
3
+ import { configureCodexModel } from "./harnesses/codex-configure.js";
4
+ import { lineCounts } from "./agent-model-ui.js";
5
+ import { stripControl, reduceOutput, estimateTokens, ANSI_RE, CTRL_RE } from "./pty-output.js";
6
+ export { stripControl, reduceOutput } from "./pty-output.js";
7
+ import { loadAgentMetadata, tryLoadAgentMetadata } from "./agent-metadata-reader.js";
1
8
  import { nativePaneTarget } from "./native-session.js";
2
9
  import { AsyncLocalStorage } from "node:async_hooks";
3
- import { inspectIdleSettings } from "./harnesses/idle-settings.js";
10
+ import { inspectIdleSettings, inspectCodexResumeSettings, codexRecoveryComposer } from "./harnesses/idle-settings.js";
4
11
  import { AGENT_TUI_READY_TIMEOUT_MS, AGENT_TUI_FIRST_DRAW_TIMEOUT_MS, AGENT_TUI_READY_POLL_MS, isAgentTuiReady, isAgentTuiBusy, isAgentTuiIdleReady, agentPaneObservation, waitAgentTuiReadyImpl, detectAgentSubmitResidueImpl, waitCursorPromptVisibleImpl, settleAgentDoneScreenImpl } from "./agent-screen-observation.js";
5
12
  export { launchEchoIsLastOnScreen, __testSetAgentTuiReadyStableSamples } from "./agent-screen-observation.js";
6
13
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
@@ -30,7 +37,7 @@ import { initializeAgentActivity, recordAgentInput, recordAgentTurnEnd, readAgen
30
37
  import { checkIdleSeat, decideIdleSeat, idleMinutes } from "./agent-idle.js";
31
38
  import { AGENT_IDLE_ENABLED, armAgentIdleClock, idleClockDeadline, isAgentIdleClockOwner, requestAgentIdleClock } from "./agent-idle-clock.js";
32
39
  import { stopProcessTree } from "./process-tree-stop.js";
33
- import { captureAgentResumeTemplate, readAgentResumeTemplate, writeAgentResumeTemplate, finishAgentResumeConfiguration, refreshAgentResumeRecipe, readAgentIdleClock, retireAgentIdleClock, readAgentResumeRecipe, writeAgentResumeRecipe, agentResumeRecipeDigest, readAgentLifecycle, writeAgentLifecycle, cancelAgentStopping, readAgentResumeAttempt, writeAgentResumeAttempt, readAgentResumeNative, writeAgentResumeNative } from "./agent-lifecycle.js";
40
+ import { writeAgentResumeRecoveryOrigin, confirmedAgentResumeRecoveryOrigin, readAgentResumeResolution, writeAgentResumeResolution, agentResumeRecordDigest, captureAgentResumeTemplate, readAgentResumeTemplate, writeAgentResumeTemplate, finishAgentResumeConfiguration, refreshAgentResumeRecipe, readAgentIdleClock, retireAgentIdleClock, readAgentResumeRecipe, writeAgentResumeRecipe, agentResumeRecipeDigest, readAgentLifecycle, writeAgentLifecycle, cancelAgentStopping, readAgentResumeAttempt, writeAgentResumeAttempt, readAgentResumeNative, writeAgentResumeNative } from "./agent-lifecycle.js";
34
41
  import { createCodexGoalObjective, editCodexGoalObjective, submitCodexGoalCommand } from "./harnesses/codex-goal-editor.js";
35
42
  import { closeExpectedExecution, parseExecutionNativeSessions, executionNativeBindingSchema } from "./execution-close.js";
36
43
  import { executionLaunchSchema, executionPointSchema } from "./execution-contract.js";
@@ -43,19 +50,19 @@ import { paneTokenHint } from "./harnesses/pane-tokens.js";
43
50
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
44
51
  import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
45
52
  import { liveNodeExecutable } from "./live-node.js";
46
- import { AitermError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
53
+ import { AitermError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
47
54
  import { isWin, SOCKDIR, SOCK, tmuxCommand, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, } from "./tmux-runtime.js";
48
- import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentEventPath, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, subagentInstruction, agentLineageFields, } from "./agent-shared.js";
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";
49
56
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
50
57
  import { processStartIdentity } from "./runtime-error-os.js";
51
58
  import { processStartIdentities } from "./process-start.js";
52
59
  import { catalogUnavailable } from "./model-catalog.js";
53
60
  import { FastModeError, fastModeFailure } from "./fast-mode.js";
54
- import { readFileOrNull, restoreJsonSetting, withUserConfigLock } from "./user-config.js";
61
+ import { readFileOrNull, restoreJsonSetting, withUserConfigLock, restoreUserDefaults, keepingUserDefaults, USER_DEFAULT_SETTLE_MS } from "./user-config.js";
55
62
  import { isDeepStrictEqual } from "node:util";
56
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";
57
- import { codexAuthPlan, codexAuthStatus, codexAuthPane, realCodexHome, readCodexConfigPins, bindCodexTranscriptSession, latestCodexCompletion, codexTurnSettled, codexCompletedTurnId, captureCodexResumeProof, readCodexResumeProof, codexResumeProofDigest, codexRunningTurn, codexInterruptionRecord, observeCodexDone, buildCodexAgentCmd, codexAgentArgv, codexResumeArgv, codexLaunchNote, codexPaneObservation, CODEX_INTERRUPT_KEY, codexHelperProcess, codexRateLimitModelSwitchDialog, codexApprovalDialog, codexStartupAction, codexModelChoice, codexModelChangeNotices, codexEffortChoice, codexCurrentEffort, codexMoreReasoningChoice, codexTranscriptText, createCodexAgentMetadata, codexModelChoices, codexFastCommandOffered, codexFooterShowsFast, codexServiceTierNotices, restoreCodexDefaults, restoreCodexDefaultInFile, } from "./harnesses/codex.js";
58
- import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS, agentManagedClaudeSettingsPath, agentClaudeResultPath, agentClaudeOperationPath, agentClaudeApprovalReceiptPath, agentClaudeDispatchReceiptPath, validateOperationId, readClaudeResultText, assertClaudeAuthenticationReady, claudeModelChoices, claudeConfigDir, claudeFastIndicatorShown, claudeFastResult, buildClaudeAgentCmd, claudeAgentArgv, claudeResumeArgv, claudeLaunchNote, claudePaneObservation, CLAUDE_INTERRUPT_KEY, claudeUsageLimit, claudeLiveSelectMenu, claudeModelPicker, claudeModelPickerRow, claudeModelSwitchConfirm, claudeModelSwitchResult, claudeStartupAction, createClaudeAgentMetadata, claudeSessionTranscriptPath, claudeApiErrorFromLine, claudeApiErrorAfter, } from "./harnesses/claude.js";
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";
59
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";
60
67
  import { interimFromNow, readInterimWords, recordInterimBoundary } from "./interim-words.js";
61
68
  import { codexSeatTurn, grokSteerAcceptance, observeSteerDone, readSteerEntry, recordSteer } from "./steer-follow.js";
@@ -76,20 +83,10 @@ const NON_POSIX_MARK_SHELLS = new Set(["fish", "csh", "tcsh"]);
76
83
  // エコーは rc=%d(リテラル)。数字アンカーでエコーに免疫化し、部分一致による早期誤完了を防ぐ(B1)。
77
84
  // send の printf 書式(`rc=%d`)と対で保守すること。
78
85
  const MARK_DONE_RE = /<<<AITERM_DONE rc=[0-9]+>>>/;
79
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
80
- const AGENT_LINEAGE_RE = /^[A-Za-z0-9_.:-]+(?:>[A-Za-z0-9_.:-]+)*$/;
81
86
  const AGENT_SUBMIT_DELAY_MS = 250;
82
87
  const AGENT_METADATA_NEGATIVE_CACHE_TTL_MS = 2_000;
83
88
  const AGENT_TUI_READY_LINES = 45;
84
89
  const CLAUDE_APPROVAL_SCREEN_LINES = 80;
85
- // 出力削減(RTK の CAP 思想を移植)
86
- const MAX_LINES_BEFORE_ELIDE = 60;
87
- const HEAD_LINES = 30;
88
- const TAIL_LINES = 20;
89
- const MAX_LINE_CHARS_BEFORE_ELIDE = 2000;
90
- const LINE_HEAD_CHARS = 1200;
91
- const LINE_TAIL_CHARS = 600;
92
- const DEDUP_MIN_RUN = 3; // 同一行がこれ以上連続したら 1 行+件数に畳む
93
90
  const MAX_FULL_BYTES = 8 * 1024 * 1024; // full/range 読取で一度にメモリへ載せる上限(B7)
94
91
  const MAX_SEND_BYTES = 64 * 1024;
95
92
  // PTY入力queueはOSを問わず、tmuxが長文を1回で流すと後半を落とすことがある。
@@ -105,10 +102,6 @@ const SESSION_SEND_LOCK_POLL_MS = 25;
105
102
  // 起動から最初の描画を待つ上限と、貼り付けの上限の和。前の1通が正常に進んでいる間は待ち切れる長さにする。
106
103
  const AGENT_SEND_LOCK_WAIT_MS = AGENT_TUI_FIRST_DRAW_TIMEOUT_MS + SESSION_SEND_LOCK_WAIT_MS;
107
104
  const AGENT_SEND_LOCK_POLL_MS = 50;
108
- // CSI/OSC/ESC エスケープ・制御文字
109
- // CSI / OSC(BEL or ST 終端) / DCS・PM・APC・SOS(ESC P/^/_/X … BEL or ST 終端。ペイロード本文ごと除去=B10) / 残る2文字エスケープ
110
- const ANSI_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P^_X][\s\S]*?(?:\x07|\x1b\\)|\x1b[@-_]/g;
111
- const CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; // \t(09) \n(0a) は残す
112
105
  const PASTE_MARKERS_RE = /\x1b\[20[01]~/g;
113
106
  // よく使う制御キーの別名(tmux のキー名へ)
114
107
  const KEYMAP = {
@@ -374,6 +367,10 @@ function cleanupAgentState(name) {
374
367
  f.endsWith(".activity.jsonl") ||
375
368
  f.endsWith(".resume.json") ||
376
369
  f.endsWith(".resume-attempt.json") ||
370
+ f.endsWith(".resume-failure.json") ||
371
+ f.endsWith(".resume-resolution.json") ||
372
+ f.endsWith(".resume-recovery-origin.json") ||
373
+ f.endsWith(".resume-restore.json") ||
377
374
  f.endsWith(".resume-native.json") ||
378
375
  f.endsWith(".resume-template.json") ||
379
376
  f.endsWith(".codex-resume.json") ||
@@ -394,7 +391,7 @@ function cleanupAgentState(name) {
394
391
  f.endsWith(".steers.jsonl") ||
395
392
  f.endsWith(".auth.json"))
396
393
  fs.unlinkSync(p);
397
- else if (f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".home")) {
394
+ else if (f.endsWith(".codex-home") || f.endsWith(".grok-home") || f.endsWith(".cursor-plugin") || f.endsWith(".home") || f.endsWith(".resume-restore.d")) {
398
395
  fs.rmSync(p, { recursive: true, force: true });
399
396
  }
400
397
  }
@@ -468,103 +465,6 @@ export function attachHint(name) {
468
465
  ` (抜けるには Ctrl-b d)`);
469
466
  }
470
467
  // ---------------------------------------------------------------- 出力削減
471
- function estimateTokens(s) {
472
- return Math.ceil(s.length / 4.0);
473
- }
474
- export function stripControl(text) {
475
- // OSC/DCS等の本文内のCRを、印字された進捗断片として扱わない。
476
- text = text.replace(ANSI_RE, sequence => sequence.startsWith("\x1b[") ? sequence : "");
477
- text = text.replace(/\r\n/g, "\n"); // CRLF 正規化
478
- const out = [];
479
- for (const line of text.split("\n")) {
480
- let visibleLine = "";
481
- for (const part of line.split("\r")) {
482
- const visible = part.replace(ANSI_RE, "").replace(CTRL_RE, "");
483
- // CRとcursor表示切替だけでは、既に印字した結果や完了印を消さない。
484
- if (visible !== "" || /\x1b\[[0-2]?K/.test(part))
485
- visibleLine = visible;
486
- }
487
- out.push(visibleLine.replace(/\s+$/, "")); // rstrip
488
- }
489
- return out.join("\n");
490
- }
491
- function collapseBlanks(lines) {
492
- const out = [];
493
- let blanks = 0;
494
- for (const ln of lines) {
495
- if (ln === "") {
496
- blanks++;
497
- if (blanks <= 1)
498
- out.push(ln);
499
- }
500
- else {
501
- blanks = 0;
502
- out.push(ln);
503
- }
504
- }
505
- while (out.length && out[0] === "")
506
- out.shift();
507
- while (out.length && out[out.length - 1] === "")
508
- out.pop();
509
- return out;
510
- }
511
- function dedupRuns(lines) {
512
- const out = [];
513
- let i = 0;
514
- const n = lines.length;
515
- while (i < n) {
516
- let j = i;
517
- while (j < n && lines[j] === lines[i])
518
- j++;
519
- const run = j - i;
520
- if (run >= DEDUP_MIN_RUN && lines[i] !== "")
521
- out.push(`${lines[i]} 〈×${run}〉`);
522
- else
523
- out.push(...lines.slice(i, j));
524
- i = j;
525
- }
526
- return out;
527
- }
528
- function surrogateSafeEnd(text, end) {
529
- return end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end])
530
- ? end + 1
531
- : end;
532
- }
533
- function surrogateSafeStart(text, start) {
534
- return start > 0 && start < text.length && /[\uD800-\uDBFF]/.test(text[start - 1]) && /[\uDC00-\uDFFF]/.test(text[start])
535
- ? start - 1
536
- : start;
537
- }
538
- function elideLongLines(lines) {
539
- return lines.map((line) => {
540
- if (line.length <= MAX_LINE_CHARS_BEFORE_ELIDE)
541
- return line;
542
- const headEnd = surrogateSafeEnd(line, LINE_HEAD_CHARS);
543
- const tailStart = surrogateSafeStart(line, line.length - LINE_TAIL_CHARS);
544
- const omitted = tailStart - headEnd;
545
- return `${line.slice(0, headEnd)}… 〈行内 ${omitted} 文字省略。全文は raw:true か line_range で取得〉 …${line.slice(tailStart)}`;
546
- });
547
- }
548
- /** RTK 4戦略を移植: 制御除去 / 空白正規化 / 連続重複圧縮 / head+tail 折りたたみ。返り値 [body, meta]。 */
549
- export function reduceOutput(raw, name, elide = true) {
550
- const rawLinesN = (raw.match(/\n/g)?.length ?? 0) + (raw && !raw.endsWith("\n") ? 1 : 0);
551
- const cleaned = stripControl(raw);
552
- let lines = collapseBlanks(cleaned.split("\n"));
553
- lines = dedupRuns(lines);
554
- let elided = 0;
555
- if (elide && lines.length > MAX_LINES_BEFORE_ELIDE) {
556
- elided = lines.length - HEAD_LINES - TAIL_LINES;
557
- const hint = `… 〈${elided} 行省略。全文は full=true、範囲は line_range="A:B"〉 …`;
558
- lines = [...lines.slice(0, HEAD_LINES), hint, ...lines.slice(lines.length - TAIL_LINES)];
559
- }
560
- if (elide)
561
- lines = elideLongLines(lines);
562
- const body = lines.join("\n");
563
- const meta = `[aiterm ${name}: ${lines.length} 行 / ~${estimateTokens(body)} tok ` +
564
- `(raw ${rawLinesN} 行 / ~${estimateTokens(raw)} tok)` +
565
- (elided ? `; ${elided} 行 hidden]` : "]");
566
- return [body, meta];
567
- }
568
468
  // ---------------------------------------------------------------- tmux 補助
569
469
  function autoName() {
570
470
  const r = tmux("list-sessions", "-F", "#{session_name}");
@@ -1681,7 +1581,7 @@ function agentDormantState(meta) {
1681
1581
  const previous = readAgentResumeAttempt({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from });
1682
1582
  if (!previous || previous.next_launch_id !== meta.launch_id)
1683
1583
  return "unknown";
1684
- if (previous.state !== "ready")
1584
+ if (previous.state !== "ready" && !hasCompletedResumeRecovery(meta))
1685
1585
  return previous.state;
1686
1586
  }
1687
1587
  return null;
@@ -3026,21 +2926,6 @@ function hasClaudeDispatchReceipt(meta, operationId) {
3026
2926
  throw new AitermError(`Claude dispatch receiptを確認できません: ${error.message}`, 2);
3027
2927
  }
3028
2928
  }
3029
- function normalizeInitialPromptState(v) {
3030
- if (v === true)
3031
- return "pending";
3032
- if (v === false || v == null)
3033
- return "none";
3034
- if (v === "none" ||
3035
- v === "not_sent" ||
3036
- v === "sent" ||
3037
- v === "pending" ||
3038
- v === "done" ||
3039
- v === "failed") {
3040
- return v;
3041
- }
3042
- return "none";
3043
- }
3044
2929
  function setInitialPromptState(meta, state) {
3045
2930
  meta.initial_prompt = state;
3046
2931
  writeAgentMetadata(meta);
@@ -3418,6 +3303,33 @@ async function withAgentSendLock(name, run, untouched = AGENT_SEND_UNSENT, pinRe
3418
3303
  if (meta && !readAgentLifecycle(meta)) {
3419
3304
  if (!fs.existsSync(SOCKDIR) && !meta.resumed_from)
3420
3305
  throw new AitermError(`agent session '${name}' の ${agentLabel(meta.kind)} TUI が入力受付状態になりません。文字列は送信していません。`, 2);
3306
+ const uncertain = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "復帰対象のnativeを確認できません。本文は送信していません。", name, meta.launch_id);
3307
+ let failed;
3308
+ try {
3309
+ failed = !!failedCodexResumeRecipe(meta);
3310
+ const old = meta.resumed_from ? readAgentResumeAttempt({ aiterm_session: name, launch_id: meta.resumed_from }) : null;
3311
+ if (old?.state === "failed" && old.next_launch_id === meta.launch_id && !hasCompletedResumeRecovery(meta) && !failed)
3312
+ throw uncertain();
3313
+ }
3314
+ catch {
3315
+ throw uncertain();
3316
+ }
3317
+ if (failed) {
3318
+ const native = observeExecutionNativeSessions();
3319
+ if (native.state !== "known")
3320
+ throw uncertain();
3321
+ if (!native.sessions.some(row => row.session_id === name))
3322
+ return await run();
3323
+ let entered = false;
3324
+ try {
3325
+ return await withAgentResumeTarget(meta, () => { entered = true; return run(); });
3326
+ }
3327
+ catch (error) {
3328
+ if (entered)
3329
+ throw error;
3330
+ throw uncertain();
3331
+ }
3332
+ }
3421
3333
  return await withAgentResumeTarget(meta, run);
3422
3334
  }
3423
3335
  return await run();
@@ -3475,247 +3387,6 @@ function liveWaitLocks(name) {
3475
3387
  }
3476
3388
  return out;
3477
3389
  }
3478
- function loadAgentLineageFields(m, required) {
3479
- const present = m.agent_role !== undefined ||
3480
- m.parent_session_id !== undefined ||
3481
- m.delegation_depth !== undefined ||
3482
- m.lineage !== undefined ||
3483
- m.delegation_allowed !== undefined;
3484
- if (!present && !required)
3485
- return {};
3486
- if (m.agent_role !== "subagent" ||
3487
- typeof m.parent_session_id !== "string" ||
3488
- !/^[A-Za-z0-9_-]{1,64}$/.test(m.parent_session_id) ||
3489
- !Number.isSafeInteger(m.delegation_depth) ||
3490
- m.delegation_depth < 1 ||
3491
- typeof m.lineage !== "string" ||
3492
- m.lineage.length > 4096 ||
3493
- !AGENT_LINEAGE_RE.test(m.lineage) ||
3494
- m.delegation_allowed !== true) {
3495
- throw new AitermError("agent metadata のsub-agent lineageが不正です", 2);
3496
- }
3497
- return agentLineageFields({
3498
- agentRole: "subagent",
3499
- parentSessionId: m.parent_session_id,
3500
- delegationDepth: m.delegation_depth,
3501
- lineage: m.lineage,
3502
- delegationAllowed: true,
3503
- });
3504
- }
3505
- function loadAgentMetadata(name) {
3506
- assertSessionName(name);
3507
- const dir = agentsDir();
3508
- const files = fs
3509
- .readdirSync(dir)
3510
- .filter((f) => f.startsWith(`${name}.`) && f.endsWith(".agent.json"));
3511
- if (files.length === 0) {
3512
- if (readAgentGeneration(name))
3513
- throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動記録がありません。", 2);
3514
- throw new AitermError(`session '${name}' は agent_done 管理セッションではありません。claude_agent/codex_agent 等の launcher で起動してください。`, 2);
3515
- }
3516
- const selectedFile = selectAgentMetadataFile(name, files);
3517
- let raw;
3518
- try {
3519
- raw = JSON.parse(fs.readFileSync(path.join(dir, selectedFile), "utf8"));
3520
- }
3521
- catch (e) {
3522
- throw new AitermError(`agent metadata を読めません: ${e.message}`, 2);
3523
- }
3524
- const m = raw;
3525
- if ((m.kind !== "claude" && m.kind !== "codex" && m.kind !== "grok" && m.kind !== "cursor" && m.kind !== "antigravity") ||
3526
- m.aiterm_session !== name ||
3527
- typeof m.launch_id !== "string" ||
3528
- !LAUNCH_ID_RE.test(m.launch_id)) {
3529
- throw new AitermError(`agent metadata が不正です: ${files[0]}`, 2);
3530
- }
3531
- const generation = readAgentGeneration(name);
3532
- if (m.resumed_from !== undefined && (typeof m.resumed_from !== "string" || !LAUNCH_ID_RE.test(m.resumed_from)
3533
- || generation?.launch_id !== m.launch_id || generation.previous_launch_id !== m.resumed_from))
3534
- throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰した起動世代が一致しません。", 2);
3535
- const resumeFields = m.resumed_from === undefined ? {} : { resumed_from: m.resumed_from };
3536
- const expectedEvent = agentEventPath(name, m.launch_id);
3537
- if (m.event_file !== expectedEvent) {
3538
- throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
3539
- }
3540
- if (m.initial_prompt_delivery !== undefined && (!["not_requested", "not_sent", "submitted_unconfirmed", "started"].includes(m.initial_prompt_delivery.status)
3541
- || typeof m.initial_prompt_delivery.reason !== "string"
3542
- || ![true, false, null].includes(m.initial_prompt_delivery.turn_started)
3543
- || (m.initial_prompt_cursor !== null && !Number.isSafeInteger(m.initial_prompt_cursor))))
3544
- throw new AitermError("初手delivery metadataが不正です", 2);
3545
- const deliveryFields = m.initial_prompt_delivery === undefined ? {} : {
3546
- initial_prompt_delivery: m.initial_prompt_delivery, initial_prompt_cursor: m.initial_prompt_cursor,
3547
- };
3548
- const parsedNative = m.execution_native === undefined ? null : executionNativeBindingSchema.safeParse(m.execution_native);
3549
- if (parsedNative && !parsedNative.success)
3550
- throw new AitermError("agent native bindingが不正です", 2);
3551
- if (m.windows_launch_exit_tracked !== undefined && m.windows_launch_exit_tracked !== true)
3552
- throw new AitermError("Windows launch exit metadataが不正です", 2);
3553
- const executableFields = {
3554
- ...(m.windows_launch_exit_tracked === true ? { windows_launch_exit_tracked: true } : {}),
3555
- ...(m.agent_executable === undefined ? {} : { agent_executable: m.agent_executable }),
3556
- ...(parsedNative?.success ? { execution_native: parsedNative.data } : {}),
3557
- };
3558
- // 席のファストの状態と、起動・設定替えで渡したmodel(ADR 0114)。この項目より前の版が書いた控えには無い。
3559
- const fastFields = {
3560
- ...(typeof m.fast === "boolean" ? { fast: m.fast } : {}),
3561
- ...(typeof m.model === "string" || m.model === null ? { model: m.model } : {}),
3562
- };
3563
- const startupShapes = Array.isArray(m.startup_process_shapes) && m.startup_process_shapes.every((shape) => shape && typeof shape.identity === "string" && (shape.parent === null || typeof shape.parent === "string") && typeof shape.argv_digest === "string")
3564
- ? { startup_process_shapes: m.startup_process_shapes } : {};
3565
- const startupFields = Array.isArray(m.startup_processes) && m.startup_processes.every((identity) => typeof identity === "string")
3566
- ? { startup_processes: m.startup_processes, ...startupShapes } : {};
3567
- if (m.kind === "antigravity") {
3568
- if (m.hook_route !== "shared_antigravity_home" || typeof m.antigravity_home !== "string" || !path.isAbsolute(m.antigravity_home)
3569
- || (m.vendor_session_id != null && (typeof m.vendor_session_id !== "string" || !UUID_RE.test(m.vendor_session_id))))
3570
- throw new AitermError("Antigravity metadataが不正です", 2);
3571
- return { kind: "antigravity", aiterm_session: name, launch_id: m.launch_id, event_file: expectedEvent,
3572
- cwd: typeof m.cwd === "string" ? m.cwd : null, created_at: typeof m.created_at === "string" ? m.created_at : "",
3573
- vendor_session_id: m.vendor_session_id ?? null, initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3574
- hook_route: "shared_antigravity_home", antigravity_home: m.antigravity_home, node_platform: process.platform,
3575
- ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3576
- ...deliveryFields, ...executableFields, ...fastFields, ...startupFields, ...loadAgentLineageFields(m, true) };
3577
- }
3578
- if (m.kind === "claude") {
3579
- const expectedSettings = agentManagedClaudeSettingsPath(name, m.launch_id);
3580
- const expectedResult = agentClaudeResultPath(name, m.launch_id);
3581
- const launchOperationId = m.launch_operation_id ?? null;
3582
- const launchRequestDigest = m.launch_request_digest ?? null;
3583
- if (m.hook_route !== "shared_claude_settings" ||
3584
- m.claude_settings !== expectedSettings ||
3585
- typeof m.vendor_session_id !== "string" ||
3586
- !UUID_RE.test(m.vendor_session_id) ||
3587
- m.result_file !== expectedResult ||
3588
- (m.claude_home !== undefined && (typeof m.claude_home !== "string" || !path.isAbsolute(m.claude_home))) ||
3589
- ((launchOperationId === null) !== (launchRequestDigest === null)) ||
3590
- (launchOperationId !== null && !OPERATION_ID_RE.test(launchOperationId)) ||
3591
- (launchRequestDigest !== null && !OPERATION_ID_RE.test(launchRequestDigest))) {
3592
- throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
3593
- }
3594
- return {
3595
- kind: "claude",
3596
- aiterm_session: name,
3597
- launch_id: m.launch_id,
3598
- event_file: expectedEvent,
3599
- created_at: typeof m.created_at === "string" ? m.created_at : "",
3600
- cwd: typeof m.cwd === "string" ? m.cwd : null,
3601
- ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3602
- vendor_session_id: m.vendor_session_id,
3603
- initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3604
- ...deliveryFields,
3605
- ...executableFields,
3606
- ...fastFields,
3607
- ...resumeFields,
3608
- ...startupFields,
3609
- launch_operation_id: launchOperationId,
3610
- launch_request_digest: launchRequestDigest,
3611
- hook_route: "shared_claude_settings",
3612
- ...loadAgentLineageFields(m, true),
3613
- node_platform: process.platform,
3614
- claude_settings: expectedSettings,
3615
- ...(m.claude_home === undefined ? {} : { claude_home: m.claude_home }),
3616
- result_file: expectedResult,
3617
- };
3618
- }
3619
- if (m.kind === "codex") {
3620
- // codex_home は起動時に記録した per-launch の正本を信じる。現在の process env
3621
- // (realCodexHome())との等値を要求すると、席専用 CODEX_HOME で起動した正当な
3622
- // session が別の aiterm instance から全部拒否される(2026-08-22 実測: peertable の
3623
- // 席へ pty_key できず円卓が停止した)。検証は形(絶対パス)だけにする。
3624
- const recordedHome = m.codex_home;
3625
- if (m.hook_route !== "shared_codex_home" || m.completion_route !== "codex_transcript"
3626
- || typeof recordedHome !== "string" || !path.isAbsolute(recordedHome)) {
3627
- throw new AitermError("agent metadata の codex_home が不正です(絶対パスの記録が必要)", 2);
3628
- }
3629
- return {
3630
- kind: "codex",
3631
- aiterm_session: name,
3632
- launch_id: m.launch_id,
3633
- event_file: expectedEvent,
3634
- created_at: typeof m.created_at === "string" ? m.created_at : "",
3635
- cwd: typeof m.cwd === "string" ? m.cwd : null,
3636
- ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3637
- vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
3638
- initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3639
- ...deliveryFields,
3640
- ...executableFields,
3641
- ...fastFields,
3642
- ...resumeFields,
3643
- ...startupFields,
3644
- hook_route: "shared_codex_home",
3645
- completion_route: "codex_transcript",
3646
- ...loadAgentLineageFields(m, true),
3647
- node_platform: process.platform,
3648
- codex_home: recordedHome,
3649
- };
3650
- }
3651
- if (m.kind === "cursor") {
3652
- const recordedHome = m.cursor_home;
3653
- if (m.hook_route !== "shared_cursor_home" ||
3654
- m.completion_route !== "cursor_transcript" ||
3655
- typeof recordedHome !== "string" ||
3656
- !path.isAbsolute(recordedHome)) {
3657
- throw new AitermError("agent metadata の cursor_home が不正です(絶対パスの記録が必要)", 2);
3658
- }
3659
- return {
3660
- kind: "cursor",
3661
- aiterm_session: name,
3662
- launch_id: m.launch_id,
3663
- event_file: expectedEvent,
3664
- created_at: typeof m.created_at === "string" ? m.created_at : "",
3665
- cwd: typeof m.cwd === "string" ? m.cwd : null,
3666
- ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3667
- vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
3668
- initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3669
- ...deliveryFields,
3670
- ...executableFields,
3671
- ...fastFields,
3672
- ...resumeFields,
3673
- ...startupFields,
3674
- hook_route: "shared_cursor_home",
3675
- completion_route: "cursor_transcript",
3676
- ...loadAgentLineageFields(m, true),
3677
- node_platform: process.platform,
3678
- cursor_home: recordedHome,
3679
- };
3680
- }
3681
- // grok_home も codex_home と同じ理由で per-launch の記録値を正とする(席専用 GROK_HOME)。
3682
- // 認証正本の照合も記録された home に対して行う——現在の env の home と比較すると、
3683
- // 席専用 home で起動した session が別 instance から拒否される。
3684
- const recordedGrokHome = m.grok_home;
3685
- if (m.hook_route !== "shared_grok_home" ||
3686
- m.completion_route !== "grok_transcript" ||
3687
- typeof recordedGrokHome !== "string" ||
3688
- !path.isAbsolute(recordedGrokHome) ||
3689
- typeof m.vendor_session_id !== "string" ||
3690
- !UUID_RE.test(m.vendor_session_id)) {
3691
- throw new AitermError("agent metadata の grok_home が不正です(絶対パスの記録が必要)", 2);
3692
- }
3693
- const expectedAuthPath = resolveAndValidateGrokAuth(recordedGrokHome);
3694
- if ((typeof m.grok_auth_path === "string" ? m.grok_auth_path : null) !== expectedAuthPath) {
3695
- throw new AitermError("agent metadata の認証正本が現在の設定と一致しません", 2);
3696
- }
3697
- return {
3698
- kind: m.kind,
3699
- aiterm_session: name,
3700
- launch_id: m.launch_id,
3701
- event_file: expectedEvent,
3702
- created_at: typeof m.created_at === "string" ? m.created_at : "",
3703
- cwd: typeof m.cwd === "string" ? m.cwd : null,
3704
- ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
3705
- vendor_session_id: m.vendor_session_id,
3706
- initial_prompt: normalizeInitialPromptState(m.initial_prompt),
3707
- ...deliveryFields,
3708
- ...executableFields,
3709
- ...fastFields,
3710
- ...startupFields,
3711
- hook_route: "shared_grok_home",
3712
- completion_route: "grok_transcript",
3713
- ...loadAgentLineageFields(m, true),
3714
- node_platform: process.platform,
3715
- grok_home: recordedGrokHome,
3716
- grok_auth_path: expectedAuthPath,
3717
- };
3718
- }
3719
3390
  function parseAgentDoneEvent(line, meta) {
3720
3391
  let obj;
3721
3392
  try {
@@ -3853,14 +3524,6 @@ function bindCompletedInitialPrompt(meta) {
3853
3524
  bindAgentHarnessSession(meta, scanned.event);
3854
3525
  setInitialPromptState(meta, "done");
3855
3526
  }
3856
- function tryLoadAgentMetadata(name) {
3857
- try {
3858
- return loadAgentMetadata(name);
3859
- }
3860
- catch {
3861
- return null;
3862
- }
3863
- }
3864
3527
  function latestAgentDoneEvent(meta, expectedOperationId = null) {
3865
3528
  if (meta.kind === "codex")
3866
3529
  return latestCodexCompletion(meta, readTranscriptLines);
@@ -4677,11 +4340,15 @@ async function waitStartupSelection(name, selected) {
4677
4340
  }
4678
4341
  return false;
4679
4342
  }
4680
- async function prepareAgentInput(name, meta, options) {
4343
+ async function prepareAgentInput(name, meta, options, acceptRunningCodex = false) {
4681
4344
  await ensureAgentOwnsPaneInput(name, meta.kind);
4682
- let ready = await waitAgentTuiReady(name, meta, options.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS);
4345
+ // A resumed Codex can consume its native queue before the composer becomes idle.
4346
+ const running = (screen) => acceptRunningCodex && meta.kind === "codex" && !!meta.resumed_from
4347
+ && codexPaneObservation(screen).state === "busy" && codexRunningTurn(meta) !== null;
4348
+ const wait = () => waitAgentTuiReady(name, meta, options.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS, { selectSteer: running });
4349
+ let ready = await wait();
4683
4350
  const handled = new Set();
4684
- while (!ready.ready) {
4351
+ while (!ready.ready && !ready.steer) {
4685
4352
  const action = meta.kind === "codex" ? codexStartupAction(ready.lastScreen, options.trust_project === true)
4686
4353
  : meta.kind === "claude" ? claudeStartupAction(ready.lastScreen, options.trust_project === true)
4687
4354
  : meta.kind === "grok" ? grokStartupAction(ready.lastScreen, options.trust_project === true)
@@ -4709,15 +4376,17 @@ async function prepareAgentInput(name, meta, options) {
4709
4376
  await withExecutionNativeAdmission(name, () => sendKey(name, action.keys.at(-1), { preserveAgentOperation: true }));
4710
4377
  await sleep(AGENT_SUBMIT_DELAY_MS);
4711
4378
  }
4712
- ready = await waitAgentTuiReady(name, meta, options.ready_timeout ?? AGENT_TUI_READY_TIMEOUT_MS);
4379
+ ready = await wait();
4713
4380
  }
4714
- if (!ready.ready)
4381
+ if (!ready.ready && !ready.steer)
4715
4382
  return { status: "blocked", reason: agentPaneObservation(meta.kind, ready.lastScreen).reason };
4716
4383
  const live = observeNativeSession(name);
4717
- if (live.harness_alive !== true || live.harness_process === null || live.state !== "idle")
4384
+ if (live.harness_alive !== true || live.harness_process === null
4385
+ || (live.state !== "idle" && !(ready.steer && live.state === "busy" && codexRunningTurn(meta) !== null)))
4718
4386
  return { status: "blocked", reason: live.reason };
4719
4387
  // ここまでに居るprocessは起動時の足場(harness・MCP・起動時hook)。初手を送る前に控える。
4720
- if (live.activity.cursor !== null) {
4388
+ // shortcut: a native queued turn can already own children, so leave its startup baseline unknown until a future lifecycle can distinguish them.
4389
+ if (live.activity.cursor !== null && !ready.steer) {
4721
4390
  meta.startup_processes = Object.keys(decodeActivityCursor(live.activity.cursor, name).processes);
4722
4391
  meta.startup_process_shapes = startupProcessShapes(meta.startup_processes, readRuntimeProcesses());
4723
4392
  writeAgentMetadata(meta);
@@ -4848,13 +4517,6 @@ async function waitForScreenText(name, text, timeoutMs = 3_000) {
4848
4517
  } while (performance.now() < deadline);
4849
4518
  throw new AitermError(`${agentLabel(loadAgentMetadata(name).kind)} の ${text} 画面を確認できません`, 2);
4850
4519
  }
4851
- function lineCounts(screen) {
4852
- const counts = new Map();
4853
- for (const line of screen.split("\n").map((value) => value.trim()).filter(Boolean)) {
4854
- counts.set(line, (counts.get(line) ?? 0) + 1);
4855
- }
4856
- return counts;
4857
- }
4858
4520
  async function waitForGrokConfigurationResult(name, before, model, effort, timeoutMs = 3_000) {
4859
4521
  const beforeCounts = lineCounts(before);
4860
4522
  const footerAlreadyMatched = grokFooterHasConfiguration(before, model, effort);
@@ -5372,187 +5034,6 @@ export async function __testInspectAgentIdleSettings(name) {
5372
5034
  return !!template && typeof meta.fast === "boolean" && inspectAgentIdleSettings(name, meta, { ...template, fast: meta.fast });
5373
5035
  });
5374
5036
  }
5375
- const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
5376
- const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
5377
- const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
5378
- const CLAUDE_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
5379
- /**
5380
- * Claude Codeの席のmodel/effortを、この会話だけで替える(ADR 0111)。
5381
- * `/model <名前>` と `/effort <値>` は、選んだ値を端末の ~/.claude/settings.json へ新しい会話の既定として保存する
5382
- * (2.1.296で確かめた)。引数なしの `/model` の選ぶ画面で s を押すと保存されないので、画面を1歩ずつ読んでそちらを打つ。
5383
- * 保存しない選び方が画面に無い時、行やeffortを選べない時は、Escで閉じて何も変えずに断る。
5384
- */
5385
- async function configureClaudeForSessionOnly(name, meta, model, effort, beforeChange) {
5386
- let selectionIssued = false;
5387
- const screen = () => captureScreen(name, AGENT_TUI_READY_LINES);
5388
- const until = async (read, timeoutMs) => {
5389
- const deadline = performance.now() + timeoutMs;
5390
- do {
5391
- const got = read();
5392
- if (got)
5393
- return got;
5394
- await sleep(100);
5395
- } while (performance.now() < deadline);
5396
- return null;
5397
- };
5398
- // Escは、選ぶ画面か確かめの画面が出ている間だけ打つ(入力欄へ戻った後のEscは、ほかの操作を取り消してしまう)。
5399
- const refuse = async (code, reason) => {
5400
- for (let i = 0; i < 3; i++) {
5401
- const now = screen();
5402
- if (!claudeModelPicker(now) && !claudeModelSwitchConfirm(now))
5403
- break;
5404
- sendMenuChoice(name, "Escape");
5405
- await sleep(300);
5406
- }
5407
- throw new AitermError(`${code} vendor=claude session=${name}\n${reason}。` +
5408
- (selectionIssued ? "設定が変わった可能性があります。再送しないでください。" : "modelとreasoning_effortは変えていません。"), 2);
5409
- };
5410
- const picker = () => claudeModelPicker(screen());
5411
- const cursorOf = (p) => p?.rows.find((row) => row.cursor) ?? null;
5412
- // 1回押して、画面の今の行かeffortが変わるまで待つ。変わらなければnull(端で止まった・キーが落ちた)。
5413
- // キーが落ちる事があるので、変わらなければ1度だけ押し直す。
5414
- const press = async (key, changed) => {
5415
- for (let attempt = 0; attempt < 2; attempt++) {
5416
- sendMenuChoice(name, key);
5417
- const next = await until(() => { const p = picker(); return p && changed(p) ? p : null; }, CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS);
5418
- if (next)
5419
- return next;
5420
- }
5421
- return null;
5422
- };
5423
- await sendAgentPromptText(name, "/model");
5424
- let now = await until(picker, CLAUDE_MODEL_PICKER_TIMEOUT_MS);
5425
- if (!now) {
5426
- // 読めない形の画面が開いたままだと、席が次の文を受け取れない。入力待ちでも動作中でもない時だけ、Escを1度打って閉じる。
5427
- let state = claudePaneObservation(screen());
5428
- if (state.state === "unknown") {
5429
- sendMenuChoice(name, "Escape");
5430
- await sleep(500);
5431
- state = claudePaneObservation(screen());
5432
- }
5433
- throw new AitermError(`CLAUDE_MODEL_PICKER_NOT_SHOWN vendor=claude session=${name} state=${state.state}/${state.reason}\n` +
5434
- "Claude Codeの /model の選ぶ画面を読めません(Claude Codeの版で画面の形が変わった見込み)。modelとreasoning_effortは変えていません。", 2);
5435
- }
5436
- if (!now.session_only) {
5437
- return refuse("CLAUDE_MODEL_SESSION_ONLY_UNAVAILABLE", "このClaude Codeの /model の選ぶ画面に、この会話だけで使う選び方(s to use this session only)がありません。" +
5438
- "端末の既定を書き換える選び方は使いません");
5439
- }
5440
- let targetIndex = null;
5441
- if (model) {
5442
- // 見えていない行は、下へ送りながら集める(一周するか、端で止まるまで)。
5443
- const known = new Map(now.rows.map((row) => [row.index, row]));
5444
- const start = cursorOf(now);
5445
- if (!start)
5446
- return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ画面の今の行を読めません");
5447
- let at = start.index;
5448
- const seen = new Set([at]);
5449
- for (let i = 0; i < 80; i++) {
5450
- const before = at;
5451
- const next = await press("Down", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
5452
- if (!next)
5453
- break;
5454
- now = next;
5455
- for (const row of next.rows)
5456
- known.set(row.index, row);
5457
- at = cursorOf(next).index;
5458
- if (seen.has(at))
5459
- break;
5460
- seen.add(at);
5461
- }
5462
- let target = claudeModelPickerRow([...known.values()], model);
5463
- if (!target || /^[a-z]+$/iu.test(model)) {
5464
- const bin = meta.agent_executable ?? resolveAgentBin("claude");
5465
- if (!bin)
5466
- return refuse("CLAUDE_MODEL_NOT_IN_PICKER", "Claude CodeのCLIが見つかりません");
5467
- let catalog;
5468
- try {
5469
- catalog = await claudeModelChoices(bin, meta.cwd ?? process.cwd());
5470
- }
5471
- catch (error) {
5472
- return refuse("CLAUDE_MODEL_CATALOG_UNAVAILABLE", error instanceof Error ? error.message : String(error));
5473
- }
5474
- const native = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
5475
- // The native alias can resolve to an older model; picker order is not alias authority.
5476
- const label = native?.display_name ?? native?.id ?? model;
5477
- const matching = [...known.values()].filter(row => row.label.toLowerCase() === label.toLowerCase());
5478
- target = matching.length === 1 ? matching[0] : null;
5479
- }
5480
- if (!target) {
5481
- const names = [...known.values()].sort((a, b) => a.index - b.index).map((row) => row.label).join(", ");
5482
- return refuse("CLAUDE_MODEL_NOT_IN_PICKER", `Claude Codeの /model の選ぶ画面に ${model} がありません(選べる機種: ${names})`);
5483
- }
5484
- for (let i = 0; i < 80 && at !== target.index; i++) {
5485
- const before = at;
5486
- const next = await press(target.index > at ? "Down" : "Up", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
5487
- if (!next)
5488
- break;
5489
- now = next;
5490
- at = cursorOf(next).index;
5491
- }
5492
- if (at !== target.index)
5493
- return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", `選ぶ画面で ${target.label} の行へ動けません`);
5494
- // 起きた後にClaude Codeが更新された席では、「Update Claude Code to use this model」の行が出る。その行にはEnterもsも無い。
5495
- if (!now.session_only) {
5496
- return refuse("CLAUDE_MODEL_NOT_SELECTABLE", `${target.label} は、この席のClaude Codeでは選べません(選ぶ画面のその行に、選ぶためのキーが出ていません。席のClaude Codeが古い見込み)`);
5497
- }
5498
- targetIndex = target.index;
5499
- }
5500
- if (effort) {
5501
- const wanted = CLAUDE_EFFORT_ORDER.indexOf(effort);
5502
- const row = cursorOf(now)?.label ?? model ?? "このmodel";
5503
- // そのmodelに無い段は飛ばされて行き来になるので、回数で打ち切る。
5504
- for (let i = 0; i < CLAUDE_EFFORT_ORDER.length + 3 && now.effort !== effort; i++) {
5505
- const current = now.effort;
5506
- const from = current === null ? -1 : CLAUDE_EFFORT_ORDER.indexOf(current);
5507
- if (from < 0)
5508
- return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort を選べません`);
5509
- const next = await press(wanted > from ? "Right" : "Left", (p) => p.effort !== current);
5510
- if (!next)
5511
- break;
5512
- now = next;
5513
- }
5514
- if (now.effort !== effort)
5515
- return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort=${effort} を選べません`);
5516
- }
5517
- // 打つ直前に、もう1度読んで確かめる。
5518
- const last = picker();
5519
- const lastRow = cursorOf(last);
5520
- if (!last || !lastRow || !last.session_only
5521
- || (targetIndex !== null && lastRow.index !== targetIndex)
5522
- || (effort && last.effort !== effort)) {
5523
- return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ直前の画面が、選んだ行・effortと合いません");
5524
- }
5525
- beforeChange();
5526
- selectionIssued = true;
5527
- sendMenuChoice(name, "s");
5528
- let confirmed = false;
5529
- const result = await until(() => {
5530
- const text = screen();
5531
- const confirm = claudeModelSwitchConfirm(text);
5532
- if (confirm === "yes_selected" && !confirmed) {
5533
- // 会話が今のmodelでcacheされている時の確かめ。1番(Yes, switch)が選ばれている時だけ進める。
5534
- confirmed = true;
5535
- sendMenuChoice(name, "Enter");
5536
- return null;
5537
- }
5538
- if (confirm || claudeModelPicker(text))
5539
- return null;
5540
- return claudeModelSwitchResult(text);
5541
- }, CLAUDE_MODEL_SWITCH_TIMEOUT_MS);
5542
- if (!result)
5543
- return refuse("CLAUDE_MODEL_SWITCH_UNCONFIRMED", "Claude Codeの切り替えの知らせを確認できません");
5544
- if (result.scope === "saved_as_default") {
5545
- throw new AitermError(`CLAUDE_MODEL_SAVED_AS_DEFAULT vendor=claude session=${name}\n` +
5546
- `Claude Codeが、選んだ値を端末の既定として保存したと返しました(${result.line})。~/.claude/settings.json を確かめてください。`, 2);
5547
- }
5548
- if (result.scope !== "session_only") {
5549
- throw new AitermError(`CLAUDE_MODEL_SWITCH_REFUSED vendor=claude session=${name}\n` +
5550
- `Claude Codeがmodelを切り替えませんでした(${result.line})。modelとreasoning_effortは変えていません。`, 2);
5551
- }
5552
- const ready = await waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS);
5553
- if (!ready.ready)
5554
- throw new AitermError("Claudeのmodel変更完了を確認できません", 2);
5555
- }
5556
5037
  // ===================== ファスト(高速の応答)の切り替え(ADR 0114) =====================
5557
5038
  // 席は必ず通常の速度で起こす。fast: true は、通常で起こしてから、その席で切り替える(Claude Code・Codex)。
5558
5039
  // CursorとGrokはfastが別のmodel IDなので、起動時のIDをfast版にする。
@@ -5650,33 +5131,6 @@ async function planLaunchFast(kind, o) {
5650
5131
  }
5651
5132
  return { ...plan, model: fastId, state: true };
5652
5133
  }
5653
- const USER_DEFAULT_SETTLE_MS = 400;
5654
- const USER_DEFAULT_RESTORE_PASSES = 3;
5655
- /**
5656
- * harnessが利用者の既定へ書いた分を、切り替えの直前の中身(before)を元に戻す。
5657
- * harnessは1回の切り替えで何度か書く事があるので(Grokの起動で見た)、少し置きながら何度か見て、後から書かれた分も戻す。
5658
- */
5659
- async function restoreUserDefaults(restore) {
5660
- for (let pass = 0; pass < USER_DEFAULT_RESTORE_PASSES; pass++) {
5661
- await sleep(USER_DEFAULT_SETTLE_MS);
5662
- try {
5663
- restore();
5664
- }
5665
- catch { /* 戻せなくても、切り替えの結果は返す */ }
5666
- }
5667
- }
5668
- /** 設定fileを触る切り替えを鍵の中で流し、終わったら、harnessが書いた既定を切り替えの直前の値へ戻す。 */
5669
- async function keepingUserDefaults(configPath, restore, action) {
5670
- return withUserConfigLock(configPath, async () => {
5671
- const before = readFileOrNull(configPath);
5672
- try {
5673
- return await action();
5674
- }
5675
- finally {
5676
- await restoreUserDefaults(() => restore(before));
5677
- }
5678
- });
5679
- }
5680
5134
  /**
5681
5135
  * 起動の --model の値を利用者の既定へ書くharness(Grok 1.0.50。Cursorは、既定のmodelを設定に持つ端末)を起こす。
5682
5136
  * 鍵を取り、起動の直前の中身を読み、起こして、既定が書かれるのを待ってから、直前の値へ戻す。
@@ -6092,6 +5546,11 @@ async function applyLaunchFast(name, meta) {
6092
5546
  }
6093
5547
  /** Goal operations share the existing seat admission and original launch ID. */
6094
5548
  export async function agentGoal(input, origin = "automatic", expectedGoal) {
5549
+ return agentGoalInContext(input, origin, expectedGoal);
5550
+ }
5551
+ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false) {
5552
+ if (sendHeld && (!agentSendHeld.has(input.session_id) || agentSendOwner.getStore() !== activeAgentSendOwner.get(input.session_id)))
5553
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6095
5554
  assertSessionName(input.session_id);
6096
5555
  if (input.action !== "inspect")
6097
5556
  assertExecutionContext(input.session_id);
@@ -6258,6 +5717,8 @@ export async function agentGoal(input, origin = "automatic", expectedGoal) {
6258
5717
  return { ui, rows: () => { const text = read('updates.jsonl', true); return text === null ? [] : text.split('\n').filter(line => line.trim()).map(line => JSON.parse(line)); }, state: () => { const text = read('goal/state.json', true); return text === null ? null : JSON.parse(text); } };
6259
5718
  };
6260
5719
  const harness = resolve()?.harness;
5720
+ if (sendHeld && harness !== "codex-cli")
5721
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6261
5722
  if (harness === 'grok-cli')
6262
5723
  return withAgentSendLock(input.session_id, () => manageGrokAgentGoal(input, { resolve,
6263
5724
  read: target => readFreshGrokGoal(target.vendor_session_id, grokPort(target)),
@@ -6292,7 +5753,7 @@ export async function agentGoal(input, origin = "automatic", expectedGoal) {
6292
5753
  return request(method, params);
6293
5754
  });
6294
5755
  }, supported, fields), command => submitCodexGoalCommand(goalUi(target), command), (before, objective) => editCodexGoalObjective(goalUi(target), before, objective), objective => createCodexGoalObjective(goalUi(target), objective)) }, origin);
6295
- return input.action === "inspect" ? run() : withAgentSendLock(input.session_id, run);
5756
+ return input.action === "inspect" || sendHeld ? run() : withAgentSendLock(input.session_id, run);
6296
5757
  }
6297
5758
  /** Whole-app stop uses native goal state, not the host's displayed snapshot. */
6298
5759
  export async function pauseAgentGoalForStop(target) {
@@ -6507,7 +5968,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6507
5968
  throw new AitermError("Claude Code の reasoning_effort は low/medium/high/xhigh/max/ultracode のいずれかです。設定は変えていません。", 2);
6508
5969
  }
6509
5970
  if (model || level)
6510
- await configureClaudeForSessionOnly(name, meta, model, level, beforeChange);
5971
+ await configureClaudeForSessionOnly(name, meta, model, level, beforeChange, { ...agentModelUi(name), ready: () => waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS) });
6511
5972
  if (effort && !level) {
6512
5973
  beforeChange();
6513
5974
  await sendAgentPromptText(name, `/effort ${effort}`);
@@ -6629,7 +6090,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6629
6090
  }
6630
6091
  // `/model` の選択は、利用者のconfig.tomlへ model と model_reasoning_effort を既定として保存する。席だけの替えにするため、直前の値へ戻す。
6631
6092
  if (model || effort) {
6632
- await keepingCodexDefaults(meta.agent_executable ?? resolveAgentBin("codex"), meta.codex_home ?? realCodexHome(), ["model", "model_reasoning_effort"], () => configureCodexModel(name, model, effort, beforeChange));
6093
+ await keepingCodexDefaults(meta.agent_executable ?? resolveAgentBin("codex"), meta.codex_home ?? realCodexHome(), ["model", "model_reasoning_effort"], () => configureCodexModel(name, model, effort, beforeChange, { ...agentModelUi(name), waitForText: text => waitForScreenText(name, text) }));
6633
6094
  }
6634
6095
  rememberModel();
6635
6096
  if (fast !== null) {
@@ -6640,98 +6101,6 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
6640
6101
  await dropFastIfUnsupported();
6641
6102
  return configured();
6642
6103
  }
6643
- /** Codexの `/model` の選ぶ画面で、modelとreasoning effortを替える。 */
6644
- async function configureCodexModel(name, model, effort, beforeChange) {
6645
- try {
6646
- await chooseCodexModel(name, model, effort, beforeChange);
6647
- }
6648
- catch (error) {
6649
- // 選べずに断る時は、開いた選ぶ画面を閉じてから断る(開いたままだと、席は次の文を受け付けない)。
6650
- for (let i = 0; i < 3; i++) {
6651
- const tail = captureScreen(name, AGENT_TUI_READY_LINES).split("\n").map((line) => line.trim()).filter(Boolean).slice(-2).join("\n");
6652
- if (!/esc back/.test(tail))
6653
- break;
6654
- sendMenuChoice(name, "Escape");
6655
- await sleep(400);
6656
- }
6657
- throw error;
6658
- }
6659
- }
6660
- async function chooseCodexModel(name, model, effort, beforeChange) {
6661
- const beforeCounts = lineCounts(captureScreen(name, AGENT_TUI_READY_LINES));
6662
- await sendAgentPromptText(name, "/model");
6663
- let modelScreen = await waitForScreenText(name, "Select Model and Effort");
6664
- if (model && !effort) {
6665
- sendMenuChoice(name, "Enter");
6666
- let currentScreen = await waitForScreenText(name, "Select Reasoning Level");
6667
- let advanced = false;
6668
- if (/More reasoning[^\n]*\(current\)/.test(currentScreen)) {
6669
- const more = codexMoreReasoningChoice(currentScreen);
6670
- if (more) {
6671
- sendMenuChoice(name, more);
6672
- currentScreen = await waitForScreenText(name, "Advanced Reasoning");
6673
- advanced = true;
6674
- }
6675
- }
6676
- effort = codexCurrentEffort(currentScreen);
6677
- if (!effort)
6678
- throw new AitermError("CODEX_CURRENT_EFFORT_UNKNOWN: 現在のeffortを確認できません。設定は変えていません。", 2);
6679
- if (advanced) {
6680
- sendMenuChoice(name, "Escape");
6681
- await waitForScreenText(name, "Select Reasoning Level");
6682
- }
6683
- sendMenuChoice(name, "Escape");
6684
- modelScreen = await waitForScreenText(name, "Select Model and Effort");
6685
- }
6686
- if (model) {
6687
- let choice = codexModelChoice(modelScreen, model);
6688
- if (!choice) {
6689
- const meta = loadAgentMetadata(name);
6690
- const bin = meta.agent_executable ?? resolveAgentBin("codex");
6691
- if (!bin)
6692
- throw new AitermError("Codex の CLI が見つかりません", 2);
6693
- const catalog = await codexModelChoices(bin, true);
6694
- const target = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
6695
- const displayName = target?.display_name;
6696
- if (displayName && catalog.models.filter(item => item.display_name?.toLowerCase() === displayName.toLowerCase()).length === 1) {
6697
- choice = codexModelChoice(modelScreen, model, displayName);
6698
- }
6699
- }
6700
- if (!choice)
6701
- throw new AitermError(`Codexの/modelに ${model} がありません`, 2);
6702
- sendMenuChoice(name, choice);
6703
- }
6704
- else {
6705
- sendMenuChoice(name, "Enter");
6706
- }
6707
- let effortScreen = await waitForScreenText(name, "Select Reasoning Level");
6708
- if (effort) {
6709
- let choice = codexEffortChoice(effortScreen, effort);
6710
- if (!choice && (effort === "max" || effort === "ultra")) {
6711
- const more = codexMoreReasoningChoice(effortScreen);
6712
- if (more) {
6713
- sendMenuChoice(name, more);
6714
- effortScreen = await waitForScreenText(name, "Advanced Reasoning");
6715
- choice = codexEffortChoice(effortScreen, effort);
6716
- }
6717
- }
6718
- if (!choice)
6719
- throw new AitermError(`Codexの/modelに reasoning_effort=${effort} がありません`, 2);
6720
- beforeChange();
6721
- sendMenuChoice(name, choice);
6722
- }
6723
- else {
6724
- beforeChange();
6725
- sendMenuChoice(name, "Enter");
6726
- }
6727
- for (const deadline = performance.now() + 3_000; performance.now() < deadline; await sleep(100)) {
6728
- const screen = captureScreen(name, AGENT_TUI_READY_LINES);
6729
- const counts = lineCounts(screen);
6730
- if (codexModelChangeNotices(screen, model, effort).some(line => (counts.get(line) ?? 0) > (beforeCounts.get(line) ?? 0)))
6731
- return;
6732
- }
6733
- throw new AitermError("CODEX_MODEL_SWITCH_UNCONFIRMED: 指定したmodel/effortの新しい変更通知を確認できません。設定が変わった可能性があります。再送しないでください。", 2);
6734
- }
6735
6104
  export function __testCodexConfigureChoices(screen, model, effort) {
6736
6105
  return {
6737
6106
  model: codexModelChoice(screen, model),
@@ -6857,143 +6226,387 @@ function confirmedAgentResumeRecipe(meta, lifecycle) {
6857
6226
  throw unavailable();
6858
6227
  return recipe;
6859
6228
  }
6229
+ /** A completion is historical: later legitimate configuration does not revoke it. */
6230
+ function hasCompletedResumeRecovery(meta) {
6231
+ const resolution = readAgentResumeResolution(meta);
6232
+ if (!resolution)
6233
+ return false;
6234
+ if (meta.kind !== "codex" || meta.resumed_from !== resolution.previous_launch_id)
6235
+ return false;
6236
+ const origin = previousResumeMetadata(meta);
6237
+ const attempt = readAgentResumeAttempt(origin), life = resumeSourceRecord(origin), recipe = readAgentResumeRecipe(origin);
6238
+ const native = readAgentResumeNative(meta);
6239
+ return !!attempt && attempt.state === "failed" && attempt.next_launch_id === meta.launch_id
6240
+ && agentResumeRecordDigest(attempt) === resolution.attempt_digest && !!life
6241
+ && (life.schema !== "aiterm.agent-lifecycle.v1" || life.state === "hibernated")
6242
+ && life.socket === SOCK && life.recipe_digest === resolution.recipe_digest
6243
+ && life.resume_proof_digest === resolution.resume_proof_digest && !!recipe
6244
+ && recipe.vendor_session_id === resolution.vendor_session_id && agentResumeRecipeDigest(recipe) === resolution.recipe_digest
6245
+ && !!native && agentResumeRecordDigest(native) === resolution.native_digest;
6246
+ }
6247
+ function previousResumeMetadata(meta) {
6248
+ if (!meta.resumed_from || !/^[a-f0-9]{32}$/.test(meta.resumed_from) || meta.resumed_from === meta.launch_id)
6249
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6250
+ const file = agentMetadataPath(meta.aiterm_session, meta.resumed_from), stat = fs.lstatSync(file);
6251
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024)
6252
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6253
+ const source = JSON.parse(fs.readFileSync(file, "utf8"));
6254
+ if (source.kind !== meta.kind || source.aiterm_session !== meta.aiterm_session || source.launch_id !== meta.resumed_from
6255
+ || source.codex_home !== meta.codex_home || source.hook_route !== meta.hook_route
6256
+ || ["agent_role", "parent_session_id", "delegation_depth", "lineage", "delegation_allowed"].some(key => source[key] !== meta[key]))
6257
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6258
+ return source;
6259
+ }
6260
+ function resumeSourceRecord(meta) {
6261
+ return readAgentLifecycle(meta) ?? confirmedAgentResumeRecoveryOrigin(meta);
6262
+ }
6263
+ function assertFailedCodexNativeAbsent(meta) {
6264
+ const unavailable = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "元のnative不在を確認できません。本文は送信していません。", meta.aiterm_session, meta.launch_id);
6265
+ const current = observeExecutionNativeSessions(), native = readAgentResumeNative(meta);
6266
+ if (!native || current.state !== "known" || current.sessions.some(row => row.session_id === meta.aiterm_session))
6267
+ throw unavailable();
6268
+ const processes = readRuntimeProcesses();
6269
+ // Linux's normal resume argv retains the exact vendor UUID, including orphaned CLI processes.
6270
+ if (processes.some(row => row.command.includes(meta.vendor_session_id)))
6271
+ throw unavailable();
6272
+ if (processes.some(row => row.pid === native.pane_pid)) {
6273
+ const identity = processStartIdentities([native.pane_pid], process.platform)[0];
6274
+ if (!identity || identity === native.pane_started_identity)
6275
+ throw unavailable();
6276
+ }
6277
+ }
6278
+ function prepareColdCodexRecovery(meta) {
6279
+ const recipe = failedCodexResumeRecipe(meta), native = readAgentResumeNative(meta);
6280
+ if (!recipe || !native || !meta.resumed_from)
6281
+ throw new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "復帰元を確認できません。本文は送信していません。", meta.aiterm_session, meta.launch_id);
6282
+ assertFailedCodexNativeAbsent(meta);
6283
+ const attempt = readAgentResumeAttempt({ aiterm_session: meta.aiterm_session, launch_id: meta.resumed_from });
6284
+ const proof = captureCodexRecoveryProof(meta);
6285
+ assertFailedCodexNativeAbsent(meta);
6286
+ if (!isDeepStrictEqual(loadAgentMetadata(meta.aiterm_session), meta) || !isDeepStrictEqual(failedCodexResumeRecipe(meta), recipe))
6287
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6288
+ const value = { schema: "aiterm.agent-resume-recovery-origin.v1", launch_id: meta.launch_id,
6289
+ previous_launch_id: meta.resumed_from, socket: SOCK, at: new Date().toISOString(), failed_attempt_digest: agentResumeRecordDigest(attempt),
6290
+ recipe_digest: agentResumeRecipeDigest(readAgentResumeRecipe(meta)), resume_proof_digest: codexResumeProofDigest(proof),
6291
+ previous_native_digest: agentResumeRecordDigest(native) };
6292
+ writeAgentResumeRecoveryOrigin(meta, value);
6293
+ if (!isDeepStrictEqual(confirmedAgentResumeRecoveryOrigin(meta), value))
6294
+ throw new ExecutionError("EXECUTION_STALE_GENERATION");
6295
+ return value;
6296
+ }
6297
+ function failedCodexResumeRecipe(meta) {
6298
+ if (process.platform !== "linux" || meta.kind !== "codex" || !meta.resumed_from || meta.fast !== false
6299
+ || readAgentLifecycle(meta) || readAgentResumeAttempt(meta))
6300
+ return null;
6301
+ const source = previousResumeMetadata(meta);
6302
+ const attempt = readAgentResumeAttempt(source), life = resumeSourceRecord(source);
6303
+ if (attempt?.state !== "failed" || attempt.next_launch_id !== meta.launch_id || !life
6304
+ || (life.schema === "aiterm.agent-lifecycle.v1" && life.state !== "hibernated"))
6305
+ return null;
6306
+ const recipe = confirmedAgentResumeRecipe(source, life);
6307
+ const current = readAgentResumeRecipe(meta);
6308
+ if (!current || recipe.fast || current.launch_id !== meta.launch_id || meta.vendor_session_id !== recipe.vendor_session_id
6309
+ || meta.cwd !== recipe.cwd || meta.agent_executable !== recipe.executable || meta.model !== recipe.model || meta.codex_home !== recipe.configuration_root
6310
+ || !isDeepStrictEqual({ ...recipe, launch_id: meta.launch_id }, current))
6311
+ return null;
6312
+ return recipe;
6313
+ }
6314
+ async function completeFailedCodexResume(meta, readyTimeout) {
6315
+ const name = meta.aiterm_session;
6316
+ const unavailable = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "同じ会話の復帰準備を確認できません。本文は送信していません。", name, meta.launch_id);
6317
+ const recipe = failedCodexResumeRecipe(meta), native = readAgentResumeNative(meta);
6318
+ if (!recipe || !native)
6319
+ throw unavailable();
6320
+ const source = previousResumeMetadata(meta);
6321
+ const attempt = readAgentResumeAttempt(source), life = resumeSourceRecord(source);
6322
+ const verify = () => {
6323
+ verifyAgentResumeNative(meta, native);
6324
+ if (!isDeepStrictEqual(loadAgentMetadata(name), meta) || !isDeepStrictEqual(readAgentResumeAttempt(source), attempt)
6325
+ || !isDeepStrictEqual(failedCodexResumeRecipe(meta), recipe))
6326
+ throw unavailable();
6327
+ const proof = readCodexResumeProof(source);
6328
+ if (codexRootTranscript(meta) !== proof.file)
6329
+ throw unavailable();
6330
+ };
6331
+ const ready = async () => {
6332
+ const result = await waitAgentTuiReady(name, meta, readyTimeout);
6333
+ const live = observeNativeSession(name);
6334
+ return result.ready && live.state === "idle" && live.reason === "composer_ready" && live.harness_alive === true;
6335
+ };
6336
+ return withAgentResumeTarget(meta, async () => {
6337
+ verify();
6338
+ const initial = observeNativeSession(name);
6339
+ if (initial.harness_alive !== true || initial.state !== "idle" || initial.reason !== "composer_ready")
6340
+ throw unavailable();
6341
+ if (!await ready())
6342
+ throw unavailable();
6343
+ const ui = {
6344
+ screen: () => captureScreen(name, AGENT_TUI_READY_LINES),
6345
+ command: async (command) => {
6346
+ await withExecutionNativeAdmission(name, () => {
6347
+ verify();
6348
+ const draft = codexRecoveryComposer(captureScreen(name, AGENT_TUI_READY_LINES));
6349
+ // shortcut: only the accepted native empty composer/placeholder layout; other layouts remain unknown.
6350
+ if (draft !== "" && draft !== "Ask Codex to do anything")
6351
+ throw unavailable();
6352
+ send(name, command, { enter: false, force: true, raw: true, mark: false, rtk: false, preserveAgentOperation: true });
6353
+ });
6354
+ await sleep(AGENT_SUBMIT_DELAY_MS);
6355
+ await withExecutionNativeAdmission(name, () => {
6356
+ verify();
6357
+ // Never submit a slash command concatenated with an existing draft.
6358
+ if (codexRecoveryComposer(captureScreen(name, AGENT_TUI_READY_LINES)) !== command)
6359
+ throw unavailable();
6360
+ sendKey(name, "Enter", { preserveAgentOperation: true });
6361
+ });
6362
+ },
6363
+ text: (text) => { verify(); send(name, text, { enter: false, force: true, raw: true, mark: false, rtk: false, preserveAgentOperation: true }); },
6364
+ key: (...keys) => { verify(); sendMenuChoice(name, ...keys); },
6365
+ ready,
6366
+ };
6367
+ let actual = await inspectCodexResumeSettings(recipe.vendor_session_id, ui);
6368
+ verify();
6369
+ if (!actual || actual.fast !== false)
6370
+ throw unavailable();
6371
+ const settingsDiffer = actual.model?.toLowerCase() !== recipe.model?.toLowerCase() || actual.reasoning_effort !== recipe.reasoning_effort;
6372
+ const complete = async () => {
6373
+ if (settingsDiffer) {
6374
+ if (!recipe.model || !recipe.reasoning_effort)
6375
+ throw unavailable();
6376
+ await keepingCodexDefaults(recipe.executable, recipe.configuration_root, ["model", "model_reasoning_effort"], () => configureCodexModel(name, recipe.model, recipe.reasoning_effort, verify, { ...ui, waitForText: text => waitForScreenText(name, text) }));
6377
+ verify();
6378
+ if (!await ready())
6379
+ throw unavailable();
6380
+ actual = await inspectCodexResumeSettings(recipe.vendor_session_id, ui);
6381
+ verify();
6382
+ }
6383
+ if (!actual || actual.model?.toLowerCase() !== recipe.model?.toLowerCase()
6384
+ || actual.reasoning_effort !== recipe.reasoning_effort || actual.fast !== recipe.fast)
6385
+ throw unavailable();
6386
+ // Do not recapture startup processes: this same native may already own children.
6387
+ writeAgentResumeTemplate(meta, { schema: "aiterm.agent-resume-template.v1", launch_id: meta.launch_id,
6388
+ state: "confirmed", kind: "codex", executable: recipe.executable, cwd: recipe.cwd,
6389
+ configuration_root: recipe.configuration_root, model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: recipe.environment });
6390
+ verify();
6391
+ writeAgentResumeResolution(meta, { schema: "aiterm.agent-resume-resolution.v1", launch_id: meta.launch_id,
6392
+ previous_launch_id: source.launch_id, vendor_session_id: recipe.vendor_session_id,
6393
+ attempt_digest: agentResumeRecordDigest(attempt), recipe_digest: life.recipe_digest,
6394
+ resume_proof_digest: life.resume_proof_digest, native_digest: agentResumeRecordDigest(native), at: new Date().toISOString() });
6395
+ if (!hasCompletedResumeRecovery(meta))
6396
+ throw unavailable();
6397
+ return meta;
6398
+ };
6399
+ if (!settingsDiffer)
6400
+ return complete();
6401
+ return configureWithPausedGoal({
6402
+ goal: async (action, expected) => {
6403
+ verify();
6404
+ const result = await agentGoalInContext({ session_id: name, launch_id: meta.launch_id, action,
6405
+ expected_thread_id: recipe.vendor_session_id }, "user", expected, true);
6406
+ verify();
6407
+ if (action === "inspect" && (result.availability !== "available" || result.readback !== "confirmed"
6408
+ || result.schema !== "aiterm.agent-goal-result.v1" || result.goal === undefined))
6409
+ throw unavailable();
6410
+ return result;
6411
+ },
6412
+ waitForTurnEnd: async () => {
6413
+ verify();
6414
+ // A paused goal may leave an idle-looking pane before its native turn ends.
6415
+ if (!codexTurnSettled(meta))
6416
+ throw unavailable();
6417
+ },
6418
+ }, complete);
6419
+ });
6420
+ }
6860
6421
  async function resumeAgentInLock(name, readyTimeout = AGENT_TUI_READY_TIMEOUT_MS) {
6861
- const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
6862
- const uncertain = () => new AitermError("AGENT_RESUME_UNCONFIRMED: 前の復帰処理を確認できません。本文は送信していません。再送せず席の状態を確認してください。", 2);
6422
+ const previous = loadAgentMetadata(name);
6423
+ let lifecycle = readAgentLifecycle(previous);
6424
+ const uncertain = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "前の復帰処理を確認できません。本文は送信していません。再送せず席の状態を確認してください。", name, previous.launch_id);
6863
6425
  const ownAttempt = readAgentResumeAttempt(previous);
6864
6426
  if (!lifecycle) {
6865
6427
  if (previous.resumed_from) {
6866
6428
  const attempt = readAgentResumeAttempt({ aiterm_session: name, launch_id: previous.resumed_from });
6867
- if (attempt?.state !== "ready" || attempt.next_launch_id !== previous.launch_id)
6429
+ if (attempt?.next_launch_id !== previous.launch_id)
6868
6430
  throw uncertain();
6431
+ if (attempt.state !== "ready" && !hasCompletedResumeRecovery(previous)) {
6432
+ if (ownAttempt || attempt.state !== "failed")
6433
+ throw uncertain();
6434
+ try {
6435
+ const native = observeExecutionNativeSessions();
6436
+ if (native.state !== "known")
6437
+ throw uncertain();
6438
+ if (native.sessions.some(row => row.session_id === name))
6439
+ return await completeFailedCodexResume(previous, readyTimeout);
6440
+ lifecycle = prepareColdCodexRecovery(previous);
6441
+ }
6442
+ catch {
6443
+ throw uncertain();
6444
+ }
6445
+ }
6869
6446
  }
6870
6447
  if (ownAttempt)
6871
6448
  throw uncertain();
6872
- return previous;
6449
+ if (!lifecycle)
6450
+ return previous;
6873
6451
  }
6874
- if (lifecycle.state !== "hibernated" || ownAttempt)
6875
- throw uncertain();
6876
- assertExecutionResumeSupported();
6877
- const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
6878
- if (sessionExists(name))
6452
+ if ((lifecycle.schema === "aiterm.agent-lifecycle.v1" && lifecycle.state !== "hibernated") || ownAttempt)
6879
6453
  throw uncertain();
6880
- const controlEnv = { ...process.env };
6881
- for (const [key, value] of Object.entries(recipe.environment)) {
6882
- if (value === null)
6883
- delete controlEnv[key];
6884
- else
6885
- controlEnv[key] = value;
6886
- }
6887
- if (recipe.kind === "codex")
6888
- controlEnv.CODEX_HOME = recipe.configuration_root;
6889
- if (recipe.fast) {
6890
- if (recipe.kind === "claude") {
6891
- if (await assertClaudeFastSupported(recipe.executable, recipe.cwd, recipe.model, "本文は送信していません。", controlEnv))
6892
- throw uncertain();
6893
- }
6894
- else
6895
- await assertCodexFastSupported(recipe.executable, recipe.configuration_root, recipe.model, "本文は送信していません。", controlEnv);
6896
- }
6897
- const lineage = { agentRole: "subagent", parentSessionId: previous.parent_session_id,
6898
- delegationDepth: previous.delegation_depth, lineage: previous.lineage, delegationAllowed: true };
6454
+ const cold = lifecycle.schema === "aiterm.agent-resume-recovery-origin.v1";
6455
+ let phase = "recipe_validation";
6899
6456
  let next = null, attempt = null;
6900
- let native = null, published = false;
6901
- return withNativeSessionCreation(name, receipt => {
6902
- const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
6903
- if (!next || !server || !pane)
6904
- throw uncertain();
6905
- native = { schema: "aiterm.agent-resume-native.v1", launch_id: next.launch_id, ...receipt,
6906
- server_started_identity: server, pane_started_identity: pane };
6907
- writeAgentResumeNative(next, native);
6908
- }, () => {
6909
- if (!next || !native)
6457
+ let readiness = null, attemptedAt = null;
6458
+ let attemptRecord = "not_created", recorded = false;
6459
+ const recordFailure = (error) => {
6460
+ if (recorded)
6461
+ return;
6462
+ recorded = true;
6463
+ recordAgentResumeFailure({ session_id: name, launch_id: next?.launch_id ?? previous.launch_id,
6464
+ previous_launch_id: previous.launch_id, next_launch_id: next?.launch_id ?? null, phase, readiness,
6465
+ attempted_at: attemptedAt, attempt_record: attemptRecord }, error);
6466
+ };
6467
+ try {
6468
+ assertExecutionResumeSupported();
6469
+ const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
6470
+ if (sessionExists(name))
6910
6471
  throw uncertain();
6911
- verifyAgentResumeNative(next, native, published ? next.launch_id : previous.launch_id);
6912
- }, async () => {
6913
- try {
6914
- await withExecutionNativeAdmission(name, () => {
6915
- if (!isDeepStrictEqual(loadAgentMetadata(name), previous) || sessionExists(name))
6916
- throw uncertain();
6917
- if (readAgentLifecycle(previous)?.state !== "hibernated"
6918
- || agentResumeRecipeDigest(readAgentResumeRecipe(previous)) !== lifecycle.recipe_digest)
6472
+ const controlEnv = { ...process.env };
6473
+ for (const [key, value] of Object.entries(recipe.environment)) {
6474
+ if (value === null)
6475
+ delete controlEnv[key];
6476
+ else
6477
+ controlEnv[key] = value;
6478
+ }
6479
+ if (recipe.kind === "codex")
6480
+ controlEnv.CODEX_HOME = recipe.configuration_root;
6481
+ if (recipe.fast) {
6482
+ if (recipe.kind === "claude") {
6483
+ if (await assertClaudeFastSupported(recipe.executable, recipe.cwd, recipe.model, "本文は送信していません。", controlEnv))
6919
6484
  throw uncertain();
6920
- if (previous.kind === "codex" && codexResumeProofDigest(readCodexResumeProof(previous)) !== lifecycle.resume_proof_digest)
6485
+ }
6486
+ else
6487
+ await assertCodexFastSupported(recipe.executable, recipe.configuration_root, recipe.model, "本文は送信していません。", controlEnv);
6488
+ }
6489
+ const lineage = { agentRole: "subagent", parentSessionId: previous.parent_session_id,
6490
+ delegationDepth: previous.delegation_depth, lineage: previous.lineage, delegationAllowed: true };
6491
+ let native = null, published = false;
6492
+ return await withNativeSessionCreation(name, receipt => {
6493
+ phase = "native_identity";
6494
+ const [server, pane] = processStartIdentities([receipt.server_pid, receipt.pane_pid], process.platform);
6495
+ if (!next || !server || !pane)
6496
+ throw uncertain();
6497
+ native = { schema: "aiterm.agent-resume-native.v1", launch_id: next.launch_id, ...receipt,
6498
+ server_started_identity: server, pane_started_identity: pane };
6499
+ writeAgentResumeNative(next, native);
6500
+ }, () => {
6501
+ if (!next || !native)
6502
+ throw uncertain();
6503
+ verifyAgentResumeNative(next, native, published ? next.launch_id : previous.launch_id);
6504
+ }, async () => {
6505
+ try {
6506
+ phase = "generation_preparation";
6507
+ await withExecutionNativeAdmission(name, () => {
6508
+ if (!isDeepStrictEqual(loadAgentMetadata(name), previous) || sessionExists(name))
6509
+ throw uncertain();
6510
+ if (!isDeepStrictEqual(resumeSourceRecord(previous), lifecycle)
6511
+ || agentResumeRecipeDigest(readAgentResumeRecipe(previous)) !== lifecycle.recipe_digest)
6512
+ throw uncertain();
6513
+ if (cold)
6514
+ assertFailedCodexNativeAbsent(previous);
6515
+ if (previous.kind === "codex" && codexResumeProofDigest(readCodexResumeProof(previous)) !== lifecycle.resume_proof_digest)
6516
+ throw uncertain();
6517
+ publishAgentGeneration(previous);
6518
+ next = previous.kind === "claude"
6519
+ ? createClaudeAgentMetadata(name, recipe.cwd, "none", null, null, lineage, recipe.model, recipe.reasoning_effort)
6520
+ : createCodexAgentMetadata(name, recipe.cwd, "none", { model: recipe.model, effort: recipe.reasoning_effort }, previous.write_scope, lineage);
6521
+ next.vendor_session_id = previous.vendor_session_id;
6522
+ next.resumed_from = previous.launch_id;
6523
+ next.launch_operation_id = previous.launch_operation_id;
6524
+ next.launch_request_digest = previous.launch_request_digest;
6525
+ next.model = recipe.model;
6526
+ next.fast = false;
6527
+ next.agent_executable = recipe.executable;
6528
+ if (isWin)
6529
+ next.windows_launch_exit_tracked = true;
6530
+ if (next.kind === "claude")
6531
+ next.claude_home = recipe.configuration_root;
6532
+ else
6533
+ next.codex_home = recipe.configuration_root;
6534
+ if (previous.write_scope !== undefined)
6535
+ next.write_scope = previous.write_scope;
6536
+ writeAgentMetadata(next);
6537
+ initializeAgentActivity(next);
6538
+ writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
6539
+ attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
6540
+ state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
6541
+ phase = "attempt_save";
6542
+ attemptRecord = "unknown";
6543
+ writeAgentResumeAttempt(previous, attempt);
6544
+ const shell = isWin ? "pwsh" : "bash";
6545
+ phase = "native_create";
6546
+ attemptedAt = new Date().toISOString();
6547
+ openSessionInternal(name, shell, [], true);
6548
+ phase = "environment_setup";
6549
+ const environment = [...Object.entries(recipe.environment),
6550
+ ...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
6551
+ for (const [key, value] of environment) {
6552
+ const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
6553
+ if (stored.code !== 0)
6554
+ throw uncertain();
6555
+ }
6556
+ if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6557
+ throw uncertain();
6558
+ phase = "vendor_start";
6559
+ const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6560
+ : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6561
+ const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6562
+ : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6563
+ + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6564
+ agentLaunchLines.set(name, atomicShellMultiline(full, shell));
6565
+ send(name, full, { enter: true, mark: false, force: true, rtk: false, raw: true, launchShell: shell, preserveAgentOperation: true });
6566
+ phase = "generation_publish";
6567
+ publishAgentGeneration(previous, next);
6568
+ published = true;
6569
+ });
6570
+ const resumed = next;
6571
+ phase = "readiness";
6572
+ const ready = await prepareAgentInput(name, resumed, { ready_timeout: readyTimeout }, !recipe.fast);
6573
+ readiness = safeResumeReadiness(ready);
6574
+ if (ready.status !== "ready")
6921
6575
  throw uncertain();
6922
- publishAgentGeneration(previous);
6923
- next = previous.kind === "claude"
6924
- ? createClaudeAgentMetadata(name, recipe.cwd, "none", null, null, lineage, recipe.model, recipe.reasoning_effort)
6925
- : createCodexAgentMetadata(name, recipe.cwd, "none", { model: recipe.model, effort: recipe.reasoning_effort }, previous.write_scope, lineage);
6926
- next.vendor_session_id = previous.vendor_session_id;
6927
- next.resumed_from = previous.launch_id;
6928
- next.launch_operation_id = previous.launch_operation_id;
6929
- next.launch_request_digest = previous.launch_request_digest;
6930
- next.model = recipe.model;
6931
- next.fast = false;
6932
- next.agent_executable = recipe.executable;
6933
- if (isWin)
6934
- next.windows_launch_exit_tracked = true;
6935
- if (next.kind === "claude")
6936
- next.claude_home = recipe.configuration_root;
6937
- else
6938
- next.codex_home = recipe.configuration_root;
6939
- if (previous.write_scope !== undefined)
6940
- next.write_scope = previous.write_scope;
6941
- writeAgentMetadata(next);
6942
- initializeAgentActivity(next);
6943
- writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
6944
- attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
6945
- state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
6946
- writeAgentResumeAttempt(previous, attempt);
6947
- const shell = isWin ? "pwsh" : "bash";
6948
- openSessionInternal(name, shell, [], true);
6949
- const environment = [...Object.entries(recipe.environment),
6950
- ...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
6951
- for (const [key, value] of environment) {
6952
- const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
6953
- if (stored.code !== 0)
6576
+ // Launch argv pins standard speed; restore fast only after the native composer is ready.
6577
+ if (recipe.fast) {
6578
+ phase = "configuration_restore";
6579
+ const failed = await applyLaunchFast(name, resumed);
6580
+ if (failed || resumed.fast !== true)
6954
6581
  throw uncertain();
6955
6582
  }
6956
- if (registerSessionEnvironment(true, name, [...(registeredSessionEnvironment(name) ?? []), ...Object.keys(recipe.environment)]).code !== 0)
6957
- throw uncertain();
6958
- const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
6959
- : codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
6960
- const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
6961
- : `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
6962
- + `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
6963
- agentLaunchLines.set(name, atomicShellMultiline(full, shell));
6964
- send(name, full, { enter: true, mark: false, force: true, rtk: false, raw: true, launchShell: shell, preserveAgentOperation: true });
6965
- publishAgentGeneration(previous, next);
6966
- published = true;
6967
- });
6968
- const resumed = next;
6969
- const ready = await prepareAgentInput(name, resumed, { ready_timeout: readyTimeout });
6970
- if (ready.status !== "ready")
6971
- throw uncertain();
6972
- // Launch argv pins standard speed; restore fast only after the native composer is ready.
6973
- if (recipe.fast) {
6974
- const failed = await applyLaunchFast(name, resumed);
6975
- if (failed || resumed.fast !== true)
6583
+ if (loadAgentMetadata(name).launch_id !== resumed.launch_id)
6976
6584
  throw uncertain();
6585
+ phase = "ready_save";
6586
+ writeAgentResumeTemplate(resumed, { schema: "aiterm.agent-resume-template.v1", launch_id: resumed.launch_id, state: "confirmed",
6587
+ kind: recipe.kind, executable: recipe.executable, cwd: recipe.cwd, configuration_root: recipe.configuration_root,
6588
+ model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: recipe.environment });
6589
+ writeAgentResumeRecipe(resumed, { ...recipe, launch_id: resumed.launch_id });
6590
+ writeAgentResumeAttempt(previous, { ...attempt, state: "ready", at: new Date().toISOString() });
6591
+ return resumed;
6977
6592
  }
6978
- if (loadAgentMetadata(name).launch_id !== resumed.launch_id)
6979
- throw uncertain();
6980
- writeAgentResumeTemplate(resumed, { schema: "aiterm.agent-resume-template.v1", launch_id: resumed.launch_id, state: "confirmed",
6981
- kind: recipe.kind, executable: recipe.executable, cwd: recipe.cwd, configuration_root: recipe.configuration_root,
6982
- model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: recipe.environment });
6983
- writeAgentResumeRecipe(resumed, { ...recipe, launch_id: resumed.launch_id });
6984
- writeAgentResumeAttempt(previous, { ...attempt, state: "ready", at: new Date().toISOString() });
6985
- return resumed;
6986
- }
6987
- catch (error) {
6988
- const issued = attempt;
6989
- if (issued)
6990
- try {
6991
- writeAgentResumeAttempt(previous, { ...issued, state: "failed", at: new Date().toISOString() });
6992
- }
6993
- catch { /* resuming also blocks replay */ }
6994
- throw new AitermError(`AGENT_RESUME_FAILED: 同じ会話への復帰を確認できません。本文は送信していません。再送せず席の状態を確認してください。${error instanceof ExecutionError ? ` ${error.code}` : ""}`, 2);
6995
- }
6996
- });
6593
+ catch (error) {
6594
+ const issued = attempt;
6595
+ if (issued)
6596
+ try {
6597
+ writeAgentResumeAttempt(previous, { ...issued, state: "failed", at: new Date().toISOString() });
6598
+ attemptRecord = "failed";
6599
+ }
6600
+ catch { /* resuming also blocks replay */ }
6601
+ recordFailure(error);
6602
+ throw new AgentResumeError("AGENT_RESUME_FAILED", `同じ会話への復帰を確認できません。本文は送信していません。再送せず席の状態を確認してください。${error instanceof ExecutionError ? ` ${error.code}` : ""}`, name, next?.launch_id ?? previous.launch_id);
6603
+ }
6604
+ });
6605
+ }
6606
+ catch (error) {
6607
+ recordFailure(error);
6608
+ throw error;
6609
+ }
6997
6610
  }
6998
6611
  export async function dispatchAgentTurn(name, text, o = {}) {
6999
6612
  assertExecutionContext(name);
@@ -7981,9 +7594,9 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
7981
7594
  if (saved && (readAgentLifecycle(saved) || agentDormantState(saved))) {
7982
7595
  return withAgentSendLock(name, async () => {
7983
7596
  const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
7984
- if (!isDeepStrictEqual(previous, saved) || lifecycle?.state !== "hibernated" || readAgentResumeAttempt(previous))
7597
+ if (!isDeepStrictEqual(previous, saved) || (lifecycle?.state !== "hibernated" && !failedCodexResumeRecipe(previous)) || readAgentResumeAttempt(previous))
7985
7598
  throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
7986
- const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
7599
+ const recipe = lifecycle ? confirmedAgentResumeRecipe(previous, lifecycle) : failedCodexResumeRecipe(previous);
7987
7600
  if (kind !== previous.kind || sourceSessionId !== null
7988
7601
  || (opts.model != null && opts.model.trim() !== recipe.model)
7989
7602
  || (opts.reasoning_effort != null && opts.reasoning_effort.trim() !== recipe.reasoning_effort)
@@ -8133,3 +7746,10 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
8133
7746
  reason: meta.initial_prompt_delivery?.reason ?? "startup_failed" });
8134
7747
  }
8135
7748
  }
7749
+ function agentModelUi(name) {
7750
+ return {
7751
+ screen: () => captureScreen(name, AGENT_TUI_READY_LINES),
7752
+ command: text => sendAgentPromptText(name, text),
7753
+ key: (...keys) => sendMenuChoice(name, ...keys),
7754
+ };
7755
+ }