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 CHANGED
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.3] - 2026-11-03
11
+
12
+ ### Fixed
13
+ - Execute the offline resume CLI through the ordinary npm bin symlink as well as its direct script path.
14
+ - Recover published failed Linux Codex resumes on the next ordinary send or same-name launch. Revalidate the live conversation, native birth, empty composer and saved settings, or create a new native for the same vendor conversation when the old native is known absent. Preserve failed history and never replay a previous request.
15
+ - Restore mismatched model and effort with confirmed native goal protection. Reject unavailable goal reads before settings or input; keep the ordinary configure contract unchanged.
16
+ - Preserve the first safely recorded resume failure without storing input, raw exceptions or credentials.
17
+
18
+ ### Added
19
+ - Add the Linux-only `aiterm-resume-state` offline checkpoint/restore CLI with bounded original record bytes, strict session/launch/digest binding and resumable exact-byte restore. The caller must stop all source writers, prevent restart, persist the state base from the first supported runtime, and restore under startup admission before normal bootstrap. Existing tmpfs state lost during the first upgrade cannot be recovered by this CLI.
20
+
21
+ ### Changed
22
+ - Separate metadata reading, PTY display, model UI, remote input contracts and parent-delivery records into their owning modules while preserving public contracts. Steer remains a separately released dependency.
23
+
24
+ ### Upgrade and rollback
25
+ - Checkpoint preservation is opt-in through the documented offline supply contract. A successful snapshot is not proof that the source runtime stopped. Do not replay a restore input after ordinary bootstrap.
26
+ - Older versions do not understand the new recovery and restore records. Do not downgrade a recovered or restored state directory in place; use a separately retained compatible state and vendor conversation backup, or the ordinary explicitly chosen state reset. Published failed records are never converted to successful records.
27
+
10
28
  ## [0.63.2] - 2026-11-02
11
29
 
12
30
  ### Fixed
@@ -3005,7 +3023,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3005
3023
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3006
3024
  provenance.
3007
3025
 
3008
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.2...HEAD
3026
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.3...HEAD
3027
+ [0.63.3]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.2...v0.63.3
3009
3028
  [0.63.2]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.1...v0.63.2
3010
3029
  [0.63.1]: https://github.com/kitepon/aiterm-mcp/compare/v0.63.0...v0.63.1
3011
3030
  [0.63.0]: https://github.com/kitepon/aiterm-mcp/compare/v0.62.6...v0.63.0
package/README.ja.md CHANGED
@@ -209,7 +209,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
209
209
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
210
210
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
211
211
 
212
- **状態:** 開発継続中 · 現行公開版 **v0.63.2** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
212
+ **状態:** 開発継続中 · 現行公開版 **v0.63.3** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
213
213
 
214
214
  ### 更新と巻き戻し
215
215
 
@@ -870,3 +870,12 @@ Claude作成/目的文編集はcomposerとnative goal dialogの全行を確認
870
870
  Claudeのgoal入力は公式PID別の現在session記録も確認し、native session ID・process開始tick・PID namespaceを各入力境界で照合する。会話切替はgoal入力前に拒否し、入力後の所有喪失はunknownを保持する。会話を勝手に切り戻さない。この開始形式は現在Linuxで検証済みで、未検証OS/記録はunavailableとする。
871
871
 
872
872
  Grok 1.0.70のLinux読取は公式active_sessions.jsonのPID・開始tick・cwd・会話を元のTUIへ結ぶ。入力欄がidleなら、同じ会話への新しい公式status応答から「ゴールなし」又は既存goalを確認する。goal.nativeは保存snapshot、goal.current_statusは元workerの新しい状態・phase・token数・経過表示であり、保存phaseや会計を現在値へ代入しない。既にfullscreenのTUIなら、元workerを止めずに公式Goal詳細を開閉して実行中の状態も読む。current_status.sourceはgoal detail、正確なphaseとtokens_usedはnullとし、phase_display/status_display/budget_displayへ丸めを含むUI原文を保持する。画面モードを勝手に替えず、空の入力欄を保つ。minimalのbusy時は命令をキューへ積まず取得不能。ユーザー由来のclearだけは、同じ元workerの公式statusがUserPaused/Idleで空の入力欄で公式local命令を一回送る。新しいdurable clear応答・native state消失に加え、続く新しいstatusのgoalなしを確認する。作用が不明なら再送やGoal復元をせずunknownとする。他の変更操作は未対応。通常launcherからのmetadata結合は手修正なしで確認済み。他OSはnative登録と入力所有が未受入のため取得不能とし、Grok全対応とはしない。
873
+
874
+
875
+ ### オフラインでの復帰状態の保存と復元
876
+
877
+ `aiterm-resume-state checkpoint --session ID --launch LAUNCH` は非公開の保存データを標準出力へ、本文を含まない結果を標準エラーへ出す。`aiterm-resume-state restore --session ID --launch LAUNCH --sha256 SHA` は保存データを標準入力から読み、結果を標準出力へ出す。成功は終了コード0、拒否は2と固定文字列 `aiterm: RESUME_STATE_UNCONFIRMED`+LF(33 bytes)。保存データはLF込み16 MiBまで、結果は512 bytesまでである。
878
+
879
+ 対象はLinux/Codex。明示した永続保存先 `AITERM_STATE_BASE`、同じUIDと絶対パス、元のCodex会話記録の保持が必要。呼出側は保存前に元runtimeの全書込processを停止し、再起動を防ぐ。復元は新runtimeの起動時排他を取得してから、通常の初期化やnative起動より前に行う。保存成功は全process停止の証明にはならない。
880
+
881
+ 初回更新で既に失われた旧tmpfsの状態と、未配送の回答は復元しない。通常の初期化後に復元入力を再使用しない。復元した保存先を旧版へそのまま戻さず、互換性のある別の保存先と会話の控えを使うか、利用者が明示して状態を初期化する。詳細は[保存・復元の契約と図](https://github.com/kitepon/aiterm-mcp/blob/v0.63.3/docs/architecture/resume-checkpoint.md)と[更新・巻き戻し条件](CHANGELOG.md)を参照する。
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.63.2** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.63.3** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -944,3 +944,7 @@ Claude objective creation and replacement accept literal lines that can be fully
944
944
  Native Claude goal input also verifies the official per-PID current-session registration, including native session ID, process birth ticks and PID namespace before each input boundary. A switched conversation is refused before goal input; ownership loss after input remains unknown. No conversation is switched back automatically. This registration birth format is currently verified on Linux; unverified OS/registry data remains unavailable.
945
945
 
946
946
  The Linux Grok 1.0.70 inspector binds the native current-session registry to the original PID, birth ticks, cwd and conversation. A fresh local status reply confirms no goal or an existing goal when the composer is idle. `goal.native` is the persisted snapshot; `goal.current_status` holds the fresh worker status, phase, token count and exact elapsed display. Stored phase and accounting values are never substituted for these current values. An already fullscreen TUI can also expose its live Goal detail without stopping the worker: inspection opens and closes that native view, preserving an empty composer. Its `current_status.source` is `goal detail`; `phase` and exact `tokens_used` remain null while `phase_display`, `status_display` and `budget_display` preserve the UI text, including rounded usage. Inspection never changes the screen mode. Busy minimal views remain unavailable without queuing a command. A user-origin clear is supported only on the same worker with fresh UserPaused/Idle status and an empty composer: it submits the official local command once, requires its fresh durable-clear reply and deleted native state, then confirms a fresh no-goal status. Uncertain effects remain unknown without retry or restoring the goal. Other mutations remain unsupported. The ordinary launcher has been checked without manually editing its metadata. This adapter is limited to the verified Linux contract; other operating systems remain unavailable until their native registration and input ownership are accepted.
947
+
948
+ ### Offline resume checkpoint
949
+
950
+ `aiterm-resume-state checkpoint --session ID --launch LAUNCH` emits a private bundle on stdout and a safe receipt on stderr. `aiterm-resume-state restore --session ID --launch LAUNCH --sha256 SHA` reads that bundle on stdin and emits its receipt on stdout. This Linux/Codex scope requires the explicit persistent `AITERM_STATE_BASE`, the same UID/absolute paths and retained vendor rollout identity. The caller must stop all source writers and prevent restart before checkpoint; restore runs under startup admission before bootstrap or native startup. It does not recover already-lost legacy tmpfs state or migrate pending deliveries. The bundle is limited to 16 MiB including LF; the safe receipt is at most 512 bytes. Success exits 0; refusal exits 2 with `aiterm: RESUME_STATE_UNCONFIRMED` plus LF (33 bytes). See the [contract and diagram](https://github.com/kitepon/aiterm-mcp/blob/v0.63.3/docs/architecture/resume-checkpoint.md).
@@ -75,7 +75,7 @@ export function cancelAgentStopping(meta, anchor) {
75
75
  throw unavailable();
76
76
  fs.unlinkSync(file(meta, ".lifecycle.json"));
77
77
  }
78
- const resumeAttemptSchema = z.object({ schema: z.literal("aiterm.agent-resume-attempt.v1"), launch_id: launchId,
78
+ export const resumeAttemptSchema = z.object({ schema: z.literal("aiterm.agent-resume-attempt.v1"), launch_id: launchId,
79
79
  next_launch_id: launchId, state: z.enum(["resuming", "ready", "failed"]), at: z.iso.datetime(),
80
80
  recipe_digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
81
81
  export function readAgentResumeAttempt(meta) {
@@ -89,7 +89,7 @@ export function writeAgentResumeAttempt(meta, value) {
89
89
  throw unavailable();
90
90
  writeJson0600(file(meta, ".resume-attempt.json"), resumeAttemptSchema.parse(value));
91
91
  }
92
- const resumeNativeSchema = z.object({ schema: z.literal("aiterm.agent-resume-native.v1"), launch_id: launchId,
92
+ export const resumeNativeSchema = z.object({ schema: z.literal("aiterm.agent-resume-native.v1"), launch_id: launchId,
93
93
  native_id: z.string().regex(/^\$\d+$/), session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
94
94
  server_pid: z.number().int().positive(), server_started_identity: z.string().min(1),
95
95
  pane_id: z.string().regex(/^%\d+$/), pane_pid: z.number().int().positive(), pane_started_identity: z.string().min(1),
@@ -126,7 +126,7 @@ export function retireAgentIdleClock(meta, token) {
126
126
  return;
127
127
  fs.unlinkSync(file(meta, ".idle-clock.json"));
128
128
  }
129
- const resumeTemplateSchema = agentResumeRecipeSchema.omit({ vendor_session_id: true, fast: true }).extend({
129
+ export const resumeTemplateSchema = agentResumeRecipeSchema.omit({ vendor_session_id: true, fast: true }).extend({
130
130
  schema: z.literal("aiterm.agent-resume-template.v1"), state: z.enum(["confirmed", "unconfirmed"]),
131
131
  }).strict();
132
132
  export function readAgentResumeTemplate(meta) {
@@ -180,3 +180,54 @@ export function refreshAgentResumeRecipe(meta) {
180
180
  writeAgentResumeRecipe(meta, candidate.data);
181
181
  return candidate.data;
182
182
  }
183
+ export const resumeResolutionSchema = z.object({ schema: z.literal("aiterm.agent-resume-resolution.v1"),
184
+ launch_id: launchId, previous_launch_id: launchId, vendor_session_id: z.string().uuid(),
185
+ attempt_digest: z.string().regex(/^[a-f0-9]{64}$/), recipe_digest: z.string().regex(/^[a-f0-9]{64}$/),
186
+ resume_proof_digest: z.string().regex(/^[a-f0-9]{64}$/), native_digest: z.string().regex(/^[a-f0-9]{64}$/), at: z.iso.datetime(),
187
+ }).strict().refine(value => value.launch_id !== value.previous_launch_id);
188
+ export function agentResumeRecordDigest(value) {
189
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
190
+ }
191
+ export function readAgentResumeResolution(meta) {
192
+ const value = read(meta, ".resume-resolution.json", resumeResolutionSchema);
193
+ if (value && value.launch_id !== meta.launch_id)
194
+ throw unavailable();
195
+ return value;
196
+ }
197
+ export function writeAgentResumeResolution(meta, input) {
198
+ const value = resumeResolutionSchema.parse(input);
199
+ if (value.launch_id !== meta.launch_id)
200
+ throw unavailable();
201
+ writeJson0600(file(meta, ".resume-resolution.json"), value);
202
+ }
203
+ export const recoveryOriginSchema = z.object({ schema: z.literal("aiterm.agent-resume-recovery-origin.v1"),
204
+ launch_id: launchId, previous_launch_id: launchId, socket: z.string().min(1), at: z.iso.datetime(),
205
+ failed_attempt_digest: z.string().regex(/^[a-f0-9]{64}$/), recipe_digest: z.string().regex(/^[a-f0-9]{64}$/),
206
+ resume_proof_digest: z.string().regex(/^[a-f0-9]{64}$/), previous_native_digest: z.string().regex(/^[a-f0-9]{64}$/),
207
+ }).strict().refine(value => value.launch_id !== value.previous_launch_id);
208
+ export function readAgentResumeRecoveryOrigin(meta) {
209
+ const value = read(meta, ".resume-recovery-origin.json", recoveryOriginSchema);
210
+ if (value && value.launch_id !== meta.launch_id)
211
+ throw unavailable();
212
+ return value;
213
+ }
214
+ export function writeAgentResumeRecoveryOrigin(meta, input) {
215
+ const value = recoveryOriginSchema.parse(input);
216
+ if (value.launch_id !== meta.launch_id)
217
+ throw unavailable();
218
+ writeJson0600(file(meta, ".resume-recovery-origin.json"), value);
219
+ }
220
+ /** This authorizes a cold resume source, never a successful stop or native liveness. */
221
+ export function confirmedAgentResumeRecoveryOrigin(meta) {
222
+ const origin = readAgentResumeRecoveryOrigin(meta);
223
+ if (!origin)
224
+ return null;
225
+ const attempt = readAgentResumeAttempt({ aiterm_session: meta.aiterm_session, launch_id: origin.previous_launch_id });
226
+ const recipe = readAgentResumeRecipe(meta), native = readAgentResumeNative(meta);
227
+ if (meta.kind !== "codex" || meta.resumed_from !== origin.previous_launch_id || !attempt || attempt.state !== "failed"
228
+ || attempt.next_launch_id !== meta.launch_id || agentResumeRecordDigest(attempt) !== origin.failed_attempt_digest
229
+ || !recipe || recipe.vendor_session_id !== meta.vendor_session_id || agentResumeRecipeDigest(recipe) !== origin.recipe_digest
230
+ || !native || agentResumeRecordDigest(native) !== origin.previous_native_digest)
231
+ throw unavailable();
232
+ return origin;
233
+ }
@@ -0,0 +1,273 @@
1
+ // 起動記録の選択・検証・旧形式の読取。書込と進行状態は呼出元が所有する。
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { AitermError } from "./errors.js";
5
+ import { executionNativeBindingSchema } from "./execution-close.js";
6
+ import { OPERATION_ID_RE, agentManagedClaudeSettingsPath, agentClaudeResultPath } from "./harnesses/claude.js";
7
+ import { resolveAndValidateGrokAuth } from "./harnesses/grok.js";
8
+ import { assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, agentEventPath, agentLineageFields, LAUNCH_ID_RE, AGENT_LINEAGE_RE } from "./agent-shared.js";
9
+ 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;
10
+ function normalizeInitialPromptState(v) {
11
+ if (v === true)
12
+ return "pending";
13
+ if (v === false || v == null)
14
+ return "none";
15
+ if (v === "none" ||
16
+ v === "not_sent" ||
17
+ v === "sent" ||
18
+ v === "pending" ||
19
+ v === "done" ||
20
+ v === "failed") {
21
+ return v;
22
+ }
23
+ return "none";
24
+ }
25
+ function loadAgentLineageFields(m, required) {
26
+ const present = m.agent_role !== undefined ||
27
+ m.parent_session_id !== undefined ||
28
+ m.delegation_depth !== undefined ||
29
+ m.lineage !== undefined ||
30
+ m.delegation_allowed !== undefined;
31
+ if (!present && !required)
32
+ return {};
33
+ if (m.agent_role !== "subagent" ||
34
+ typeof m.parent_session_id !== "string" ||
35
+ !/^[A-Za-z0-9_-]{1,64}$/.test(m.parent_session_id) ||
36
+ !Number.isSafeInteger(m.delegation_depth) ||
37
+ m.delegation_depth < 1 ||
38
+ typeof m.lineage !== "string" ||
39
+ m.lineage.length > 4096 ||
40
+ !AGENT_LINEAGE_RE.test(m.lineage) ||
41
+ m.delegation_allowed !== true) {
42
+ throw new AitermError("agent metadata のsub-agent lineageが不正です", 2);
43
+ }
44
+ return agentLineageFields({
45
+ agentRole: "subagent",
46
+ parentSessionId: m.parent_session_id,
47
+ delegationDepth: m.delegation_depth,
48
+ lineage: m.lineage,
49
+ delegationAllowed: true,
50
+ });
51
+ }
52
+ export function loadAgentMetadata(name) {
53
+ assertSessionName(name);
54
+ const dir = agentsDir();
55
+ const files = fs
56
+ .readdirSync(dir)
57
+ .filter((f) => f.startsWith(`${name}.`) && f.endsWith(".agent.json"));
58
+ if (files.length === 0) {
59
+ if (readAgentGeneration(name))
60
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動記録がありません。", 2);
61
+ throw new AitermError(`session '${name}' は agent_done 管理セッションではありません。claude_agent/codex_agent 等の launcher で起動してください。`, 2);
62
+ }
63
+ const selectedFile = selectAgentMetadataFile(name, files);
64
+ let raw;
65
+ try {
66
+ raw = JSON.parse(fs.readFileSync(path.join(dir, selectedFile), "utf8"));
67
+ }
68
+ catch (e) {
69
+ throw new AitermError(`agent metadata を読めません: ${e.message}`, 2);
70
+ }
71
+ const m = raw;
72
+ if ((m.kind !== "claude" && m.kind !== "codex" && m.kind !== "grok" && m.kind !== "cursor" && m.kind !== "antigravity") ||
73
+ m.aiterm_session !== name ||
74
+ typeof m.launch_id !== "string" ||
75
+ !LAUNCH_ID_RE.test(m.launch_id)) {
76
+ throw new AitermError(`agent metadata が不正です: ${files[0]}`, 2);
77
+ }
78
+ const generation = readAgentGeneration(name);
79
+ if (m.resumed_from !== undefined && (typeof m.resumed_from !== "string" || !LAUNCH_ID_RE.test(m.resumed_from)
80
+ || generation?.launch_id !== m.launch_id || generation.previous_launch_id !== m.resumed_from))
81
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰した起動世代が一致しません。", 2);
82
+ const resumeFields = m.resumed_from === undefined ? {} : { resumed_from: m.resumed_from };
83
+ const expectedEvent = agentEventPath(name, m.launch_id);
84
+ if (m.event_file !== expectedEvent) {
85
+ throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
86
+ }
87
+ if (m.initial_prompt_delivery !== undefined && (!["not_requested", "not_sent", "submitted_unconfirmed", "started"].includes(m.initial_prompt_delivery.status)
88
+ || typeof m.initial_prompt_delivery.reason !== "string"
89
+ || ![true, false, null].includes(m.initial_prompt_delivery.turn_started)
90
+ || (m.initial_prompt_cursor !== null && !Number.isSafeInteger(m.initial_prompt_cursor))))
91
+ throw new AitermError("初手delivery metadataが不正です", 2);
92
+ const deliveryFields = m.initial_prompt_delivery === undefined ? {} : {
93
+ initial_prompt_delivery: m.initial_prompt_delivery, initial_prompt_cursor: m.initial_prompt_cursor,
94
+ };
95
+ const parsedNative = m.execution_native === undefined ? null : executionNativeBindingSchema.safeParse(m.execution_native);
96
+ if (parsedNative && !parsedNative.success)
97
+ throw new AitermError("agent native bindingが不正です", 2);
98
+ if (m.windows_launch_exit_tracked !== undefined && m.windows_launch_exit_tracked !== true)
99
+ throw new AitermError("Windows launch exit metadataが不正です", 2);
100
+ const executableFields = {
101
+ ...(m.windows_launch_exit_tracked === true ? { windows_launch_exit_tracked: true } : {}),
102
+ ...(m.agent_executable === undefined ? {} : { agent_executable: m.agent_executable }),
103
+ ...(parsedNative?.success ? { execution_native: parsedNative.data } : {}),
104
+ };
105
+ // 席のファストの状態と、起動・設定替えで渡したmodel(ADR 0114)。この項目より前の版が書いた控えには無い。
106
+ const fastFields = {
107
+ ...(typeof m.fast === "boolean" ? { fast: m.fast } : {}),
108
+ ...(typeof m.model === "string" || m.model === null ? { model: m.model } : {}),
109
+ };
110
+ 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")
111
+ ? { startup_process_shapes: m.startup_process_shapes } : {};
112
+ const startupFields = Array.isArray(m.startup_processes) && m.startup_processes.every((identity) => typeof identity === "string")
113
+ ? { startup_processes: m.startup_processes, ...startupShapes } : {};
114
+ if (m.kind === "antigravity") {
115
+ if (m.hook_route !== "shared_antigravity_home" || typeof m.antigravity_home !== "string" || !path.isAbsolute(m.antigravity_home)
116
+ || (m.vendor_session_id != null && (typeof m.vendor_session_id !== "string" || !UUID_RE.test(m.vendor_session_id))))
117
+ throw new AitermError("Antigravity metadataが不正です", 2);
118
+ return { kind: "antigravity", aiterm_session: name, launch_id: m.launch_id, event_file: expectedEvent,
119
+ cwd: typeof m.cwd === "string" ? m.cwd : null, created_at: typeof m.created_at === "string" ? m.created_at : "",
120
+ vendor_session_id: m.vendor_session_id ?? null, initial_prompt: normalizeInitialPromptState(m.initial_prompt),
121
+ hook_route: "shared_antigravity_home", antigravity_home: m.antigravity_home, node_platform: process.platform,
122
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
123
+ ...deliveryFields, ...executableFields, ...fastFields, ...startupFields, ...loadAgentLineageFields(m, true) };
124
+ }
125
+ if (m.kind === "claude") {
126
+ const expectedSettings = agentManagedClaudeSettingsPath(name, m.launch_id);
127
+ const expectedResult = agentClaudeResultPath(name, m.launch_id);
128
+ const launchOperationId = m.launch_operation_id ?? null;
129
+ const launchRequestDigest = m.launch_request_digest ?? null;
130
+ if (m.hook_route !== "shared_claude_settings" ||
131
+ m.claude_settings !== expectedSettings ||
132
+ typeof m.vendor_session_id !== "string" ||
133
+ !UUID_RE.test(m.vendor_session_id) ||
134
+ m.result_file !== expectedResult ||
135
+ (m.claude_home !== undefined && (typeof m.claude_home !== "string" || !path.isAbsolute(m.claude_home))) ||
136
+ ((launchOperationId === null) !== (launchRequestDigest === null)) ||
137
+ (launchOperationId !== null && !OPERATION_ID_RE.test(launchOperationId)) ||
138
+ (launchRequestDigest !== null && !OPERATION_ID_RE.test(launchRequestDigest))) {
139
+ throw new AitermError("agent metadata の path が現在の secure state root と一致しません", 2);
140
+ }
141
+ return {
142
+ kind: "claude",
143
+ aiterm_session: name,
144
+ launch_id: m.launch_id,
145
+ event_file: expectedEvent,
146
+ created_at: typeof m.created_at === "string" ? m.created_at : "",
147
+ cwd: typeof m.cwd === "string" ? m.cwd : null,
148
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
149
+ vendor_session_id: m.vendor_session_id,
150
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
151
+ ...deliveryFields,
152
+ ...executableFields,
153
+ ...fastFields,
154
+ ...resumeFields,
155
+ ...startupFields,
156
+ launch_operation_id: launchOperationId,
157
+ launch_request_digest: launchRequestDigest,
158
+ hook_route: "shared_claude_settings",
159
+ ...loadAgentLineageFields(m, true),
160
+ node_platform: process.platform,
161
+ claude_settings: expectedSettings,
162
+ ...(m.claude_home === undefined ? {} : { claude_home: m.claude_home }),
163
+ result_file: expectedResult,
164
+ };
165
+ }
166
+ if (m.kind === "codex") {
167
+ // codex_home は起動時に記録した per-launch の正本を信じる。現在の process env
168
+ // (realCodexHome())との等値を要求すると、席専用 CODEX_HOME で起動した正当な
169
+ // session が別の aiterm instance から全部拒否される(2026-08-22 実測: peertable の
170
+ // 席へ pty_key できず円卓が停止した)。検証は形(絶対パス)だけにする。
171
+ const recordedHome = m.codex_home;
172
+ if (m.hook_route !== "shared_codex_home" || m.completion_route !== "codex_transcript"
173
+ || typeof recordedHome !== "string" || !path.isAbsolute(recordedHome)) {
174
+ throw new AitermError("agent metadata の codex_home が不正です(絶対パスの記録が必要)", 2);
175
+ }
176
+ return {
177
+ kind: "codex",
178
+ aiterm_session: name,
179
+ launch_id: m.launch_id,
180
+ event_file: expectedEvent,
181
+ created_at: typeof m.created_at === "string" ? m.created_at : "",
182
+ cwd: typeof m.cwd === "string" ? m.cwd : null,
183
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
184
+ vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
185
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
186
+ ...deliveryFields,
187
+ ...executableFields,
188
+ ...fastFields,
189
+ ...resumeFields,
190
+ ...startupFields,
191
+ hook_route: "shared_codex_home",
192
+ completion_route: "codex_transcript",
193
+ ...loadAgentLineageFields(m, true),
194
+ node_platform: process.platform,
195
+ codex_home: recordedHome,
196
+ };
197
+ }
198
+ if (m.kind === "cursor") {
199
+ const recordedHome = m.cursor_home;
200
+ if (m.hook_route !== "shared_cursor_home" ||
201
+ m.completion_route !== "cursor_transcript" ||
202
+ typeof recordedHome !== "string" ||
203
+ !path.isAbsolute(recordedHome)) {
204
+ throw new AitermError("agent metadata の cursor_home が不正です(絶対パスの記録が必要)", 2);
205
+ }
206
+ return {
207
+ kind: "cursor",
208
+ aiterm_session: name,
209
+ launch_id: m.launch_id,
210
+ event_file: expectedEvent,
211
+ created_at: typeof m.created_at === "string" ? m.created_at : "",
212
+ cwd: typeof m.cwd === "string" ? m.cwd : null,
213
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
214
+ vendor_session_id: typeof m.vendor_session_id === "string" ? m.vendor_session_id : null,
215
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
216
+ ...deliveryFields,
217
+ ...executableFields,
218
+ ...fastFields,
219
+ ...resumeFields,
220
+ ...startupFields,
221
+ hook_route: "shared_cursor_home",
222
+ completion_route: "cursor_transcript",
223
+ ...loadAgentLineageFields(m, true),
224
+ node_platform: process.platform,
225
+ cursor_home: recordedHome,
226
+ };
227
+ }
228
+ // grok_home も codex_home と同じ理由で per-launch の記録値を正とする(席専用 GROK_HOME)。
229
+ // 認証正本の照合も記録された home に対して行う——現在の env の home と比較すると、
230
+ // 席専用 home で起動した session が別 instance から拒否される。
231
+ const recordedGrokHome = m.grok_home;
232
+ if (m.hook_route !== "shared_grok_home" ||
233
+ m.completion_route !== "grok_transcript" ||
234
+ typeof recordedGrokHome !== "string" ||
235
+ !path.isAbsolute(recordedGrokHome) ||
236
+ typeof m.vendor_session_id !== "string" ||
237
+ !UUID_RE.test(m.vendor_session_id)) {
238
+ throw new AitermError("agent metadata の grok_home が不正です(絶対パスの記録が必要)", 2);
239
+ }
240
+ const expectedAuthPath = resolveAndValidateGrokAuth(recordedGrokHome);
241
+ if ((typeof m.grok_auth_path === "string" ? m.grok_auth_path : null) !== expectedAuthPath) {
242
+ throw new AitermError("agent metadata の認証正本が現在の設定と一致しません", 2);
243
+ }
244
+ return {
245
+ kind: m.kind,
246
+ aiterm_session: name,
247
+ launch_id: m.launch_id,
248
+ event_file: expectedEvent,
249
+ created_at: typeof m.created_at === "string" ? m.created_at : "",
250
+ cwd: typeof m.cwd === "string" ? m.cwd : null,
251
+ ...(typeof m.write_scope === "string" ? { write_scope: m.write_scope } : {}),
252
+ vendor_session_id: m.vendor_session_id,
253
+ initial_prompt: normalizeInitialPromptState(m.initial_prompt),
254
+ ...deliveryFields,
255
+ ...executableFields,
256
+ ...fastFields,
257
+ ...startupFields,
258
+ hook_route: "shared_grok_home",
259
+ completion_route: "grok_transcript",
260
+ ...loadAgentLineageFields(m, true),
261
+ node_platform: process.platform,
262
+ grok_home: recordedGrokHome,
263
+ grok_auth_path: expectedAuthPath,
264
+ };
265
+ }
266
+ export function tryLoadAgentMetadata(name) {
267
+ try {
268
+ return loadAgentMetadata(name);
269
+ }
270
+ catch {
271
+ return null;
272
+ }
273
+ }
@@ -0,0 +1,7 @@
1
+ export function lineCounts(screen) {
2
+ const counts = new Map();
3
+ for (const line of screen.split("\n").map((value) => value.trim()).filter(Boolean)) {
4
+ counts.set(line, (counts.get(line) ?? 0) + 1);
5
+ }
6
+ return counts;
7
+ }
@@ -0,0 +1,72 @@
1
+ import fs from "node:fs";
2
+ import { z } from "zod";
3
+ import { agentMetadataPath, writeJson0600 } from "./agent-shared.js";
4
+ import { AitermError } from "./errors.js";
5
+ import { ExecutionError, executionErrorCodeSchema } from "./execution-wire.js";
6
+ import { ProcessProbeError } from "./process-runtime.js";
7
+ const launch = z.string().regex(/^[a-f0-9]{32}$/);
8
+ const systemCode = z.enum(["ETIMEDOUT", "ENOBUFS", "EAGAIN", "ENOENT", "EACCES", "ENOMEM", "EMFILE", "ENFILE", "E2BIG", "EPERM", "UNKNOWN"]);
9
+ const signal = z.enum(["SIGABRT", "SIGALRM", "SIGBUS", "SIGFPE", "SIGHUP", "SIGILL", "SIGINT", "SIGKILL", "SIGPIPE", "SIGQUIT", "SIGSEGV", "SIGTERM", "SIGTRAP", "SIGUSR1", "SIGUSR2"]);
10
+ const integer = z.number().int().safe();
11
+ const reason = z.enum(["composer_ready", "turn_running", "command_approval", "mcp_approval", "hooks_review", "rate_limit_model_switch",
12
+ "startup_dialog", "unknown_dialog", "unrecognized_screen", "vendor_onboarding_required", "tool_approval", "project_mcp_consent",
13
+ "session_missing", "pane_dead", "native_pane_process_unresolved", "harness_exited", "harness_start_unconfirmed",
14
+ "harness_process_unresolved", "harness_process_ambiguous", "harness_stopped", "unknown"]);
15
+ const readiness = z.object({ status: z.enum(["ready", "blocked"]), reason }).strict();
16
+ export const resumeFailurePhaseSchema = z.enum(["recipe_validation", "generation_preparation", "attempt_save", "native_create", "native_identity",
17
+ "environment_setup", "vendor_start", "generation_publish", "readiness", "configuration_restore", "ready_save"]);
18
+ const cause = z.discriminatedUnion("kind", [
19
+ z.object({ kind: z.literal("process_probe"), code: systemCode.nullable(), exit_code: integer.nullable(), signal: signal.nullable() }).strict(),
20
+ z.object({ kind: z.literal("system"), code: systemCode.nullable(), exit_code: z.null(), signal: z.null() }).strict(),
21
+ z.object({ kind: z.literal("execution"), code: executionErrorCodeSchema, exit_code: z.null(), signal: z.null() }).strict(),
22
+ z.object({ kind: z.literal("aiterm"), code: integer, exit_code: z.null(), signal: z.null() }).strict(),
23
+ z.object({ kind: z.literal("unknown"), code: z.null(), exit_code: z.null(), signal: z.null() }).strict(),
24
+ ]);
25
+ export const agentResumeFailureSchema = z.object({
26
+ schema: z.literal("aiterm.agent-resume-failure.v1"), session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), launch_id: launch,
27
+ previous_launch_id: launch, next_launch_id: launch.nullable(), phase: resumeFailurePhaseSchema, readiness: readiness.nullable(), cause,
28
+ body_input: z.literal("not_sent"), native_outcome: z.literal("unknown"), attempt_record: z.enum(["failed", "unknown", "not_created"]),
29
+ attempted_at: z.iso.datetime().nullable(), observed_at: z.iso.datetime(),
30
+ }).strict().refine(value => value.next_launch_id === null ? value.launch_id === value.previous_launch_id
31
+ : value.next_launch_id !== value.previous_launch_id && value.launch_id === value.next_launch_id);
32
+ export function safeResumeFailureCause(error) {
33
+ const unknown = { kind: "unknown", code: null, exit_code: null, signal: null };
34
+ try {
35
+ if (error instanceof ProcessProbeError)
36
+ return { kind: "process_probe", code: systemCode.safeParse(error.processFailure.code).data ?? null,
37
+ exit_code: integer.safeParse(error.processFailure.status).data ?? null, signal: signal.safeParse(error.processFailure.signal).data ?? null };
38
+ if (error instanceof ExecutionError)
39
+ return cause.parse({ kind: "execution", code: error.code, exit_code: null, signal: null });
40
+ if (error instanceof AitermError)
41
+ return cause.parse({ kind: "aiterm", code: error.code, exit_code: null, signal: null });
42
+ if (error instanceof Error && typeof error.code === "string")
43
+ return {
44
+ kind: "system", code: systemCode.safeParse(error.code).data ?? "UNKNOWN", exit_code: null, signal: null
45
+ };
46
+ }
47
+ catch { /* A broken error object must not replace the original failure. */ }
48
+ return unknown;
49
+ }
50
+ export function safeResumeReadiness(value) {
51
+ if (!value || (value.status !== "ready" && value.status !== "blocked"))
52
+ return null;
53
+ return { status: value.status, reason: reason.safeParse(value.reason).data ?? "unknown" };
54
+ }
55
+ /** Caller holds the seat send admission. Keep the first saved failure, including invalid existing files. */
56
+ export function recordAgentResumeFailure(input, error) {
57
+ try {
58
+ const value = agentResumeFailureSchema.parse({ ...input, schema: "aiterm.agent-resume-failure.v1", cause: safeResumeFailureCause(error),
59
+ body_input: "not_sent", native_outcome: "unknown", observed_at: new Date().toISOString() });
60
+ const file = agentMetadataPath(value.session_id, value.launch_id).replace(/\.agent\.json$/, ".resume-failure.json");
61
+ try {
62
+ fs.lstatSync(file);
63
+ return;
64
+ }
65
+ catch (error) {
66
+ if (error.code !== "ENOENT")
67
+ return;
68
+ }
69
+ writeJson0600(file, value);
70
+ }
71
+ catch { /* Diagnostics must not alter resume, its exception, or its attempt record. */ }
72
+ }
@@ -141,6 +141,7 @@ export function createEmpty0600(p) {
141
141
  export function shq(s) {
142
142
  return `'${s.replace(/'/g, "'\\''")}'`;
143
143
  }
144
+ export const AGENT_LINEAGE_RE = /^[A-Za-z0-9_.:-]+(?:>[A-Za-z0-9_.:-]+)*$/;
144
145
  export const LAUNCH_ID_RE = /^[0-9a-f]{32}$/;
145
146
  export const AGENT_DONE_POLL_MS = 100;
146
147
  // 完了待ちの中で画面を読む間隔。画面を読むたびにtmux(capture-pane)を1回起動するので、完了の見回りとは別に持つ。