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/parent-delivery.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { recordSchema, readRecord, answerMessage } from "./parent-delivery-record.js";
|
|
1
2
|
// Aitermが所有する、子の完了観測・回答本文の保存・親への配送。
|
|
2
3
|
import * as fs from "node:fs";
|
|
3
4
|
import * as path from "node:path";
|
|
@@ -7,54 +8,18 @@ import { ensureStateRoot, writeJson0600 } from "./agent-shared.js";
|
|
|
7
8
|
import { readProcessIdentities } from "./process-runtime.js";
|
|
8
9
|
import { deliveryOwnerPrefix } from "./parent-delivery-owners.js";
|
|
9
10
|
import { CodexDeliveryError, submitCodexParentAnswer, verifyCodexParent } from "./codex-parent-receiver.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
11
|
+
import { ClaudeDeliveryError, bindClaudeParentDelivery, submitClaudeParentAnswer, verifyClaudeParent } from "./claude-parent-receiver.js";
|
|
12
|
+
import { CursorDeliveryError, prepareCursorDelivery, submitCursorParentAnswer, verifyCursorParent } from "./cursor-parent-receiver.js";
|
|
12
13
|
import { cursorReceiveProcess } from "./cursor-parent-receive.js";
|
|
13
14
|
import { AitermError } from "./errors.js";
|
|
14
15
|
import { codexHookDeliveryState } from "./codex-hook-state.js";
|
|
15
|
-
import { answerAnywhere, observeAnywhere, remoteKey
|
|
16
|
+
import { answerAnywhere, observeAnywhere, remoteKey } from "./remote.js";
|
|
16
17
|
import { currentExecutionRequest } from "./execution-context.js";
|
|
17
18
|
import { ExecutionError } from "./execution-wire.js";
|
|
18
19
|
import { withExecutionPreparation } from "./execution-effect.js";
|
|
19
|
-
import { executionRequestSchema } from "./execution-contract.js";
|
|
20
20
|
import { parentSourceSchema } from "./execution-parent-source.js";
|
|
21
21
|
import { writeExecutionCheckpoint, syncExecutionDirectories } from "./execution-checkpoint.js";
|
|
22
22
|
import { executionActorSchema } from "./execution-inventory.js";
|
|
23
|
-
const recordSchema = z.object({
|
|
24
|
-
schema: z.literal("aiterm.parent-delivery.v1"),
|
|
25
|
-
delivery_id: z.uuid(),
|
|
26
|
-
created_at: z.string(),
|
|
27
|
-
updated_at: z.string(),
|
|
28
|
-
parent: z.union([z.object({ thread_id: z.uuid(), codex_home: z.string() }).strict(), claudeParentSchema, cursorParentSchema]),
|
|
29
|
-
boundary: z.object({
|
|
30
|
-
session_id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
|
|
31
|
-
launch_id: z.string().regex(/^[0-9a-f]{32}$/),
|
|
32
|
-
vendor: z.enum(["claude", "codex", "grok", "cursor", "antigravity"]),
|
|
33
|
-
harness: z.enum(["claude-code", "codex-cli", "grok-cli", "cursor-cli", "antigravity-cli"]),
|
|
34
|
-
event_cursor: z.number().int().nonnegative(), operation_id: z.string().nullable(),
|
|
35
|
-
// 別端末の子。remote用の保存場所にだけ書き、旧版のreaderへ渡さない。
|
|
36
|
-
remote: remoteTargetSchema.optional(),
|
|
37
|
-
}).strict(),
|
|
38
|
-
state: z.enum(["waiting", "ready", "sending", "submitted", "failed", "unknown"]),
|
|
39
|
-
text: z.string().nullable(),
|
|
40
|
-
child_outcome: z.enum(["done", "closed", "rate_limited", "error"]).nullable(),
|
|
41
|
-
child_turn_id: z.string().nullable(),
|
|
42
|
-
error: z.string().nullable(),
|
|
43
|
-
queued_submission_id: z.string().nullable(),
|
|
44
|
-
// Private references for this existing delivery, never a payload/retry queue.
|
|
45
|
-
// Legacy unmounted records retain their original shape.
|
|
46
|
-
execution: z.object({ request: executionRequestSchema, source_evidence: parentSourceSchema.optional(),
|
|
47
|
-
origin_owner: executionActorSchema.optional() }).strict().optional(),
|
|
48
|
-
}).strict().superRefine((record, context) => {
|
|
49
|
-
if (record.execution?.source_evidence && JSON.stringify(record.execution.request) !== JSON.stringify(record.execution.source_evidence.request))
|
|
50
|
-
context.addIssue({ code: "custom", message: "parent delivery source request must match its original reference" });
|
|
51
|
-
const execution = record.execution;
|
|
52
|
-
if (execution?.origin_owner && (execution.request.kind !== "mcp" || !execution.source_evidence
|
|
53
|
-
|| execution.origin_owner.pid !== execution.request.process_pid
|
|
54
|
-
|| execution.origin_owner.started_identity !== execution.request.process_started_identity
|
|
55
|
-
|| JSON.stringify(execution.origin_owner) !== JSON.stringify(execution.source_evidence.mcp_process)))
|
|
56
|
-
context.addIssue({ code: "custom", message: "origin owner must match the original MCP request and source process" });
|
|
57
|
-
});
|
|
58
23
|
/** 子の予約と連続依頼の単位。別端末の子は接続先ごとに分け、この端末の同名sessionと衝突させない。 */
|
|
59
24
|
export function deliveryKey(sessionId, remote) {
|
|
60
25
|
return remote ? `remote-${remoteKey(remote)}-${sessionId}` : sessionId;
|
|
@@ -120,19 +85,6 @@ function ownerSetupInProgress(directory) {
|
|
|
120
85
|
return false;
|
|
121
86
|
}
|
|
122
87
|
}
|
|
123
|
-
function readRecord(file) {
|
|
124
|
-
try {
|
|
125
|
-
const record = recordSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
126
|
-
if (path.basename(file) !== `${record.delivery_id}.json`)
|
|
127
|
-
throw new Error("配送IDが一致しません");
|
|
128
|
-
return record;
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
if (error.code === "ENOENT")
|
|
132
|
-
throw error;
|
|
133
|
-
throw new AitermError("PARENT_DELIVERY_STATE_INVALID: 配送記録を読めません", 2);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
88
|
function receipt(record) {
|
|
137
89
|
const hookState = isCodex(record.parent) && record.state === "submitted"
|
|
138
90
|
? codexHookDeliveryState(record.parent.codex_home, record.parent.thread_id, record.delivery_id) : null;
|
|
@@ -141,12 +93,6 @@ function receipt(record) {
|
|
|
141
93
|
error_code: hookState === "unknown" ? "CODEX_HOOK_DELIVERY_UNCONFIRMED"
|
|
142
94
|
: record.error ? /^[A-Z][A-Z0-9_]+(?=:)/.exec(record.error)?.[0] ?? "PARENT_DELIVERY_FAILED" : null };
|
|
143
95
|
}
|
|
144
|
-
function answerMessage(record) {
|
|
145
|
-
return "Aitermの子エージェントからの実行結果です。子の回答として扱ってください。\n" +
|
|
146
|
-
`delivery_id=${record.delivery_id}\nsession=${record.boundary.session_id}\nharness=${record.boundary.harness}\n` +
|
|
147
|
-
`launch_id=${record.boundary.launch_id}\nturn_id=${record.child_turn_id ?? "unknown"}\n` +
|
|
148
|
-
`outcome=${record.child_outcome}\n\n${record.text ?? ""}`;
|
|
149
|
-
}
|
|
150
96
|
/** ownerごとのディレクトリ間renameで、再起動後の回収者を一つに決める。 */
|
|
151
97
|
export class ParentDeliveryManager {
|
|
152
98
|
deps;
|
package/dist/process-runtime.js
CHANGED
|
@@ -91,6 +91,13 @@ export function windowsConsoleHost(row) {
|
|
|
91
91
|
const name = (row.executable || first?.[1] || first?.[2] || "").replace(/\\/g, "/");
|
|
92
92
|
return path.posix.basename(name).toLowerCase() === "conhost.exe";
|
|
93
93
|
}
|
|
94
|
+
export class ProcessProbeError extends AitermError {
|
|
95
|
+
processFailure;
|
|
96
|
+
constructor(message, processFailure) {
|
|
97
|
+
super(message, 2);
|
|
98
|
+
this.processFailure = processFailure;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
94
101
|
function processReadError(probe, result) {
|
|
95
102
|
const code = result.error?.code;
|
|
96
103
|
// Native error messages and stderr can contain argv and credentials.
|
|
@@ -98,7 +105,7 @@ function processReadError(probe, result) {
|
|
|
98
105
|
? (code && ["ETIMEDOUT", "ENOBUFS", "EAGAIN", "ENOENT", "EACCES", "ENOMEM", "EMFILE", "ENFILE", "E2BIG", "EPERM"].includes(code) ? code : "UNKNOWN") : null,
|
|
99
106
|
status: result.status ?? null, signal: result.signal ?? null,
|
|
100
107
|
stdout_bytes: Buffer.byteLength(result.stdout ?? ""), stderr_bytes: Buffer.byteLength(result.stderr ?? "") };
|
|
101
|
-
return new
|
|
108
|
+
return new ProcessProbeError(`${isWin ? "Windowsのnative process" : "OSのprocess"}一覧を取得できません ${JSON.stringify(detail)}`, Object.freeze({ code: detail.code, status: detail.status, signal: detail.signal }));
|
|
102
109
|
}
|
|
103
110
|
export function readRuntimeProcesses(includeSession = false) {
|
|
104
111
|
if (!isWin) {
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// PTY表示の純粋な縮約。入力・native操作・完了判定はcoreが所有する。
|
|
2
|
+
// 出力削減(RTK の CAP 思想を移植)
|
|
3
|
+
const MAX_LINES_BEFORE_ELIDE = 60;
|
|
4
|
+
const HEAD_LINES = 30;
|
|
5
|
+
const TAIL_LINES = 20;
|
|
6
|
+
const MAX_LINE_CHARS_BEFORE_ELIDE = 2000;
|
|
7
|
+
const LINE_HEAD_CHARS = 1200;
|
|
8
|
+
const LINE_TAIL_CHARS = 600;
|
|
9
|
+
const DEDUP_MIN_RUN = 3; // 同一行がこれ以上連続したら 1 行+件数に畳む
|
|
10
|
+
// CSI/OSC/ESC エスケープ・制御文字
|
|
11
|
+
// CSI / OSC(BEL or ST 終端) / DCS・PM・APC・SOS(ESC P/^/_/X … BEL or ST 終端。ペイロード本文ごと除去=B10) / 残る2文字エスケープ
|
|
12
|
+
export const ANSI_RE = /\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P^_X][\s\S]*?(?:\x07|\x1b\\)|\x1b[@-_]/g;
|
|
13
|
+
export const CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; // \t(09) \n(0a) は残す
|
|
14
|
+
export function estimateTokens(s) {
|
|
15
|
+
return Math.ceil(s.length / 4.0);
|
|
16
|
+
}
|
|
17
|
+
export function stripControl(text) {
|
|
18
|
+
// OSC/DCS等の本文内のCRを、印字された進捗断片として扱わない。
|
|
19
|
+
text = text.replace(ANSI_RE, sequence => sequence.startsWith("\x1b[") ? sequence : "");
|
|
20
|
+
text = text.replace(/\r\n/g, "\n"); // CRLF 正規化
|
|
21
|
+
const out = [];
|
|
22
|
+
for (const line of text.split("\n")) {
|
|
23
|
+
let visibleLine = "";
|
|
24
|
+
for (const part of line.split("\r")) {
|
|
25
|
+
const visible = part.replace(ANSI_RE, "").replace(CTRL_RE, "");
|
|
26
|
+
// CRとcursor表示切替だけでは、既に印字した結果や完了印を消さない。
|
|
27
|
+
if (visible !== "" || /\x1b\[[0-2]?K/.test(part))
|
|
28
|
+
visibleLine = visible;
|
|
29
|
+
}
|
|
30
|
+
out.push(visibleLine.replace(/\s+$/, "")); // rstrip
|
|
31
|
+
}
|
|
32
|
+
return out.join("\n");
|
|
33
|
+
}
|
|
34
|
+
function collapseBlanks(lines) {
|
|
35
|
+
const out = [];
|
|
36
|
+
let blanks = 0;
|
|
37
|
+
for (const ln of lines) {
|
|
38
|
+
if (ln === "") {
|
|
39
|
+
blanks++;
|
|
40
|
+
if (blanks <= 1)
|
|
41
|
+
out.push(ln);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
blanks = 0;
|
|
45
|
+
out.push(ln);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
while (out.length && out[0] === "")
|
|
49
|
+
out.shift();
|
|
50
|
+
while (out.length && out[out.length - 1] === "")
|
|
51
|
+
out.pop();
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
function dedupRuns(lines) {
|
|
55
|
+
const out = [];
|
|
56
|
+
let i = 0;
|
|
57
|
+
const n = lines.length;
|
|
58
|
+
while (i < n) {
|
|
59
|
+
let j = i;
|
|
60
|
+
while (j < n && lines[j] === lines[i])
|
|
61
|
+
j++;
|
|
62
|
+
const run = j - i;
|
|
63
|
+
if (run >= DEDUP_MIN_RUN && lines[i] !== "")
|
|
64
|
+
out.push(`${lines[i]} 〈×${run}〉`);
|
|
65
|
+
else
|
|
66
|
+
out.push(...lines.slice(i, j));
|
|
67
|
+
i = j;
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
function surrogateSafeEnd(text, end) {
|
|
72
|
+
return end > 0 && end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end])
|
|
73
|
+
? end + 1
|
|
74
|
+
: end;
|
|
75
|
+
}
|
|
76
|
+
function surrogateSafeStart(text, start) {
|
|
77
|
+
return start > 0 && start < text.length && /[\uD800-\uDBFF]/.test(text[start - 1]) && /[\uDC00-\uDFFF]/.test(text[start])
|
|
78
|
+
? start - 1
|
|
79
|
+
: start;
|
|
80
|
+
}
|
|
81
|
+
function elideLongLines(lines) {
|
|
82
|
+
return lines.map((line) => {
|
|
83
|
+
if (line.length <= MAX_LINE_CHARS_BEFORE_ELIDE)
|
|
84
|
+
return line;
|
|
85
|
+
const headEnd = surrogateSafeEnd(line, LINE_HEAD_CHARS);
|
|
86
|
+
const tailStart = surrogateSafeStart(line, line.length - LINE_TAIL_CHARS);
|
|
87
|
+
const omitted = tailStart - headEnd;
|
|
88
|
+
return `${line.slice(0, headEnd)}… 〈行内 ${omitted} 文字省略。全文は raw:true か line_range で取得〉 …${line.slice(tailStart)}`;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** RTK 4戦略を移植: 制御除去 / 空白正規化 / 連続重複圧縮 / head+tail 折りたたみ。返り値 [body, meta]。 */
|
|
92
|
+
export function reduceOutput(raw, name, elide = true) {
|
|
93
|
+
const rawLinesN = (raw.match(/\n/g)?.length ?? 0) + (raw && !raw.endsWith("\n") ? 1 : 0);
|
|
94
|
+
const cleaned = stripControl(raw);
|
|
95
|
+
let lines = collapseBlanks(cleaned.split("\n"));
|
|
96
|
+
lines = dedupRuns(lines);
|
|
97
|
+
let elided = 0;
|
|
98
|
+
if (elide && lines.length > MAX_LINES_BEFORE_ELIDE) {
|
|
99
|
+
elided = lines.length - HEAD_LINES - TAIL_LINES;
|
|
100
|
+
const hint = `… 〈${elided} 行省略。全文は full=true、範囲は line_range="A:B"〉 …`;
|
|
101
|
+
lines = [...lines.slice(0, HEAD_LINES), hint, ...lines.slice(lines.length - TAIL_LINES)];
|
|
102
|
+
}
|
|
103
|
+
if (elide)
|
|
104
|
+
lines = elideLongLines(lines);
|
|
105
|
+
const body = lines.join("\n");
|
|
106
|
+
const meta = `[aiterm ${name}: ${lines.length} 行 / ~${estimateTokens(body)} tok ` +
|
|
107
|
+
`(raw ${rawLinesN} 行 / ~${estimateTokens(raw)} tok)` +
|
|
108
|
+
(elided ? `; ${elided} 行 hidden]` : "]");
|
|
109
|
+
return [body, meta];
|
|
110
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// ssh_configの接続名、DNS名、IPv4/IPv6。先頭の`-`はsshのoptionとして解釈されるため受け付けない。
|
|
3
|
+
const hostPattern = /^(?!-)[A-Za-z0-9._%:\[\]-]{1,255}$/;
|
|
4
|
+
const sshOptionPattern = /^[A-Za-z][A-Za-z0-9]*=[^\r\n]*$/;
|
|
5
|
+
const envNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
|
+
/** 記録に残してよい接続情報。パスフレーズ本文は含めない。 */
|
|
7
|
+
export const remoteTargetSchema = z.object({
|
|
8
|
+
host: z.string().regex(hostPattern),
|
|
9
|
+
user: z.string().regex(/^(?!-)[A-Za-z0-9._@\\-]{1,128}$/).optional(),
|
|
10
|
+
port: z.number().int().min(1).max(65535).optional(),
|
|
11
|
+
identity_file: z.string().min(1).optional(),
|
|
12
|
+
passphrase_env: z.string().regex(envNamePattern).optional(),
|
|
13
|
+
ssh_options: z.array(z.string().regex(sshOptionPattern)).max(32).optional(),
|
|
14
|
+
}).strict();
|
|
15
|
+
export const remoteInputSchema = remoteTargetSchema.extend({
|
|
16
|
+
passphrase: z.string().min(1).optional(),
|
|
17
|
+
}).strict().refine((value) => !(value.passphrase && value.passphrase_env), {
|
|
18
|
+
message: "passphraseとpassphrase_envは同時に指定できません",
|
|
19
|
+
});
|
|
20
|
+
export const remoteInputDescription = "別端末のAitermで実行する時のSSH接続情報。hostだけならssh_configの接続名として使う。" +
|
|
21
|
+
"Aitermは接続情報を保存・管理しない。passphraseは会話記録に残るため、ssh-agentかpassphrase_env(環境変数名)を推奨する。";
|
package/dist/remote.js
CHANGED
|
@@ -5,33 +5,13 @@ import * as fs from "node:fs";
|
|
|
5
5
|
import * as path from "node:path";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { createRequire } from "node:module";
|
|
8
|
-
import { z } from "zod";
|
|
9
8
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
10
9
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
11
10
|
import { AitermError, observeAgentDone, readAgentTranscriptResult, windowsStartProcessArgumentList } from "./core.js";
|
|
12
11
|
import { ensureStateRoot, stateRoot } from "./agent-shared.js";
|
|
13
12
|
import { currentUid } from "./state-root.js";
|
|
14
13
|
const pkg = createRequire(import.meta.url)("../package.json");
|
|
15
|
-
|
|
16
|
-
const hostPattern = /^(?!-)[A-Za-z0-9._%:\[\]-]{1,255}$/;
|
|
17
|
-
const sshOptionPattern = /^[A-Za-z][A-Za-z0-9]*=[^\r\n]*$/;
|
|
18
|
-
const envNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
19
|
-
/** 記録に残してよい接続情報。パスフレーズ本文は含めない。 */
|
|
20
|
-
export const remoteTargetSchema = z.object({
|
|
21
|
-
host: z.string().regex(hostPattern),
|
|
22
|
-
user: z.string().regex(/^(?!-)[A-Za-z0-9._@\\-]{1,128}$/).optional(),
|
|
23
|
-
port: z.number().int().min(1).max(65535).optional(),
|
|
24
|
-
identity_file: z.string().min(1).optional(),
|
|
25
|
-
passphrase_env: z.string().regex(envNamePattern).optional(),
|
|
26
|
-
ssh_options: z.array(z.string().regex(sshOptionPattern)).max(32).optional(),
|
|
27
|
-
}).strict();
|
|
28
|
-
export const remoteInputSchema = remoteTargetSchema.extend({
|
|
29
|
-
passphrase: z.string().min(1).optional(),
|
|
30
|
-
}).strict().refine((value) => !(value.passphrase && value.passphrase_env), {
|
|
31
|
-
message: "passphraseとpassphrase_envは同時に指定できません",
|
|
32
|
-
});
|
|
33
|
-
export const remoteInputDescription = "別端末のAitermで実行する時のSSH接続情報。hostだけならssh_configの接続名として使う。" +
|
|
34
|
-
"Aitermは接続情報を保存・管理しない。passphraseは会話記録に残るため、ssh-agentかpassphrase_env(環境変数名)を推奨する。";
|
|
14
|
+
export { remoteTargetSchema, remoteInputSchema, remoteInputDescription } from "./remote-contract.js";
|
|
35
15
|
// 平文で受け取ったパスフレーズは、このMCP processのメモリにだけ置く。ControlMasterが落ちた後の再接続に使う。
|
|
36
16
|
const passphrases = new Map();
|
|
37
17
|
export function remoteKey(target) {
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { resumeCheckpointSchema, resumeCheckpointSuffixes, resumeCheckpointRecord, resumeCheckpointRecordPath, validateResumeCheckpoint, encodeResumeCheckpoint, decodeResumeCheckpoint, resumeCheckpointDigest, RESUME_CHECKPOINT_FILE_BYTES, RESUME_CHECKPOINT_MAX_BYTES } from './resume-checkpoint.js';
|
|
4
|
+
function refuse() { throw new Error('RESUME_STATE_UNCONFIRMED'); }
|
|
5
|
+
function directory(file, uid) {
|
|
6
|
+
const st = fs.lstatSync(file);
|
|
7
|
+
if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== uid || (st.mode & 0o077) !== 0 || fs.realpathSync(file) !== file)
|
|
8
|
+
refuse();
|
|
9
|
+
}
|
|
10
|
+
function stable(a, b) {
|
|
11
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
12
|
+
}
|
|
13
|
+
function readRecord(file, uid, optional) {
|
|
14
|
+
let fd;
|
|
15
|
+
try {
|
|
16
|
+
let item;
|
|
17
|
+
try {
|
|
18
|
+
item = fs.lstatSync(file);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (optional && error.code === 'ENOENT')
|
|
22
|
+
return null;
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
if (item.isSymbolicLink() || fs.realpathSync(file) !== file)
|
|
26
|
+
refuse();
|
|
27
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
28
|
+
const before = fs.fstatSync(fd);
|
|
29
|
+
if (!before.isFile() || before.uid !== uid || (before.mode & 0o077) !== 0 || before.size > RESUME_CHECKPOINT_FILE_BYTES)
|
|
30
|
+
refuse();
|
|
31
|
+
const bytes = Buffer.alloc(before.size);
|
|
32
|
+
let offset = 0;
|
|
33
|
+
while (offset < bytes.length) {
|
|
34
|
+
const n = fs.readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
35
|
+
if (!n)
|
|
36
|
+
refuse();
|
|
37
|
+
offset += n;
|
|
38
|
+
}
|
|
39
|
+
const after = fs.fstatSync(fd);
|
|
40
|
+
if (bytes.length !== before.size || !stable(before, after) || !stable(after, fs.lstatSync(file)))
|
|
41
|
+
refuse();
|
|
42
|
+
return bytes;
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
if (fd !== undefined)
|
|
46
|
+
fs.closeSync(fd);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Validate the retained vendor file; state-directory inode is deliberately not the vendor identity. */
|
|
50
|
+
export function verifyResumeCheckpointRoots(bundle) {
|
|
51
|
+
for (const record of bundle.records.filter(r => r.kind === 'proof')) {
|
|
52
|
+
const proof = JSON.parse(Buffer.from(record.bytes_base64, 'base64').toString('utf8'));
|
|
53
|
+
if (fs.realpathSync(proof.file) !== proof.file)
|
|
54
|
+
refuse();
|
|
55
|
+
const fd = fs.openSync(proof.file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
56
|
+
try {
|
|
57
|
+
const before = fs.fstatSync(fd), prefix = Buffer.alloc(proof.prefix_bytes);
|
|
58
|
+
if (!before.isFile() || before.uid !== bundle.scope.uid || (before.mode & 0o022) !== 0
|
|
59
|
+
|| String(before.dev) !== proof.device || String(before.ino) !== proof.inode || before.size < proof.cursor)
|
|
60
|
+
refuse();
|
|
61
|
+
if (fs.readSync(fd, prefix, 0, prefix.length, 0) !== prefix.length || resumeCheckpointDigest(prefix) !== proof.prefix_sha256
|
|
62
|
+
|| !stable(before, fs.fstatSync(fd)) || !stable(before, fs.lstatSync(proof.file)))
|
|
63
|
+
refuse();
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
fs.closeSync(fd);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Caller owns source shutdown and restart prevention. This function never creates state or locks. */
|
|
71
|
+
export function createOfflineResumeCheckpoint(session_id, launch_id) {
|
|
72
|
+
if (process.platform !== 'linux' || typeof process.getuid !== 'function')
|
|
73
|
+
refuse();
|
|
74
|
+
const state_base = process.env.AITERM_STATE_BASE, uid = process.getuid();
|
|
75
|
+
if (!state_base || !path.isAbsolute(state_base) || path.normalize(state_base) !== state_base)
|
|
76
|
+
refuse();
|
|
77
|
+
directory(state_base, uid);
|
|
78
|
+
const dir = path.join(state_base, `aiterm-mcp-${uid}`, 'agents');
|
|
79
|
+
directory(path.dirname(dir), uid);
|
|
80
|
+
directory(dir, uid);
|
|
81
|
+
// Parse target before deriving any path. Configuration/vendor fields are filled from selected metadata below.
|
|
82
|
+
const provisional = resumeCheckpointSchema.shape.scope.parse({ session_id, launch_id, uid, node_platform: 'linux', state_base,
|
|
83
|
+
socket: path.join(process.env.TMPDIR ?? '/tmp', 'claude-tmux-sockets', 'claude.sock'), configuration_root: '/placeholder', vendor_session_id: '00000000-0000-4000-8000-000000000000' });
|
|
84
|
+
const records = [], reads = new Map();
|
|
85
|
+
let total = 0;
|
|
86
|
+
const read = (id, kind, optional = false) => {
|
|
87
|
+
const file = resumeCheckpointRecordPath(provisional, { launch_id: id, kind }), bytes = readRecord(file, uid, optional);
|
|
88
|
+
reads.set(file, bytes);
|
|
89
|
+
if (bytes) {
|
|
90
|
+
total += Math.ceil(bytes.length / 3) * 4;
|
|
91
|
+
if (total > RESUME_CHECKPOINT_MAX_BYTES || records.length >= 512)
|
|
92
|
+
refuse();
|
|
93
|
+
records.push(resumeCheckpointRecord(id, kind, bytes));
|
|
94
|
+
}
|
|
95
|
+
return bytes;
|
|
96
|
+
};
|
|
97
|
+
read(launch_id, 'generation');
|
|
98
|
+
let id = launch_id;
|
|
99
|
+
const seen = new Set();
|
|
100
|
+
let selected;
|
|
101
|
+
while (id !== undefined) {
|
|
102
|
+
if (seen.has(id) || seen.size >= 64 || !/^[a-f0-9]{32}$/.test(id))
|
|
103
|
+
refuse();
|
|
104
|
+
seen.add(id);
|
|
105
|
+
const m = JSON.parse(read(id, 'metadata').toString('utf8'));
|
|
106
|
+
selected ??= m;
|
|
107
|
+
for (const kind of Object.keys(resumeCheckpointSuffixes))
|
|
108
|
+
if (kind !== 'generation' && kind !== 'metadata')
|
|
109
|
+
read(id, kind, true);
|
|
110
|
+
id = m.resumed_from;
|
|
111
|
+
}
|
|
112
|
+
const bundle = validateResumeCheckpoint({ schema: 'aiterm.resume-checkpoint.v1', scope: { ...provisional,
|
|
113
|
+
configuration_root: selected.codex_home, vendor_session_id: selected.vendor_session_id }, records });
|
|
114
|
+
verifyResumeCheckpointRoots(bundle);
|
|
115
|
+
for (const [file, bytes] of reads) {
|
|
116
|
+
const again = readRecord(file, uid, bytes === null);
|
|
117
|
+
if (bytes === null ? again !== null : !again?.equals(bytes))
|
|
118
|
+
refuse();
|
|
119
|
+
}
|
|
120
|
+
return encodeResumeCheckpoint(bundle);
|
|
121
|
+
}
|
|
122
|
+
/** Caller holds the runtime's startup admission: no bootstrap, normal client, or second restore runs concurrently. */
|
|
123
|
+
export function restoreOfflineResumeCheckpoint(bytes, expected, observeNative) {
|
|
124
|
+
const bundle = decodeResumeCheckpoint(bytes), scope = bundle.scope;
|
|
125
|
+
if (process.platform !== 'linux' || process.getuid?.() !== scope.uid || process.env.AITERM_STATE_BASE !== scope.state_base
|
|
126
|
+
|| expected.session_id !== scope.session_id || expected.launch_id !== scope.launch_id || expected.sha256 !== resumeCheckpointDigest(bytes)
|
|
127
|
+
|| scope.socket !== path.join(process.env.TMPDIR ?? '/tmp', 'claude-tmux-sockets', 'claude.sock'))
|
|
128
|
+
refuse();
|
|
129
|
+
directory(scope.state_base, scope.uid);
|
|
130
|
+
verifyResumeCheckpointRoots(bundle);
|
|
131
|
+
const absent = () => { const n = observeNative(); if (n.state !== 'known' || n.sessions.some(s => s.session_id === scope.session_id))
|
|
132
|
+
refuse(); };
|
|
133
|
+
absent();
|
|
134
|
+
const root = path.join(scope.state_base, `aiterm-mcp-${scope.uid}`), dir = path.join(root, 'agents');
|
|
135
|
+
for (const p of [root, dir]) {
|
|
136
|
+
try {
|
|
137
|
+
fs.mkdirSync(p, { mode: 0o700 });
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
if (e.code !== 'EEXIST')
|
|
141
|
+
throw e;
|
|
142
|
+
}
|
|
143
|
+
directory(p, scope.uid);
|
|
144
|
+
}
|
|
145
|
+
const journal = path.join(dir, scope.session_id + '.resume-restore.json'), stage = path.join(dir, scope.session_id + '.resume-restore.d');
|
|
146
|
+
const state = { schema: 'aiterm.resume-restore.v1', session_id: scope.session_id, launch_id: scope.launch_id, sha256: expected.sha256 };
|
|
147
|
+
let prior = readRecord(journal, scope.uid, true);
|
|
148
|
+
const allowed = new Set(bundle.records.map(r => path.basename(resumeCheckpointRecordPath(scope, r))));
|
|
149
|
+
allowed.add(path.basename(journal));
|
|
150
|
+
allowed.add(path.basename(stage));
|
|
151
|
+
const names = () => fs.readdirSync(dir).filter(n => n.startsWith(scope.session_id + '.'));
|
|
152
|
+
if (names().some(n => !allowed.has(n)))
|
|
153
|
+
refuse();
|
|
154
|
+
if (prior) {
|
|
155
|
+
const value = JSON.parse(prior.toString('utf8'));
|
|
156
|
+
if (JSON.stringify(value) !== JSON.stringify(state))
|
|
157
|
+
refuse();
|
|
158
|
+
}
|
|
159
|
+
else if (names().some(n => n !== path.basename(stage)))
|
|
160
|
+
refuse();
|
|
161
|
+
try {
|
|
162
|
+
fs.mkdirSync(stage, { mode: 0o700 });
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
if (e.code !== 'EEXIST')
|
|
166
|
+
throw e;
|
|
167
|
+
}
|
|
168
|
+
directory(stage, scope.uid);
|
|
169
|
+
for (const n of fs.readdirSync(stage)) {
|
|
170
|
+
if (!['journal.pending', 'record.pending'].includes(n))
|
|
171
|
+
refuse();
|
|
172
|
+
readRecord(path.join(stage, n), scope.uid, false);
|
|
173
|
+
// A crash may leave this name hard-linked to an already published record.
|
|
174
|
+
fs.unlinkSync(path.join(stage, n));
|
|
175
|
+
}
|
|
176
|
+
const syncDir = () => { const fd = fs.openSync(dir, 'r'); try {
|
|
177
|
+
fs.fsyncSync(fd);
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
fs.closeSync(fd);
|
|
181
|
+
} };
|
|
182
|
+
const publish = (file, data, pending) => {
|
|
183
|
+
const tmp = path.join(stage, pending), fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
184
|
+
try {
|
|
185
|
+
fs.writeFileSync(fd, data);
|
|
186
|
+
fs.fsyncSync(fd);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
fs.closeSync(fd);
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
fs.linkSync(tmp, file);
|
|
193
|
+
syncDir();
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
fs.unlinkSync(tmp);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
if (!prior)
|
|
200
|
+
publish(journal, Buffer.from(JSON.stringify(state) + '\n'), 'journal.pending');
|
|
201
|
+
const pointer = bundle.records.find(r => r.kind === 'generation');
|
|
202
|
+
const current = bundle.records.find(r => r.kind === 'metadata' && r.launch_id === scope.launch_id);
|
|
203
|
+
const ordered = [pointer, ...bundle.records.filter(r => r !== pointer && r !== current), current];
|
|
204
|
+
let changed = false;
|
|
205
|
+
// Detect every conflict before the first target-record write. Same-digest partial records remain exact-byte only.
|
|
206
|
+
for (const r of ordered) {
|
|
207
|
+
const old = readRecord(resumeCheckpointRecordPath(scope, r), scope.uid, true);
|
|
208
|
+
if (old && !old.equals(Buffer.from(r.bytes_base64, 'base64')))
|
|
209
|
+
refuse();
|
|
210
|
+
}
|
|
211
|
+
for (const r of ordered) {
|
|
212
|
+
absent();
|
|
213
|
+
const file = resumeCheckpointRecordPath(scope, r), data = Buffer.from(r.bytes_base64, 'base64');
|
|
214
|
+
if (readRecord(file, scope.uid, true))
|
|
215
|
+
continue;
|
|
216
|
+
publish(file, data, 'record.pending');
|
|
217
|
+
changed = true;
|
|
218
|
+
}
|
|
219
|
+
for (const r of ordered)
|
|
220
|
+
if (!readRecord(resumeCheckpointRecordPath(scope, r), scope.uid, false).equals(Buffer.from(r.bytes_base64, 'base64')))
|
|
221
|
+
refuse();
|
|
222
|
+
absent();
|
|
223
|
+
return changed ? 'restored' : 'already_restored';
|
|
224
|
+
}
|