aiterm-mcp 0.63.2 → 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/CHANGELOG.md +20 -1
- package/README.ja.md +10 -1
- package/README.md +5 -1
- package/dist/agent-lifecycle.js +54 -3
- package/dist/agent-metadata-reader.js +273 -0
- package/dist/agent-model-ui.js +7 -0
- package/dist/agent-resume-diagnostic.js +72 -0
- package/dist/agent-shared.js +1 -0
- package/dist/core.js +426 -812
- package/dist/harnesses/claude-configure.js +179 -0
- package/dist/harnesses/codex-configure.js +97 -0
- package/dist/harnesses/codex.js +48 -13
- package/dist/harnesses/idle-settings.js +104 -50
- package/dist/index.js +2 -1
- package/dist/parent-delivery-record.js +65 -0
- package/dist/parent-delivery.js +4 -58
- package/dist/process-runtime.js +8 -1
- package/dist/pty-output.js +110 -0
- package/dist/remote-contract.js +21 -0
- package/dist/remote.js +1 -21
- package/dist/resume-checkpoint-files.js +224 -0
- package/dist/resume-checkpoint.js +181 -0
- package/dist/resume-state-cli.js +89 -0
- package/dist/update-cli.js +1 -1
- package/dist/user-config.js +22 -0
- package/docs/00_overview.md +1 -0
- package/package.json +3 -2
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";
|
|
@@ -45,17 +52,17 @@ import { readLinuxProcessRegistrationIdentity, readRuntimeProcesses, readProcess
|
|
|
45
52
|
import { liveNodeExecutable } from "./live-node.js";
|
|
46
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,
|
|
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,
|
|
58
|
-
import { claudeAuthPlan, claudeAuthStatus, claudeAuthPane, OPERATION_ID_RE, CLAUDE_RESULT_MAX_BYTES, CLAUDE_EFFORTS,
|
|
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);
|
|
@@ -4854,13 +4517,6 @@ async function waitForScreenText(name, text, timeoutMs = 3_000) {
|
|
|
4854
4517
|
} while (performance.now() < deadline);
|
|
4855
4518
|
throw new AitermError(`${agentLabel(loadAgentMetadata(name).kind)} の ${text} 画面を確認できません`, 2);
|
|
4856
4519
|
}
|
|
4857
|
-
function lineCounts(screen) {
|
|
4858
|
-
const counts = new Map();
|
|
4859
|
-
for (const line of screen.split("\n").map((value) => value.trim()).filter(Boolean)) {
|
|
4860
|
-
counts.set(line, (counts.get(line) ?? 0) + 1);
|
|
4861
|
-
}
|
|
4862
|
-
return counts;
|
|
4863
|
-
}
|
|
4864
4520
|
async function waitForGrokConfigurationResult(name, before, model, effort, timeoutMs = 3_000) {
|
|
4865
4521
|
const beforeCounts = lineCounts(before);
|
|
4866
4522
|
const footerAlreadyMatched = grokFooterHasConfiguration(before, model, effort);
|
|
@@ -5378,187 +5034,6 @@ export async function __testInspectAgentIdleSettings(name) {
|
|
|
5378
5034
|
return !!template && typeof meta.fast === "boolean" && inspectAgentIdleSettings(name, meta, { ...template, fast: meta.fast });
|
|
5379
5035
|
});
|
|
5380
5036
|
}
|
|
5381
|
-
const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
|
|
5382
|
-
const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
|
|
5383
|
-
const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
|
|
5384
|
-
const CLAUDE_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
|
|
5385
|
-
/**
|
|
5386
|
-
* Claude Codeの席のmodel/effortを、この会話だけで替える(ADR 0111)。
|
|
5387
|
-
* `/model <名前>` と `/effort <値>` は、選んだ値を端末の ~/.claude/settings.json へ新しい会話の既定として保存する
|
|
5388
|
-
* (2.1.296で確かめた)。引数なしの `/model` の選ぶ画面で s を押すと保存されないので、画面を1歩ずつ読んでそちらを打つ。
|
|
5389
|
-
* 保存しない選び方が画面に無い時、行やeffortを選べない時は、Escで閉じて何も変えずに断る。
|
|
5390
|
-
*/
|
|
5391
|
-
async function configureClaudeForSessionOnly(name, meta, model, effort, beforeChange) {
|
|
5392
|
-
let selectionIssued = false;
|
|
5393
|
-
const screen = () => captureScreen(name, AGENT_TUI_READY_LINES);
|
|
5394
|
-
const until = async (read, timeoutMs) => {
|
|
5395
|
-
const deadline = performance.now() + timeoutMs;
|
|
5396
|
-
do {
|
|
5397
|
-
const got = read();
|
|
5398
|
-
if (got)
|
|
5399
|
-
return got;
|
|
5400
|
-
await sleep(100);
|
|
5401
|
-
} while (performance.now() < deadline);
|
|
5402
|
-
return null;
|
|
5403
|
-
};
|
|
5404
|
-
// Escは、選ぶ画面か確かめの画面が出ている間だけ打つ(入力欄へ戻った後のEscは、ほかの操作を取り消してしまう)。
|
|
5405
|
-
const refuse = async (code, reason) => {
|
|
5406
|
-
for (let i = 0; i < 3; i++) {
|
|
5407
|
-
const now = screen();
|
|
5408
|
-
if (!claudeModelPicker(now) && !claudeModelSwitchConfirm(now))
|
|
5409
|
-
break;
|
|
5410
|
-
sendMenuChoice(name, "Escape");
|
|
5411
|
-
await sleep(300);
|
|
5412
|
-
}
|
|
5413
|
-
throw new AitermError(`${code} vendor=claude session=${name}\n${reason}。` +
|
|
5414
|
-
(selectionIssued ? "設定が変わった可能性があります。再送しないでください。" : "modelとreasoning_effortは変えていません。"), 2);
|
|
5415
|
-
};
|
|
5416
|
-
const picker = () => claudeModelPicker(screen());
|
|
5417
|
-
const cursorOf = (p) => p?.rows.find((row) => row.cursor) ?? null;
|
|
5418
|
-
// 1回押して、画面の今の行かeffortが変わるまで待つ。変わらなければnull(端で止まった・キーが落ちた)。
|
|
5419
|
-
// キーが落ちる事があるので、変わらなければ1度だけ押し直す。
|
|
5420
|
-
const press = async (key, changed) => {
|
|
5421
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
5422
|
-
sendMenuChoice(name, key);
|
|
5423
|
-
const next = await until(() => { const p = picker(); return p && changed(p) ? p : null; }, CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS);
|
|
5424
|
-
if (next)
|
|
5425
|
-
return next;
|
|
5426
|
-
}
|
|
5427
|
-
return null;
|
|
5428
|
-
};
|
|
5429
|
-
await sendAgentPromptText(name, "/model");
|
|
5430
|
-
let now = await until(picker, CLAUDE_MODEL_PICKER_TIMEOUT_MS);
|
|
5431
|
-
if (!now) {
|
|
5432
|
-
// 読めない形の画面が開いたままだと、席が次の文を受け取れない。入力待ちでも動作中でもない時だけ、Escを1度打って閉じる。
|
|
5433
|
-
let state = claudePaneObservation(screen());
|
|
5434
|
-
if (state.state === "unknown") {
|
|
5435
|
-
sendMenuChoice(name, "Escape");
|
|
5436
|
-
await sleep(500);
|
|
5437
|
-
state = claudePaneObservation(screen());
|
|
5438
|
-
}
|
|
5439
|
-
throw new AitermError(`CLAUDE_MODEL_PICKER_NOT_SHOWN vendor=claude session=${name} state=${state.state}/${state.reason}\n` +
|
|
5440
|
-
"Claude Codeの /model の選ぶ画面を読めません(Claude Codeの版で画面の形が変わった見込み)。modelとreasoning_effortは変えていません。", 2);
|
|
5441
|
-
}
|
|
5442
|
-
if (!now.session_only) {
|
|
5443
|
-
return refuse("CLAUDE_MODEL_SESSION_ONLY_UNAVAILABLE", "このClaude Codeの /model の選ぶ画面に、この会話だけで使う選び方(s to use this session only)がありません。" +
|
|
5444
|
-
"端末の既定を書き換える選び方は使いません");
|
|
5445
|
-
}
|
|
5446
|
-
let targetIndex = null;
|
|
5447
|
-
if (model) {
|
|
5448
|
-
// 見えていない行は、下へ送りながら集める(一周するか、端で止まるまで)。
|
|
5449
|
-
const known = new Map(now.rows.map((row) => [row.index, row]));
|
|
5450
|
-
const start = cursorOf(now);
|
|
5451
|
-
if (!start)
|
|
5452
|
-
return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ画面の今の行を読めません");
|
|
5453
|
-
let at = start.index;
|
|
5454
|
-
const seen = new Set([at]);
|
|
5455
|
-
for (let i = 0; i < 80; i++) {
|
|
5456
|
-
const before = at;
|
|
5457
|
-
const next = await press("Down", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
|
|
5458
|
-
if (!next)
|
|
5459
|
-
break;
|
|
5460
|
-
now = next;
|
|
5461
|
-
for (const row of next.rows)
|
|
5462
|
-
known.set(row.index, row);
|
|
5463
|
-
at = cursorOf(next).index;
|
|
5464
|
-
if (seen.has(at))
|
|
5465
|
-
break;
|
|
5466
|
-
seen.add(at);
|
|
5467
|
-
}
|
|
5468
|
-
let target = claudeModelPickerRow([...known.values()], model);
|
|
5469
|
-
if (!target || /^[a-z]+$/iu.test(model)) {
|
|
5470
|
-
const bin = meta.agent_executable ?? resolveAgentBin("claude");
|
|
5471
|
-
if (!bin)
|
|
5472
|
-
return refuse("CLAUDE_MODEL_NOT_IN_PICKER", "Claude CodeのCLIが見つかりません");
|
|
5473
|
-
let catalog;
|
|
5474
|
-
try {
|
|
5475
|
-
catalog = await claudeModelChoices(bin, meta.cwd ?? process.cwd());
|
|
5476
|
-
}
|
|
5477
|
-
catch (error) {
|
|
5478
|
-
return refuse("CLAUDE_MODEL_CATALOG_UNAVAILABLE", error instanceof Error ? error.message : String(error));
|
|
5479
|
-
}
|
|
5480
|
-
const native = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
|
|
5481
|
-
// The native alias can resolve to an older model; picker order is not alias authority.
|
|
5482
|
-
const label = native?.display_name ?? native?.id ?? model;
|
|
5483
|
-
const matching = [...known.values()].filter(row => row.label.toLowerCase() === label.toLowerCase());
|
|
5484
|
-
target = matching.length === 1 ? matching[0] : null;
|
|
5485
|
-
}
|
|
5486
|
-
if (!target) {
|
|
5487
|
-
const names = [...known.values()].sort((a, b) => a.index - b.index).map((row) => row.label).join(", ");
|
|
5488
|
-
return refuse("CLAUDE_MODEL_NOT_IN_PICKER", `Claude Codeの /model の選ぶ画面に ${model} がありません(選べる機種: ${names})`);
|
|
5489
|
-
}
|
|
5490
|
-
for (let i = 0; i < 80 && at !== target.index; i++) {
|
|
5491
|
-
const before = at;
|
|
5492
|
-
const next = await press(target.index > at ? "Down" : "Up", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
|
|
5493
|
-
if (!next)
|
|
5494
|
-
break;
|
|
5495
|
-
now = next;
|
|
5496
|
-
at = cursorOf(next).index;
|
|
5497
|
-
}
|
|
5498
|
-
if (at !== target.index)
|
|
5499
|
-
return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", `選ぶ画面で ${target.label} の行へ動けません`);
|
|
5500
|
-
// 起きた後にClaude Codeが更新された席では、「Update Claude Code to use this model」の行が出る。その行にはEnterもsも無い。
|
|
5501
|
-
if (!now.session_only) {
|
|
5502
|
-
return refuse("CLAUDE_MODEL_NOT_SELECTABLE", `${target.label} は、この席のClaude Codeでは選べません(選ぶ画面のその行に、選ぶためのキーが出ていません。席のClaude Codeが古い見込み)`);
|
|
5503
|
-
}
|
|
5504
|
-
targetIndex = target.index;
|
|
5505
|
-
}
|
|
5506
|
-
if (effort) {
|
|
5507
|
-
const wanted = CLAUDE_EFFORT_ORDER.indexOf(effort);
|
|
5508
|
-
const row = cursorOf(now)?.label ?? model ?? "このmodel";
|
|
5509
|
-
// そのmodelに無い段は飛ばされて行き来になるので、回数で打ち切る。
|
|
5510
|
-
for (let i = 0; i < CLAUDE_EFFORT_ORDER.length + 3 && now.effort !== effort; i++) {
|
|
5511
|
-
const current = now.effort;
|
|
5512
|
-
const from = current === null ? -1 : CLAUDE_EFFORT_ORDER.indexOf(current);
|
|
5513
|
-
if (from < 0)
|
|
5514
|
-
return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort を選べません`);
|
|
5515
|
-
const next = await press(wanted > from ? "Right" : "Left", (p) => p.effort !== current);
|
|
5516
|
-
if (!next)
|
|
5517
|
-
break;
|
|
5518
|
-
now = next;
|
|
5519
|
-
}
|
|
5520
|
-
if (now.effort !== effort)
|
|
5521
|
-
return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort=${effort} を選べません`);
|
|
5522
|
-
}
|
|
5523
|
-
// 打つ直前に、もう1度読んで確かめる。
|
|
5524
|
-
const last = picker();
|
|
5525
|
-
const lastRow = cursorOf(last);
|
|
5526
|
-
if (!last || !lastRow || !last.session_only
|
|
5527
|
-
|| (targetIndex !== null && lastRow.index !== targetIndex)
|
|
5528
|
-
|| (effort && last.effort !== effort)) {
|
|
5529
|
-
return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ直前の画面が、選んだ行・effortと合いません");
|
|
5530
|
-
}
|
|
5531
|
-
beforeChange();
|
|
5532
|
-
selectionIssued = true;
|
|
5533
|
-
sendMenuChoice(name, "s");
|
|
5534
|
-
let confirmed = false;
|
|
5535
|
-
const result = await until(() => {
|
|
5536
|
-
const text = screen();
|
|
5537
|
-
const confirm = claudeModelSwitchConfirm(text);
|
|
5538
|
-
if (confirm === "yes_selected" && !confirmed) {
|
|
5539
|
-
// 会話が今のmodelでcacheされている時の確かめ。1番(Yes, switch)が選ばれている時だけ進める。
|
|
5540
|
-
confirmed = true;
|
|
5541
|
-
sendMenuChoice(name, "Enter");
|
|
5542
|
-
return null;
|
|
5543
|
-
}
|
|
5544
|
-
if (confirm || claudeModelPicker(text))
|
|
5545
|
-
return null;
|
|
5546
|
-
return claudeModelSwitchResult(text);
|
|
5547
|
-
}, CLAUDE_MODEL_SWITCH_TIMEOUT_MS);
|
|
5548
|
-
if (!result)
|
|
5549
|
-
return refuse("CLAUDE_MODEL_SWITCH_UNCONFIRMED", "Claude Codeの切り替えの知らせを確認できません");
|
|
5550
|
-
if (result.scope === "saved_as_default") {
|
|
5551
|
-
throw new AitermError(`CLAUDE_MODEL_SAVED_AS_DEFAULT vendor=claude session=${name}\n` +
|
|
5552
|
-
`Claude Codeが、選んだ値を端末の既定として保存したと返しました(${result.line})。~/.claude/settings.json を確かめてください。`, 2);
|
|
5553
|
-
}
|
|
5554
|
-
if (result.scope !== "session_only") {
|
|
5555
|
-
throw new AitermError(`CLAUDE_MODEL_SWITCH_REFUSED vendor=claude session=${name}\n` +
|
|
5556
|
-
`Claude Codeがmodelを切り替えませんでした(${result.line})。modelとreasoning_effortは変えていません。`, 2);
|
|
5557
|
-
}
|
|
5558
|
-
const ready = await waitAgentTuiReady(name, meta, AGENT_TUI_READY_TIMEOUT_MS);
|
|
5559
|
-
if (!ready.ready)
|
|
5560
|
-
throw new AitermError("Claudeのmodel変更完了を確認できません", 2);
|
|
5561
|
-
}
|
|
5562
5037
|
// ===================== ファスト(高速の応答)の切り替え(ADR 0114) =====================
|
|
5563
5038
|
// 席は必ず通常の速度で起こす。fast: true は、通常で起こしてから、その席で切り替える(Claude Code・Codex)。
|
|
5564
5039
|
// CursorとGrokはfastが別のmodel IDなので、起動時のIDをfast版にする。
|
|
@@ -5656,33 +5131,6 @@ async function planLaunchFast(kind, o) {
|
|
|
5656
5131
|
}
|
|
5657
5132
|
return { ...plan, model: fastId, state: true };
|
|
5658
5133
|
}
|
|
5659
|
-
const USER_DEFAULT_SETTLE_MS = 400;
|
|
5660
|
-
const USER_DEFAULT_RESTORE_PASSES = 3;
|
|
5661
|
-
/**
|
|
5662
|
-
* harnessが利用者の既定へ書いた分を、切り替えの直前の中身(before)を元に戻す。
|
|
5663
|
-
* harnessは1回の切り替えで何度か書く事があるので(Grokの起動で見た)、少し置きながら何度か見て、後から書かれた分も戻す。
|
|
5664
|
-
*/
|
|
5665
|
-
async function restoreUserDefaults(restore) {
|
|
5666
|
-
for (let pass = 0; pass < USER_DEFAULT_RESTORE_PASSES; pass++) {
|
|
5667
|
-
await sleep(USER_DEFAULT_SETTLE_MS);
|
|
5668
|
-
try {
|
|
5669
|
-
restore();
|
|
5670
|
-
}
|
|
5671
|
-
catch { /* 戻せなくても、切り替えの結果は返す */ }
|
|
5672
|
-
}
|
|
5673
|
-
}
|
|
5674
|
-
/** 設定fileを触る切り替えを鍵の中で流し、終わったら、harnessが書いた既定を切り替えの直前の値へ戻す。 */
|
|
5675
|
-
async function keepingUserDefaults(configPath, restore, action) {
|
|
5676
|
-
return withUserConfigLock(configPath, async () => {
|
|
5677
|
-
const before = readFileOrNull(configPath);
|
|
5678
|
-
try {
|
|
5679
|
-
return await action();
|
|
5680
|
-
}
|
|
5681
|
-
finally {
|
|
5682
|
-
await restoreUserDefaults(() => restore(before));
|
|
5683
|
-
}
|
|
5684
|
-
});
|
|
5685
|
-
}
|
|
5686
5134
|
/**
|
|
5687
5135
|
* 起動の --model の値を利用者の既定へ書くharness(Grok 1.0.50。Cursorは、既定のmodelを設定に持つ端末)を起こす。
|
|
5688
5136
|
* 鍵を取り、起動の直前の中身を読み、起こして、既定が書かれるのを待ってから、直前の値へ戻す。
|
|
@@ -6098,6 +5546,11 @@ async function applyLaunchFast(name, meta) {
|
|
|
6098
5546
|
}
|
|
6099
5547
|
/** Goal operations share the existing seat admission and original launch ID. */
|
|
6100
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");
|
|
6101
5554
|
assertSessionName(input.session_id);
|
|
6102
5555
|
if (input.action !== "inspect")
|
|
6103
5556
|
assertExecutionContext(input.session_id);
|
|
@@ -6264,6 +5717,8 @@ export async function agentGoal(input, origin = "automatic", expectedGoal) {
|
|
|
6264
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); } };
|
|
6265
5718
|
};
|
|
6266
5719
|
const harness = resolve()?.harness;
|
|
5720
|
+
if (sendHeld && harness !== "codex-cli")
|
|
5721
|
+
throw new ExecutionError("EXECUTION_STALE_GENERATION");
|
|
6267
5722
|
if (harness === 'grok-cli')
|
|
6268
5723
|
return withAgentSendLock(input.session_id, () => manageGrokAgentGoal(input, { resolve,
|
|
6269
5724
|
read: target => readFreshGrokGoal(target.vendor_session_id, grokPort(target)),
|
|
@@ -6298,7 +5753,7 @@ export async function agentGoal(input, origin = "automatic", expectedGoal) {
|
|
|
6298
5753
|
return request(method, params);
|
|
6299
5754
|
});
|
|
6300
5755
|
}, supported, fields), command => submitCodexGoalCommand(goalUi(target), command), (before, objective) => editCodexGoalObjective(goalUi(target), before, objective), objective => createCodexGoalObjective(goalUi(target), objective)) }, origin);
|
|
6301
|
-
return input.action === "inspect" ? run() : withAgentSendLock(input.session_id, run);
|
|
5756
|
+
return input.action === "inspect" || sendHeld ? run() : withAgentSendLock(input.session_id, run);
|
|
6302
5757
|
}
|
|
6303
5758
|
/** Whole-app stop uses native goal state, not the host's displayed snapshot. */
|
|
6304
5759
|
export async function pauseAgentGoalForStop(target) {
|
|
@@ -6513,7 +5968,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
|
|
|
6513
5968
|
throw new AitermError("Claude Code の reasoning_effort は low/medium/high/xhigh/max/ultracode のいずれかです。設定は変えていません。", 2);
|
|
6514
5969
|
}
|
|
6515
5970
|
if (model || level)
|
|
6516
|
-
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) });
|
|
6517
5972
|
if (effort && !level) {
|
|
6518
5973
|
beforeChange();
|
|
6519
5974
|
await sendAgentPromptText(name, `/effort ${effort}`);
|
|
@@ -6635,7 +6090,7 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
|
|
|
6635
6090
|
}
|
|
6636
6091
|
// `/model` の選択は、利用者のconfig.tomlへ model と model_reasoning_effort を既定として保存する。席だけの替えにするため、直前の値へ戻す。
|
|
6637
6092
|
if (model || effort) {
|
|
6638
|
-
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) }));
|
|
6639
6094
|
}
|
|
6640
6095
|
rememberModel();
|
|
6641
6096
|
if (fast !== null) {
|
|
@@ -6646,98 +6101,6 @@ async function configureAgentInLock(name, model, effort, fast, beforeChange) {
|
|
|
6646
6101
|
await dropFastIfUnsupported();
|
|
6647
6102
|
return configured();
|
|
6648
6103
|
}
|
|
6649
|
-
/** Codexの `/model` の選ぶ画面で、modelとreasoning effortを替える。 */
|
|
6650
|
-
async function configureCodexModel(name, model, effort, beforeChange) {
|
|
6651
|
-
try {
|
|
6652
|
-
await chooseCodexModel(name, model, effort, beforeChange);
|
|
6653
|
-
}
|
|
6654
|
-
catch (error) {
|
|
6655
|
-
// 選べずに断る時は、開いた選ぶ画面を閉じてから断る(開いたままだと、席は次の文を受け付けない)。
|
|
6656
|
-
for (let i = 0; i < 3; i++) {
|
|
6657
|
-
const tail = captureScreen(name, AGENT_TUI_READY_LINES).split("\n").map((line) => line.trim()).filter(Boolean).slice(-2).join("\n");
|
|
6658
|
-
if (!/esc back/.test(tail))
|
|
6659
|
-
break;
|
|
6660
|
-
sendMenuChoice(name, "Escape");
|
|
6661
|
-
await sleep(400);
|
|
6662
|
-
}
|
|
6663
|
-
throw error;
|
|
6664
|
-
}
|
|
6665
|
-
}
|
|
6666
|
-
async function chooseCodexModel(name, model, effort, beforeChange) {
|
|
6667
|
-
const beforeCounts = lineCounts(captureScreen(name, AGENT_TUI_READY_LINES));
|
|
6668
|
-
await sendAgentPromptText(name, "/model");
|
|
6669
|
-
let modelScreen = await waitForScreenText(name, "Select Model and Effort");
|
|
6670
|
-
if (model && !effort) {
|
|
6671
|
-
sendMenuChoice(name, "Enter");
|
|
6672
|
-
let currentScreen = await waitForScreenText(name, "Select Reasoning Level");
|
|
6673
|
-
let advanced = false;
|
|
6674
|
-
if (/More reasoning[^\n]*\(current\)/.test(currentScreen)) {
|
|
6675
|
-
const more = codexMoreReasoningChoice(currentScreen);
|
|
6676
|
-
if (more) {
|
|
6677
|
-
sendMenuChoice(name, more);
|
|
6678
|
-
currentScreen = await waitForScreenText(name, "Advanced Reasoning");
|
|
6679
|
-
advanced = true;
|
|
6680
|
-
}
|
|
6681
|
-
}
|
|
6682
|
-
effort = codexCurrentEffort(currentScreen);
|
|
6683
|
-
if (!effort)
|
|
6684
|
-
throw new AitermError("CODEX_CURRENT_EFFORT_UNKNOWN: 現在のeffortを確認できません。設定は変えていません。", 2);
|
|
6685
|
-
if (advanced) {
|
|
6686
|
-
sendMenuChoice(name, "Escape");
|
|
6687
|
-
await waitForScreenText(name, "Select Reasoning Level");
|
|
6688
|
-
}
|
|
6689
|
-
sendMenuChoice(name, "Escape");
|
|
6690
|
-
modelScreen = await waitForScreenText(name, "Select Model and Effort");
|
|
6691
|
-
}
|
|
6692
|
-
if (model) {
|
|
6693
|
-
let choice = codexModelChoice(modelScreen, model);
|
|
6694
|
-
if (!choice) {
|
|
6695
|
-
const meta = loadAgentMetadata(name);
|
|
6696
|
-
const bin = meta.agent_executable ?? resolveAgentBin("codex");
|
|
6697
|
-
if (!bin)
|
|
6698
|
-
throw new AitermError("Codex の CLI が見つかりません", 2);
|
|
6699
|
-
const catalog = await codexModelChoices(bin, true);
|
|
6700
|
-
const target = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
|
|
6701
|
-
const displayName = target?.display_name;
|
|
6702
|
-
if (displayName && catalog.models.filter(item => item.display_name?.toLowerCase() === displayName.toLowerCase()).length === 1) {
|
|
6703
|
-
choice = codexModelChoice(modelScreen, model, displayName);
|
|
6704
|
-
}
|
|
6705
|
-
}
|
|
6706
|
-
if (!choice)
|
|
6707
|
-
throw new AitermError(`Codexの/modelに ${model} がありません`, 2);
|
|
6708
|
-
sendMenuChoice(name, choice);
|
|
6709
|
-
}
|
|
6710
|
-
else {
|
|
6711
|
-
sendMenuChoice(name, "Enter");
|
|
6712
|
-
}
|
|
6713
|
-
let effortScreen = await waitForScreenText(name, "Select Reasoning Level");
|
|
6714
|
-
if (effort) {
|
|
6715
|
-
let choice = codexEffortChoice(effortScreen, effort);
|
|
6716
|
-
if (!choice && (effort === "max" || effort === "ultra")) {
|
|
6717
|
-
const more = codexMoreReasoningChoice(effortScreen);
|
|
6718
|
-
if (more) {
|
|
6719
|
-
sendMenuChoice(name, more);
|
|
6720
|
-
effortScreen = await waitForScreenText(name, "Advanced Reasoning");
|
|
6721
|
-
choice = codexEffortChoice(effortScreen, effort);
|
|
6722
|
-
}
|
|
6723
|
-
}
|
|
6724
|
-
if (!choice)
|
|
6725
|
-
throw new AitermError(`Codexの/modelに reasoning_effort=${effort} がありません`, 2);
|
|
6726
|
-
beforeChange();
|
|
6727
|
-
sendMenuChoice(name, choice);
|
|
6728
|
-
}
|
|
6729
|
-
else {
|
|
6730
|
-
beforeChange();
|
|
6731
|
-
sendMenuChoice(name, "Enter");
|
|
6732
|
-
}
|
|
6733
|
-
for (const deadline = performance.now() + 3_000; performance.now() < deadline; await sleep(100)) {
|
|
6734
|
-
const screen = captureScreen(name, AGENT_TUI_READY_LINES);
|
|
6735
|
-
const counts = lineCounts(screen);
|
|
6736
|
-
if (codexModelChangeNotices(screen, model, effort).some(line => (counts.get(line) ?? 0) > (beforeCounts.get(line) ?? 0)))
|
|
6737
|
-
return;
|
|
6738
|
-
}
|
|
6739
|
-
throw new AitermError("CODEX_MODEL_SWITCH_UNCONFIRMED: 指定したmodel/effortの新しい変更通知を確認できません。設定が変わった可能性があります。再送しないでください。", 2);
|
|
6740
|
-
}
|
|
6741
6104
|
export function __testCodexConfigureChoices(screen, model, effort) {
|
|
6742
6105
|
return {
|
|
6743
6106
|
model: codexModelChoice(screen, model),
|
|
@@ -6863,143 +6226,387 @@ function confirmedAgentResumeRecipe(meta, lifecycle) {
|
|
|
6863
6226
|
throw unavailable();
|
|
6864
6227
|
return recipe;
|
|
6865
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
|
+
}
|
|
6866
6421
|
async function resumeAgentInLock(name, readyTimeout = AGENT_TUI_READY_TIMEOUT_MS) {
|
|
6867
|
-
const previous = loadAgentMetadata(name)
|
|
6422
|
+
const previous = loadAgentMetadata(name);
|
|
6423
|
+
let lifecycle = readAgentLifecycle(previous);
|
|
6868
6424
|
const uncertain = () => new AgentResumeError("AGENT_RESUME_UNCONFIRMED", "前の復帰処理を確認できません。本文は送信していません。再送せず席の状態を確認してください。", name, previous.launch_id);
|
|
6869
6425
|
const ownAttempt = readAgentResumeAttempt(previous);
|
|
6870
6426
|
if (!lifecycle) {
|
|
6871
6427
|
if (previous.resumed_from) {
|
|
6872
6428
|
const attempt = readAgentResumeAttempt({ aiterm_session: name, launch_id: previous.resumed_from });
|
|
6873
|
-
if (attempt?.
|
|
6429
|
+
if (attempt?.next_launch_id !== previous.launch_id)
|
|
6874
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
|
+
}
|
|
6875
6446
|
}
|
|
6876
6447
|
if (ownAttempt)
|
|
6877
6448
|
throw uncertain();
|
|
6878
|
-
|
|
6449
|
+
if (!lifecycle)
|
|
6450
|
+
return previous;
|
|
6879
6451
|
}
|
|
6880
|
-
if (lifecycle.state !== "hibernated" || ownAttempt)
|
|
6881
|
-
throw uncertain();
|
|
6882
|
-
assertExecutionResumeSupported();
|
|
6883
|
-
const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
|
|
6884
|
-
if (sessionExists(name))
|
|
6452
|
+
if ((lifecycle.schema === "aiterm.agent-lifecycle.v1" && lifecycle.state !== "hibernated") || ownAttempt)
|
|
6885
6453
|
throw uncertain();
|
|
6886
|
-
const
|
|
6887
|
-
|
|
6888
|
-
if (value === null)
|
|
6889
|
-
delete controlEnv[key];
|
|
6890
|
-
else
|
|
6891
|
-
controlEnv[key] = value;
|
|
6892
|
-
}
|
|
6893
|
-
if (recipe.kind === "codex")
|
|
6894
|
-
controlEnv.CODEX_HOME = recipe.configuration_root;
|
|
6895
|
-
if (recipe.fast) {
|
|
6896
|
-
if (recipe.kind === "claude") {
|
|
6897
|
-
if (await assertClaudeFastSupported(recipe.executable, recipe.cwd, recipe.model, "本文は送信していません。", controlEnv))
|
|
6898
|
-
throw uncertain();
|
|
6899
|
-
}
|
|
6900
|
-
else
|
|
6901
|
-
await assertCodexFastSupported(recipe.executable, recipe.configuration_root, recipe.model, "本文は送信していません。", controlEnv);
|
|
6902
|
-
}
|
|
6903
|
-
const lineage = { agentRole: "subagent", parentSessionId: previous.parent_session_id,
|
|
6904
|
-
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";
|
|
6905
6456
|
let next = null, attempt = null;
|
|
6906
|
-
let
|
|
6907
|
-
|
|
6908
|
-
|
|
6909
|
-
if (
|
|
6910
|
-
|
|
6911
|
-
|
|
6912
|
-
|
|
6913
|
-
|
|
6914
|
-
|
|
6915
|
-
|
|
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))
|
|
6916
6471
|
throw uncertain();
|
|
6917
|
-
|
|
6918
|
-
|
|
6919
|
-
|
|
6920
|
-
|
|
6921
|
-
|
|
6922
|
-
|
|
6923
|
-
|
|
6924
|
-
|
|
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))
|
|
6925
6484
|
throw uncertain();
|
|
6926
|
-
|
|
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")
|
|
6927
6575
|
throw uncertain();
|
|
6928
|
-
|
|
6929
|
-
|
|
6930
|
-
|
|
6931
|
-
|
|
6932
|
-
|
|
6933
|
-
next.resumed_from = previous.launch_id;
|
|
6934
|
-
next.launch_operation_id = previous.launch_operation_id;
|
|
6935
|
-
next.launch_request_digest = previous.launch_request_digest;
|
|
6936
|
-
next.model = recipe.model;
|
|
6937
|
-
next.fast = false;
|
|
6938
|
-
next.agent_executable = recipe.executable;
|
|
6939
|
-
if (isWin)
|
|
6940
|
-
next.windows_launch_exit_tracked = true;
|
|
6941
|
-
if (next.kind === "claude")
|
|
6942
|
-
next.claude_home = recipe.configuration_root;
|
|
6943
|
-
else
|
|
6944
|
-
next.codex_home = recipe.configuration_root;
|
|
6945
|
-
if (previous.write_scope !== undefined)
|
|
6946
|
-
next.write_scope = previous.write_scope;
|
|
6947
|
-
writeAgentMetadata(next);
|
|
6948
|
-
initializeAgentActivity(next);
|
|
6949
|
-
writeAgentResumeRecipe(next, { ...recipe, launch_id: next.launch_id });
|
|
6950
|
-
attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
|
|
6951
|
-
state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
|
|
6952
|
-
writeAgentResumeAttempt(previous, attempt);
|
|
6953
|
-
const shell = isWin ? "pwsh" : "bash";
|
|
6954
|
-
openSessionInternal(name, shell, [], true);
|
|
6955
|
-
const environment = [...Object.entries(recipe.environment),
|
|
6956
|
-
...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
|
|
6957
|
-
for (const [key, value] of environment) {
|
|
6958
|
-
const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
|
|
6959
|
-
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)
|
|
6960
6581
|
throw uncertain();
|
|
6961
6582
|
}
|
|
6962
|
-
if (
|
|
6963
|
-
throw uncertain();
|
|
6964
|
-
const argv = next.kind === "claude" ? claudeResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next)
|
|
6965
|
-
: codexResumeArgv(recipe.executable, recipe.model, recipe.reasoning_effort, next, recipe.cwd);
|
|
6966
|
-
const full = isWin ? windowsAgentLaunchLine(recipe.cwd, environment, windowsAgentArgv(argv, () => resolveWinPaneShell("bash")), { file: agentMetadataPath(name, next.launch_id) + ".launch-exited", launch_id: next.launch_id })
|
|
6967
|
-
: `cd ${shq(recipe.cwd)} && /usr/bin/env ${environment.filter(([, value]) => value === null).map(([key]) => `-u ${shq(key)}`).join(" ")} `
|
|
6968
|
-
+ `${environment.filter(([, value]) => value !== null).map(([key, value]) => shq(`${key}=${value}`)).join(" ")} ${argv.map(shq).join(" ")}`;
|
|
6969
|
-
agentLaunchLines.set(name, atomicShellMultiline(full, shell));
|
|
6970
|
-
send(name, full, { enter: true, mark: false, force: true, rtk: false, raw: true, launchShell: shell, preserveAgentOperation: true });
|
|
6971
|
-
publishAgentGeneration(previous, next);
|
|
6972
|
-
published = true;
|
|
6973
|
-
});
|
|
6974
|
-
const resumed = next;
|
|
6975
|
-
const ready = await prepareAgentInput(name, resumed, { ready_timeout: readyTimeout }, !recipe.fast);
|
|
6976
|
-
if (ready.status !== "ready")
|
|
6977
|
-
throw uncertain();
|
|
6978
|
-
// Launch argv pins standard speed; restore fast only after the native composer is ready.
|
|
6979
|
-
if (recipe.fast) {
|
|
6980
|
-
const failed = await applyLaunchFast(name, resumed);
|
|
6981
|
-
if (failed || resumed.fast !== true)
|
|
6583
|
+
if (loadAgentMetadata(name).launch_id !== resumed.launch_id)
|
|
6982
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;
|
|
6983
6592
|
}
|
|
6984
|
-
|
|
6985
|
-
|
|
6986
|
-
|
|
6987
|
-
|
|
6988
|
-
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
|
|
6992
|
-
|
|
6993
|
-
|
|
6994
|
-
|
|
6995
|
-
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
}
|
|
7002
|
-
});
|
|
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
|
+
}
|
|
7003
6610
|
}
|
|
7004
6611
|
export async function dispatchAgentTurn(name, text, o = {}) {
|
|
7005
6612
|
assertExecutionContext(name);
|
|
@@ -7987,9 +7594,9 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
7987
7594
|
if (saved && (readAgentLifecycle(saved) || agentDormantState(saved))) {
|
|
7988
7595
|
return withAgentSendLock(name, async () => {
|
|
7989
7596
|
const previous = loadAgentMetadata(name), lifecycle = readAgentLifecycle(previous);
|
|
7990
|
-
if (!isDeepStrictEqual(previous, saved) || lifecycle?.state !== "hibernated" || readAgentResumeAttempt(previous))
|
|
7597
|
+
if (!isDeepStrictEqual(previous, saved) || (lifecycle?.state !== "hibernated" && !failedCodexResumeRecipe(previous)) || readAgentResumeAttempt(previous))
|
|
7991
7598
|
throw new AitermError("AGENT_RESUME_UNCONFIRMED: 保存した会話席の再開世代を確認できません。", 2);
|
|
7992
|
-
const recipe = confirmedAgentResumeRecipe(previous, lifecycle);
|
|
7599
|
+
const recipe = lifecycle ? confirmedAgentResumeRecipe(previous, lifecycle) : failedCodexResumeRecipe(previous);
|
|
7993
7600
|
if (kind !== previous.kind || sourceSessionId !== null
|
|
7994
7601
|
|| (opts.model != null && opts.model.trim() !== recipe.model)
|
|
7995
7602
|
|| (opts.reasoning_effort != null && opts.reasoning_effort.trim() !== recipe.reasoning_effort)
|
|
@@ -8139,3 +7746,10 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
8139
7746
|
reason: meta.initial_prompt_delivery?.reason ?? "startup_failed" });
|
|
8140
7747
|
}
|
|
8141
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
|
+
}
|