coremind-runtime 0.3.1 → 0.7.0
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/README.md +49 -1
- package/dist/active-run-binding.d.ts +24 -0
- package/dist/active-run-binding.d.ts.map +1 -0
- package/dist/active-run-binding.js +22 -0
- package/dist/active-run-binding.js.map +1 -0
- package/dist/agent-driver.d.ts +139 -0
- package/dist/agent-driver.d.ts.map +1 -0
- package/dist/agent-driver.js +135 -0
- package/dist/agent-driver.js.map +1 -0
- package/dist/agent-factory.d.ts +10 -10
- package/dist/agent-factory.d.ts.map +1 -1
- package/dist/agent-factory.js +179 -14
- package/dist/agent-factory.js.map +1 -1
- package/dist/budget.d.ts +11 -1
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +59 -16
- package/dist/budget.js.map +1 -1
- package/dist/canonical-json.d.ts +3 -0
- package/dist/canonical-json.d.ts.map +1 -0
- package/dist/canonical-json.js +28 -0
- package/dist/canonical-json.js.map +1 -0
- package/dist/chat-session.d.ts +3 -0
- package/dist/chat-session.d.ts.map +1 -1
- package/dist/chat-session.js +5 -0
- package/dist/chat-session.js.map +1 -1
- package/dist/checkpoint.d.ts +25 -8
- package/dist/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +135 -52
- package/dist/checkpoint.js.map +1 -1
- package/dist/child-run.d.ts +344 -0
- package/dist/child-run.d.ts.map +1 -0
- package/dist/child-run.js +1373 -0
- package/dist/child-run.js.map +1 -0
- package/dist/child-runtime-adapter.d.ts +18 -0
- package/dist/child-runtime-adapter.d.ts.map +1 -0
- package/dist/child-runtime-adapter.js +309 -0
- package/dist/child-runtime-adapter.js.map +1 -0
- package/dist/compaction-projection.d.ts +5 -0
- package/dist/compaction-projection.d.ts.map +1 -1
- package/dist/compaction-projection.js +19 -1
- package/dist/compaction-projection.js.map +1 -1
- package/dist/context-lifecycle.d.ts +182 -0
- package/dist/context-lifecycle.d.ts.map +1 -0
- package/dist/context-lifecycle.js +455 -0
- package/dist/context-lifecycle.js.map +1 -0
- package/dist/context-task-state.d.ts +23 -0
- package/dist/context-task-state.d.ts.map +1 -0
- package/dist/context-task-state.js +183 -0
- package/dist/context-task-state.js.map +1 -0
- package/dist/control-inbox.d.ts +106 -0
- package/dist/control-inbox.d.ts.map +1 -0
- package/dist/control-inbox.js +291 -0
- package/dist/control-inbox.js.map +1 -0
- package/dist/delegated-context.d.ts +29 -0
- package/dist/delegated-context.d.ts.map +1 -0
- package/dist/delegated-context.js +76 -0
- package/dist/delegated-context.js.map +1 -0
- package/dist/delegation-tool.d.ts +30 -0
- package/dist/delegation-tool.d.ts.map +1 -0
- package/dist/delegation-tool.js +232 -0
- package/dist/delegation-tool.js.map +1 -0
- package/dist/effect-receipt-binding.d.ts +34 -0
- package/dist/effect-receipt-binding.d.ts.map +1 -0
- package/dist/effect-receipt-binding.js +125 -0
- package/dist/effect-receipt-binding.js.map +1 -0
- package/dist/errors.d.ts +11 -315
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +7 -129
- package/dist/errors.js.map +1 -1
- package/dist/evaluation.d.ts.map +1 -1
- package/dist/evaluation.js +12 -5
- package/dist/evaluation.js.map +1 -1
- package/dist/events.d.ts +91 -3
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +44 -0
- package/dist/events.js.map +1 -1
- package/dist/execution-error.d.ts +14 -0
- package/dist/execution-error.d.ts.map +1 -0
- package/dist/execution-error.js +129 -0
- package/dist/execution-error.js.map +1 -0
- package/dist/execution-security.d.ts +11 -0
- package/dist/execution-security.d.ts.map +1 -0
- package/dist/execution-security.js +40 -0
- package/dist/execution-security.js.map +1 -0
- package/dist/fact-ledger.d.ts +60 -0
- package/dist/fact-ledger.d.ts.map +1 -0
- package/dist/fact-ledger.js +167 -0
- package/dist/fact-ledger.js.map +1 -0
- package/dist/ids.d.ts +4 -0
- package/dist/ids.d.ts.map +1 -1
- package/dist/ids.js.map +1 -1
- package/dist/index.d.ts +15 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +11 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +11 -0
- package/dist/internal.js.map +1 -0
- package/dist/invariant-checker.d.ts.map +1 -1
- package/dist/invariant-checker.js +51 -10
- package/dist/invariant-checker.js.map +1 -1
- package/dist/loop-runner.d.ts.map +1 -1
- package/dist/loop-runner.js +14 -8
- package/dist/loop-runner.js.map +1 -1
- package/dist/observability.d.ts +211 -0
- package/dist/observability.d.ts.map +1 -0
- package/dist/observability.js +814 -0
- package/dist/observability.js.map +1 -0
- package/dist/orchestrator.d.ts +2 -2
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +12 -6
- package/dist/orchestrator.js.map +1 -1
- package/dist/project-check.d.ts +3 -0
- package/dist/project-check.d.ts.map +1 -1
- package/dist/project-check.js +21 -5
- package/dist/project-check.js.map +1 -1
- package/dist/projection.d.ts +131 -0
- package/dist/projection.d.ts.map +1 -0
- package/dist/projection.js +972 -0
- package/dist/projection.js.map +1 -0
- package/dist/provider.d.ts +23 -1
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +134 -23
- package/dist/provider.js.map +1 -1
- package/dist/public-tool.d.ts +3 -0
- package/dist/public-tool.d.ts.map +1 -1
- package/dist/public-tool.js +28 -3
- package/dist/public-tool.js.map +1 -1
- package/dist/replay-kit.d.ts +41 -0
- package/dist/replay-kit.d.ts.map +1 -0
- package/dist/replay-kit.js +96 -0
- package/dist/replay-kit.js.map +1 -0
- package/dist/result.d.ts +17 -1
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +16 -0
- package/dist/result.js.map +1 -1
- package/dist/retry-policy.d.ts.map +1 -1
- package/dist/retry-policy.js +22 -72
- package/dist/retry-policy.js.map +1 -1
- package/dist/run-context.d.ts +77 -0
- package/dist/run-context.d.ts.map +1 -0
- package/dist/run-context.js +159 -0
- package/dist/run-context.js.map +1 -0
- package/dist/run-effect-coordinator.d.ts.map +1 -1
- package/dist/run-effect-coordinator.js +3 -0
- package/dist/run-effect-coordinator.js.map +1 -1
- package/dist/run-kernel.d.ts +14 -0
- package/dist/run-kernel.d.ts.map +1 -0
- package/dist/run-kernel.js +34 -0
- package/dist/run-kernel.js.map +1 -0
- package/dist/run-state.d.ts +65 -4
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +502 -76
- package/dist/run-state.js.map +1 -1
- package/dist/run-terminalizer.d.ts.map +1 -1
- package/dist/run-terminalizer.js +4 -3
- package/dist/run-terminalizer.js.map +1 -1
- package/dist/runtime-instance-authority.d.ts +3 -0
- package/dist/runtime-instance-authority.d.ts.map +1 -0
- package/dist/runtime-instance-authority.js +8 -0
- package/dist/runtime-instance-authority.js.map +1 -0
- package/dist/runtime.d.ts +83 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2048 -348
- package/dist/runtime.js.map +1 -1
- package/dist/session.d.ts +4 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js.map +1 -1
- package/dist/tool-call-lifecycle.d.ts +89 -0
- package/dist/tool-call-lifecycle.d.ts.map +1 -0
- package/dist/tool-call-lifecycle.js +379 -0
- package/dist/tool-call-lifecycle.js.map +1 -0
- package/dist/tool-capability-identity.d.ts +3 -0
- package/dist/tool-capability-identity.d.ts.map +1 -0
- package/dist/tool-capability-identity.js +5 -0
- package/dist/tool-capability-identity.js.map +1 -0
- package/dist/tool-capability-projection.d.ts +17 -0
- package/dist/tool-capability-projection.d.ts.map +1 -0
- package/dist/tool-capability-projection.js +99 -0
- package/dist/tool-capability-projection.js.map +1 -0
- package/dist/tool-effect-selectors.d.ts +3 -0
- package/dist/tool-effect-selectors.d.ts.map +1 -0
- package/dist/tool-effect-selectors.js +18 -0
- package/dist/tool-effect-selectors.js.map +1 -0
- package/dist/tool-policy.d.ts +13 -2
- package/dist/tool-policy.d.ts.map +1 -1
- package/dist/tool-policy.js +149 -44
- package/dist/tool-policy.js.map +1 -1
- package/dist/trace.d.ts +1 -0
- package/dist/trace.d.ts.map +1 -1
- package/dist/trace.js +10 -3
- package/dist/trace.js.map +1 -1
- package/dist/turn-tracker.d.ts.map +1 -1
- package/dist/turn-tracker.js +1 -0
- package/dist/turn-tracker.js.map +1 -1
- package/dist/workspace-lease.d.ts +81 -0
- package/dist/workspace-lease.d.ts.map +1 -0
- package/dist/workspace-lease.js +300 -0
- package/dist/workspace-lease.js.map +1 -0
- package/package.json +11 -5
package/dist/run-state.js
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { link, mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { isResolvedToolCapability, RECOVERY_DISPOSITIONS, recoveryDispositionFor, } from "coremind-tools";
|
|
5
|
+
import { canonicalJson as stableJson } from "./canonical-json.js";
|
|
6
|
+
import { validateEffectReceiptBindingsAgainstFacts } from "./effect-receipt-binding.js";
|
|
4
7
|
import { CoreMindError } from "./errors.js";
|
|
5
|
-
import {
|
|
8
|
+
import { FactLedger, flushFactLedgerWith, } from "./fact-ledger.js";
|
|
9
|
+
import { foldInputReceipts, inputFingerprint } from "./input-receipt.js";
|
|
6
10
|
import { restoreDurableOperation, } from "./operation-state.js";
|
|
11
|
+
import { projectToolCallLifecycles, validateToolCallLifecycleFact } from "./tool-call-lifecycle.js";
|
|
12
|
+
import { toolCapabilityCallKey } from "./tool-capability-identity.js";
|
|
13
|
+
import { projectToolCapabilities } from "./tool-capability-projection.js";
|
|
7
14
|
export class FileRunStore {
|
|
8
15
|
directory;
|
|
9
16
|
options;
|
|
17
|
+
supportedDurability = ["ordinary", "critical"];
|
|
18
|
+
durabilityBoundary = "process_crash";
|
|
10
19
|
constructor(directory, options = {}) {
|
|
11
20
|
this.directory = directory;
|
|
12
21
|
this.options = options;
|
|
@@ -19,23 +28,7 @@ export class FileRunStore {
|
|
|
19
28
|
}
|
|
20
29
|
async append(record) {
|
|
21
30
|
try {
|
|
22
|
-
|
|
23
|
-
validateRecord(record, record.runId);
|
|
24
|
-
await this.withWriterLock(destination, async () => {
|
|
25
|
-
const parsed = await this.readUnlocked(record.runId, destination);
|
|
26
|
-
const duplicate = parsed.records.find((item) => item.sequence === record.sequence);
|
|
27
|
-
if (duplicate) {
|
|
28
|
-
if (stableJson(duplicate) === stableJson(record))
|
|
29
|
-
return;
|
|
30
|
-
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
|
|
31
|
-
}
|
|
32
|
-
const expectedSequence = (parsed.records.at(-1)?.sequence ?? 0) + 1;
|
|
33
|
-
if (record.sequence !== expectedSequence) {
|
|
34
|
-
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
|
|
35
|
-
}
|
|
36
|
-
const text = `${parsed.records.map((item) => JSON.stringify(item)).join("\n")}${parsed.records.length > 0 ? "\n" : ""}${JSON.stringify(record)}\n`;
|
|
37
|
-
await this.publishAtomically(destination, text, record);
|
|
38
|
-
});
|
|
31
|
+
await this.writeRecord(record, "ordinary");
|
|
39
32
|
}
|
|
40
33
|
catch (error) {
|
|
41
34
|
if (error instanceof CoreMindError)
|
|
@@ -43,6 +36,42 @@ export class FileRunStore {
|
|
|
43
36
|
throw new CoreMindError("run_state_failed", `RunState 写入失败:${error instanceof Error ? error.message : String(error)}`);
|
|
44
37
|
}
|
|
45
38
|
}
|
|
39
|
+
async commit(record, durability) {
|
|
40
|
+
assertSupportedDurability(this, durability);
|
|
41
|
+
try {
|
|
42
|
+
await this.writeRecord(record, durability);
|
|
43
|
+
return durabilityAcknowledgement(this, durability);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof CoreMindError)
|
|
47
|
+
throw error;
|
|
48
|
+
const code = durability === "critical" ? "durability_barrier_failed" : "run_state_failed";
|
|
49
|
+
throw new CoreMindError(code, `RunState ${record.runId} 的 ${durability} commit 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async barrier(runId, requested) {
|
|
53
|
+
assertSupportedDurability(this, requested);
|
|
54
|
+
if (requested === "ordinary")
|
|
55
|
+
return durabilityAcknowledgement(this, requested);
|
|
56
|
+
const destination = this.pathFor(runId);
|
|
57
|
+
try {
|
|
58
|
+
return await this.withWriterLock(destination, async () => {
|
|
59
|
+
let handle;
|
|
60
|
+
try {
|
|
61
|
+
handle = await open(destination, "r+");
|
|
62
|
+
await this.options.beforeBarrier?.({ destination, runId, requested });
|
|
63
|
+
await handle.sync();
|
|
64
|
+
return durabilityAcknowledgement(this, requested);
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await handle?.close().catch(() => undefined);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw new CoreMindError("durability_barrier_failed", `RunState ${runId} 的 critical barrier 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
46
75
|
async read(runId) {
|
|
47
76
|
try {
|
|
48
77
|
const destination = this.pathFor(runId);
|
|
@@ -100,30 +129,97 @@ export class FileRunStore {
|
|
|
100
129
|
}
|
|
101
130
|
return { records };
|
|
102
131
|
}
|
|
103
|
-
async publishAtomically(destination, text, record) {
|
|
132
|
+
async publishAtomically(destination, text, record, durability = "ordinary") {
|
|
104
133
|
const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
|
|
105
134
|
try {
|
|
106
135
|
await writeFile(temporary, text, { encoding: "utf8", flag: "wx" });
|
|
107
136
|
await this.options.beforeCommit?.({ destination, temporary, record });
|
|
108
|
-
|
|
137
|
+
if (durability === "critical") {
|
|
138
|
+
let handle;
|
|
139
|
+
try {
|
|
140
|
+
handle = await open(temporary, "r+");
|
|
141
|
+
await this.options.beforeBarrier?.({
|
|
142
|
+
destination,
|
|
143
|
+
runId: record.runId,
|
|
144
|
+
requested: durability,
|
|
145
|
+
record,
|
|
146
|
+
});
|
|
147
|
+
await handle.sync();
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
await handle?.close().catch(() => undefined);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
await renameAtomically(temporary, destination);
|
|
109
154
|
}
|
|
110
155
|
finally {
|
|
111
156
|
await rm(temporary, { force: true }).catch(() => undefined);
|
|
112
157
|
}
|
|
113
158
|
}
|
|
159
|
+
async writeRecord(record, durability) {
|
|
160
|
+
const destination = this.pathFor(record.runId);
|
|
161
|
+
validateRecord(record, record.runId);
|
|
162
|
+
await this.withWriterLock(destination, async () => {
|
|
163
|
+
const parsed = await this.readUnlocked(record.runId, destination);
|
|
164
|
+
const duplicate = parsed.records.find((item) => item.sequence === record.sequence);
|
|
165
|
+
if (duplicate) {
|
|
166
|
+
if (stableJson(duplicate) === stableJson(record)) {
|
|
167
|
+
if (durability === "critical") {
|
|
168
|
+
let handle;
|
|
169
|
+
try {
|
|
170
|
+
handle = await open(destination, "r+");
|
|
171
|
+
await this.options.beforeBarrier?.({
|
|
172
|
+
destination,
|
|
173
|
+
runId: record.runId,
|
|
174
|
+
requested: durability,
|
|
175
|
+
record,
|
|
176
|
+
});
|
|
177
|
+
await handle.sync();
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
await handle?.close().catch(() => undefined);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
|
|
186
|
+
}
|
|
187
|
+
const expectedSequence = (parsed.records.at(-1)?.sequence ?? 0) + 1;
|
|
188
|
+
if (record.sequence !== expectedSequence) {
|
|
189
|
+
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
|
|
190
|
+
}
|
|
191
|
+
const text = `${parsed.records.map((item) => JSON.stringify(item)).join("\n")}${parsed.records.length > 0 ? "\n" : ""}${JSON.stringify(record)}\n`;
|
|
192
|
+
await this.publishAtomically(destination, text, record, durability);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
114
195
|
async withWriterLock(destination, operation) {
|
|
115
196
|
await mkdir(this.directory, { recursive: true });
|
|
116
197
|
const lockPath = `${destination}.lock`;
|
|
117
|
-
const deadline = Date.now() + (this.options.lockTimeoutMs ??
|
|
118
|
-
|
|
119
|
-
|
|
198
|
+
const deadline = Date.now() + (this.options.lockTimeoutMs ?? 10_000);
|
|
199
|
+
const owner = {
|
|
200
|
+
pid: process.pid,
|
|
201
|
+
createdAt: new Date().toISOString(),
|
|
202
|
+
nonce: randomUUID(),
|
|
203
|
+
};
|
|
204
|
+
let acquired = false;
|
|
205
|
+
let transientPermissionError;
|
|
206
|
+
while (!acquired) {
|
|
120
207
|
try {
|
|
121
|
-
|
|
208
|
+
await publishWriterLock(lockPath, owner);
|
|
209
|
+
acquired = true;
|
|
122
210
|
}
|
|
123
211
|
catch (error) {
|
|
124
|
-
|
|
212
|
+
const contention = await classifyWriterLockContention(error, lockPath);
|
|
213
|
+
if (contention === "not_contention")
|
|
125
214
|
throw error;
|
|
215
|
+
if (contention === "transient_missing")
|
|
216
|
+
transientPermissionError ??= error;
|
|
217
|
+
if (await this.reclaimStaleWriterLock(lockPath))
|
|
218
|
+
continue;
|
|
126
219
|
if (Date.now() >= deadline) {
|
|
220
|
+
if (contention === "transient_missing" && transientPermissionError) {
|
|
221
|
+
throw transientPermissionError;
|
|
222
|
+
}
|
|
127
223
|
throw new CoreMindError("run_state_locked", `RunState ${path.basename(destination)} 正由另一 writer 使用`);
|
|
128
224
|
}
|
|
129
225
|
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
@@ -133,14 +229,128 @@ export class FileRunStore {
|
|
|
133
229
|
return await operation();
|
|
134
230
|
}
|
|
135
231
|
finally {
|
|
136
|
-
await handle.close();
|
|
137
232
|
await rm(lockPath, { force: true });
|
|
138
233
|
}
|
|
139
234
|
}
|
|
235
|
+
async reclaimStaleWriterLock(lockPath) {
|
|
236
|
+
const inspected = await inspectWriterLock(lockPath);
|
|
237
|
+
if (inspected.state !== "valid" || isProcessAlive(inspected.owner.pid))
|
|
238
|
+
return false;
|
|
239
|
+
const claimPath = `${lockPath}.reclaim-${inspected.owner.nonce}`;
|
|
240
|
+
const tombstonePath = `${claimPath}.tombstone-${randomUUID()}`;
|
|
241
|
+
let claimHandle;
|
|
242
|
+
try {
|
|
243
|
+
claimHandle = await open(claimPath, "wx");
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
if (error.code === "EEXIST")
|
|
247
|
+
return false;
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
await claimHandle.writeFile(JSON.stringify({ pid: process.pid, ownerNonce: inspected.owner.nonce }), "utf8");
|
|
252
|
+
const current = await inspectWriterLock(lockPath);
|
|
253
|
+
if (current.state !== "valid" ||
|
|
254
|
+
current.owner.nonce !== inspected.owner.nonce ||
|
|
255
|
+
isProcessAlive(current.owner.pid)) {
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
// 固定 claim 文件由 wx 原子选出唯一回收者;只移动已复核的旧锁,随后只删 tombstone,
|
|
259
|
+
// 永远不对可能已由新 writer 重建的 lockPath 执行删除。
|
|
260
|
+
await rename(lockPath, tombstonePath);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
await claimHandle.close().catch(() => undefined);
|
|
265
|
+
await rm(tombstonePath, { force: true }).catch(() => undefined);
|
|
266
|
+
await rm(claimPath, { force: true }).catch(() => undefined);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async function publishWriterLock(lockPath, owner) {
|
|
271
|
+
const candidatePath = `${lockPath}.candidate-${owner.nonce}`;
|
|
272
|
+
try {
|
|
273
|
+
// 先完整并持久化候选文件,再通过 hard link 原子发布,避免崩溃留下无 owner 的空锁。
|
|
274
|
+
await writeFile(candidatePath, JSON.stringify(owner), {
|
|
275
|
+
encoding: "utf8",
|
|
276
|
+
flag: "wx",
|
|
277
|
+
flush: true,
|
|
278
|
+
});
|
|
279
|
+
await link(candidatePath, lockPath);
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
await rm(candidatePath, { force: true }).catch(() => undefined);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
const ATOMIC_RENAME_RETRY_DELAYS_MS = [5, 10, 20, 40, 80, 160, 320, 640, 1_280];
|
|
286
|
+
/** Windows 扫描器可能短暂占用新文件;只重试可恢复的 rename 错误。 */
|
|
287
|
+
async function renameAtomically(temporary, destination) {
|
|
288
|
+
for (let attempt = 0;; attempt += 1) {
|
|
289
|
+
try {
|
|
290
|
+
await rename(temporary, destination);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
const delay = ATOMIC_RENAME_RETRY_DELAYS_MS[attempt];
|
|
295
|
+
if (delay === undefined || !isTransientRenameError(error))
|
|
296
|
+
throw error;
|
|
297
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function isTransientRenameError(error) {
|
|
302
|
+
const code = error?.code;
|
|
303
|
+
return code === "EPERM" || code === "EACCES" || code === "EBUSY";
|
|
304
|
+
}
|
|
305
|
+
async function classifyWriterLockContention(error, lockPath) {
|
|
306
|
+
const code = error.code;
|
|
307
|
+
if (code === "EEXIST") {
|
|
308
|
+
return (await inspectWriterLock(lockPath)).state === "valid"
|
|
309
|
+
? "valid_contention"
|
|
310
|
+
: "path_contention";
|
|
311
|
+
}
|
|
312
|
+
if (process.platform !== "win32" || (code !== "EPERM" && code !== "EACCES")) {
|
|
313
|
+
return "not_contention";
|
|
314
|
+
}
|
|
315
|
+
const inspected = await inspectWriterLock(lockPath);
|
|
316
|
+
if (inspected.state === "valid")
|
|
317
|
+
return "valid_contention";
|
|
318
|
+
// 锁刚好消失时允许短暂重试,但若截止前从未观察到有效 owner,调用方保留原权限异常。
|
|
319
|
+
return inspected.state === "missing" ? "transient_missing" : "not_contention";
|
|
320
|
+
}
|
|
321
|
+
async function inspectWriterLock(lockPath) {
|
|
322
|
+
try {
|
|
323
|
+
const owner = JSON.parse(await readFile(lockPath, "utf8"));
|
|
324
|
+
if (typeof owner.pid === "number" &&
|
|
325
|
+
Number.isInteger(owner.pid) &&
|
|
326
|
+
owner.pid > 0 &&
|
|
327
|
+
typeof owner.nonce === "string" &&
|
|
328
|
+
owner.nonce.length > 0) {
|
|
329
|
+
return { state: "valid", owner: { pid: owner.pid, nonce: owner.nonce } };
|
|
330
|
+
}
|
|
331
|
+
return { state: "invalid" };
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
return error.code === "ENOENT"
|
|
335
|
+
? { state: "missing" }
|
|
336
|
+
: { state: "invalid" };
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function isProcessAlive(pid) {
|
|
340
|
+
try {
|
|
341
|
+
process.kill(pid, 0);
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
return error.code !== "ESRCH";
|
|
346
|
+
}
|
|
140
347
|
}
|
|
141
348
|
export class MemoryRunStore {
|
|
349
|
+
supportedDurability = ["ordinary"];
|
|
350
|
+
durabilityBoundary = "process_memory";
|
|
142
351
|
records = new Map();
|
|
143
352
|
async append(record) {
|
|
353
|
+
validateRecord(record, record.runId);
|
|
144
354
|
const items = this.records.get(record.runId) ?? [];
|
|
145
355
|
const duplicate = items.find((item) => item.sequence === record.sequence);
|
|
146
356
|
if (duplicate) {
|
|
@@ -155,23 +365,35 @@ export class MemoryRunStore {
|
|
|
155
365
|
items.push(structuredClone(record));
|
|
156
366
|
this.records.set(record.runId, items);
|
|
157
367
|
}
|
|
368
|
+
async commit(record, durability) {
|
|
369
|
+
assertSupportedDurability(this, durability);
|
|
370
|
+
await this.append(record);
|
|
371
|
+
return durabilityAcknowledgement(this, durability);
|
|
372
|
+
}
|
|
158
373
|
async read(runId) {
|
|
159
374
|
return structuredClone(this.records.get(runId) ?? []);
|
|
160
375
|
}
|
|
376
|
+
async barrier(_runId, requested) {
|
|
377
|
+
assertSupportedDurability(this, requested);
|
|
378
|
+
return durabilityAcknowledgement(this, requested);
|
|
379
|
+
}
|
|
161
380
|
}
|
|
162
381
|
/** 把同步事件串行化为 RunStore 的有序异步写入。 */
|
|
163
382
|
export class RunStateJournal {
|
|
164
383
|
runId;
|
|
165
384
|
store;
|
|
166
|
-
|
|
167
|
-
pending = Promise.resolve();
|
|
385
|
+
ledger;
|
|
168
386
|
aborted = false;
|
|
169
387
|
rejectedAfterAbortCount = 0;
|
|
170
388
|
knownTurnIds;
|
|
389
|
+
durabilityCounters = {
|
|
390
|
+
ordinary: { succeeded: 0, failed: 0 },
|
|
391
|
+
critical: { succeeded: 0, failed: 0 },
|
|
392
|
+
};
|
|
171
393
|
constructor(runId, store, initialSequence = 0) {
|
|
172
394
|
this.runId = runId;
|
|
173
395
|
this.store = store;
|
|
174
|
-
this.
|
|
396
|
+
this.ledger = new FactLedger(runId, store, initialSequence);
|
|
175
397
|
}
|
|
176
398
|
/**
|
|
177
399
|
* 取消收敛:设置事件准入分界点(规格 03 §3)。
|
|
@@ -204,8 +426,7 @@ export class RunStateJournal {
|
|
|
204
426
|
return true;
|
|
205
427
|
}
|
|
206
428
|
async start(payload) {
|
|
207
|
-
this.
|
|
208
|
-
await this.flush();
|
|
429
|
+
await this.appendFact("start", payload);
|
|
209
430
|
}
|
|
210
431
|
event(payload) {
|
|
211
432
|
this.enqueue("event", payload);
|
|
@@ -228,8 +449,37 @@ export class RunStateJournal {
|
|
|
228
449
|
finish(payload) {
|
|
229
450
|
this.enqueue("finish", payload);
|
|
230
451
|
}
|
|
231
|
-
async flush() {
|
|
232
|
-
|
|
452
|
+
async flush(durability = "ordinary") {
|
|
453
|
+
try {
|
|
454
|
+
const acknowledgement = await flushFactLedgerWith(this.ledger, async () => {
|
|
455
|
+
assertSupportedDurability(this.store, durability);
|
|
456
|
+
return this.store.barrier
|
|
457
|
+
? this.store.barrier(this.runId, durability)
|
|
458
|
+
: legacyDurabilityAcknowledgement(this.store, durability);
|
|
459
|
+
});
|
|
460
|
+
validateDurabilityAcknowledgement(this.store, durability, acknowledgement);
|
|
461
|
+
this.durabilityCounters[durability].succeeded += 1;
|
|
462
|
+
return acknowledgement;
|
|
463
|
+
}
|
|
464
|
+
catch (error) {
|
|
465
|
+
this.durabilityCounters[durability].failed += 1;
|
|
466
|
+
throw error;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
durabilityMetrics() {
|
|
470
|
+
return structuredClone(this.durabilityCounters);
|
|
471
|
+
}
|
|
472
|
+
appendFact(kind, payload, options = {}) {
|
|
473
|
+
return this.ledger.append(kind, payload, options);
|
|
474
|
+
}
|
|
475
|
+
factMetrics() {
|
|
476
|
+
return this.ledger.metrics();
|
|
477
|
+
}
|
|
478
|
+
factStatus() {
|
|
479
|
+
return this.ledger.status();
|
|
480
|
+
}
|
|
481
|
+
pendingFactCount() {
|
|
482
|
+
return this.ledger.metrics().pending;
|
|
233
483
|
}
|
|
234
484
|
enqueue(kind, payload) {
|
|
235
485
|
// 事件准入(规格 03 §3):分界点后的终态类事件拒绝写入,静默不抛错
|
|
@@ -237,39 +487,45 @@ export class RunStateJournal {
|
|
|
237
487
|
this.rejectedAfterAbortCount += 1;
|
|
238
488
|
return;
|
|
239
489
|
}
|
|
240
|
-
|
|
241
|
-
version: 1,
|
|
242
|
-
runId: this.runId,
|
|
243
|
-
sequence: ++this.sequence,
|
|
244
|
-
timestamp: new Date().toISOString(),
|
|
245
|
-
kind,
|
|
246
|
-
payload,
|
|
247
|
-
};
|
|
248
|
-
incrementPendingFlush(this);
|
|
249
|
-
this.pending = this.pending
|
|
250
|
-
.then(() => this.store.append(record))
|
|
251
|
-
.finally(() => decrementPendingFlush(this));
|
|
490
|
+
void this.appendFact(kind, payload);
|
|
252
491
|
}
|
|
253
492
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
function
|
|
261
|
-
|
|
493
|
+
function assertSupportedDurability(store, requested) {
|
|
494
|
+
const supported = store.supportedDurability ?? ["ordinary"];
|
|
495
|
+
if (supported.includes(requested))
|
|
496
|
+
return;
|
|
497
|
+
throw new CoreMindError("durability_unsupported", `RunStore 仅支持 ${supported.join(", ")},不能满足 ${requested}`);
|
|
498
|
+
}
|
|
499
|
+
function durabilityAcknowledgement(store, requested) {
|
|
500
|
+
return {
|
|
501
|
+
requested,
|
|
502
|
+
achieved: requested,
|
|
503
|
+
boundary: store.durabilityBoundary ?? "process_memory",
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function legacyDurabilityAcknowledgement(store, requested) {
|
|
507
|
+
assertSupportedDurability(store, requested);
|
|
508
|
+
if (requested === "critical") {
|
|
509
|
+
throw new CoreMindError("durability_unsupported", "旧 RunStore 未实现 critical barrier acknowledgement");
|
|
510
|
+
}
|
|
511
|
+
return durabilityAcknowledgement(store, requested);
|
|
262
512
|
}
|
|
263
|
-
function
|
|
264
|
-
const
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
513
|
+
function validateDurabilityAcknowledgement(store, requested, acknowledgement) {
|
|
514
|
+
const supported = store.supportedDurability ?? ["ordinary"];
|
|
515
|
+
const boundary = store.durabilityBoundary ?? "process_memory";
|
|
516
|
+
const achievedSatisfiesRequest = acknowledgement.achieved === "critical" || requested === "ordinary";
|
|
517
|
+
if (acknowledgement.requested === requested &&
|
|
518
|
+
achievedSatisfiesRequest &&
|
|
519
|
+
supported.includes(acknowledgement.achieved) &&
|
|
520
|
+
acknowledgement.boundary === boundary &&
|
|
521
|
+
!(requested === "critical" && boundary === "process_memory")) {
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
throw new CoreMindError("durability_barrier_failed", `RunStore 返回了与 ${requested}/${boundary} 不一致的 durability acknowledgement`);
|
|
269
525
|
}
|
|
270
526
|
/** journal 是否仍有未落盘的写入(规格 03 §5:静止条件之一) */
|
|
271
527
|
export function hasPendingJournalFlush(journal) {
|
|
272
|
-
return
|
|
528
|
+
return journal.pendingFactCount() > 0;
|
|
273
529
|
}
|
|
274
530
|
/**
|
|
275
531
|
* 准入判定:分界点后到达的终态类事件(规格 03 §3)。
|
|
@@ -295,15 +551,72 @@ export function isRejectedAfterAbort(payload, knownTurnIds) {
|
|
|
295
551
|
}
|
|
296
552
|
return false;
|
|
297
553
|
}
|
|
298
|
-
const REPLAY_SAFE_TOOLS = new Set(["read", "ls", "find", "grep", "web-fetch", "web-search"]);
|
|
299
554
|
/**
|
|
300
555
|
* resumable 安全门单点实现(缺口 G-1):
|
|
301
556
|
* 找出第一个副作用状态无法证明为 not_started 的非 replay-safe 工具调用。
|
|
302
557
|
* 快照 resumable 标志与恢复计划共用此判定,避免双实现漂移。
|
|
303
558
|
*/
|
|
304
559
|
export function findUnsafeToolCall(trace) {
|
|
560
|
+
const replayCandidateKeys = new Set(collectToolReplayCandidates(trace).map((candidate) => toolCapabilityCallKey(candidate.agent, candidate.stepId, candidate.previousCallId)));
|
|
561
|
+
const completedSteps = new Set(trace
|
|
562
|
+
.map((entry) => entry.event)
|
|
563
|
+
.filter((event) => event.type === "step_output")
|
|
564
|
+
.map((event) => event.stepId));
|
|
565
|
+
const lifecycleFacts = trace
|
|
566
|
+
.map((entry) => entry.event)
|
|
567
|
+
.filter((event) => event.type === "tool_lifecycle");
|
|
568
|
+
const lifecycleStates = projectToolCallLifecycles(lifecycleFacts);
|
|
569
|
+
const receiptByIdempotencyKey = new Map();
|
|
570
|
+
const receiptByLifecycleCall = new Map();
|
|
571
|
+
for (const entry of trace) {
|
|
572
|
+
const event = entry.event;
|
|
573
|
+
if (event.type === "effect_receipt") {
|
|
574
|
+
receiptByIdempotencyKey.set(event.idempotencyKey, event);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
for (const entry of trace) {
|
|
578
|
+
const event = entry.event;
|
|
579
|
+
if (event.type !== "tool_call" || !event.callId || !event.idempotencyKey)
|
|
580
|
+
continue;
|
|
581
|
+
const receipt = receiptByIdempotencyKey.get(event.idempotencyKey);
|
|
582
|
+
if (receipt) {
|
|
583
|
+
receiptByLifecycleCall.set(toolCapabilityCallKey(event.agent, event.stepId, event.callId), receipt);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const lifecycleCallKeys = new Set(lifecycleStates.map((state) => toolCapabilityCallKey(state.agent, state.stepId, state.callId)));
|
|
587
|
+
if (lifecycleFacts.length > 0) {
|
|
588
|
+
for (const state of lifecycleStates) {
|
|
589
|
+
if (state.stepId && completedSteps.has(state.stepId))
|
|
590
|
+
continue;
|
|
591
|
+
const receipt = receiptByLifecycleCall.get(toolCapabilityCallKey(state.agent, state.stepId, state.callId));
|
|
592
|
+
const effectState = state.result.effectState === "not_started" && receipt?.status === "started"
|
|
593
|
+
? "unknown"
|
|
594
|
+
: state.result.effectState === "not_started" &&
|
|
595
|
+
(receipt?.status === "committed" || receipt?.status === "unknown")
|
|
596
|
+
? receipt.status
|
|
597
|
+
: state.result.effectState;
|
|
598
|
+
if (effectState === "not_started")
|
|
599
|
+
continue;
|
|
600
|
+
if (state.result.recoveryDisposition === "replay_safe")
|
|
601
|
+
continue;
|
|
602
|
+
if (replayCandidateKeys.has(toolCapabilityCallKey(state.agent, state.stepId, state.callId))) {
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
tool: state.tool,
|
|
607
|
+
...(state.stepId ? { stepId: state.stepId } : {}),
|
|
608
|
+
...(receipt?.idempotencyKey ? { idempotencyKey: receipt.idempotencyKey } : {}),
|
|
609
|
+
receiptStatus: effectState,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
}
|
|
305
613
|
const receipts = new Map();
|
|
306
|
-
const
|
|
614
|
+
const capabilities = new Map(projectToolCapabilities(trace.map((entry) => entry.event))
|
|
615
|
+
.filter((projection) => projection.callId !== undefined)
|
|
616
|
+
.map((projection) => [
|
|
617
|
+
toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
|
|
618
|
+
projection,
|
|
619
|
+
]));
|
|
307
620
|
for (const entry of trace) {
|
|
308
621
|
const event = entry.event;
|
|
309
622
|
if (event.type === "effect_receipt")
|
|
@@ -315,13 +628,24 @@ export function findUnsafeToolCall(trace) {
|
|
|
315
628
|
const event = entry.event;
|
|
316
629
|
if (event.type !== "tool_call")
|
|
317
630
|
continue;
|
|
318
|
-
if (
|
|
631
|
+
if (event.callId &&
|
|
632
|
+
lifecycleCallKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
|
|
319
633
|
continue;
|
|
634
|
+
}
|
|
320
635
|
if (event.stepId && completedSteps.has(event.stepId))
|
|
321
636
|
continue;
|
|
322
637
|
const receipt = event.idempotencyKey ? receipts.get(event.idempotencyKey) : undefined;
|
|
323
638
|
if (receipt?.status === "not_started")
|
|
324
639
|
continue;
|
|
640
|
+
const capability = event.callId
|
|
641
|
+
? capabilities.get(toolCapabilityCallKey(event.agent, event.stepId, event.callId))
|
|
642
|
+
: undefined;
|
|
643
|
+
if (capability?.recoveryDisposition === "replay_safe")
|
|
644
|
+
continue;
|
|
645
|
+
if (event.callId &&
|
|
646
|
+
replayCandidateKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
325
649
|
return {
|
|
326
650
|
tool: event.tool,
|
|
327
651
|
...(event.stepId ? { stepId: event.stepId } : {}),
|
|
@@ -331,6 +655,62 @@ export function findUnsafeToolCall(trace) {
|
|
|
331
655
|
}
|
|
332
656
|
return undefined;
|
|
333
657
|
}
|
|
658
|
+
export function collectToolReplayCandidates(trace) {
|
|
659
|
+
const events = trace.map((entry) => entry.event);
|
|
660
|
+
const completedSteps = new Set(events.filter((event) => event.type === "step_output").map((event) => event.stepId));
|
|
661
|
+
const bindings = events.some((event) => event.type === "effect_receipt" && event.binding !== undefined)
|
|
662
|
+
? validateEffectReceiptBindingsAgainstFacts(trace[0]?.runId ?? "", events)
|
|
663
|
+
: [];
|
|
664
|
+
const bindingByReceipt = new Map(bindings.map((binding) => [binding.idempotencyKey, binding]));
|
|
665
|
+
const capabilityByCall = new Map(projectToolCapabilities(events)
|
|
666
|
+
.filter((projection) => projection.callId !== undefined)
|
|
667
|
+
.map((projection) => [
|
|
668
|
+
toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
|
|
669
|
+
projection,
|
|
670
|
+
]));
|
|
671
|
+
const priorAttemptByCall = new Map(events.flatMap((event) => event.type === "tool_attempt"
|
|
672
|
+
? [[toolCapabilityCallKey(event.agent, event.stepId, event.callId), event.attempt]]
|
|
673
|
+
: []));
|
|
674
|
+
const candidates = [];
|
|
675
|
+
for (const event of events) {
|
|
676
|
+
if (event.type !== "tool_call" ||
|
|
677
|
+
!event.callId ||
|
|
678
|
+
!event.idempotencyKey ||
|
|
679
|
+
(event.stepId && completedSteps.has(event.stepId))) {
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
const callKey = toolCapabilityCallKey(event.agent, event.stepId, event.callId);
|
|
683
|
+
const capability = capabilityByCall.get(callKey);
|
|
684
|
+
const receipt = bindingByReceipt.get(event.idempotencyKey);
|
|
685
|
+
if (capability?.capability.replay !== "idempotent" ||
|
|
686
|
+
capability.recoveryDisposition !== "requires_proof" ||
|
|
687
|
+
receipt?.provenance !== "bound" ||
|
|
688
|
+
!receipt.binding ||
|
|
689
|
+
(receipt.status !== "started" && receipt.status !== "unknown")) {
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
candidates.push({
|
|
693
|
+
previousReceiptId: event.idempotencyKey,
|
|
694
|
+
previousCallId: event.callId,
|
|
695
|
+
attempt: (priorAttemptByCall.get(callKey) ?? 1) + 1,
|
|
696
|
+
agent: event.agent,
|
|
697
|
+
tool: event.tool,
|
|
698
|
+
...(event.stepId ? { stepId: event.stepId } : {}),
|
|
699
|
+
argumentsFingerprint: receipt.binding.argumentsFingerprint,
|
|
700
|
+
capabilityFingerprint: receipt.binding.capabilityFingerprint,
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
return candidates;
|
|
704
|
+
}
|
|
705
|
+
/** 由 Runtime 单点判断持久化运行是否满足自动恢复的安全前提。 */
|
|
706
|
+
export function isRunStateResumable(records) {
|
|
707
|
+
if (records.length === 0 || records.some((record) => record.kind === "finish"))
|
|
708
|
+
return false;
|
|
709
|
+
const trace = records
|
|
710
|
+
.filter((record) => record.kind === "event")
|
|
711
|
+
.map((record) => tracePayload(record.payload, record.runId));
|
|
712
|
+
return inputReceiptsAreResumable(trace) && findUnsafeToolCall(trace) === undefined;
|
|
713
|
+
}
|
|
334
714
|
/** 从中断的 append-only RunState 构造安全恢复计划。 */
|
|
335
715
|
export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
336
716
|
if (records.length === 0)
|
|
@@ -405,6 +785,9 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
405
785
|
}
|
|
406
786
|
}
|
|
407
787
|
const operationSnapshot = operationSnapshotFromRecords(ordered);
|
|
788
|
+
if (!inputReceiptsAreResumable(previousTrace)) {
|
|
789
|
+
throw new CoreMindError("run_already_finished", "输入已到终态,不能自动恢复");
|
|
790
|
+
}
|
|
408
791
|
const unsafe = findUnsafeToolCall(previousTrace);
|
|
409
792
|
if (unsafe) {
|
|
410
793
|
if (unsafe.receiptStatus === "committed") {
|
|
@@ -419,12 +802,22 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
419
802
|
nextTraceSequence,
|
|
420
803
|
completedSteps,
|
|
421
804
|
effectReceipts,
|
|
805
|
+
toolReplayCandidates: collectToolReplayCandidates(previousTrace),
|
|
422
806
|
previousTrace,
|
|
423
807
|
operationRecords,
|
|
424
808
|
...(loopSnapshot ? { loopSnapshot } : {}),
|
|
425
809
|
...(operationSnapshot ? { operationSnapshot } : {}),
|
|
426
810
|
};
|
|
427
811
|
}
|
|
812
|
+
function inputReceiptsAreResumable(trace) {
|
|
813
|
+
try {
|
|
814
|
+
const statuses = foldInputReceipts(trace.map((entry) => entry.event));
|
|
815
|
+
return [...statuses.values()].every((status) => status === "pending" || status === "claimed");
|
|
816
|
+
}
|
|
817
|
+
catch (error) {
|
|
818
|
+
throw new CoreMindError("run_state_corrupt", `输入收据无法安全折叠:${error instanceof Error ? error.message : String(error)}`);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
428
821
|
/** 从 RunState 中校验并提取最新 operation 快照,供 CLI/SDK/Worker 共用。 */
|
|
429
822
|
export function operationSnapshotFromRecords(records) {
|
|
430
823
|
const operationRecords = records
|
|
@@ -436,7 +829,10 @@ export function operationSnapshotFromRecords(records) {
|
|
|
436
829
|
}
|
|
437
830
|
/** 配置指纹只落 hash,不把配置或凭据复制进 RunState。 */
|
|
438
831
|
export function fingerprintRunConfig(config) {
|
|
439
|
-
|
|
832
|
+
const resumeConfig = config !== null && typeof config === "object" && !Array.isArray(config)
|
|
833
|
+
? Object.fromEntries(Object.entries(config).filter(([key]) => key !== "telemetry"))
|
|
834
|
+
: config;
|
|
835
|
+
return createHash("sha256").update(stableJson(resumeConfig)).digest("hex");
|
|
440
836
|
}
|
|
441
837
|
function tracePayload(payload, expectedRunId) {
|
|
442
838
|
if (payload === null || typeof payload !== "object") {
|
|
@@ -476,18 +872,26 @@ function tracePayload(payload, expectedRunId) {
|
|
|
476
872
|
(event.stepId !== undefined && typeof event.stepId !== "string"))) {
|
|
477
873
|
throw new CoreMindError("run_state_corrupt", "RunState 包含非法 effect_receipt");
|
|
478
874
|
}
|
|
875
|
+
if (event.type === "capability_resolved" &&
|
|
876
|
+
(typeof event.agent !== "string" ||
|
|
877
|
+
typeof event.tool !== "string" ||
|
|
878
|
+
typeof event.callId !== "string" ||
|
|
879
|
+
(event.stepId !== undefined && typeof event.stepId !== "string") ||
|
|
880
|
+
!isResolvedToolCapability(event.capability, event.tool) ||
|
|
881
|
+
!RECOVERY_DISPOSITIONS.includes(event.recoveryDisposition) ||
|
|
882
|
+
recoveryDispositionFor(event.capability) !== event.recoveryDisposition)) {
|
|
883
|
+
throw new CoreMindError("run_state_corrupt", "RunState 包含非法 capability_resolved");
|
|
884
|
+
}
|
|
885
|
+
if (event.type === "tool_lifecycle") {
|
|
886
|
+
try {
|
|
887
|
+
validateToolCallLifecycleFact(event);
|
|
888
|
+
}
|
|
889
|
+
catch {
|
|
890
|
+
throw new CoreMindError("run_state_corrupt", "RunState 包含非法 tool_lifecycle");
|
|
891
|
+
}
|
|
892
|
+
}
|
|
479
893
|
return trace;
|
|
480
894
|
}
|
|
481
|
-
function stableJson(value) {
|
|
482
|
-
if (value === null || typeof value !== "object")
|
|
483
|
-
return JSON.stringify(value);
|
|
484
|
-
if (Array.isArray(value))
|
|
485
|
-
return `[${value.map(stableJson).join(",")}]`;
|
|
486
|
-
const entries = Object.entries(value)
|
|
487
|
-
.filter(([, item]) => item !== undefined)
|
|
488
|
-
.sort(([left], [right]) => left.localeCompare(right));
|
|
489
|
-
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
|
|
490
|
-
}
|
|
491
895
|
const LOOP_PHASES = new Set([
|
|
492
896
|
"idle",
|
|
493
897
|
"planning",
|
|
@@ -541,9 +945,31 @@ function validateRecord(value, expectedRunId) {
|
|
|
541
945
|
record.runId !== expectedRunId ||
|
|
542
946
|
!Number.isInteger(record.sequence) ||
|
|
543
947
|
typeof record.timestamp !== "string" ||
|
|
544
|
-
|
|
948
|
+
(record.eventId !== undefined &&
|
|
949
|
+
(typeof record.eventId !== "string" || record.eventId.trim().length === 0)) ||
|
|
950
|
+
![
|
|
951
|
+
"start",
|
|
952
|
+
"resume",
|
|
953
|
+
"telemetry_configuration",
|
|
954
|
+
"telemetry_consent",
|
|
955
|
+
"control",
|
|
956
|
+
"delegation",
|
|
957
|
+
"event",
|
|
958
|
+
"checkpoint",
|
|
959
|
+
"checkpoint_restore",
|
|
960
|
+
"loop",
|
|
961
|
+
"operation",
|
|
962
|
+
"pause",
|
|
963
|
+
"finish",
|
|
964
|
+
].includes(record.kind ?? "")) {
|
|
545
965
|
throw new CoreMindError("run_state_corrupt", `RunState ${expectedRunId} 包含非法记录`);
|
|
546
966
|
}
|
|
967
|
+
if (record.kind === "event" &&
|
|
968
|
+
record.payload !== null &&
|
|
969
|
+
typeof record.payload === "object" &&
|
|
970
|
+
"event" in record.payload) {
|
|
971
|
+
tracePayload(record.payload, expectedRunId);
|
|
972
|
+
}
|
|
547
973
|
return record;
|
|
548
974
|
}
|
|
549
975
|
/** 从 RunState 事件记录中找第一个 input_receipt 的指纹(恢复时输入收据联动校验用) */
|