coremind-runtime 0.3.0 → 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 +45 -0
- package/dist/compaction-projection.d.ts.map +1 -0
- package/dist/compaction-projection.js +133 -0
- package/dist/compaction-projection.js.map +1 -0
- 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/context.d.ts +9 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +24 -1
- package/dist/context.js.map +1 -1
- 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 +18 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +36 -2
- 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 +131 -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 +51 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +27 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +16 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/input-receipt.d.ts +59 -0
- package/dist/input-receipt.d.ts.map +1 -0
- package/dist/input-receipt.js +102 -0
- package/dist/input-receipt.js.map +1 -0
- 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 +28 -0
- package/dist/invariant-checker.d.ts.map +1 -0
- package/dist/invariant-checker.js +441 -0
- package/dist/invariant-checker.js.map +1 -0
- package/dist/loop-runner.d.ts.map +1 -1
- package/dist/loop-runner.js +37 -24
- 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/race-seeds.d.ts +43 -0
- package/dist/race-seeds.d.ts.map +1 -0
- package/dist/race-seeds.js +53 -0
- package/dist/race-seeds.js.map +1 -0
- package/dist/rebuild-request.d.ts +30 -0
- package/dist/rebuild-request.d.ts.map +1 -0
- package/dist/rebuild-request.js +37 -0
- package/dist/rebuild-request.js.map +1 -0
- 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 +20 -2
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +18 -1
- package/dist/result.js.map +1 -1
- package/dist/retry-policy.d.ts.map +1 -1
- package/dist/retry-policy.js +21 -85
- 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 +2 -1
- package/dist/run-effect-coordinator.d.ts.map +1 -1
- package/dist/run-effect-coordinator.js +6 -5
- 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 +107 -4
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +627 -77
- package/dist/run-state.js.map +1 -1
- package/dist/run-terminalizer.d.ts.map +1 -1
- package/dist/run-terminalizer.js +6 -17
- 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 +104 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2242 -288
- package/dist/runtime.js.map +1 -1
- package/dist/session.d.ts +19 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +43 -2
- package/dist/session.js.map +1 -1
- package/dist/snapshot.d.ts.map +1 -1
- package/dist/snapshot.js +3 -20
- package/dist/snapshot.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 +14 -0
- package/dist/turn-tracker.d.ts.map +1 -0
- package/dist/turn-tracker.js +50 -0
- package/dist/turn-tracker.js.map +1 -0
- 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,11 +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";
|
|
8
|
+
import { FactLedger, flushFactLedgerWith, } from "./fact-ledger.js";
|
|
9
|
+
import { foldInputReceipts, inputFingerprint } from "./input-receipt.js";
|
|
5
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";
|
|
6
14
|
export class FileRunStore {
|
|
7
15
|
directory;
|
|
8
16
|
options;
|
|
17
|
+
supportedDurability = ["ordinary", "critical"];
|
|
18
|
+
durabilityBoundary = "process_crash";
|
|
9
19
|
constructor(directory, options = {}) {
|
|
10
20
|
this.directory = directory;
|
|
11
21
|
this.options = options;
|
|
@@ -18,23 +28,7 @@ export class FileRunStore {
|
|
|
18
28
|
}
|
|
19
29
|
async append(record) {
|
|
20
30
|
try {
|
|
21
|
-
|
|
22
|
-
validateRecord(record, record.runId);
|
|
23
|
-
await this.withWriterLock(destination, async () => {
|
|
24
|
-
const parsed = await this.readUnlocked(record.runId, destination);
|
|
25
|
-
const duplicate = parsed.records.find((item) => item.sequence === record.sequence);
|
|
26
|
-
if (duplicate) {
|
|
27
|
-
if (stableJson(duplicate) === stableJson(record))
|
|
28
|
-
return;
|
|
29
|
-
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
|
|
30
|
-
}
|
|
31
|
-
const expectedSequence = (parsed.records.at(-1)?.sequence ?? 0) + 1;
|
|
32
|
-
if (record.sequence !== expectedSequence) {
|
|
33
|
-
throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
|
|
34
|
-
}
|
|
35
|
-
const text = `${parsed.records.map((item) => JSON.stringify(item)).join("\n")}${parsed.records.length > 0 ? "\n" : ""}${JSON.stringify(record)}\n`;
|
|
36
|
-
await this.publishAtomically(destination, text, record);
|
|
37
|
-
});
|
|
31
|
+
await this.writeRecord(record, "ordinary");
|
|
38
32
|
}
|
|
39
33
|
catch (error) {
|
|
40
34
|
if (error instanceof CoreMindError)
|
|
@@ -42,6 +36,42 @@ export class FileRunStore {
|
|
|
42
36
|
throw new CoreMindError("run_state_failed", `RunState 写入失败:${error instanceof Error ? error.message : String(error)}`);
|
|
43
37
|
}
|
|
44
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
|
+
}
|
|
45
75
|
async read(runId) {
|
|
46
76
|
try {
|
|
47
77
|
const destination = this.pathFor(runId);
|
|
@@ -99,30 +129,97 @@ export class FileRunStore {
|
|
|
99
129
|
}
|
|
100
130
|
return { records };
|
|
101
131
|
}
|
|
102
|
-
async publishAtomically(destination, text, record) {
|
|
132
|
+
async publishAtomically(destination, text, record, durability = "ordinary") {
|
|
103
133
|
const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
|
|
104
134
|
try {
|
|
105
135
|
await writeFile(temporary, text, { encoding: "utf8", flag: "wx" });
|
|
106
136
|
await this.options.beforeCommit?.({ destination, temporary, record });
|
|
107
|
-
|
|
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);
|
|
108
154
|
}
|
|
109
155
|
finally {
|
|
110
156
|
await rm(temporary, { force: true }).catch(() => undefined);
|
|
111
157
|
}
|
|
112
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
|
+
}
|
|
113
195
|
async withWriterLock(destination, operation) {
|
|
114
196
|
await mkdir(this.directory, { recursive: true });
|
|
115
197
|
const lockPath = `${destination}.lock`;
|
|
116
|
-
const deadline = Date.now() + (this.options.lockTimeoutMs ??
|
|
117
|
-
|
|
118
|
-
|
|
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) {
|
|
119
207
|
try {
|
|
120
|
-
|
|
208
|
+
await publishWriterLock(lockPath, owner);
|
|
209
|
+
acquired = true;
|
|
121
210
|
}
|
|
122
211
|
catch (error) {
|
|
123
|
-
|
|
212
|
+
const contention = await classifyWriterLockContention(error, lockPath);
|
|
213
|
+
if (contention === "not_contention")
|
|
124
214
|
throw error;
|
|
215
|
+
if (contention === "transient_missing")
|
|
216
|
+
transientPermissionError ??= error;
|
|
217
|
+
if (await this.reclaimStaleWriterLock(lockPath))
|
|
218
|
+
continue;
|
|
125
219
|
if (Date.now() >= deadline) {
|
|
220
|
+
if (contention === "transient_missing" && transientPermissionError) {
|
|
221
|
+
throw transientPermissionError;
|
|
222
|
+
}
|
|
126
223
|
throw new CoreMindError("run_state_locked", `RunState ${path.basename(destination)} 正由另一 writer 使用`);
|
|
127
224
|
}
|
|
128
225
|
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
@@ -132,14 +229,128 @@ export class FileRunStore {
|
|
|
132
229
|
return await operation();
|
|
133
230
|
}
|
|
134
231
|
finally {
|
|
135
|
-
await handle.close();
|
|
136
232
|
await rm(lockPath, { force: true });
|
|
137
233
|
}
|
|
138
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
|
+
}
|
|
139
347
|
}
|
|
140
348
|
export class MemoryRunStore {
|
|
349
|
+
supportedDurability = ["ordinary"];
|
|
350
|
+
durabilityBoundary = "process_memory";
|
|
141
351
|
records = new Map();
|
|
142
352
|
async append(record) {
|
|
353
|
+
validateRecord(record, record.runId);
|
|
143
354
|
const items = this.records.get(record.runId) ?? [];
|
|
144
355
|
const duplicate = items.find((item) => item.sequence === record.sequence);
|
|
145
356
|
if (duplicate) {
|
|
@@ -154,24 +365,68 @@ export class MemoryRunStore {
|
|
|
154
365
|
items.push(structuredClone(record));
|
|
155
366
|
this.records.set(record.runId, items);
|
|
156
367
|
}
|
|
368
|
+
async commit(record, durability) {
|
|
369
|
+
assertSupportedDurability(this, durability);
|
|
370
|
+
await this.append(record);
|
|
371
|
+
return durabilityAcknowledgement(this, durability);
|
|
372
|
+
}
|
|
157
373
|
async read(runId) {
|
|
158
374
|
return structuredClone(this.records.get(runId) ?? []);
|
|
159
375
|
}
|
|
376
|
+
async barrier(_runId, requested) {
|
|
377
|
+
assertSupportedDurability(this, requested);
|
|
378
|
+
return durabilityAcknowledgement(this, requested);
|
|
379
|
+
}
|
|
160
380
|
}
|
|
161
381
|
/** 把同步事件串行化为 RunStore 的有序异步写入。 */
|
|
162
382
|
export class RunStateJournal {
|
|
163
383
|
runId;
|
|
164
384
|
store;
|
|
165
|
-
|
|
166
|
-
|
|
385
|
+
ledger;
|
|
386
|
+
aborted = false;
|
|
387
|
+
rejectedAfterAbortCount = 0;
|
|
388
|
+
knownTurnIds;
|
|
389
|
+
durabilityCounters = {
|
|
390
|
+
ordinary: { succeeded: 0, failed: 0 },
|
|
391
|
+
critical: { succeeded: 0, failed: 0 },
|
|
392
|
+
};
|
|
167
393
|
constructor(runId, store, initialSequence = 0) {
|
|
168
394
|
this.runId = runId;
|
|
169
395
|
this.store = store;
|
|
170
|
-
this.
|
|
396
|
+
this.ledger = new FactLedger(runId, store, initialSequence);
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* 取消收敛:设置事件准入分界点(规格 03 §3)。
|
|
400
|
+
* 此后收尾事实(operation/loop/pause/finish)放行;终态类事件被静默拒绝并计数。
|
|
401
|
+
* knownTurnIds:分界前已启动的活动集合(R3 判定:分界前启动的工具 receipt 放行)。
|
|
402
|
+
*/
|
|
403
|
+
markAborted(knownTurnIds) {
|
|
404
|
+
this.aborted = true;
|
|
405
|
+
this.knownTurnIds = knownTurnIds;
|
|
406
|
+
}
|
|
407
|
+
/** 已设置准入分界点(transcript 回退等取消语义依赖此标志) */
|
|
408
|
+
isAborted() {
|
|
409
|
+
return this.aborted;
|
|
410
|
+
}
|
|
411
|
+
/** 准入拒绝的事件计数(记入 metrics.rejectedAfterAbort) */
|
|
412
|
+
rejectedAfterAbort() {
|
|
413
|
+
return this.rejectedAfterAbortCount;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* 事件准入(trace 层前置调用,规格 03 §3 / ADR"不入 Trace 或 journal"):
|
|
417
|
+
* abort 后的迟到终态事实返回 false(计数),调用方不写入 trace/collected/回调。
|
|
418
|
+
*/
|
|
419
|
+
admitEvent(event) {
|
|
420
|
+
if (!this.aborted)
|
|
421
|
+
return true;
|
|
422
|
+
if (isRejectedAfterAbort({ event }, this.knownTurnIds)) {
|
|
423
|
+
this.rejectedAfterAbortCount += 1;
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
return true;
|
|
171
427
|
}
|
|
172
428
|
async start(payload) {
|
|
173
|
-
this.
|
|
174
|
-
await this.flush();
|
|
429
|
+
await this.appendFact("start", payload);
|
|
175
430
|
}
|
|
176
431
|
event(payload) {
|
|
177
432
|
this.enqueue("event", payload);
|
|
@@ -194,22 +449,268 @@ export class RunStateJournal {
|
|
|
194
449
|
finish(payload) {
|
|
195
450
|
this.enqueue("finish", payload);
|
|
196
451
|
}
|
|
197
|
-
async flush() {
|
|
198
|
-
|
|
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;
|
|
199
483
|
}
|
|
200
484
|
enqueue(kind, payload) {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
485
|
+
// 事件准入(规格 03 §3):分界点后的终态类事件拒绝写入,静默不抛错
|
|
486
|
+
if (this.aborted && kind === "event" && isRejectedAfterAbort(payload, this.knownTurnIds)) {
|
|
487
|
+
this.rejectedAfterAbortCount += 1;
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
void this.appendFact(kind, payload);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
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);
|
|
512
|
+
}
|
|
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`);
|
|
525
|
+
}
|
|
526
|
+
/** journal 是否仍有未落盘的写入(规格 03 §5:静止条件之一) */
|
|
527
|
+
export function hasPendingJournalFlush(journal) {
|
|
528
|
+
return journal.pendingFactCount() > 0;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* 准入判定:分界点后到达的终态类事件(规格 03 §3)。
|
|
532
|
+
* - tool_result / turn_end(assistant 文本落定)→ 拒绝(旧活动的迟到终态事实);
|
|
533
|
+
* - effect_receipt 终态:turnId 属于分界前已启动的活动(R3,knownTurnIds 命中)→ 放行;
|
|
534
|
+
* 否则(无归属或 abort 后新生成的活动)→ 拒绝;
|
|
535
|
+
* - 非终态事件(text_delta / approval_required / error 等)→ 放行。
|
|
536
|
+
*/
|
|
537
|
+
export function isRejectedAfterAbort(payload, knownTurnIds) {
|
|
538
|
+
const trace = payload;
|
|
539
|
+
const event = trace?.event;
|
|
540
|
+
if (event === null || typeof event !== "object")
|
|
541
|
+
return false;
|
|
542
|
+
const type = event.type;
|
|
543
|
+
if (type === "tool_result" || type === "turn_end")
|
|
544
|
+
return true;
|
|
545
|
+
if (type === "effect_receipt") {
|
|
546
|
+
const receipt = event;
|
|
547
|
+
if (receipt.status === undefined || receipt.status === "not_started")
|
|
548
|
+
return false;
|
|
549
|
+
const turnId = receipt.turnId;
|
|
550
|
+
return turnId === undefined || !knownTurnIds?.has(String(turnId));
|
|
551
|
+
}
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* resumable 安全门单点实现(缺口 G-1):
|
|
556
|
+
* 找出第一个副作用状态无法证明为 not_started 的非 replay-safe 工具调用。
|
|
557
|
+
* 快照 resumable 标志与恢复计划共用此判定,避免双实现漂移。
|
|
558
|
+
*/
|
|
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
|
+
}
|
|
613
|
+
const receipts = new Map();
|
|
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
|
+
]));
|
|
620
|
+
for (const entry of trace) {
|
|
621
|
+
const event = entry.event;
|
|
622
|
+
if (event.type === "effect_receipt")
|
|
623
|
+
receipts.set(event.idempotencyKey, event);
|
|
624
|
+
if (event.type === "step_output")
|
|
625
|
+
completedSteps.add(event.stepId);
|
|
626
|
+
}
|
|
627
|
+
for (const entry of trace) {
|
|
628
|
+
const event = entry.event;
|
|
629
|
+
if (event.type !== "tool_call")
|
|
630
|
+
continue;
|
|
631
|
+
if (event.callId &&
|
|
632
|
+
lifecycleCallKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
|
|
633
|
+
continue;
|
|
634
|
+
}
|
|
635
|
+
if (event.stepId && completedSteps.has(event.stepId))
|
|
636
|
+
continue;
|
|
637
|
+
const receipt = event.idempotencyKey ? receipts.get(event.idempotencyKey) : undefined;
|
|
638
|
+
if (receipt?.status === "not_started")
|
|
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
|
+
}
|
|
649
|
+
return {
|
|
650
|
+
tool: event.tool,
|
|
651
|
+
...(event.stepId ? { stepId: event.stepId } : {}),
|
|
652
|
+
...(event.idempotencyKey ? { idempotencyKey: event.idempotencyKey } : {}),
|
|
653
|
+
...(receipt ? { receiptStatus: receipt.status } : {}),
|
|
208
654
|
};
|
|
209
|
-
this.pending = this.pending.then(() => this.store.append(record));
|
|
210
655
|
}
|
|
656
|
+
return undefined;
|
|
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;
|
|
211
713
|
}
|
|
212
|
-
const REPLAY_SAFE_TOOLS = new Set(["read", "ls", "find", "grep", "web-fetch", "web-search"]);
|
|
213
714
|
/** 从中断的 append-only RunState 构造安全恢复计划。 */
|
|
214
715
|
export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
215
716
|
if (records.length === 0)
|
|
@@ -232,11 +733,18 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
232
733
|
throw new CoreMindError("resume_config_mismatch", "当前配置与中断运行不一致,已拒绝恢复");
|
|
233
734
|
}
|
|
234
735
|
const storedPrompt = typeof startPayload.initialPrompt === "string" ? startPayload.initialPrompt : undefined;
|
|
235
|
-
if (requestedPrompt !== undefined
|
|
236
|
-
|
|
736
|
+
if (requestedPrompt !== undefined) {
|
|
737
|
+
// 输入收据联动(规格 03 §4/§6 R9):原 run 已登记 input_receipt 时按指纹校验
|
|
738
|
+
// (Trace 只存摘要不落原文);无收据(0.3.0 旧格式)保留现状字符串比对,语义不变
|
|
739
|
+
const receiptFingerprint = findInputReceiptFingerprint(records);
|
|
740
|
+
const mismatch = receiptFingerprint !== undefined
|
|
741
|
+
? inputFingerprint(requestedPrompt) !== receiptFingerprint
|
|
742
|
+
: requestedPrompt !== storedPrompt;
|
|
743
|
+
if (mismatch) {
|
|
744
|
+
throw new CoreMindError("resume_input_mismatch", "恢复输入与原运行不一致,已拒绝恢复");
|
|
745
|
+
}
|
|
237
746
|
}
|
|
238
747
|
const completedSteps = new Map();
|
|
239
|
-
const unsafeToolStarts = [];
|
|
240
748
|
const effectReceipts = new Map();
|
|
241
749
|
const previousTrace = [];
|
|
242
750
|
let loopSnapshot;
|
|
@@ -265,16 +773,7 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
265
773
|
},
|
|
266
774
|
});
|
|
267
775
|
}
|
|
268
|
-
|
|
269
|
-
const toolEvent = event;
|
|
270
|
-
if (!REPLAY_SAFE_TOOLS.has(toolEvent.tool)) {
|
|
271
|
-
unsafeToolStarts.push({
|
|
272
|
-
tool: toolEvent.tool,
|
|
273
|
-
...(toolEvent.stepId ? { stepId: toolEvent.stepId } : {}),
|
|
274
|
-
...(toolEvent.idempotencyKey ? { idempotencyKey: toolEvent.idempotencyKey } : {}),
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
}
|
|
776
|
+
// tool_call 的安全门判定统一走 findUnsafeToolCall(见下方),这里不再重复收集。
|
|
278
777
|
if (event.type === "effect_receipt") {
|
|
279
778
|
const receipt = event;
|
|
280
779
|
effectReceipts.set(receipt.idempotencyKey, {
|
|
@@ -286,17 +785,12 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
286
785
|
}
|
|
287
786
|
}
|
|
288
787
|
const operationSnapshot = operationSnapshotFromRecords(ordered);
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
? effectReceipts.get(toolCall.idempotencyKey)
|
|
294
|
-
: undefined;
|
|
295
|
-
return receipt?.status !== "not_started";
|
|
296
|
-
});
|
|
788
|
+
if (!inputReceiptsAreResumable(previousTrace)) {
|
|
789
|
+
throw new CoreMindError("run_already_finished", "输入已到终态,不能自动恢复");
|
|
790
|
+
}
|
|
791
|
+
const unsafe = findUnsafeToolCall(previousTrace);
|
|
297
792
|
if (unsafe) {
|
|
298
|
-
|
|
299
|
-
if (receipt?.status === "committed") {
|
|
793
|
+
if (unsafe.receiptStatus === "committed") {
|
|
300
794
|
throw new CoreMindError("committed_effect_pending", `工具 ${unsafe.tool} 的副作用已提交,但步骤尚未到达稳定边界;为避免重复执行,已暂停自动恢复`);
|
|
301
795
|
}
|
|
302
796
|
throw new CoreMindError("unknown_effect", `未完成步骤的工具 ${unsafe.tool} 副作用状态未知;请先人工核对后再决定`);
|
|
@@ -308,12 +802,22 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
|
|
|
308
802
|
nextTraceSequence,
|
|
309
803
|
completedSteps,
|
|
310
804
|
effectReceipts,
|
|
805
|
+
toolReplayCandidates: collectToolReplayCandidates(previousTrace),
|
|
311
806
|
previousTrace,
|
|
312
807
|
operationRecords,
|
|
313
808
|
...(loopSnapshot ? { loopSnapshot } : {}),
|
|
314
809
|
...(operationSnapshot ? { operationSnapshot } : {}),
|
|
315
810
|
};
|
|
316
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
|
+
}
|
|
317
821
|
/** 从 RunState 中校验并提取最新 operation 快照,供 CLI/SDK/Worker 共用。 */
|
|
318
822
|
export function operationSnapshotFromRecords(records) {
|
|
319
823
|
const operationRecords = records
|
|
@@ -325,7 +829,10 @@ export function operationSnapshotFromRecords(records) {
|
|
|
325
829
|
}
|
|
326
830
|
/** 配置指纹只落 hash,不把配置或凭据复制进 RunState。 */
|
|
327
831
|
export function fingerprintRunConfig(config) {
|
|
328
|
-
|
|
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");
|
|
329
836
|
}
|
|
330
837
|
function tracePayload(payload, expectedRunId) {
|
|
331
838
|
if (payload === null || typeof payload !== "object") {
|
|
@@ -365,18 +872,26 @@ function tracePayload(payload, expectedRunId) {
|
|
|
365
872
|
(event.stepId !== undefined && typeof event.stepId !== "string"))) {
|
|
366
873
|
throw new CoreMindError("run_state_corrupt", "RunState 包含非法 effect_receipt");
|
|
367
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
|
+
}
|
|
368
893
|
return trace;
|
|
369
894
|
}
|
|
370
|
-
function stableJson(value) {
|
|
371
|
-
if (value === null || typeof value !== "object")
|
|
372
|
-
return JSON.stringify(value);
|
|
373
|
-
if (Array.isArray(value))
|
|
374
|
-
return `[${value.map(stableJson).join(",")}]`;
|
|
375
|
-
const entries = Object.entries(value)
|
|
376
|
-
.filter(([, item]) => item !== undefined)
|
|
377
|
-
.sort(([left], [right]) => left.localeCompare(right));
|
|
378
|
-
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
|
|
379
|
-
}
|
|
380
895
|
const LOOP_PHASES = new Set([
|
|
381
896
|
"idle",
|
|
382
897
|
"planning",
|
|
@@ -430,9 +945,44 @@ function validateRecord(value, expectedRunId) {
|
|
|
430
945
|
record.runId !== expectedRunId ||
|
|
431
946
|
!Number.isInteger(record.sequence) ||
|
|
432
947
|
typeof record.timestamp !== "string" ||
|
|
433
|
-
|
|
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 ?? "")) {
|
|
434
965
|
throw new CoreMindError("run_state_corrupt", `RunState ${expectedRunId} 包含非法记录`);
|
|
435
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
|
+
}
|
|
436
973
|
return record;
|
|
437
974
|
}
|
|
975
|
+
/** 从 RunState 事件记录中找第一个 input_receipt 的指纹(恢复时输入收据联动校验用) */
|
|
976
|
+
function findInputReceiptFingerprint(records) {
|
|
977
|
+
for (const record of records) {
|
|
978
|
+
if (record.kind !== "event")
|
|
979
|
+
continue;
|
|
980
|
+
const trace = record.payload;
|
|
981
|
+
if (trace?.event?.type === "input_receipt" &&
|
|
982
|
+
typeof trace.event.contentFingerprint === "string") {
|
|
983
|
+
return trace.event.contentFingerprint;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return undefined;
|
|
987
|
+
}
|
|
438
988
|
//# sourceMappingURL=run-state.js.map
|