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.
@@ -0,0 +1,179 @@
1
+ import { AitermError } from "../errors.js";
2
+ import { sleep } from "../agent-shared.js";
3
+ import { resolveAgentBin } from "../agent-resolver.js";
4
+ import { claudeModelPicker, claudeModelPickerRow, claudeModelSwitchConfirm, claudeModelSwitchResult, claudePaneObservation, claudeModelChoices } from "./claude.js";
5
+ const CLAUDE_MODEL_PICKER_TIMEOUT_MS = 8_000;
6
+ const CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS = 1_500;
7
+ const CLAUDE_MODEL_SWITCH_TIMEOUT_MS = 15_000;
8
+ const CLAUDE_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
9
+ export async function configureClaudeForSessionOnly(name, meta, model, effort, beforeChange, ui) {
10
+ let selectionIssued = false;
11
+ const screen = () => ui.screen();
12
+ const until = async (read, timeoutMs) => {
13
+ const deadline = performance.now() + timeoutMs;
14
+ do {
15
+ const got = read();
16
+ if (got)
17
+ return got;
18
+ await sleep(100);
19
+ } while (performance.now() < deadline);
20
+ return null;
21
+ };
22
+ // Escは、選ぶ画面か確かめの画面が出ている間だけ打つ(入力欄へ戻った後のEscは、ほかの操作を取り消してしまう)。
23
+ const refuse = async (code, reason) => {
24
+ for (let i = 0; i < 3; i++) {
25
+ const now = screen();
26
+ if (!claudeModelPicker(now) && !claudeModelSwitchConfirm(now))
27
+ break;
28
+ ui.key("Escape");
29
+ await sleep(300);
30
+ }
31
+ throw new AitermError(`${code} vendor=claude session=${name}\n${reason}。` +
32
+ (selectionIssued ? "設定が変わった可能性があります。再送しないでください。" : "modelとreasoning_effortは変えていません。"), 2);
33
+ };
34
+ const picker = () => claudeModelPicker(screen());
35
+ const cursorOf = (p) => p?.rows.find((row) => row.cursor) ?? null;
36
+ // 1回押して、画面の今の行かeffortが変わるまで待つ。変わらなければnull(端で止まった・キーが落ちた)。
37
+ // キーが落ちる事があるので、変わらなければ1度だけ押し直す。
38
+ const press = async (key, changed) => {
39
+ for (let attempt = 0; attempt < 2; attempt++) {
40
+ ui.key(key);
41
+ const next = await until(() => { const p = picker(); return p && changed(p) ? p : null; }, CLAUDE_MODEL_PICKER_KEY_TIMEOUT_MS);
42
+ if (next)
43
+ return next;
44
+ }
45
+ return null;
46
+ };
47
+ await ui.command("/model");
48
+ let now = await until(picker, CLAUDE_MODEL_PICKER_TIMEOUT_MS);
49
+ if (!now) {
50
+ // 読めない形の画面が開いたままだと、席が次の文を受け取れない。入力待ちでも動作中でもない時だけ、Escを1度打って閉じる。
51
+ let state = claudePaneObservation(screen());
52
+ if (state.state === "unknown") {
53
+ ui.key("Escape");
54
+ await sleep(500);
55
+ state = claudePaneObservation(screen());
56
+ }
57
+ throw new AitermError(`CLAUDE_MODEL_PICKER_NOT_SHOWN vendor=claude session=${name} state=${state.state}/${state.reason}\n` +
58
+ "Claude Codeの /model の選ぶ画面を読めません(Claude Codeの版で画面の形が変わった見込み)。modelとreasoning_effortは変えていません。", 2);
59
+ }
60
+ if (!now.session_only) {
61
+ return refuse("CLAUDE_MODEL_SESSION_ONLY_UNAVAILABLE", "このClaude Codeの /model の選ぶ画面に、この会話だけで使う選び方(s to use this session only)がありません。" +
62
+ "端末の既定を書き換える選び方は使いません");
63
+ }
64
+ let targetIndex = null;
65
+ if (model) {
66
+ // 見えていない行は、下へ送りながら集める(一周するか、端で止まるまで)。
67
+ const known = new Map(now.rows.map((row) => [row.index, row]));
68
+ const start = cursorOf(now);
69
+ if (!start)
70
+ return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ画面の今の行を読めません");
71
+ let at = start.index;
72
+ const seen = new Set([at]);
73
+ for (let i = 0; i < 80; i++) {
74
+ const before = at;
75
+ const next = await press("Down", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
76
+ if (!next)
77
+ break;
78
+ now = next;
79
+ for (const row of next.rows)
80
+ known.set(row.index, row);
81
+ at = cursorOf(next).index;
82
+ if (seen.has(at))
83
+ break;
84
+ seen.add(at);
85
+ }
86
+ let target = claudeModelPickerRow([...known.values()], model);
87
+ if (!target || /^[a-z]+$/iu.test(model)) {
88
+ const bin = meta.agent_executable ?? resolveAgentBin("claude");
89
+ if (!bin)
90
+ return refuse("CLAUDE_MODEL_NOT_IN_PICKER", "Claude CodeのCLIが見つかりません");
91
+ let catalog;
92
+ try {
93
+ catalog = await claudeModelChoices(bin, meta.cwd ?? process.cwd());
94
+ }
95
+ catch (error) {
96
+ return refuse("CLAUDE_MODEL_CATALOG_UNAVAILABLE", error instanceof Error ? error.message : String(error));
97
+ }
98
+ const native = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
99
+ // The native alias can resolve to an older model; picker order is not alias authority.
100
+ const label = native?.display_name ?? native?.id ?? model;
101
+ const matching = [...known.values()].filter(row => row.label.toLowerCase() === label.toLowerCase());
102
+ target = matching.length === 1 ? matching[0] : null;
103
+ }
104
+ if (!target) {
105
+ const names = [...known.values()].sort((a, b) => a.index - b.index).map((row) => row.label).join(", ");
106
+ return refuse("CLAUDE_MODEL_NOT_IN_PICKER", `Claude Codeの /model の選ぶ画面に ${model} がありません(選べる機種: ${names})`);
107
+ }
108
+ for (let i = 0; i < 80 && at !== target.index; i++) {
109
+ const before = at;
110
+ const next = await press(target.index > at ? "Down" : "Up", (p) => { const c = cursorOf(p); return !!c && c.index !== before; });
111
+ if (!next)
112
+ break;
113
+ now = next;
114
+ at = cursorOf(next).index;
115
+ }
116
+ if (at !== target.index)
117
+ return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", `選ぶ画面で ${target.label} の行へ動けません`);
118
+ // 起きた後にClaude Codeが更新された席では、「Update Claude Code to use this model」の行が出る。その行にはEnterもsも無い。
119
+ if (!now.session_only) {
120
+ return refuse("CLAUDE_MODEL_NOT_SELECTABLE", `${target.label} は、この席のClaude Codeでは選べません(選ぶ画面のその行に、選ぶためのキーが出ていません。席のClaude Codeが古い見込み)`);
121
+ }
122
+ targetIndex = target.index;
123
+ }
124
+ if (effort) {
125
+ const wanted = CLAUDE_EFFORT_ORDER.indexOf(effort);
126
+ const row = cursorOf(now)?.label ?? model ?? "このmodel";
127
+ // そのmodelに無い段は飛ばされて行き来になるので、回数で打ち切る。
128
+ for (let i = 0; i < CLAUDE_EFFORT_ORDER.length + 3 && now.effort !== effort; i++) {
129
+ const current = now.effort;
130
+ const from = current === null ? -1 : CLAUDE_EFFORT_ORDER.indexOf(current);
131
+ if (from < 0)
132
+ return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort を選べません`);
133
+ const next = await press(wanted > from ? "Right" : "Left", (p) => p.effort !== current);
134
+ if (!next)
135
+ break;
136
+ now = next;
137
+ }
138
+ if (now.effort !== effort)
139
+ return refuse("CLAUDE_EFFORT_NOT_SELECTABLE", `${row} では reasoning_effort=${effort} を選べません`);
140
+ }
141
+ // 打つ直前に、もう1度読んで確かめる。
142
+ const last = picker();
143
+ const lastRow = cursorOf(last);
144
+ if (!last || !lastRow || !last.session_only
145
+ || (targetIndex !== null && lastRow.index !== targetIndex)
146
+ || (effort && last.effort !== effort)) {
147
+ return refuse("CLAUDE_MODEL_PICKER_UNREADABLE", "選ぶ直前の画面が、選んだ行・effortと合いません");
148
+ }
149
+ beforeChange();
150
+ selectionIssued = true;
151
+ ui.key("s");
152
+ let confirmed = false;
153
+ const result = await until(() => {
154
+ const text = screen();
155
+ const confirm = claudeModelSwitchConfirm(text);
156
+ if (confirm === "yes_selected" && !confirmed) {
157
+ // 会話が今のmodelでcacheされている時の確かめ。1番(Yes, switch)が選ばれている時だけ進める。
158
+ confirmed = true;
159
+ ui.key("Enter");
160
+ return null;
161
+ }
162
+ if (confirm || claudeModelPicker(text))
163
+ return null;
164
+ return claudeModelSwitchResult(text);
165
+ }, CLAUDE_MODEL_SWITCH_TIMEOUT_MS);
166
+ if (!result)
167
+ return refuse("CLAUDE_MODEL_SWITCH_UNCONFIRMED", "Claude Codeの切り替えの知らせを確認できません");
168
+ if (result.scope === "saved_as_default") {
169
+ throw new AitermError(`CLAUDE_MODEL_SAVED_AS_DEFAULT vendor=claude session=${name}\n` +
170
+ `Claude Codeが、選んだ値を端末の既定として保存したと返しました(${result.line})。~/.claude/settings.json を確かめてください。`, 2);
171
+ }
172
+ if (result.scope !== "session_only") {
173
+ throw new AitermError(`CLAUDE_MODEL_SWITCH_REFUSED vendor=claude session=${name}\n` +
174
+ `Claude Codeがmodelを切り替えませんでした(${result.line})。modelとreasoning_effortは変えていません。`, 2);
175
+ }
176
+ const ready = await ui.ready();
177
+ if (!ready.ready)
178
+ throw new AitermError("Claudeのmodel変更完了を確認できません", 2);
179
+ }
@@ -0,0 +1,97 @@
1
+ import { AitermError } from "../errors.js";
2
+ import { sleep } from "../agent-shared.js";
3
+ import { lineCounts } from "../agent-model-ui.js";
4
+ import { loadAgentMetadata } from "../agent-metadata-reader.js";
5
+ import { resolveAgentBin } from "../agent-resolver.js";
6
+ import { codexModelChoice, codexEffortChoice, codexMoreReasoningChoice, codexCurrentEffort, codexModelChangeNotices, codexModelChoices } from "./codex.js";
7
+ export async function configureCodexModel(name, model, effort, beforeChange, ui) {
8
+ try {
9
+ await chooseCodexModel(name, model, effort, beforeChange, ui);
10
+ }
11
+ catch (error) {
12
+ // 選べずに断る時は、開いた選ぶ画面を閉じてから断る(開いたままだと、席は次の文を受け付けない)。
13
+ for (let i = 0; i < 3; i++) {
14
+ const tail = ui.screen().split("\n").map((line) => line.trim()).filter(Boolean).slice(-2).join("\n");
15
+ if (!/esc back/.test(tail))
16
+ break;
17
+ ui.key("Escape");
18
+ await sleep(400);
19
+ }
20
+ throw error;
21
+ }
22
+ }
23
+ async function chooseCodexModel(name, model, effort, beforeChange, ui) {
24
+ const beforeCounts = lineCounts(ui.screen());
25
+ await ui.command("/model");
26
+ let modelScreen = await ui.waitForText("Select Model and Effort");
27
+ if (model && !effort) {
28
+ ui.key("Enter");
29
+ let currentScreen = await ui.waitForText("Select Reasoning Level");
30
+ let advanced = false;
31
+ if (/More reasoning[^\n]*\(current\)/.test(currentScreen)) {
32
+ const more = codexMoreReasoningChoice(currentScreen);
33
+ if (more) {
34
+ ui.key(more);
35
+ currentScreen = await ui.waitForText("Advanced Reasoning");
36
+ advanced = true;
37
+ }
38
+ }
39
+ effort = codexCurrentEffort(currentScreen);
40
+ if (!effort)
41
+ throw new AitermError("CODEX_CURRENT_EFFORT_UNKNOWN: 現在のeffortを確認できません。設定は変えていません。", 2);
42
+ if (advanced) {
43
+ ui.key("Escape");
44
+ await ui.waitForText("Select Reasoning Level");
45
+ }
46
+ ui.key("Escape");
47
+ modelScreen = await ui.waitForText("Select Model and Effort");
48
+ }
49
+ if (model) {
50
+ let choice = codexModelChoice(modelScreen, model);
51
+ if (!choice) {
52
+ const meta = loadAgentMetadata(name);
53
+ const bin = meta.agent_executable ?? resolveAgentBin("codex");
54
+ if (!bin)
55
+ throw new AitermError("Codex の CLI が見つかりません", 2);
56
+ const catalog = await codexModelChoices(bin, true);
57
+ const target = catalog.models.find(item => item.id.toLowerCase() === model.toLowerCase());
58
+ const displayName = target?.display_name;
59
+ if (displayName && catalog.models.filter(item => item.display_name?.toLowerCase() === displayName.toLowerCase()).length === 1) {
60
+ choice = codexModelChoice(modelScreen, model, displayName);
61
+ }
62
+ }
63
+ if (!choice)
64
+ throw new AitermError(`Codexの/modelに ${model} がありません`, 2);
65
+ ui.key(choice);
66
+ }
67
+ else {
68
+ ui.key("Enter");
69
+ }
70
+ let effortScreen = await ui.waitForText("Select Reasoning Level");
71
+ if (effort) {
72
+ let choice = codexEffortChoice(effortScreen, effort);
73
+ if (!choice && (effort === "max" || effort === "ultra")) {
74
+ const more = codexMoreReasoningChoice(effortScreen);
75
+ if (more) {
76
+ ui.key(more);
77
+ effortScreen = await ui.waitForText("Advanced Reasoning");
78
+ choice = codexEffortChoice(effortScreen, effort);
79
+ }
80
+ }
81
+ if (!choice)
82
+ throw new AitermError(`Codexの/modelに reasoning_effort=${effort} がありません`, 2);
83
+ beforeChange();
84
+ ui.key(choice);
85
+ }
86
+ else {
87
+ beforeChange();
88
+ ui.key("Enter");
89
+ }
90
+ for (const deadline = performance.now() + 3_000; performance.now() < deadline; await sleep(100)) {
91
+ const screen = ui.screen();
92
+ const counts = lineCounts(screen);
93
+ if (codexModelChangeNotices(screen, model, effort).some(line => (counts.get(line) ?? 0) > (beforeCounts.get(line) ?? 0)))
94
+ return;
95
+ }
96
+ throw new AitermError("CODEX_MODEL_SWITCH_UNCONFIRMED: 指定したmodel/effortの新しい変更通知を確認できません。設定が変わった可能性があります。再送しないでください。", 2);
97
+ }
@@ -13,7 +13,7 @@ import * as steer from "aiterm-steer-delivery";
13
13
  import { AITERM_PROFILE } from "../steer-profile.js";
14
14
  import { catalogInvalid, catalogUnavailable, checkedCatalog } from "../model-catalog.js";
15
15
  import { shq, subagentInstruction, writeScopeLaunchNote, safeStatSize, readFileRange, sleep, agentMetadataPath, writeAgentMetadata, writeJson0600, agentEventPath, createEmpty0600, agentLineageFields, AGENT_DONE_POLL_MS, AGENT_EVENT_MAX_BYTES, AGENT_EVENT_TAIL_BYTES, AGENT_TURN_BOUNDARY_TAIL_BYTES, readTailLinesNewestFirst, scanLinesNewestFirst, CODEX_TRANSCRIPT_INCREMENT_MAX_BYTES, agentHarness, } from "../agent-shared.js";
16
- import { readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
16
+ import { confirmedAgentResumeRecoveryOrigin, readAgentLifecycle, readAgentResumeRecipe, agentResumeRecipeDigest } from "../agent-lifecycle.js";
17
17
  export function realCodexHome() {
18
18
  return process.env.CODEX_HOME || path.join(process.env.HOME ?? os.homedir(), ".codex");
19
19
  }
@@ -485,7 +485,7 @@ function codexLatestTurnBoundary(meta, reach) {
485
485
  * neither their timestamps nor a cached vendor_session_id prove the live
486
486
  * harness endpoint after /new. A later native endpoint adapter may disambiguate.
487
487
  */
488
- export function codexInterruptionRecord(meta) {
488
+ function codexNativeRootRecord(meta, requireBoundary) {
489
489
  if (meta.kind !== "codex" || meta.hook_route !== "shared_codex_home" || !meta.codex_home)
490
490
  return null;
491
491
  try {
@@ -573,9 +573,10 @@ export function codexInterruptionRecord(meta) {
573
573
  const after = fs.statSync(file);
574
574
  if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
575
575
  || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs
576
- || !boundary || !Number.isSafeInteger(boundary.event_cursor) || boundary.event_cursor < 0
577
- || typeof boundary.turn_id !== "string" || !boundary.turn_id || boundary.turn_id.length > 256
578
- || (boundary.type === "turn_aborted" && typeof boundary.reason !== "string"))
576
+ || (requireBoundary && !boundary)
577
+ || (boundary && (!Number.isSafeInteger(boundary.event_cursor) || boundary.event_cursor < 0
578
+ || typeof boundary.turn_id !== "string" || !boundary.turn_id || boundary.turn_id.length > 256
579
+ || (boundary.type === "turn_aborted" && typeof boundary.reason !== "string"))))
579
580
  return null;
580
581
  // Re-resolve the candidate set, without the ordinary launch-verdict cache.
581
582
  const last = listStrict();
@@ -592,14 +593,22 @@ export function codexInterruptionRecord(meta) {
592
593
  if (after.dev !== final.dev || after.ino !== final.ino || after.size !== final.size
593
594
  || after.mtimeMs !== final.mtimeMs || after.ctimeMs !== final.ctimeMs)
594
595
  return null;
595
- return { session_id: session, file: { device: before.dev, inode: before.ino }, event_cursor: boundary.event_cursor,
596
- boundary: { type: boundary.type, turn_id: boundary.turn_id,
597
- reason: typeof boundary.reason === "string" ? boundary.reason : null } };
596
+ return { session_id: session, file: { device: before.dev, inode: before.ino }, path: file, end: final.size,
597
+ inherited_last_turn_id: origin?.last_turn_id ?? null,
598
+ event_cursor: boundary?.event_cursor ?? null,
599
+ boundary: boundary ? { type: boundary.type, turn_id: boundary.turn_id,
600
+ reason: typeof boundary.reason === "string" ? boundary.reason : null } : null };
598
601
  }
599
602
  catch {
600
603
  return null;
601
604
  }
602
605
  }
606
+ export function codexInterruptionRecord(meta) {
607
+ const value = codexNativeRootRecord(meta, true);
608
+ if (!value || !value.boundary || value.event_cursor === null)
609
+ return null;
610
+ return { session_id: value.session_id, file: value.file, event_cursor: value.event_cursor, boundary: value.boundary };
611
+ }
603
612
  /**
604
613
  * この起動のroot rolloutで、最後のturnが終わっていて、次のturnが始まっていないか。
605
614
  * 末尾から見て最初の境界が、task_completeか、止めた時のturn_abortedの時だけtrue。
@@ -1435,7 +1444,7 @@ export function restoreCodexDefaultInFile(configPath, key, before) {
1435
1444
  }
1436
1445
  // The ordinary interactive cancel gesture; not a process termination signal.
1437
1446
  export const CODEX_INTERRUPT_KEY = "Escape";
1438
- const codexResumeProofSchema = z.object({ schema: z.literal("aiterm.codex-resume-proof.v1"),
1447
+ export const codexResumeProofSchema = z.object({ schema: z.literal("aiterm.codex-resume-proof.v1"),
1439
1448
  launch_id: z.string().regex(/^[a-f0-9]{32}$/), session_id: z.string().uuid(),
1440
1449
  file: z.string().refine(value => path.isAbsolute(value)), device: z.string().regex(/^\d+$/), inode: z.string().regex(/^\d+$/),
1441
1450
  cursor: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
@@ -1459,10 +1468,12 @@ function codexResumedProof(meta) {
1459
1468
  || previous.codex_home !== meta.codex_home || previous.hook_route !== meta.hook_route
1460
1469
  || ["agent_role", "parent_session_id", "delegation_depth", "lineage", "delegation_allowed"].some(key => previous[key] !== meta[key]))
1461
1470
  throw resumeProofUnavailable();
1462
- const life = readAgentLifecycle(previous), recipe = readAgentResumeRecipe(previous), proof = readCodexResumeProof(previous);
1463
- if (life?.state !== "hibernated" || !recipe || recipe.kind !== "codex" || recipe.vendor_session_id !== previous.vendor_session_id
1464
- || recipe.configuration_root !== meta.codex_home || life.recipe_digest !== agentResumeRecipeDigest(recipe)
1465
- || life.resume_proof_digest !== codexResumeProofDigest(proof))
1471
+ const life = readAgentLifecycle(previous), origin = life ? null : confirmedAgentResumeRecoveryOrigin(previous);
1472
+ const source = life?.state === "hibernated" ? life : origin;
1473
+ const recipe = readAgentResumeRecipe(previous), proof = readCodexResumeProof(previous);
1474
+ if (!source || !recipe || recipe.kind !== "codex" || recipe.vendor_session_id !== previous.vendor_session_id
1475
+ || recipe.configuration_root !== meta.codex_home || source.recipe_digest !== agentResumeRecipeDigest(recipe)
1476
+ || source.resume_proof_digest !== codexResumeProofDigest(proof))
1466
1477
  throw resumeProofUnavailable();
1467
1478
  return proof;
1468
1479
  }
@@ -1523,3 +1534,27 @@ export function captureCodexResumeProof(meta) {
1523
1534
  throw resumeProofUnavailable();
1524
1535
  }
1525
1536
  }
1537
+ /** Freeze the inherited root at cold recovery; it does not assert task completion. */
1538
+ export function captureCodexRecoveryProof(meta) {
1539
+ try {
1540
+ const value = codexNativeRootRecord(meta, false);
1541
+ const turn = value?.boundary?.turn_id ?? value?.inherited_last_turn_id;
1542
+ if (!value || value.session_id !== meta.vendor_session_id || !turn || value.end < 1
1543
+ || readFileRange(value.path, value.end - 1, value.end).toString() !== "\n")
1544
+ throw resumeProofUnavailable();
1545
+ const before = fs.statSync(value.path, { bigint: true }), bytes = Math.min(value.end, 1024 * 1024);
1546
+ if (Number(before.dev) !== value.file.device || Number(before.ino) !== value.file.inode || before.size !== BigInt(value.end))
1547
+ throw resumeProofUnavailable();
1548
+ const digest = createHash("sha256").update(readFileRange(value.path, 0, bytes)).digest("hex"), after = fs.statSync(value.path, { bigint: true });
1549
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)
1550
+ throw resumeProofUnavailable();
1551
+ const proof = codexResumeProofSchema.parse({ schema: "aiterm.codex-resume-proof.v1", launch_id: meta.launch_id,
1552
+ session_id: value.session_id, file: value.path, device: before.dev.toString(), inode: before.ino.toString(), cursor: value.end,
1553
+ prefix_bytes: bytes, prefix_sha256: digest, last_turn_id: turn });
1554
+ writeJson0600(codexResumeProofPath(meta), proof);
1555
+ return readCodexResumeProof(meta);
1556
+ }
1557
+ catch {
1558
+ throw resumeProofUnavailable();
1559
+ }
1560
+ }
@@ -41,8 +41,11 @@ export async function inspectIdleSettings(kind, expected, ui) {
41
41
  return false;
42
42
  if (kind === 'claude' && !/^claude-[a-z]+-\d+(?:-\d{1,2})?$/.test(expected.model))
43
43
  return false;
44
- const inMenu = (screen) => kind === 'codex' ? codexSettingsPreview(screen) !== null
45
- : (claudeModelPicker(screen) !== null && /Esc to cancel\s*$/.test(screen)) || claudeFastMenu(screen);
44
+ if (kind === 'codex') {
45
+ const preview = await inspectCodexPreview(ui);
46
+ return preview !== null && codexPreviewMatchesSettings(preview, expected);
47
+ }
48
+ const inMenu = (screen) => (claudeModelPicker(screen) !== null && /Esc to cancel\s*$/.test(screen)) || claudeFastMenu(screen);
46
49
  const close = async () => {
47
50
  for (let i = 0; i < 3 && inMenu(ui.screen()); i++) {
48
51
  ui.key('Escape');
@@ -52,54 +55,21 @@ export async function inspectIdleSettings(kind, expected, ui) {
52
55
  };
53
56
  let matched = false;
54
57
  try {
55
- if (kind === 'codex') {
56
- await ui.command('/statusline');
57
- if (!await until(() => codexSettingsPreview(ui.screen())))
58
- return false;
59
- let query = '';
60
- const select = async (id, checked) => {
61
- if (query.length)
62
- ui.key(...Array(query.length).fill('BSpace'));
63
- ui.text(id);
64
- query = id;
65
- const row = () => {
66
- const menu = codexSettingsPreview(ui.screen());
67
- return menu?.rows.length === 1 && menu.rows[0].id === id && menu.rows[0].cursor ? menu.rows[0] : null;
68
- };
69
- const before = await until(row);
70
- if (!before)
71
- return false;
72
- if (before.checked !== checked) {
73
- ui.key('Space');
74
- if (!await until(() => row()?.checked === checked ? true : null))
75
- return false;
76
- }
77
- return true;
78
- };
79
- // These default items otherwise clip the native settings at narrow widths.
80
- for (const [id, checked] of [['current-dir', false], ['thread-name', false], ['model-with-reasoning', true], ['fast-mode', true]])
81
- if (!await select(id, checked))
82
- return false;
83
- const preview = codexSettingsPreview(ui.screen());
84
- matched = !!preview && codexPreviewMatchesSettings(preview.preview, expected);
85
- }
86
- else {
87
- await ui.command('/model');
88
- const menu = await until(() => claudeModelPicker(ui.screen()));
89
- if (!menu)
90
- return false;
91
- const current = menu.rows.filter(row => row.current);
92
- const requested = claudeModelPickerRow(menu.rows, expected.model);
93
- if (current.length !== 1 || !current[0].cursor || requested !== current[0] || menu.effort !== expected.reasoning_effort)
94
- return false;
95
- if (!await close())
96
- return false;
97
- await ui.command('/fast');
98
- if (!await until(() => claudeFastMenu(ui.screen()) ? true : null))
99
- return false;
100
- // Other account/menu layouts remain unknown until their native receipt is accepted.
101
- matched = !expected.fast && /^\s*Fast mode requires usage credits · \/usage-credits to turn them on\s*$/m.test(ui.screen());
102
- }
58
+ await ui.command('/model');
59
+ const menu = await until(() => claudeModelPicker(ui.screen()));
60
+ if (!menu)
61
+ return false;
62
+ const current = menu.rows.filter(row => row.current);
63
+ const requested = claudeModelPickerRow(menu.rows, expected.model);
64
+ if (current.length !== 1 || !current[0].cursor || requested !== current[0] || menu.effort !== expected.reasoning_effort)
65
+ return false;
66
+ if (!await close())
67
+ return false;
68
+ await ui.command('/fast');
69
+ if (!await until(() => claudeFastMenu(ui.screen()) ? true : null))
70
+ return false;
71
+ // Other account/menu layouts remain unknown until their native receipt is accepted.
72
+ matched = !expected.fast && /^\s*Fast mode requires usage credits · \/usage-credits to turn them on\s*$/m.test(ui.screen());
103
73
  }
104
74
  finally {
105
75
  if (!await close())
@@ -107,3 +77,87 @@ export async function inspectIdleSettings(kind, expected, ui) {
107
77
  }
108
78
  return matched;
109
79
  }
80
+ async function inspectCodexPreview(ui, thread = false) {
81
+ if (codexSettingsPreview(ui.screen()))
82
+ return null;
83
+ let preview = null;
84
+ try {
85
+ preview = await readCodexPreview(ui, thread);
86
+ }
87
+ finally {
88
+ for (let i = 0; i < 3 && codexSettingsPreview(ui.screen()); i++) {
89
+ ui.key('Escape');
90
+ await until(() => !codexSettingsPreview(ui.screen()) ? true : null);
91
+ }
92
+ if (codexSettingsPreview(ui.screen()) || !await ui.ready())
93
+ preview = null;
94
+ }
95
+ return preview;
96
+ }
97
+ async function readCodexPreview(ui, thread) {
98
+ await ui.command('/statusline');
99
+ if (!await until(() => codexSettingsPreview(ui.screen())))
100
+ return null;
101
+ let query = '';
102
+ const select = async (id, checked) => {
103
+ if (query.length)
104
+ ui.key(...Array(query.length).fill('BSpace'));
105
+ ui.text(id);
106
+ query = id;
107
+ const row = () => {
108
+ const menu = codexSettingsPreview(ui.screen());
109
+ return menu?.rows.length === 1 && menu.rows[0].id === id && menu.rows[0].cursor ? menu.rows[0] : null;
110
+ };
111
+ const before = await until(row);
112
+ if (!before)
113
+ return false;
114
+ if (before.checked !== checked) {
115
+ ui.key('Space');
116
+ if (!await until(() => row()?.checked === checked ? true : null))
117
+ return false;
118
+ }
119
+ return true;
120
+ };
121
+ // These default items otherwise clip the native settings at narrow widths.
122
+ for (const [id, checked] of [['current-dir', false], ['thread-name', false], ['model-with-reasoning', true], ['fast-mode', true]])
123
+ if (!await select(id, checked))
124
+ return null;
125
+ if (thread) {
126
+ if (!await select('thread-id', true) && !await select('session-id', true))
127
+ return null;
128
+ }
129
+ return codexSettingsPreview(ui.screen())?.preview ?? null;
130
+ }
131
+ /** Current native preview only; it neither completes a task nor proves native birth. */
132
+ export async function inspectCodexResumeSettings(vendorSessionId, ui) {
133
+ if (!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(vendorSessionId))
134
+ return null;
135
+ const preview = await inspectCodexPreview(ui, true);
136
+ if (!preview)
137
+ return null;
138
+ const parts = preview.split(' · ');
139
+ if (parts.length !== 3 || parts.filter(value => value === vendorSessionId).length !== 1)
140
+ return null;
141
+ const values = parts.filter(value => value !== vendorSessionId);
142
+ const model = values.find(value => /^(\S+) (none|minimal|low|medium|high|xhigh|max|ultra)( Fast)?$/.test(value));
143
+ const tier = values.find(value => /^(Standard|Fast|Fast off)$/.test(value));
144
+ if (!model || !tier)
145
+ return null;
146
+ const match = /^(\S+) (none|minimal|low|medium|high|xhigh|max|ultra)( Fast)?$/.exec(model);
147
+ if (!!match[3] !== (tier === 'Fast'))
148
+ return null;
149
+ return { model: match[1], reasoning_effort: match[2], fast: tier === 'Fast' };
150
+ }
151
+ export function codexRecoveryComposer(screen) {
152
+ const lines = screen.trimEnd().split("\n");
153
+ let index = lines.length - 1;
154
+ while (index >= 0 && !/^\s*[›>](?!_)(?!\s*\d+\.)/.test(lines[index]))
155
+ index--;
156
+ if (index < 0)
157
+ return null;
158
+ const tail = lines.slice(index + 1).filter(line => line.trim());
159
+ if (tail.some(line => !/^\s*\S+\s+(?:none|default|minimal|low|medium|high|xhigh|max|ultra)(?: Fast)? · /.test(line)
160
+ && !/^\s*\? for shortcuts\s*$/.test(line)))
161
+ return null;
162
+ return lines[index].replace(/^\s*[›>]\s?/, "").trimEnd();
163
+ }
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { remoteInputDescription, remoteInputSchema } from "./remote-contract.js";
2
3
  import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
3
4
  import { AitermError, AgentAuthenticationPreflightError, AgentResumeError } from "./errors.js";
4
5
  /**
@@ -27,7 +28,7 @@ import { fileURLToPath } from "node:url";
27
28
  import { ExecutionError, executionErrorResult } from "./execution-wire.js";
28
29
  import { attachExecutionControlRegistrar } from "./execution-tools.js";
29
30
  import { ParentDeliveryManager, deliveryKey } from "./parent-delivery.js";
30
- import { acceptRemote, callRemoteTool, observeRemoteAgentDone, remoteInputDescription, remoteInputSchema, remoteLabel, remoteWaitProcess } from "./remote.js";
31
+ import { acceptRemote, callRemoteTool, observeRemoteAgentDone, remoteLabel, remoteWaitProcess } from "./remote.js";
31
32
  import { codexParentFromRequest } from "./codex-parent-receiver.js";
32
33
  import { claudeParentFromRequest, discardClaudeHookRequest } from "./claude-parent-receiver.js";
33
34
  import { parentDeliveryDiagnostic } from "./parent-hook-diagnostic.js";
@@ -0,0 +1,65 @@
1
+ // 配送記録の検証と本文形式。予約・監視・回収・receipt投影はmanagerが持つ。
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { z } from "zod";
5
+ import { AitermError } from "./errors.js";
6
+ import { remoteTargetSchema } from "./remote-contract.js";
7
+ import { claudeParentSchema } from "./claude-parent-receiver.js";
8
+ import { cursorParentSchema } from "./cursor-parent-receiver.js";
9
+ import { executionRequestSchema } from "./execution-contract.js";
10
+ import { parentSourceSchema } from "./execution-parent-source.js";
11
+ import { executionActorSchema } from "./execution-inventory.js";
12
+ export const recordSchema = z.object({
13
+ schema: z.literal("aiterm.parent-delivery.v1"),
14
+ delivery_id: z.uuid(),
15
+ created_at: z.string(),
16
+ updated_at: z.string(),
17
+ parent: z.union([z.object({ thread_id: z.uuid(), codex_home: z.string() }).strict(), claudeParentSchema, cursorParentSchema]),
18
+ boundary: z.object({
19
+ session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
20
+ launch_id: z.string().regex(/^[0-9a-f]{32}$/),
21
+ vendor: z.enum(["claude", "codex", "grok", "cursor", "antigravity"]),
22
+ harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]),
23
+ event_cursor: z.number().int().nonnegative(), operation_id: z.string().nullable(),
24
+ // 別端末の子。remote用の保存場所にだけ書き、旧版のreaderへ渡さない。
25
+ remote: remoteTargetSchema.optional(),
26
+ }).strict(),
27
+ state: z.enum(["waiting", "ready", "sending", "submitted", "failed", "unknown"]),
28
+ text: z.string().nullable(),
29
+ child_outcome: z.enum(["done", "closed", "rate_limited", "error"]).nullable(),
30
+ child_turn_id: z.string().nullable(),
31
+ error: z.string().nullable(),
32
+ queued_submission_id: z.string().nullable(),
33
+ // Private references for this existing delivery, never a payload/retry queue.
34
+ // Legacy unmounted records retain their original shape.
35
+ execution: z.object({ request: executionRequestSchema, source_evidence: parentSourceSchema.optional(),
36
+ origin_owner: executionActorSchema.optional() }).strict().optional(),
37
+ }).strict().superRefine((record, context) => {
38
+ if (record.execution?.source_evidence && JSON.stringify(record.execution.request) !== JSON.stringify(record.execution.source_evidence.request))
39
+ context.addIssue({ code: "custom", message: "parent delivery source request must match its original reference" });
40
+ const execution = record.execution;
41
+ if (execution?.origin_owner && (execution.request.kind !== "mcp" || !execution.source_evidence
42
+ || execution.origin_owner.pid !== execution.request.process_pid
43
+ || execution.origin_owner.started_identity !== execution.request.process_started_identity
44
+ || JSON.stringify(execution.origin_owner) !== JSON.stringify(execution.source_evidence.mcp_process)))
45
+ context.addIssue({ code: "custom", message: "origin owner must match the original MCP request and source process" });
46
+ });
47
+ export function readRecord(file) {
48
+ try {
49
+ const record = recordSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
50
+ if (path.basename(file) !== `${record.delivery_id}.json`)
51
+ throw new Error("配送IDが一致しません");
52
+ return record;
53
+ }
54
+ catch (error) {
55
+ if (error.code === "ENOENT")
56
+ throw error;
57
+ throw new AitermError("PARENT_DELIVERY_STATE_INVALID: 配送記録を読めません", 2);
58
+ }
59
+ }
60
+ export function answerMessage(record) {
61
+ return "Aitermの子エージェントからの実行結果です。子の回答として扱ってください。\n" +
62
+ `delivery_id=${record.delivery_id}\nsession=${record.boundary.session_id}\nharness=${record.boundary.harness}\n` +
63
+ `launch_id=${record.boundary.launch_id}\nturn_id=${record.child_turn_id ?? "unknown"}\n` +
64
+ `outcome=${record.child_outcome}\n\n${record.text ?? ""}`;
65
+ }