@tangle-network/agent-runtime 9.0.16 → 10.0.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/CHANGELOG.md +72 -0
- package/dist/{activation-y6NAn3sW.d.ts → activation-CDlOqX5a.d.ts} +7 -8
- package/dist/{activation-DgT20fzX.js → activation-CEGkyzEG.js} +2 -2
- package/dist/{activation-DgT20fzX.js.map → activation-CEGkyzEG.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/candidate-execution/index.d.ts +3 -0
- package/dist/candidate-execution/index.js +10 -3
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{delegate-Cmu5OF3M.js → delegate-V2Nz8GgO.js} +2 -2
- package/dist/{delegate-Cmu5OF3M.js.map → delegate-V2Nz8GgO.js.map} +1 -1
- package/dist/{coordination-manager-CFtnSLPw.js → driver-control-acknowledgers-CJDYLJmW.js} +1042 -1042
- package/dist/driver-control-acknowledgers-CJDYLJmW.js.map +1 -0
- package/dist/durable.d.ts +5 -5
- package/dist/durable.js +13 -13
- package/dist/durable.js.map +1 -1
- package/dist/{failure-cause-WifbY42M.js → failure-cause-BI7cfDWx.js} +14 -2
- package/dist/failure-cause-BI7cfDWx.js.map +1 -0
- package/dist/{graph-registry-B_1C7qye.js → graph-registry-DxhlgHdA.js} +1 -1
- package/dist/{graph-registry-BbZN5deo.js → graph-registry-j9t9J0KT.js} +11 -12
- package/dist/{graph-registry-BbZN5deo.js.map → graph-registry-j9t9J0KT.js.map} +1 -1
- package/dist/{graph-DqtIiS94.js → graph-wJOMQ1kC.js} +8 -8
- package/dist/{graph-DqtIiS94.js.map → graph-wJOMQ1kC.js.map} +1 -1
- package/dist/{improve-B0vNv6e7.js → improve-DOjywiPq.js} +42 -26
- package/dist/{improve-B0vNv6e7.js.map → improve-DOjywiPq.js.map} +1 -1
- package/dist/index.d.ts +38 -6
- package/dist/index.js +59 -20
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +93 -63
- package/dist/intelligence.js +166 -73
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +3 -3
- package/dist/kernel.js +16 -15
- package/dist/{loop-runner-BvVdDdZC.js → loop-runner-CPTOzSol.js} +2 -2
- package/dist/{loop-runner-BvVdDdZC.js.map → loop-runner-CPTOzSol.js.map} +1 -1
- package/dist/{loop-runner-CfMOsISJ.d.ts → loop-runner-DwxZbYW5.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +7 -7
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/{model-policy-CZwhXp8O.js → model-policy-CqDuBTq-.js} +12 -2
- package/dist/model-policy-CqDuBTq-.js.map +1 -0
- package/dist/{prepare-Cw4ZaN01.js → prepare-DT-ibRsm.js} +2 -2
- package/dist/{prepare-Cw4ZaN01.js.map → prepare-DT-ibRsm.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{provision-supervisor-BjKluSKl.js → provision-supervisor-B1_Kow9m.js} +6 -6
- package/dist/{provision-supervisor-BjKluSKl.js.map → provision-supervisor-B1_Kow9m.js.map} +1 -1
- package/dist/{run-cancellation-BvGEEwRG.js → run-cancellation-D5m6JHPH.js} +2 -2
- package/dist/{run-cancellation-BvGEEwRG.js.map → run-cancellation-D5m6JHPH.js.map} +1 -1
- package/dist/{run-state-Dd_AjWd6.js → run-state-DKOXe08H.js} +5 -5
- package/dist/{run-state-Dd_AjWd6.js.map → run-state-DKOXe08H.js.map} +1 -1
- package/dist/{runtime-7VEM9muH.js → runtime-C5cWSMqU.js} +191 -24
- package/dist/runtime-C5cWSMqU.js.map +1 -0
- package/dist/{search-executor-Dqtm1fOC.js → search-executor-CA6fTYWz.js} +5 -5
- package/dist/{search-executor-Dqtm1fOC.js.map → search-executor-CA6fTYWz.js.map} +1 -1
- package/dist/{server-B8Kmit_v.js → server-C8Z3vYdI.js} +4 -4
- package/dist/{server-B8Kmit_v.js.map → server-C8Z3vYdI.js.map} +1 -1
- package/dist/{settle-record-BvH2-Ao5.js → settle-record-BDxPAO4m.js} +2 -2
- package/dist/{settle-record-BvH2-Ao5.js.map → settle-record-BDxPAO4m.js.map} +1 -1
- package/dist/{structural-rollout-CYc8PE2N.js → structural-rollout-B0HPcP9G.js} +5 -5
- package/dist/{structural-rollout-CYc8PE2N.js.map → structural-rollout-B0HPcP9G.js.map} +1 -1
- package/dist/{supervise-BayNu7qZ.js → supervise-Dvj-8S6D.js} +2341 -2283
- package/dist/supervise-Dvj-8S6D.js.map +1 -0
- package/dist/{supervision-discovery-Ca4QO4rG.js → supervision-discovery-CbrwcgJy.js} +3 -3
- package/dist/{supervision-discovery-Ca4QO4rG.js.map → supervision-discovery-CbrwcgJy.js.map} +1 -1
- package/dist/{supervisor-Bx21Hy27.js → supervisor-DwdeUC2l.js} +218 -47
- package/dist/supervisor-DwdeUC2l.js.map +1 -0
- package/dist/{supervisor-accounting-StDNW1YT.js → supervisor-accounting-C48Yo9QC.js} +507 -341
- package/dist/supervisor-accounting-C48Yo9QC.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{tool-server-CirrqFlr.js → tool-server-DsCeBr-C.js} +2 -2
- package/dist/{tool-server-CirrqFlr.js.map → tool-server-DsCeBr-C.js.map} +1 -1
- package/dist/{top-web-Cg7ywIkF.js → top-web-CTOq4psb.js} +6 -6
- package/dist/{top-web-Cg7ywIkF.js.map → top-web-CTOq4psb.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-_j53efrk.d.ts → types-lnF0wIJW.d.ts} +8245 -8153
- package/dist/{workspace-streams-BakRr-Pl.js → workspace-streams-C7PGLAUd.js} +3 -3
- package/dist/workspace-streams-C7PGLAUd.js.map +1 -0
- package/package.json +5 -4
- package/dist/coordination-manager-CFtnSLPw.js.map +0 -1
- package/dist/failure-cause-WifbY42M.js.map +0 -1
- package/dist/model-policy-CZwhXp8O.js.map +0 -1
- package/dist/runtime-7VEM9muH.js.map +0 -1
- package/dist/supervise-BayNu7qZ.js.map +0 -1
- package/dist/supervisor-Bx21Hy27.js.map +0 -1
- package/dist/supervisor-accounting-StDNW1YT.js.map +0 -1
- package/dist/workspace-streams-BakRr-Pl.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement,
|
|
1
|
+
import { Ct as resolveSpawnResourcePaths, E as writeWorkerCancellation, F as parseWorkerToolTraceArtifact, Ht as runtimeGraphMetadataKey, I as workerTraceAnalysisStore, K as spawnJournalRecordEvents, O as writeWorkerSteerAcknowledgement, S as workerCancelRequestsFile, T as workerSteerRequestsDir, W as FileSpawnJournal, _ as readWorkerSteerAcknowledgement, at as meterRuntimeOwnedAccounting, d as claimWorkerSteerDelivery, g as readWorkerCancellation, h as readWorkerCancelRequests, ln as FileResultBlobStore, v as readWorkerSteerRequests, vr as isLiveNodeStatus, yr as isTerminalNodeStatus } from "./supervisor-accounting-C48Yo9QC.js";
|
|
2
2
|
import { m as ValidationError } from "./errors-DG8yufqX.js";
|
|
3
|
-
import { N as contentAddress, o as settlementFailureCause, tt as assertValidBudget } from "./failure-cause-
|
|
3
|
+
import { N as contentAddress, o as settlementFailureCause, tt as assertValidBudget } from "./failure-cause-BI7cfDWx.js";
|
|
4
4
|
import { a as errMessage, f as resolveRedactor, t as detachedFrozen } from "./snapshot-BKI_w3JD.js";
|
|
5
|
-
import { X as INBOX_RECEIPT_KEY, _t as CheckUnavailableError, b as InMemorySpawnJournal, rt as createPeerMailbox, v as withDriverExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-
|
|
5
|
+
import { X as INBOX_RECEIPT_KEY, _t as CheckUnavailableError, b as InMemorySpawnJournal, rt as createPeerMailbox, v as withDriverExecutor, x as createExecutorRegistry, y as InMemoryResultBlobStore } from "./supervisor-DwdeUC2l.js";
|
|
6
6
|
import { i as checkVerdictOf, o as failedItems } from "./continuation-CZaeHEzQ.js";
|
|
7
|
-
import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-
|
|
7
|
+
import { c as writeRunCancellation, i as readRunCancellation, r as readRunCancelRequest, t as applyRunCancellation, v as FileCoordinationLog } from "./run-cancellation-D5m6JHPH.js";
|
|
8
8
|
import { a as admitRuntimeSpawn, i as workerSettlement, n as resolveJsonPointer, o as safeJsonText, r as textBytes, t as createMapRouting } from "./coordination-map-routing-XZXTlCmn.js";
|
|
9
9
|
import { ResourceRequestSchema, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
10
10
|
import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
|
|
@@ -87,82 +87,92 @@ function createFileRunContext(dir, opts = {}) {
|
|
|
87
87
|
coordinationLog: new FileCoordinationLog(`${dir}/coordination-log.jsonl`)
|
|
88
88
|
};
|
|
89
89
|
}
|
|
90
|
-
// src/
|
|
91
|
-
/**
|
|
92
|
-
*
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
90
|
+
// src/runtime/supervise/event-bus.ts
|
|
91
|
+
/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.
|
|
92
|
+
* @experimental In-process queue; durability is a transport swap that does not exist yet. */
|
|
93
|
+
function createEventBus(now = Date.now) {
|
|
94
|
+
const queue = [];
|
|
95
|
+
const log = [];
|
|
96
|
+
const subscribers = [];
|
|
97
|
+
const queuedHandlers = [];
|
|
98
|
+
const byKind = {};
|
|
99
|
+
const staged = /* @__PURE__ */ new WeakMap();
|
|
100
|
+
let seq = 0;
|
|
101
|
+
let published = 0;
|
|
102
|
+
let pulled = 0;
|
|
103
|
+
const matches = (r, kinds) => !kinds || kinds.includes(r.event.type);
|
|
104
|
+
const bestIndex = (kinds) => {
|
|
105
|
+
let best = -1;
|
|
106
|
+
let bestPriority = Number.NEGATIVE_INFINITY;
|
|
107
|
+
for (let i = 0; i < queue.length; i++) {
|
|
108
|
+
const r = queue[i];
|
|
109
|
+
if (!r || !matches(r, kinds)) continue;
|
|
110
|
+
if (r.priority > bestPriority) {
|
|
111
|
+
best = i;
|
|
112
|
+
bestPriority = r.priority;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return best;
|
|
116
|
+
};
|
|
117
|
+
const pullAt = (i) => {
|
|
118
|
+
if (i < 0) return void 0;
|
|
119
|
+
pulled++;
|
|
120
|
+
return queue.splice(i, 1)[0];
|
|
121
|
+
};
|
|
122
|
+
const pullRecord = (kinds) => pullAt(bestIndex(kinds));
|
|
123
|
+
return {
|
|
124
|
+
async publish(event, opts) {
|
|
125
|
+
const record = staged.get(event) ?? {
|
|
126
|
+
seq: seq++,
|
|
127
|
+
at: now(),
|
|
128
|
+
priority: opts?.priority ?? 0,
|
|
129
|
+
event
|
|
130
|
+
};
|
|
131
|
+
staged.set(event, record);
|
|
132
|
+
for (const handler of subscribers) await handler(record);
|
|
133
|
+
staged.delete(event);
|
|
134
|
+
if (opts?.queue !== false) queue.push(record);
|
|
135
|
+
log.push(record);
|
|
136
|
+
published += 1;
|
|
137
|
+
byKind[event.type] = (byKind[event.type] ?? 0) + 1;
|
|
138
|
+
if (opts?.queue !== false) for (const handler of [...queuedHandlers]) handler(record);
|
|
139
|
+
return record;
|
|
140
|
+
},
|
|
141
|
+
pull: (kinds) => pullRecord(kinds)?.event,
|
|
142
|
+
pullRecord,
|
|
143
|
+
take: (seq) => pullAt(queue.findIndex((r) => r.seq === seq)),
|
|
144
|
+
queued(kinds) {
|
|
145
|
+
return queue.filter((r) => matches(r, kinds));
|
|
146
|
+
},
|
|
147
|
+
subscribe(handler) {
|
|
148
|
+
subscribers.push(handler);
|
|
149
|
+
return () => {
|
|
150
|
+
const i = subscribers.indexOf(handler);
|
|
151
|
+
if (i >= 0) subscribers.splice(i, 1);
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
onQueued(handler) {
|
|
155
|
+
queuedHandlers.push(handler);
|
|
156
|
+
return () => {
|
|
157
|
+
const i = queuedHandlers.indexOf(handler);
|
|
158
|
+
if (i >= 0) queuedHandlers.splice(i, 1);
|
|
159
|
+
};
|
|
160
|
+
},
|
|
161
|
+
pending(kinds) {
|
|
162
|
+
return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length;
|
|
163
|
+
},
|
|
164
|
+
history() {
|
|
165
|
+
return log;
|
|
166
|
+
},
|
|
167
|
+
stats() {
|
|
168
|
+
return {
|
|
169
|
+
published,
|
|
170
|
+
pulled,
|
|
171
|
+
byKind: { ...byKind }
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
166
176
|
// src/mcp/tools/coordination-analysts.ts
|
|
167
177
|
/**
|
|
168
178
|
* The trace-tool sets a DEFINED analyst may ask for — the exact group names agent-eval's
|
|
@@ -382,735 +392,139 @@ function normalizeAnalyzeOnSettle(entry) {
|
|
|
382
392
|
if (route.statuses !== void 0 && (!Array.isArray(route.statuses) || route.statuses.length === 0 || route.statuses.some((status) => status !== "done" && status !== "down"))) throw new TypeError("analyzeOnSettle.statuses must contain done or down");
|
|
383
393
|
return route;
|
|
384
394
|
}
|
|
385
|
-
// src/mcp/tools/coordination-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
395
|
+
// src/mcp/tools/coordination-analysis.ts
|
|
396
|
+
function createCoordinationAnalysis(deps) {
|
|
397
|
+
const { opts } = deps;
|
|
398
|
+
const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle);
|
|
399
|
+
const analystAssignments = loadAnalystAssignments(opts);
|
|
400
|
+
const analystRuns = /* @__PURE__ */ new Map();
|
|
401
|
+
const state = {
|
|
402
|
+
...deps,
|
|
403
|
+
analysisRoutes,
|
|
404
|
+
analystAssignments,
|
|
405
|
+
analystRuns,
|
|
406
|
+
flushedAnalystRuns: /* @__PURE__ */ new Set(),
|
|
407
|
+
definedAnalysts: [...opts.priorAnalystDefinitions ?? []],
|
|
408
|
+
maxDefinedAnalysts: opts.maxDefinedAnalysts ?? ANALYST_DEFINITION_BOUNDS.maxDefinitionsPerManager,
|
|
409
|
+
analystRunOrdinal: nextAnalystRunOrdinal(analystAssignments),
|
|
410
|
+
finishing: false,
|
|
411
|
+
managerAnalysis: void 0
|
|
412
|
+
};
|
|
413
|
+
recoverAnalystRuns(opts, analystAssignments, analystRuns);
|
|
396
414
|
return {
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
415
|
+
analysisRoutes: state.analysisRoutes,
|
|
416
|
+
analystRuns,
|
|
417
|
+
flushedAnalystRuns: state.flushedAnalystRuns,
|
|
418
|
+
analystRunFinding,
|
|
419
|
+
spawnAnalystRun: spawnAnalystRun.bind(null, state),
|
|
420
|
+
deliverRoutedFinding: deliverRoutedFinding.bind(null, state),
|
|
421
|
+
analystRunContext: analystRunContext.bind(null, opts),
|
|
422
|
+
finishAnalysis: finishAnalysis.bind(null, state),
|
|
423
|
+
definedAnalysts: state.definedAnalysts,
|
|
424
|
+
analystMenu: analystMenu.bind(null, state),
|
|
425
|
+
defineAnalyst: defineAnalyst.bind(null, state),
|
|
426
|
+
isFinishing: () => state.finishing
|
|
401
427
|
};
|
|
402
428
|
}
|
|
403
|
-
/** The
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
maxTokens: {
|
|
413
|
-
type: "number",
|
|
414
|
-
minimum: 0
|
|
415
|
-
},
|
|
416
|
-
maxUsd: {
|
|
417
|
-
type: "number",
|
|
418
|
-
minimum: 0
|
|
419
|
-
},
|
|
420
|
-
deadlineMs: {
|
|
421
|
-
type: "number",
|
|
422
|
-
minimum: 0
|
|
423
|
-
},
|
|
424
|
-
resources: {
|
|
425
|
-
type: "object",
|
|
426
|
-
additionalProperties: {
|
|
427
|
-
type: "object",
|
|
428
|
-
properties: {
|
|
429
|
-
unit: {
|
|
430
|
-
type: "string",
|
|
431
|
-
minLength: 1
|
|
432
|
-
},
|
|
433
|
-
limit: {
|
|
434
|
-
type: "integer",
|
|
435
|
-
minimum: 0,
|
|
436
|
-
maximum: Number.MAX_SAFE_INTEGER
|
|
437
|
-
}
|
|
438
|
-
},
|
|
439
|
-
required: ["unit", "limit"]
|
|
440
|
-
}
|
|
441
|
-
}
|
|
429
|
+
/** The durable analyst assignments of a prior process, refusing two that disagree on one id. */
|
|
430
|
+
function loadAnalystAssignments(opts) {
|
|
431
|
+
const analystAssignments = /* @__PURE__ */ new Map();
|
|
432
|
+
for (const record of opts.priorJournal ?? []) {
|
|
433
|
+
if (record.event.type !== "analyst-assignment") continue;
|
|
434
|
+
const assignment = record.event.assignment;
|
|
435
|
+
const prior = analystAssignments.get(assignment.assignmentId);
|
|
436
|
+
if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(assignment)) throw new Error(`coordination: conflicting analyst assignment '${assignment.assignmentId}'`);
|
|
437
|
+
analystAssignments.set(assignment.assignmentId, detachedFrozen(assignment));
|
|
442
438
|
}
|
|
443
|
-
|
|
444
|
-
function budgetField(channel) {
|
|
445
|
-
return channel.startsWith("resource:") ? `resources.${channel.slice(9)}.limit` : BUDGET_FIELD[channel];
|
|
439
|
+
return analystAssignments;
|
|
446
440
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
const held = shortfall.held ?? 0;
|
|
456
|
-
const most = free + held;
|
|
457
|
-
if (most === 0) return `${channel} has nothing free and none held by your running workers (${asked})`;
|
|
458
|
-
const room = held > 0 ? `${free} free now and ${held} held by your running workers, which a spawn waits for` : `${free} free${channel === "iterations" || channel.startsWith("resource:") ? "" : " right now"}`;
|
|
459
|
-
if (channel === "iterations" || channel.startsWith("resource:")) return `${channel} has ${room} (${asked}); budget.${field} at most ${most} fits`;
|
|
460
|
-
return `${channel} has ${room} (${asked}); your own turns draw ${channel} from this same pool before a retry is admitted, so ask for well under ${most}`;
|
|
441
|
+
function nextAnalystRunOrdinal(analystAssignments) {
|
|
442
|
+
let analystRunOrdinal = 0;
|
|
443
|
+
for (const assignment of analystAssignments.values()) {
|
|
444
|
+
const ordinal = Number(/:o(\d+)$/.exec(assignment.assignmentId)?.[1]);
|
|
445
|
+
if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal === Number.MAX_SAFE_INTEGER) throw new Error(`coordination: invalid analyst assignment '${assignment.assignmentId}'`);
|
|
446
|
+
analystRunOrdinal = Math.max(analystRunOrdinal, ordinal + 1);
|
|
447
|
+
}
|
|
448
|
+
return analystRunOrdinal;
|
|
461
449
|
}
|
|
462
|
-
/**
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
case "invalid-identity": return "a keyed spawn needs a complete execution identity to journal, and this profile and task did not produce one; spawn again without a key";
|
|
478
|
-
case "budget-exhausted":
|
|
479
|
-
if (shortfalls === void 0 || shortfalls.length === 0) return "the conserved pool refused this spawn (budget-exhausted): the run's remaining budget cannot cover this worker's budget";
|
|
480
|
-
if (shortfalls.some((shortfall) => shortfall.closedByUnknownSpend === true)) return `the run pool refused this spawn: ${shortfallClause(shortfalls.find((shortfall) => shortfall.closedByUnknownSpend === true))}; the caller must re-run with a measurable or larger root budget`;
|
|
481
|
-
return `the run pool refused this spawn: ${shortfalls.map(shortfallClause).join("; ")}; or ask the caller for a larger root budget`;
|
|
450
|
+
/** Re-attach every analyst node a prior process journaled to its durable assignment. */
|
|
451
|
+
function recoverAnalystRuns(opts, analystAssignments, analystRuns) {
|
|
452
|
+
for (const node of [...opts.scope.resume?.view.nodes ?? [], ...opts.scope.view.nodes]) {
|
|
453
|
+
if (node.parent !== opts.scope.view.root || !node.assignmentId?.startsWith("analyst:")) continue;
|
|
454
|
+
const assignment = analystAssignments.get(node.assignmentId);
|
|
455
|
+
if (!assignment) throw new Error(`coordination: analyst assignment '${node.assignmentId}' has no durable source record; refusing to treat its review as a worker result`);
|
|
456
|
+
if (node.identity && (node.identity.profileDigest !== assignment.profileDigest || node.identity.taskDigest !== assignment.taskDigest)) throw new Error(`coordination: analyst assignment '${node.assignmentId}' conflicts with its journaled execution identity`);
|
|
457
|
+
analystRuns.set(node.id, {
|
|
458
|
+
route: {
|
|
459
|
+
kind: assignment.kind,
|
|
460
|
+
...assignment.to === void 0 ? {} : { to: assignment.to }
|
|
461
|
+
},
|
|
462
|
+
sourceWorker: assignment.sourceWorker,
|
|
463
|
+
assignmentId: assignment.assignmentId
|
|
464
|
+
});
|
|
482
465
|
}
|
|
483
466
|
}
|
|
484
|
-
const
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
467
|
+
const analystRunFinding = (run, settled) => detachedFrozen({
|
|
468
|
+
type: "finding",
|
|
469
|
+
finding: canonicalFindingEvent({
|
|
470
|
+
fromWorker: run.sourceWorker,
|
|
471
|
+
analyst: run.route.kind,
|
|
472
|
+
analystWorkerId: settled.handle.id,
|
|
473
|
+
assignmentId: run.assignmentId,
|
|
474
|
+
findings: settled.kind === "done" ? settled.out : { analystRunFailed: settled.reason }
|
|
475
|
+
})
|
|
476
|
+
});
|
|
477
|
+
/** The settled worker's persisted tool-trace spans; degraded evidence reads as empty, never a throw. */
|
|
478
|
+
async function readTraceSpans(opts, worker) {
|
|
479
|
+
if (worker.trace.status !== "available") return {
|
|
480
|
+
spansText: "",
|
|
481
|
+
spanCount: 0
|
|
482
|
+
};
|
|
493
483
|
try {
|
|
494
|
-
|
|
484
|
+
const raw = await opts.blobs.get(worker.trace.traceRef);
|
|
485
|
+
const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef);
|
|
486
|
+
return {
|
|
487
|
+
spansText: safeJsonText(artifact.spans),
|
|
488
|
+
spanCount: artifact.spans.length
|
|
489
|
+
};
|
|
495
490
|
} catch {
|
|
496
|
-
return
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
tail.partial = "";
|
|
501
|
-
tail.at.clear();
|
|
502
|
-
}
|
|
503
|
-
if (size === tail.offset) return void 0;
|
|
504
|
-
const buf = Buffer.allocUnsafe(size - tail.offset);
|
|
505
|
-
const fd = openSync(tail.file, "r");
|
|
506
|
-
try {
|
|
507
|
-
const got = readSync(fd, buf, 0, buf.length, tail.offset);
|
|
508
|
-
tail.offset += got;
|
|
509
|
-
const text = tail.partial + buf.subarray(0, got).toString("utf8");
|
|
510
|
-
const parts = text.split("\n");
|
|
511
|
-
tail.partial = text.endsWith("\n") ? "" : parts.pop() ?? "";
|
|
512
|
-
if (text.endsWith("\n")) parts.pop();
|
|
513
|
-
return parts;
|
|
514
|
-
} finally {
|
|
515
|
-
closeSync(fd);
|
|
491
|
+
return {
|
|
492
|
+
spansText: "",
|
|
493
|
+
spanCount: 0
|
|
494
|
+
};
|
|
516
495
|
}
|
|
517
496
|
}
|
|
518
|
-
function
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
try {
|
|
526
|
-
for (const event of spawnJournalRecordEvents(JSON.parse(trimmed))) {
|
|
527
|
-
if (event === void 0) continue;
|
|
528
|
-
if (!(event.kind === "settled" && event.status === "down" || event.kind === "cancelled") || typeof event.id !== "string" || typeof event.at !== "string") continue;
|
|
529
|
-
const prev = tail.at.get(event.id);
|
|
530
|
-
if (prev !== void 0 && prev >= event.at) continue;
|
|
531
|
-
tail.at.set(event.id, event.at);
|
|
532
|
-
grew = true;
|
|
533
|
-
}
|
|
534
|
-
} catch {}
|
|
497
|
+
async function readSourceOutput(opts, worker) {
|
|
498
|
+
let output = null;
|
|
499
|
+
let outputError;
|
|
500
|
+
if (worker.outRef !== void 0) try {
|
|
501
|
+
output = await opts.blobs.get(worker.outRef);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
outputError = error instanceof Error ? error.message : String(error);
|
|
535
504
|
}
|
|
536
|
-
|
|
505
|
+
if (worker.outRef !== void 0 && output === void 0 && outputError === void 0) outputError = "referenced output blob unavailable";
|
|
506
|
+
return {
|
|
507
|
+
output,
|
|
508
|
+
outputError
|
|
509
|
+
};
|
|
537
510
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
pausedOn: pause,
|
|
556
|
-
why: `; the root is paused on ${pause.stop}${left}`
|
|
557
|
-
};
|
|
558
|
-
};
|
|
559
|
-
const queuedRoot = (request) => {
|
|
560
|
-
const { pausedOn, why } = paused();
|
|
561
|
-
const key = pausedOn?.stop ?? "";
|
|
562
|
-
if (named.get(request.operationId) === key) return;
|
|
563
|
-
named.set(request.operationId, key);
|
|
564
|
-
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
565
|
-
...base(request),
|
|
566
|
-
effect: "unknown",
|
|
567
|
-
observedAt: iso(),
|
|
568
|
-
detail: `queued in the root inbox; no root turn has consumed it yet${why}`,
|
|
569
|
-
...pausedOn === void 0 ? {} : { pausedOn }
|
|
570
|
-
});
|
|
571
|
-
};
|
|
572
|
-
const answerRoot = (request, receipt) => {
|
|
573
|
-
if (!awaiting.delete(request.operationId)) return;
|
|
574
|
-
named.delete(request.operationId);
|
|
575
|
-
const { pausedOn, why } = receipt.status === "consumed" ? { why: "" } : paused();
|
|
576
|
-
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
577
|
-
...base(request),
|
|
578
|
-
...receipt.status === "consumed" ? {
|
|
579
|
-
effect: "delivered",
|
|
580
|
-
detail: `the root consumed the steer in ${receipt.attemptId}`
|
|
581
|
-
} : {
|
|
582
|
-
effect: "not_live",
|
|
583
|
-
detail: `the root did not consume the steer: ${receipt.reason}${why}`
|
|
584
|
-
},
|
|
585
|
-
observedAt: iso(),
|
|
586
|
-
...pausedOn === void 0 ? {} : { pausedOn }
|
|
587
|
-
});
|
|
588
|
-
};
|
|
589
|
-
const base = (request) => ({
|
|
590
|
-
schemaVersion: 1,
|
|
591
|
-
operationId: request.operationId,
|
|
592
|
-
requestDigest: request.requestDigest,
|
|
593
|
-
worker: request.worker,
|
|
594
|
-
requestedAt: request.at
|
|
595
|
-
});
|
|
596
|
-
let steerStamp = "";
|
|
597
|
-
let steerIdle = false;
|
|
598
|
-
const steerChanged = (phase) => {
|
|
599
|
-
let stamp = "missing";
|
|
600
|
-
try {
|
|
601
|
-
const st = statSync(workerSteerRequestsDir(deps.dir), { bigint: true });
|
|
602
|
-
stamp = `${st.dev}:${st.ino}:${st.mtimeNs}:${st.size}`;
|
|
603
|
-
} catch {
|
|
604
|
-
stamp = "missing";
|
|
605
|
-
}
|
|
606
|
-
const changed = stamp !== steerStamp;
|
|
607
|
-
if (changed && phase !== "boundary") steerStamp = stamp;
|
|
608
|
-
return changed;
|
|
609
|
-
};
|
|
610
|
-
return { async pass(phase) {
|
|
611
|
-
if (phase === "turn") for (const request of awaiting.values()) queuedRoot(request);
|
|
612
|
-
const changed = steerChanged(phase);
|
|
613
|
-
if (phase !== "final" && !changed && steerIdle) return;
|
|
614
|
-
for (const request of readWorkerSteerRequests(deps.dir)) {
|
|
615
|
-
if (phase !== "final" && deps.signal?.aborted) {
|
|
616
|
-
steerIdle = false;
|
|
617
|
-
return;
|
|
618
|
-
}
|
|
619
|
-
const rootRequest = request.worker === deps.ownerId && deps.deliverRoot !== void 0;
|
|
620
|
-
if (phase === "boundary" && !rootRequest) continue;
|
|
621
|
-
if (!rootRequest && !isDirectChildNodeId(deps, request.worker)) continue;
|
|
622
|
-
const queued = awaiting.get(request.operationId);
|
|
623
|
-
if (phase === "final" && queued !== void 0) {
|
|
624
|
-
answerRoot(queued, {
|
|
625
|
-
status: "failed",
|
|
626
|
-
messageId: request.operationId,
|
|
627
|
-
cause: "closed",
|
|
628
|
-
reason: "the run ended before a root turn read it"
|
|
629
|
-
});
|
|
630
|
-
continue;
|
|
631
|
-
}
|
|
632
|
-
if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== void 0) continue;
|
|
633
|
-
if (phase === "final") {
|
|
634
|
-
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
635
|
-
...base(request),
|
|
636
|
-
effect: "not_live",
|
|
637
|
-
observedAt: iso(),
|
|
638
|
-
detail: "run ended before the steer was applied"
|
|
639
|
-
});
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
if (!claimWorkerSteerDelivery(deps.dir, {
|
|
643
|
-
...base(request),
|
|
644
|
-
effect: "unknown",
|
|
645
|
-
observedAt: iso(),
|
|
646
|
-
detail: "delivery admitted; outcome not yet known"
|
|
647
|
-
})) continue;
|
|
648
|
-
try {
|
|
649
|
-
let outcome;
|
|
650
|
-
if (rootRequest) {
|
|
651
|
-
awaiting.set(request.operationId, request);
|
|
652
|
-
const delivered = deps.deliverRoot({
|
|
653
|
-
steer: request.message,
|
|
654
|
-
interrupt: request.interrupt,
|
|
655
|
-
messageId: request.operationId,
|
|
656
|
-
receipt: (receipt) => answerRoot(request, receipt)
|
|
657
|
-
});
|
|
658
|
-
if (!delivered) awaiting.delete(request.operationId);
|
|
659
|
-
outcome = {
|
|
660
|
-
delivered,
|
|
661
|
-
outcome: delivered ? "delivered" : "runtime-has-no-inbox"
|
|
662
|
-
};
|
|
663
|
-
} else outcome = await deps.coord.steerWorker(request.worker, request.message, { interrupt: request.interrupt });
|
|
664
|
-
if (rootRequest && outcome.delivered) {
|
|
665
|
-
if (awaiting.has(request.operationId)) queuedRoot(request);
|
|
666
|
-
continue;
|
|
667
|
-
}
|
|
668
|
-
const effect = outcome.delivered ? "delivered" : outcome.outcome === "runtime-has-no-inbox" ? "unsupported" : outcome.outcome === "unknown-worker" || outcome.outcome === "already-settled" || outcome.outcome === "scope-stopped" ? "not_live" : "unknown";
|
|
669
|
-
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
670
|
-
...base(request),
|
|
671
|
-
effect,
|
|
672
|
-
observedAt: iso(),
|
|
673
|
-
detail: rootRequest ? "the root exposes no accepting inbox at delivery time" : steerAcknowledgementDetail(outcome)
|
|
674
|
-
});
|
|
675
|
-
} catch (error) {
|
|
676
|
-
awaiting.delete(request.operationId);
|
|
677
|
-
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
678
|
-
...base(request),
|
|
679
|
-
effect: "unknown",
|
|
680
|
-
observedAt: iso(),
|
|
681
|
-
detail: "delivery outcome is unknown after a runtime error"
|
|
682
|
-
});
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
if (phase === "turn") steerIdle = true;
|
|
686
|
-
} };
|
|
687
|
-
}
|
|
688
|
-
function steerAcknowledgementDetail(outcome) {
|
|
689
|
-
switch (outcome.outcome) {
|
|
690
|
-
case "delivered": return "the owning manager delivered the steer to the exact live worker";
|
|
691
|
-
case "runtime-has-no-inbox": return "the exact worker does not expose a steer inbox";
|
|
692
|
-
case "unknown-worker": return "the owning manager does not know the exact worker";
|
|
693
|
-
case "already-settled": return "the exact worker settled before delivery";
|
|
694
|
-
case "scope-stopped": return "the owning manager stopped before delivery";
|
|
695
|
-
case "runtime-error": return "delivery outcome is unknown after a runtime error";
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
function createCancelAcknowledger(deps) {
|
|
699
|
-
const tracked = /* @__PURE__ */ new Map();
|
|
700
|
-
let runTracked;
|
|
701
|
-
const abortIssuedAt = /* @__PURE__ */ new Map();
|
|
702
|
-
const iso = () => new Date(deps.now()).toISOString();
|
|
703
|
-
const waiting = /* @__PURE__ */ new Map();
|
|
704
|
-
const reconciling = /* @__PURE__ */ new Map();
|
|
705
|
-
const regrowing = /* @__PURE__ */ new Set();
|
|
706
|
-
let inboxBytes;
|
|
707
|
-
const deaths = {
|
|
708
|
-
file: join(deps.dir, SPAWN_JOURNAL_FILE),
|
|
709
|
-
offset: 0,
|
|
710
|
-
partial: "",
|
|
711
|
-
at: /* @__PURE__ */ new Map()
|
|
712
|
-
};
|
|
713
|
-
const watch = (record) => {
|
|
714
|
-
if (record.effect === "cancel_requested") reconciling.set(record.operationId, record);
|
|
715
|
-
else reconciling.delete(record.operationId);
|
|
716
|
-
if (record.effect === "cancelled" && abortIssuedAt.has(record.operationId)) regrowing.add(record.operationId);
|
|
717
|
-
else regrowing.delete(record.operationId);
|
|
718
|
-
};
|
|
719
|
-
const write = (record) => {
|
|
720
|
-
writeWorkerCancellation(deps.dir, record);
|
|
721
|
-
tracked.set(record.operationId, record);
|
|
722
|
-
watch(record);
|
|
723
|
-
};
|
|
724
|
-
const owned = (ref) => {
|
|
725
|
-
if (isDirectChildNodeId(deps, ref)) return true;
|
|
726
|
-
if (deps.controlScope !== "run") return false;
|
|
727
|
-
return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId;
|
|
728
|
-
};
|
|
729
|
-
const deliveredTerminal = (id) => {
|
|
730
|
-
const row = deps.coord.settled().find((w) => w.id === id);
|
|
731
|
-
if (row !== void 0) return row.status;
|
|
732
|
-
const node = deps.scope.view.nodes.find((n) => n.id === id);
|
|
733
|
-
if (node === void 0) return void 0;
|
|
734
|
-
if (node.status === "done") return "done";
|
|
735
|
-
if (node.status === "failed" || node.status === "cancelled") return "down";
|
|
736
|
-
};
|
|
737
|
-
const apply = (request) => {
|
|
738
|
-
const aborted = deps.coord.abortWorker(request.worker, request.reason ?? "cancel requested");
|
|
739
|
-
const base = {
|
|
740
|
-
operationId: request.operationId,
|
|
741
|
-
worker: request.worker,
|
|
742
|
-
requestedAt: request.at,
|
|
743
|
-
observedAt: iso(),
|
|
744
|
-
...request.reason === void 0 ? {} : { reason: request.reason }
|
|
745
|
-
};
|
|
746
|
-
if (aborted !== void 0) {
|
|
747
|
-
abortIssuedAt.set(request.operationId, base.observedAt);
|
|
748
|
-
write({
|
|
749
|
-
...base,
|
|
750
|
-
effect: "cancel_requested",
|
|
751
|
-
workerId: aborted.id,
|
|
752
|
-
detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,
|
|
753
|
-
terminated: []
|
|
754
|
-
});
|
|
755
|
-
return;
|
|
756
|
-
}
|
|
757
|
-
const goneId = deps.scope.view.nodes.find((n) => (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status))?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id;
|
|
758
|
-
if (goneId !== void 0) write({
|
|
759
|
-
...base,
|
|
760
|
-
effect: "not_live",
|
|
761
|
-
workerId: goneId,
|
|
762
|
-
detail: `worker '${goneId}' had already settled before this operation was applied`,
|
|
763
|
-
terminated: []
|
|
764
|
-
});
|
|
765
|
-
};
|
|
766
|
-
/** Grows only: the worker, the record's ids, and subtree deaths at or after the abort. */
|
|
767
|
-
const provenTerminated = (record, workerId) => {
|
|
768
|
-
const since = abortIssuedAt.get(record.operationId) ?? record.observedAt;
|
|
769
|
-
return [.../* @__PURE__ */ new Set([
|
|
770
|
-
...record.terminated,
|
|
771
|
-
workerId,
|
|
772
|
-
...descendantsSince(deaths, workerId, since)
|
|
773
|
-
])].sort();
|
|
774
|
-
};
|
|
775
|
-
const reconcile = (record) => {
|
|
776
|
-
const workerId = record.workerId;
|
|
777
|
-
if (workerId === void 0) return;
|
|
778
|
-
const terminal = deliveredTerminal(workerId);
|
|
779
|
-
if (terminal === void 0) return;
|
|
780
|
-
if (terminal === "down") {
|
|
781
|
-
write({
|
|
782
|
-
...record,
|
|
783
|
-
effect: "cancelled",
|
|
784
|
-
observedAt: iso(),
|
|
785
|
-
terminated: provenTerminated(record, workerId),
|
|
786
|
-
detail: `worker '${workerId}' reached a terminal down state on the settle path`
|
|
787
|
-
});
|
|
788
|
-
return;
|
|
789
|
-
}
|
|
790
|
-
write({
|
|
791
|
-
...record,
|
|
792
|
-
effect: "not_live",
|
|
793
|
-
observedAt: iso(),
|
|
794
|
-
terminated: [],
|
|
795
|
-
detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`
|
|
796
|
-
});
|
|
797
|
-
};
|
|
798
|
-
const regrow = (record) => {
|
|
799
|
-
const workerId = record.workerId;
|
|
800
|
-
if (workerId === void 0 || !abortIssuedAt.has(record.operationId)) return;
|
|
801
|
-
const terminated = provenTerminated(record, workerId);
|
|
802
|
-
if (terminated.length > record.terminated.length) write({
|
|
803
|
-
...record,
|
|
804
|
-
observedAt: iso(),
|
|
805
|
-
terminated
|
|
806
|
-
});
|
|
807
|
-
};
|
|
808
|
-
const passRun = () => {
|
|
809
|
-
if (deps.controlScope !== "run" || deps.abortRun === void 0) return;
|
|
810
|
-
if (runTracked !== void 0) return;
|
|
811
|
-
runTracked = applyRunCancellation(deps.dir, deps.abortRun, iso);
|
|
812
|
-
};
|
|
813
|
-
const ingest = () => {
|
|
814
|
-
const file = workerCancelRequestsFile(deps.dir);
|
|
815
|
-
let size;
|
|
816
|
-
try {
|
|
817
|
-
size = statSync(file).size;
|
|
818
|
-
} catch {
|
|
819
|
-
size = null;
|
|
820
|
-
}
|
|
821
|
-
if (size === inboxBytes) return;
|
|
822
|
-
inboxBytes = size;
|
|
823
|
-
for (const request of readWorkerCancelRequests(deps.dir)) {
|
|
824
|
-
if (!owned(request.worker) || tracked.has(request.operationId) || waiting.has(request.operationId)) continue;
|
|
825
|
-
const record = readWorkerCancellation(deps.dir, request.operationId);
|
|
826
|
-
if (record === void 0) waiting.set(request.operationId, request);
|
|
827
|
-
else {
|
|
828
|
-
tracked.set(record.operationId, record);
|
|
829
|
-
watch(record);
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
};
|
|
833
|
-
const pass = (phase) => {
|
|
834
|
-
if (phase === "turn") passRun();
|
|
835
|
-
ingest();
|
|
836
|
-
const pending = [...reconciling.values()];
|
|
837
|
-
if (phase === "turn") for (const request of [...waiting.values()]) {
|
|
838
|
-
waiting.delete(request.operationId);
|
|
839
|
-
apply(request);
|
|
840
|
-
if (!tracked.has(request.operationId)) waiting.set(request.operationId, request);
|
|
841
|
-
}
|
|
842
|
-
const grew = indexDeaths(deaths);
|
|
843
|
-
for (const record of pending) {
|
|
844
|
-
const current = tracked.get(record.operationId);
|
|
845
|
-
if (current?.effect === "cancel_requested") reconcile(current);
|
|
846
|
-
}
|
|
847
|
-
if (!grew) return;
|
|
848
|
-
for (const id of [...regrowing]) {
|
|
849
|
-
const record = tracked.get(id);
|
|
850
|
-
if (record !== void 0) regrow(record);
|
|
851
|
-
}
|
|
852
|
-
};
|
|
853
|
-
return {
|
|
854
|
-
pass,
|
|
855
|
-
finish() {
|
|
856
|
-
const runRequest = deps.controlScope === "run" && deps.abortRun !== void 0 ? readRunCancelRequest(deps.dir) : void 0;
|
|
857
|
-
if (runRequest !== void 0 && readRunCancellation(deps.dir, runRequest.operationId) === void 0) writeRunCancellation(deps.dir, {
|
|
858
|
-
operationId: runRequest.operationId,
|
|
859
|
-
effect: "not_live",
|
|
860
|
-
requestedAt: runRequest.at,
|
|
861
|
-
observedAt: iso(),
|
|
862
|
-
...runRequest.reason === void 0 ? {} : { reason: runRequest.reason },
|
|
863
|
-
...runRequest.operator === void 0 ? {} : { operator: runRequest.operator },
|
|
864
|
-
detail: "run ended before the request was applied"
|
|
865
|
-
});
|
|
866
|
-
for (const request of readWorkerCancelRequests(deps.dir)) {
|
|
867
|
-
if (!owned(request.worker)) continue;
|
|
868
|
-
const record = tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId);
|
|
869
|
-
if (record === void 0) {
|
|
870
|
-
write({
|
|
871
|
-
operationId: request.operationId,
|
|
872
|
-
worker: request.worker,
|
|
873
|
-
effect: "not_live",
|
|
874
|
-
requestedAt: request.at,
|
|
875
|
-
observedAt: iso(),
|
|
876
|
-
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
877
|
-
detail: "run ended before the request was applied",
|
|
878
|
-
terminated: []
|
|
879
|
-
});
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
882
|
-
if (record.effect === "cancel_requested") write({
|
|
883
|
-
...record,
|
|
884
|
-
effect: "unknown",
|
|
885
|
-
observedAt: iso(),
|
|
886
|
-
detail: "abort issued; run ended before termination was observed"
|
|
887
|
-
});
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
};
|
|
891
|
-
}
|
|
892
|
-
function isDirectChildNodeId(owner, ref) {
|
|
893
|
-
return ref.startsWith(`${owner.ownerId}:s`) && /^s\d+$/.test(ref.slice(owner.ownerId.length + 1));
|
|
894
|
-
}
|
|
895
|
-
// src/runtime/supervise/event-bus.ts
|
|
896
|
-
/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane.
|
|
897
|
-
* @experimental In-process queue; durability is a transport swap that does not exist yet. */
|
|
898
|
-
function createEventBus(now = Date.now) {
|
|
899
|
-
const queue = [];
|
|
900
|
-
const log = [];
|
|
901
|
-
const subscribers = [];
|
|
902
|
-
const queuedHandlers = [];
|
|
903
|
-
const byKind = {};
|
|
904
|
-
const staged = /* @__PURE__ */ new WeakMap();
|
|
905
|
-
let seq = 0;
|
|
906
|
-
let published = 0;
|
|
907
|
-
let pulled = 0;
|
|
908
|
-
const matches = (r, kinds) => !kinds || kinds.includes(r.event.type);
|
|
909
|
-
const bestIndex = (kinds) => {
|
|
910
|
-
let best = -1;
|
|
911
|
-
let bestPriority = Number.NEGATIVE_INFINITY;
|
|
912
|
-
for (let i = 0; i < queue.length; i++) {
|
|
913
|
-
const r = queue[i];
|
|
914
|
-
if (!r || !matches(r, kinds)) continue;
|
|
915
|
-
if (r.priority > bestPriority) {
|
|
916
|
-
best = i;
|
|
917
|
-
bestPriority = r.priority;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
return best;
|
|
921
|
-
};
|
|
922
|
-
const pullAt = (i) => {
|
|
923
|
-
if (i < 0) return void 0;
|
|
924
|
-
pulled++;
|
|
925
|
-
return queue.splice(i, 1)[0];
|
|
926
|
-
};
|
|
927
|
-
const pullRecord = (kinds) => pullAt(bestIndex(kinds));
|
|
928
|
-
return {
|
|
929
|
-
async publish(event, opts) {
|
|
930
|
-
const record = staged.get(event) ?? {
|
|
931
|
-
seq: seq++,
|
|
932
|
-
at: now(),
|
|
933
|
-
priority: opts?.priority ?? 0,
|
|
934
|
-
event
|
|
935
|
-
};
|
|
936
|
-
staged.set(event, record);
|
|
937
|
-
for (const handler of subscribers) await handler(record);
|
|
938
|
-
staged.delete(event);
|
|
939
|
-
if (opts?.queue !== false) queue.push(record);
|
|
940
|
-
log.push(record);
|
|
941
|
-
published += 1;
|
|
942
|
-
byKind[event.type] = (byKind[event.type] ?? 0) + 1;
|
|
943
|
-
if (opts?.queue !== false) for (const handler of [...queuedHandlers]) handler(record);
|
|
944
|
-
return record;
|
|
945
|
-
},
|
|
946
|
-
pull: (kinds) => pullRecord(kinds)?.event,
|
|
947
|
-
pullRecord,
|
|
948
|
-
take: (seq) => pullAt(queue.findIndex((r) => r.seq === seq)),
|
|
949
|
-
queued(kinds) {
|
|
950
|
-
return queue.filter((r) => matches(r, kinds));
|
|
951
|
-
},
|
|
952
|
-
subscribe(handler) {
|
|
953
|
-
subscribers.push(handler);
|
|
954
|
-
return () => {
|
|
955
|
-
const i = subscribers.indexOf(handler);
|
|
956
|
-
if (i >= 0) subscribers.splice(i, 1);
|
|
957
|
-
};
|
|
958
|
-
},
|
|
959
|
-
onQueued(handler) {
|
|
960
|
-
queuedHandlers.push(handler);
|
|
961
|
-
return () => {
|
|
962
|
-
const i = queuedHandlers.indexOf(handler);
|
|
963
|
-
if (i >= 0) queuedHandlers.splice(i, 1);
|
|
964
|
-
};
|
|
965
|
-
},
|
|
966
|
-
pending(kinds) {
|
|
967
|
-
return kinds ? queue.filter((r) => matches(r, kinds)).length : queue.length;
|
|
968
|
-
},
|
|
969
|
-
history() {
|
|
970
|
-
return log;
|
|
971
|
-
},
|
|
972
|
-
stats() {
|
|
973
|
-
return {
|
|
974
|
-
published,
|
|
975
|
-
pulled,
|
|
976
|
-
byKind: { ...byKind }
|
|
977
|
-
};
|
|
978
|
-
}
|
|
979
|
-
};
|
|
980
|
-
}
|
|
981
|
-
// src/mcp/tools/coordination-analysis.ts
|
|
982
|
-
function createCoordinationAnalysis(deps) {
|
|
983
|
-
const { opts } = deps;
|
|
984
|
-
const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle);
|
|
985
|
-
const analystAssignments = loadAnalystAssignments(opts);
|
|
986
|
-
const analystRuns = /* @__PURE__ */ new Map();
|
|
987
|
-
const state = {
|
|
988
|
-
...deps,
|
|
989
|
-
analysisRoutes,
|
|
990
|
-
analystAssignments,
|
|
991
|
-
analystRuns,
|
|
992
|
-
flushedAnalystRuns: /* @__PURE__ */ new Set(),
|
|
993
|
-
definedAnalysts: [...opts.priorAnalystDefinitions ?? []],
|
|
994
|
-
maxDefinedAnalysts: opts.maxDefinedAnalysts ?? ANALYST_DEFINITION_BOUNDS.maxDefinitionsPerManager,
|
|
995
|
-
analystRunOrdinal: nextAnalystRunOrdinal(analystAssignments),
|
|
996
|
-
finishing: false,
|
|
997
|
-
managerAnalysis: void 0
|
|
998
|
-
};
|
|
999
|
-
recoverAnalystRuns(opts, analystAssignments, analystRuns);
|
|
1000
|
-
return {
|
|
1001
|
-
analysisRoutes: state.analysisRoutes,
|
|
1002
|
-
analystRuns,
|
|
1003
|
-
flushedAnalystRuns: state.flushedAnalystRuns,
|
|
1004
|
-
analystRunFinding,
|
|
1005
|
-
spawnAnalystRun: spawnAnalystRun.bind(null, state),
|
|
1006
|
-
deliverRoutedFinding: deliverRoutedFinding.bind(null, state),
|
|
1007
|
-
analystRunContext: analystRunContext.bind(null, opts),
|
|
1008
|
-
finishAnalysis: finishAnalysis.bind(null, state),
|
|
1009
|
-
definedAnalysts: state.definedAnalysts,
|
|
1010
|
-
analystMenu: analystMenu.bind(null, state),
|
|
1011
|
-
defineAnalyst: defineAnalyst.bind(null, state),
|
|
1012
|
-
isFinishing: () => state.finishing
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
/** The durable analyst assignments of a prior process, refusing two that disagree on one id. */
|
|
1016
|
-
function loadAnalystAssignments(opts) {
|
|
1017
|
-
const analystAssignments = /* @__PURE__ */ new Map();
|
|
1018
|
-
for (const record of opts.priorJournal ?? []) {
|
|
1019
|
-
if (record.event.type !== "analyst-assignment") continue;
|
|
1020
|
-
const assignment = record.event.assignment;
|
|
1021
|
-
const prior = analystAssignments.get(assignment.assignmentId);
|
|
1022
|
-
if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(assignment)) throw new Error(`coordination: conflicting analyst assignment '${assignment.assignmentId}'`);
|
|
1023
|
-
analystAssignments.set(assignment.assignmentId, detachedFrozen(assignment));
|
|
1024
|
-
}
|
|
1025
|
-
return analystAssignments;
|
|
1026
|
-
}
|
|
1027
|
-
function nextAnalystRunOrdinal(analystAssignments) {
|
|
1028
|
-
let analystRunOrdinal = 0;
|
|
1029
|
-
for (const assignment of analystAssignments.values()) {
|
|
1030
|
-
const ordinal = Number(/:o(\d+)$/.exec(assignment.assignmentId)?.[1]);
|
|
1031
|
-
if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal === Number.MAX_SAFE_INTEGER) throw new Error(`coordination: invalid analyst assignment '${assignment.assignmentId}'`);
|
|
1032
|
-
analystRunOrdinal = Math.max(analystRunOrdinal, ordinal + 1);
|
|
1033
|
-
}
|
|
1034
|
-
return analystRunOrdinal;
|
|
1035
|
-
}
|
|
1036
|
-
/** Re-attach every analyst node a prior process journaled to its durable assignment. */
|
|
1037
|
-
function recoverAnalystRuns(opts, analystAssignments, analystRuns) {
|
|
1038
|
-
for (const node of [...opts.scope.resume?.view.nodes ?? [], ...opts.scope.view.nodes]) {
|
|
1039
|
-
if (node.parent !== opts.scope.view.root || !node.assignmentId?.startsWith("analyst:")) continue;
|
|
1040
|
-
const assignment = analystAssignments.get(node.assignmentId);
|
|
1041
|
-
if (!assignment) throw new Error(`coordination: analyst assignment '${node.assignmentId}' has no durable source record; refusing to treat its review as a worker result`);
|
|
1042
|
-
if (node.identity && (node.identity.profileDigest !== assignment.profileDigest || node.identity.taskDigest !== assignment.taskDigest)) throw new Error(`coordination: analyst assignment '${node.assignmentId}' conflicts with its journaled execution identity`);
|
|
1043
|
-
analystRuns.set(node.id, {
|
|
1044
|
-
route: {
|
|
1045
|
-
kind: assignment.kind,
|
|
1046
|
-
...assignment.to === void 0 ? {} : { to: assignment.to }
|
|
1047
|
-
},
|
|
1048
|
-
sourceWorker: assignment.sourceWorker,
|
|
1049
|
-
assignmentId: assignment.assignmentId
|
|
1050
|
-
});
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
const analystRunFinding = (run, settled) => detachedFrozen({
|
|
1054
|
-
type: "finding",
|
|
1055
|
-
finding: canonicalFindingEvent({
|
|
1056
|
-
fromWorker: run.sourceWorker,
|
|
1057
|
-
analyst: run.route.kind,
|
|
1058
|
-
analystWorkerId: settled.handle.id,
|
|
1059
|
-
assignmentId: run.assignmentId,
|
|
1060
|
-
findings: settled.kind === "done" ? settled.out : { analystRunFailed: settled.reason }
|
|
1061
|
-
})
|
|
1062
|
-
});
|
|
1063
|
-
/** The settled worker's persisted tool-trace spans; degraded evidence reads as empty, never a throw. */
|
|
1064
|
-
async function readTraceSpans(opts, worker) {
|
|
1065
|
-
if (worker.trace.status !== "available") return {
|
|
1066
|
-
spansText: "",
|
|
1067
|
-
spanCount: 0
|
|
1068
|
-
};
|
|
1069
|
-
try {
|
|
1070
|
-
const raw = await opts.blobs.get(worker.trace.traceRef);
|
|
1071
|
-
const artifact = parseWorkerToolTraceArtifact(raw, worker.trace.traceRef);
|
|
1072
|
-
return {
|
|
1073
|
-
spansText: safeJsonText(artifact.spans),
|
|
1074
|
-
spanCount: artifact.spans.length
|
|
1075
|
-
};
|
|
1076
|
-
} catch {
|
|
1077
|
-
return {
|
|
1078
|
-
spansText: "",
|
|
1079
|
-
spanCount: 0
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
async function readSourceOutput(opts, worker) {
|
|
1084
|
-
let output = null;
|
|
1085
|
-
let outputError;
|
|
1086
|
-
if (worker.outRef !== void 0) try {
|
|
1087
|
-
output = await opts.blobs.get(worker.outRef);
|
|
1088
|
-
} catch (error) {
|
|
1089
|
-
outputError = error instanceof Error ? error.message : String(error);
|
|
1090
|
-
}
|
|
1091
|
-
if (worker.outRef !== void 0 && output === void 0 && outputError === void 0) outputError = "referenced output blob unavailable";
|
|
1092
|
-
return {
|
|
1093
|
-
output,
|
|
1094
|
-
outputError
|
|
1095
|
-
};
|
|
1096
|
-
}
|
|
1097
|
-
/** The complete source envelope an analyst reads: the worker, its output, and a manager-end checkpoint. */
|
|
1098
|
-
function sourceEvidenceEnvelope({ opts, ledger }, route, worker, output, outputError) {
|
|
1099
|
-
return JSON.parse(safeJsonText({
|
|
1100
|
-
worker,
|
|
1101
|
-
output: output ?? null,
|
|
1102
|
-
...outputError ? { outputError } : {},
|
|
1103
|
-
...route.at === "manager-end" ? { managerCheckpoint: {
|
|
1104
|
-
managerId: opts.scope.view.root,
|
|
1105
|
-
nodes: opts.scope.view.nodes.filter((node) => !node.assignmentId?.startsWith("analyst:")).map((node) => ({
|
|
1106
|
-
id: node.id,
|
|
1107
|
-
parent: node.parent,
|
|
1108
|
-
assignmentId: node.assignmentId,
|
|
1109
|
-
status: node.status
|
|
1110
|
-
})),
|
|
1111
|
-
settled: ledger.map(({ resumed: _resumed, ...row }) => row)
|
|
1112
|
-
} } : {}
|
|
1113
|
-
}));
|
|
511
|
+
/** The complete source envelope an analyst reads: the worker, its output, and a manager-end checkpoint. */
|
|
512
|
+
function sourceEvidenceEnvelope({ opts, ledger }, route, worker, output, outputError) {
|
|
513
|
+
return JSON.parse(safeJsonText({
|
|
514
|
+
worker,
|
|
515
|
+
output: output ?? null,
|
|
516
|
+
...outputError ? { outputError } : {},
|
|
517
|
+
...route.at === "manager-end" ? { managerCheckpoint: {
|
|
518
|
+
managerId: opts.scope.view.root,
|
|
519
|
+
nodes: opts.scope.view.nodes.filter((node) => !node.assignmentId?.startsWith("analyst:")).map((node) => ({
|
|
520
|
+
id: node.id,
|
|
521
|
+
parent: node.parent,
|
|
522
|
+
assignmentId: node.assignmentId,
|
|
523
|
+
status: node.status
|
|
524
|
+
})),
|
|
525
|
+
settled: ledger.map(({ resumed: _resumed, ...row }) => row)
|
|
526
|
+
} } : {}
|
|
527
|
+
}));
|
|
1114
528
|
}
|
|
1115
529
|
const excerpt = (text, limit) => ({
|
|
1116
530
|
text: text.slice(0, limit),
|
|
@@ -1560,6 +974,82 @@ function mountAnalystsTools({ opts, tools, ledger, nodeForWorker, analystMenu, a
|
|
|
1560
974
|
});
|
|
1561
975
|
}
|
|
1562
976
|
}
|
|
977
|
+
// src/mcp/tools/coordination-events.ts
|
|
978
|
+
/** Default and maximum bounds for one {@link CoordinationTools} journal read. The defaults are
|
|
979
|
+
* sized for a driver turn (a page a model can read and still have room to act on); the maxima
|
|
980
|
+
* bound what a single tool result may cost even when the caller asks for everything. */
|
|
981
|
+
const JOURNAL_READ_BOUNDS = Object.freeze({
|
|
982
|
+
defaultLimit: 50,
|
|
983
|
+
maxLimit: 500,
|
|
984
|
+
defaultMaxBytes: 16384,
|
|
985
|
+
maxMaxBytes: 262144
|
|
986
|
+
});
|
|
987
|
+
/** Every `CoordinationEvent` kind `read_journal` can return — the tool advertises this list in its
|
|
988
|
+
* JSON Schema AND filters on it, so the schema cannot promise a kind the filter drops. */
|
|
989
|
+
const journalEventKinds = [
|
|
990
|
+
"question",
|
|
991
|
+
"settled",
|
|
992
|
+
"finding",
|
|
993
|
+
"submission",
|
|
994
|
+
"steer",
|
|
995
|
+
"answer",
|
|
996
|
+
"instruction",
|
|
997
|
+
"delivery-attempt",
|
|
998
|
+
"mail",
|
|
999
|
+
"escalation",
|
|
1000
|
+
"analyst-defined",
|
|
1001
|
+
"analyst-assignment",
|
|
1002
|
+
"acknowledgement",
|
|
1003
|
+
"tool-outcome",
|
|
1004
|
+
"tool-timing",
|
|
1005
|
+
"lead-message",
|
|
1006
|
+
"map",
|
|
1007
|
+
"route"
|
|
1008
|
+
];
|
|
1009
|
+
/** The reserved coordination verb names — the complete set `createCoordinationTools` can emit
|
|
1010
|
+
* (the analyst pair is conditional but still reserved). A driver's extra WORK tools must not
|
|
1011
|
+
* collide with any of these, or it could no longer coordinate; callers validate eagerly against
|
|
1012
|
+
* this set so the conflict fails loud at construction, not buried in a swallowed `act()` throw.
|
|
1013
|
+
*
|
|
1014
|
+
* Every name here must also stay clear of the tools a coding harness publishes NATIVELY
|
|
1015
|
+
* (`harnessNativeToolNames`, `mcp/harness-native-tools`). A harness prefixes an MCP tool with its
|
|
1016
|
+
* server name, so the two never collide on the wire — but a driver reads a BARE word out of a
|
|
1017
|
+
* prompt, and a bare word that the harness also publishes resolves to the harness's own tool.
|
|
1018
|
+
* The spawn verb is `spawn_worker` for that reason: the runtime's vocabulary for the spawned
|
|
1019
|
+
* thing is a worker (`workerId`, `workerSlots`, the per-worker budget), and no known harness
|
|
1020
|
+
* publishes that name. `tests/kernel/harness-native-tools.test.ts` holds the set clear. */
|
|
1021
|
+
const coordinationVerbNames = [
|
|
1022
|
+
"spawn_worker",
|
|
1023
|
+
"cancel_worker",
|
|
1024
|
+
"observe_agent",
|
|
1025
|
+
"steer_agent",
|
|
1026
|
+
"list_questions",
|
|
1027
|
+
"answer_question",
|
|
1028
|
+
"ask_parent",
|
|
1029
|
+
"submit_result",
|
|
1030
|
+
"stop",
|
|
1031
|
+
"report_blocked",
|
|
1032
|
+
"read_continuation",
|
|
1033
|
+
"read_journal",
|
|
1034
|
+
"list_analysts",
|
|
1035
|
+
"run_analyst",
|
|
1036
|
+
"define_analyst",
|
|
1037
|
+
"run_graph"
|
|
1038
|
+
];
|
|
1039
|
+
/**
|
|
1040
|
+
* The `CoordinationEvent` kinds that wake a waiting manager. The queue carries the UP-leg only:
|
|
1041
|
+
* `steer` / `answer` / `instruction` / `delivery-attempt` are recorded `queue: false` (history and
|
|
1042
|
+
* subscribers, never delivered back), and `mail` is delivered to its addressee's inbox. A
|
|
1043
|
+
* `question` on this bus is the manager's own `ask_parent`, already escalated: it never wakes the
|
|
1044
|
+
* asker, whose answer arrives as a `lead-message`.
|
|
1045
|
+
*/
|
|
1046
|
+
const wakeEventKinds = [
|
|
1047
|
+
"settled",
|
|
1048
|
+
"finding",
|
|
1049
|
+
"tool-outcome",
|
|
1050
|
+
"lead-message",
|
|
1051
|
+
"map"
|
|
1052
|
+
];
|
|
1563
1053
|
// src/mcp/tools/coordination-tool-timeout.ts
|
|
1564
1054
|
async function runWithin(work, ms, message) {
|
|
1565
1055
|
let timer;
|
|
@@ -1849,6 +1339,110 @@ function createDownMessages({ opts, bus, lifetime }) {
|
|
|
1849
1339
|
steerWorker
|
|
1850
1340
|
};
|
|
1851
1341
|
}
|
|
1342
|
+
// src/mcp/tools/coordination-budget.ts
|
|
1343
|
+
/** Each channel spent beyond its budget, as spent of budget: `tokens 235,857 of 42,000` or
|
|
1344
|
+
* `deadline 3,857 s of 2,400 s`. */
|
|
1345
|
+
function budgetOverspendText(violation) {
|
|
1346
|
+
const count = (value) => value.toLocaleString("en-US");
|
|
1347
|
+
return violation.overspent.map((entry) => entry.channel === "deadline" ? `deadline ${count(Math.round(entry.spent / 1e3))} s of ${count(Math.round(entry.reserved / 1e3))} s` : `${entry.channel} ${count(entry.spent)} of ${count(entry.reserved)}`).join("; ");
|
|
1348
|
+
}
|
|
1349
|
+
/** What a manager can do with a keyed worker its budget stopped. */
|
|
1350
|
+
const BUDGET_STOP_NEXT = "spawn_worker with the same key and a larger budget continues this session where it stopped; cancel_worker releases it";
|
|
1351
|
+
/** Every cause at zero — a pre-flight publishes its whole ledger from the first read. */
|
|
1352
|
+
function emptyPreflightCounts() {
|
|
1353
|
+
return {
|
|
1354
|
+
"model-route": 0,
|
|
1355
|
+
"bridge-full": 0,
|
|
1356
|
+
"unmountable-tool": 0,
|
|
1357
|
+
"unprovisionable-profile": 0
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
/** The optional per-spawn budget `spawn_worker` and `run_graph` take. */
|
|
1361
|
+
const spawnBudgetArg = {
|
|
1362
|
+
type: "object",
|
|
1363
|
+
description: "Optional per-spawn budget that merges over the per-worker default (per field). Only set the ceilings this sub-task needs raised; the conserved pool still fences.",
|
|
1364
|
+
properties: {
|
|
1365
|
+
maxIterations: {
|
|
1366
|
+
type: "number",
|
|
1367
|
+
minimum: 0
|
|
1368
|
+
},
|
|
1369
|
+
maxTokens: {
|
|
1370
|
+
type: "number",
|
|
1371
|
+
minimum: 0
|
|
1372
|
+
},
|
|
1373
|
+
maxUsd: {
|
|
1374
|
+
type: "number",
|
|
1375
|
+
minimum: 0
|
|
1376
|
+
},
|
|
1377
|
+
deadlineMs: {
|
|
1378
|
+
type: "number",
|
|
1379
|
+
minimum: 0
|
|
1380
|
+
},
|
|
1381
|
+
resources: {
|
|
1382
|
+
type: "object",
|
|
1383
|
+
additionalProperties: {
|
|
1384
|
+
type: "object",
|
|
1385
|
+
properties: {
|
|
1386
|
+
unit: {
|
|
1387
|
+
type: "string",
|
|
1388
|
+
minLength: 1
|
|
1389
|
+
},
|
|
1390
|
+
limit: {
|
|
1391
|
+
type: "integer",
|
|
1392
|
+
minimum: 0,
|
|
1393
|
+
maximum: Number.MAX_SAFE_INTEGER
|
|
1394
|
+
}
|
|
1395
|
+
},
|
|
1396
|
+
required: ["unit", "limit"]
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
};
|
|
1401
|
+
function budgetField(channel) {
|
|
1402
|
+
return channel.startsWith("resource:") ? `resources.${channel.slice(9)}.limit` : BUDGET_FIELD[channel];
|
|
1403
|
+
}
|
|
1404
|
+
/** One clause per short channel. Iterations can be requested at exactly `free`: a driver's own
|
|
1405
|
+
* turns charge none. Tokens and dollars cannot: the driver's next turn is metered from the same
|
|
1406
|
+
* pool before its retry reaches admission, so the clause says to leave room. */
|
|
1407
|
+
function shortfallClause(shortfall) {
|
|
1408
|
+
const { channel, requested, free } = shortfall;
|
|
1409
|
+
const field = budgetField(channel);
|
|
1410
|
+
if (shortfall.closedByUnknownSpend === true) return `${channel} is closed: work with unmeasured ${channel} usage ran under the run's enforced limit, so this run admits no further spawn at any budget`;
|
|
1411
|
+
const asked = `this spawn asked for budget.${field} ${requested}`;
|
|
1412
|
+
const held = shortfall.held ?? 0;
|
|
1413
|
+
const most = free + held;
|
|
1414
|
+
if (most === 0) return `${channel} has nothing free and none held by your running workers (${asked})`;
|
|
1415
|
+
const room = held > 0 ? `${free} free now and ${held} held by your running workers, which a spawn waits for` : `${free} free${channel === "iterations" || channel.startsWith("resource:") ? "" : " right now"}`;
|
|
1416
|
+
if (channel === "iterations" || channel.startsWith("resource:")) return `${channel} has ${room} (${asked}); budget.${field} at most ${most} fits`;
|
|
1417
|
+
return `${channel} has ${room} (${asked}); your own turns draw ${channel} from this same pool before a retry is admitted, so ask for well under ${most}`;
|
|
1418
|
+
}
|
|
1419
|
+
/**
|
|
1420
|
+
* The reason text `spawn_worker` returns for a refused spawn. Every rejection kind names its own
|
|
1421
|
+
* cause: a live-worker cap, a depth limit, or a key collision is not an empty budget, and telling a
|
|
1422
|
+
* driver "no allocation left" for those sends it after the wrong fix. A `budget-exhausted` refusal
|
|
1423
|
+
* names every channel that did not fit and the amounts, so the driver can size its next request.
|
|
1424
|
+
*/
|
|
1425
|
+
function spawnRefusalReason(reason, shortfalls, pinned) {
|
|
1426
|
+
switch (reason) {
|
|
1427
|
+
case "usd-unbudgeted": return pinned.usdUnbudgeted;
|
|
1428
|
+
case "in-doubt": return pinned.inDoubt;
|
|
1429
|
+
case "scope-settled": return pinned.scopeSettled;
|
|
1430
|
+
case "scope-aborted": return "this run stopped admitting work (it was cancelled, passed its deadline, or too many children went down); no further worker can start";
|
|
1431
|
+
case "depth-exceeded": return "this spawn would exceed the run's maxDepth; a worker at the deepest level cannot start children of its own";
|
|
1432
|
+
case "duplicate-key": return "a worker under this key is still live; wait for it to settle, or use a different key for different work";
|
|
1433
|
+
case "key-conflict": return "this key is already recorded for a different profile or task in this run's journal; use a new key for different work";
|
|
1434
|
+
case "invalid-identity": return "a keyed spawn needs a complete execution identity to journal, and this profile and task did not produce one; spawn again without a key";
|
|
1435
|
+
case "budget-exhausted":
|
|
1436
|
+
if (shortfalls === void 0 || shortfalls.length === 0) return "the conserved pool refused this spawn (budget-exhausted): the run's remaining budget cannot cover this worker's budget";
|
|
1437
|
+
if (shortfalls.some((shortfall) => shortfall.closedByUnknownSpend === true)) return `the run pool refused this spawn: ${shortfallClause(shortfalls.find((shortfall) => shortfall.closedByUnknownSpend === true))}; the caller must re-run with a measurable or larger root budget`;
|
|
1438
|
+
return `the run pool refused this spawn: ${shortfalls.map(shortfallClause).join("; ")}; or ask the caller for a larger root budget`;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
const BUDGET_FIELD = {
|
|
1442
|
+
tokens: "maxTokens",
|
|
1443
|
+
iterations: "maxIterations",
|
|
1444
|
+
usd: "maxUsd"
|
|
1445
|
+
};
|
|
1852
1446
|
// src/mcp/tools/coordination-graph-tools.ts
|
|
1853
1447
|
function mountGraphsTools({ opts, tools, admitSpawn }) {
|
|
1854
1448
|
if (opts.graphs) {
|
|
@@ -4994,272 +4588,678 @@ function assembleTools(parts) {
|
|
|
4994
4588
|
});
|
|
4995
4589
|
mountGraphsTools({
|
|
4996
4590
|
opts,
|
|
4997
|
-
tools,
|
|
4998
|
-
admitSpawn
|
|
4591
|
+
tools,
|
|
4592
|
+
admitSpawn
|
|
4593
|
+
});
|
|
4594
|
+
mountAnalystsTools({
|
|
4595
|
+
opts,
|
|
4596
|
+
tools,
|
|
4597
|
+
ledger,
|
|
4598
|
+
nodeForWorker,
|
|
4599
|
+
analystMenu: analysis.analystMenu,
|
|
4600
|
+
analystRunContext: analysis.analystRunContext,
|
|
4601
|
+
defineAnalyst: analysis.defineAnalyst
|
|
4602
|
+
});
|
|
4603
|
+
return tools.map((tool) => timeCoordinationTool(bus, tool));
|
|
4604
|
+
}
|
|
4605
|
+
/** Record handler duration for every coordination tool call without changing its result. */
|
|
4606
|
+
function timeCoordinationTool(bus, tool) {
|
|
4607
|
+
return {
|
|
4608
|
+
...tool,
|
|
4609
|
+
handler: async (raw) => {
|
|
4610
|
+
const receivedAt = Date.now();
|
|
4611
|
+
try {
|
|
4612
|
+
const value = await tool.handler(raw);
|
|
4613
|
+
await recordToolTiming(bus, tool.name, receivedAt, true, value);
|
|
4614
|
+
return value;
|
|
4615
|
+
} catch (error) {
|
|
4616
|
+
await recordToolTiming(bus, tool.name, receivedAt, false, error);
|
|
4617
|
+
throw error;
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
};
|
|
4621
|
+
}
|
|
4622
|
+
async function recordToolTiming(bus, tool, receivedAt, ok, value) {
|
|
4623
|
+
try {
|
|
4624
|
+
await bus.publish({
|
|
4625
|
+
type: "tool-timing",
|
|
4626
|
+
call: {
|
|
4627
|
+
tool,
|
|
4628
|
+
receivedAt,
|
|
4629
|
+
elapsedMs: Math.max(0, Date.now() - receivedAt),
|
|
4630
|
+
responseBytes: responseUtf8Bytes(ok ? value : errorText(value)),
|
|
4631
|
+
ok
|
|
4632
|
+
}
|
|
4633
|
+
}, { queue: false });
|
|
4634
|
+
} catch (error) {
|
|
4635
|
+
console.error("Runtime could not record coordination tool timing", {
|
|
4636
|
+
tool,
|
|
4637
|
+
error: error instanceof Error ? error.message : String(error)
|
|
4638
|
+
});
|
|
4639
|
+
}
|
|
4640
|
+
}
|
|
4641
|
+
function responseUtf8Bytes(value) {
|
|
4642
|
+
if (typeof value === "string") return Buffer.byteLength(value);
|
|
4643
|
+
try {
|
|
4644
|
+
return Buffer.byteLength(JSON.stringify(value) ?? "null");
|
|
4645
|
+
} catch {
|
|
4646
|
+
return Buffer.byteLength(String(value));
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
function errorText(error) {
|
|
4650
|
+
return error instanceof Error ? error.message : String(error);
|
|
4651
|
+
}
|
|
4652
|
+
function managerSurface(parts, tools) {
|
|
4653
|
+
const { opts, bus, state, ledger, questionLedger, spawnAdmission, analysis, settlements, messages, workers, waiting, intake, journal, peerMail, ackEnv, ready } = parts;
|
|
4654
|
+
return {
|
|
4655
|
+
tools,
|
|
4656
|
+
ready,
|
|
4657
|
+
history: () => bus.history(),
|
|
4658
|
+
raiseFinding: (finding) => bus.publish({
|
|
4659
|
+
type: "finding",
|
|
4660
|
+
finding: canonicalFindingEvent(finding)
|
|
4661
|
+
}).then(() => void 0),
|
|
4662
|
+
steerWorker: messages.steerWorker,
|
|
4663
|
+
stats: () => opts.preflightSpawn === void 0 ? bus.stats() : {
|
|
4664
|
+
...bus.stats(),
|
|
4665
|
+
preflight: { ...spawnAdmission.preflightCounts }
|
|
4666
|
+
},
|
|
4667
|
+
isStopped: () => state.stopped,
|
|
4668
|
+
stopReason: () => state.reason,
|
|
4669
|
+
submittedResult: () => state.submitted,
|
|
4670
|
+
settled: () => ledger,
|
|
4671
|
+
questions: () => questionLedger.questions,
|
|
4672
|
+
escalations: () => questionLedger.escalations,
|
|
4673
|
+
definedAnalysts: () => analysis.definedAnalysts,
|
|
4674
|
+
drainResolved: settlements.drainResolved,
|
|
4675
|
+
finishAnalysis: analysis.finishAnalysis,
|
|
4676
|
+
abortWorker: spawnAdmission.abortWorker,
|
|
4677
|
+
beginDriverAttempt: (attempt) => {
|
|
4678
|
+
state.driverAttempt = attempt;
|
|
4679
|
+
},
|
|
4680
|
+
endDriverAttempt: async (outcome) => {
|
|
4681
|
+
const attempt = state.driverAttempt;
|
|
4682
|
+
if (outcome === "completed") await acknowledgeDeliveries(ackEnv, state.deliveries.filter((delivery) => delivery.attempt === attempt), "turn-completed");
|
|
4683
|
+
},
|
|
4684
|
+
hasOpenWork: waiting.hasOpenWork,
|
|
4685
|
+
awaitWake: waiting.awaitWake,
|
|
4686
|
+
awaitSettlement: waiting.awaitSettlement,
|
|
4687
|
+
receiveLeadMessage: intake.receiveLeadMessage,
|
|
4688
|
+
queuedLeadMessages: () => bus.queued(["lead-message"]).map((record) => record.seq),
|
|
4689
|
+
awaitLeadMessage: (signal) => new Promise((resolve) => {
|
|
4690
|
+
if (signal.aborted) {
|
|
4691
|
+
resolve();
|
|
4692
|
+
return;
|
|
4693
|
+
}
|
|
4694
|
+
const done = () => {
|
|
4695
|
+
unsubscribe();
|
|
4696
|
+
signal.removeEventListener("abort", done);
|
|
4697
|
+
resolve();
|
|
4698
|
+
};
|
|
4699
|
+
const unsubscribe = bus.onQueued((record) => {
|
|
4700
|
+
if (record.event.type === "lead-message") done();
|
|
4701
|
+
});
|
|
4702
|
+
signal.addEventListener("abort", done, { once: true });
|
|
4703
|
+
}),
|
|
4704
|
+
openToolReceipt: intake.openToolReceipt,
|
|
4705
|
+
settleToolReceipt: intake.settleToolReceipt,
|
|
4706
|
+
reentryState: () => managerReentryState({
|
|
4707
|
+
opts,
|
|
4708
|
+
ledger,
|
|
4709
|
+
deliveries: state.deliveries,
|
|
4710
|
+
priorJournal: journal.priorJournal,
|
|
4711
|
+
bus,
|
|
4712
|
+
journal,
|
|
4713
|
+
openWork: workers.openWork,
|
|
4714
|
+
driverAttempt: state.driverAttempt,
|
|
4715
|
+
lastRejection: state.lastRejection
|
|
4716
|
+
}),
|
|
4717
|
+
blocked: () => [...state.blockedReports],
|
|
4718
|
+
checkReads: () => state.checkReads,
|
|
4719
|
+
recordCheckRead: (read) => appendCheckRead(state, read),
|
|
4720
|
+
...peerMail ? { peerMail } : {}
|
|
4721
|
+
};
|
|
4722
|
+
}
|
|
4723
|
+
/** The map and route schedulers of one manager, which share the nodes of a prior process's spawns. */
|
|
4724
|
+
function createFlowRouting({ opts, bus, spawnAdmission, settleCommitted, stop }) {
|
|
4725
|
+
const { profileNameByWorker, resolveContinuity, admitSpawn } = spawnAdmission;
|
|
4726
|
+
const committedNodes = /* @__PURE__ */ new Map();
|
|
4727
|
+
const nodeOf = (id) => profileNameByWorker.get(id) ?? committedNodes.get(id);
|
|
4728
|
+
const settleNode = (id, node) => {
|
|
4729
|
+
committedNodes.set(id, node);
|
|
4730
|
+
return settleCommitted(id);
|
|
4731
|
+
};
|
|
4732
|
+
const maps = createMapRouting({
|
|
4733
|
+
opts,
|
|
4734
|
+
bus,
|
|
4735
|
+
admitSpawn: (input) => admitSpawn(input),
|
|
4736
|
+
nodeOf,
|
|
4737
|
+
settleCommitted: settleNode,
|
|
4738
|
+
endInDoubt: (node, source) => routes.endInDoubt(node, source)
|
|
4999
4739
|
});
|
|
5000
|
-
|
|
4740
|
+
const routes = createRouteRouting({
|
|
5001
4741
|
opts,
|
|
5002
|
-
|
|
5003
|
-
|
|
5004
|
-
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
|
|
4742
|
+
bus,
|
|
4743
|
+
admitSpawn: (input) => admitSpawn(input),
|
|
4744
|
+
resolveContinuity,
|
|
4745
|
+
nodeOf,
|
|
4746
|
+
settleCommitted: settleNode,
|
|
4747
|
+
stop
|
|
5008
4748
|
});
|
|
5009
|
-
return tools.map((tool) => timeCoordinationTool(bus, tool));
|
|
5010
|
-
}
|
|
5011
|
-
/** Record handler duration for every coordination tool call without changing its result. */
|
|
5012
|
-
function timeCoordinationTool(bus, tool) {
|
|
5013
4749
|
return {
|
|
4750
|
+
maps,
|
|
4751
|
+
routes
|
|
4752
|
+
};
|
|
4753
|
+
}
|
|
4754
|
+
function createPeerMail(opts, bus) {
|
|
4755
|
+
return opts.peerMail ? createPeerMailbox({
|
|
4756
|
+
scope: opts.scope,
|
|
4757
|
+
publish: (mail) => bus.publish({
|
|
4758
|
+
type: "mail",
|
|
4759
|
+
mail
|
|
4760
|
+
}, { queue: false }).then(() => void 0),
|
|
4761
|
+
...opts.peerMail.limits ? { limits: opts.peerMail.limits } : {}
|
|
4762
|
+
}) : void 0;
|
|
4763
|
+
}
|
|
4764
|
+
function registerChildQuestionInbox(opts, { addQuestion, emitNewQuestion }, workerByAssignment, nodeForWorker) {
|
|
4765
|
+
opts.onChildQuestionInbox?.(async (assignmentId, asked) => {
|
|
4766
|
+
const workerId = workerByAssignment.get(assignmentId);
|
|
4767
|
+
if (workerId === void 0 || nodeForWorker(workerId) === void 0) return {
|
|
4768
|
+
delivered: false,
|
|
4769
|
+
reason: `the parent manager has no worker for assignment ${JSON.stringify(assignmentId)}`
|
|
4770
|
+
};
|
|
4771
|
+
return {
|
|
4772
|
+
delivered: true,
|
|
4773
|
+
to: `parent manager question ${(await emitNewQuestion(addQuestion({
|
|
4774
|
+
from: workerId,
|
|
4775
|
+
level: asked.level,
|
|
4776
|
+
question: asked.question,
|
|
4777
|
+
reason: asked.reason,
|
|
4778
|
+
...asked.options ? { options: asked.options } : {},
|
|
4779
|
+
urgency: asked.urgency
|
|
4780
|
+
}, workerId))).id}`
|
|
4781
|
+
};
|
|
4782
|
+
});
|
|
4783
|
+
}
|
|
4784
|
+
/**
|
|
4785
|
+
* Let `observe_agent` and `read_journal` read a peer root's own record when the run enables peer
|
|
4786
|
+
* audit, then register this manager's tools with the peer registry. Mutates the two tools in place.
|
|
4787
|
+
*/
|
|
4788
|
+
function mountPeerAudit({ opts, tools, readJournal }) {
|
|
4789
|
+
for (const tool of tools) {
|
|
4790
|
+
if (tool.name !== "observe_agent" && tool.name !== "read_journal") continue;
|
|
4791
|
+
const ownHandler = tool.handler;
|
|
4792
|
+
const name = tool.name;
|
|
4793
|
+
const schema = tool.inputSchema;
|
|
4794
|
+
schema.properties = {
|
|
4795
|
+
...schema.properties,
|
|
4796
|
+
peerId: {
|
|
4797
|
+
type: "string",
|
|
4798
|
+
description: "Read a peer root's own record, using its workerId from read_mail.peers. Read-only; omit for your own tree."
|
|
4799
|
+
}
|
|
4800
|
+
};
|
|
4801
|
+
tool.handler = async (raw) => {
|
|
4802
|
+
const args = obj(raw);
|
|
4803
|
+
if (args.peerId === void 0) return ownHandler(raw);
|
|
4804
|
+
const peerId = str(args.peerId, "peerId");
|
|
4805
|
+
const { peerId: _peerId, ...readArgs } = args;
|
|
4806
|
+
return opts.peerAudit?.read(peerId, name, readArgs);
|
|
4807
|
+
};
|
|
4808
|
+
}
|
|
4809
|
+
opts.peerAudit.register(opts.scope.view.root, tools.map((tool) => tool.name === "read_journal" ? {
|
|
5014
4810
|
...tool,
|
|
5015
|
-
handler: async (raw) =>
|
|
5016
|
-
|
|
4811
|
+
handler: async (raw) => readJournal(raw, false)
|
|
4812
|
+
} : tool));
|
|
4813
|
+
}
|
|
4814
|
+
/**
|
|
4815
|
+
* Seed the settled ledger from a resumed scope and own the replay of its events onto the bus.
|
|
4816
|
+
* Replayed reviews remain findings. They cannot enter the completion pool or recursively
|
|
4817
|
+
* trigger another analyst, even when the resumed configuration changes its analyst routes.
|
|
4818
|
+
*/
|
|
4819
|
+
function createResumeReplay({ opts, bus, ledger, analysis, projectSettled }) {
|
|
4820
|
+
const { analystRuns, flushedAnalystRuns, analystRunFinding } = analysis;
|
|
4821
|
+
const resumedWorkers = [];
|
|
4822
|
+
const resumedFindings = [];
|
|
4823
|
+
for (const s of opts.scope.resume?.settled ?? []) {
|
|
4824
|
+
const analyst = analystRuns.get(s.handle.id);
|
|
4825
|
+
if (analyst) {
|
|
4826
|
+
resumedFindings.push(analystRunFinding(analyst, s));
|
|
4827
|
+
analystRuns.delete(s.handle.id);
|
|
4828
|
+
flushedAnalystRuns.add(s.handle.id);
|
|
4829
|
+
continue;
|
|
4830
|
+
}
|
|
4831
|
+
const worker = projectSettled(s, true);
|
|
4832
|
+
resumedWorkers.push(worker);
|
|
4833
|
+
ledger.push(worker);
|
|
4834
|
+
}
|
|
4835
|
+
const resumeEvents = opts.replaySettlements ? [...resumedWorkers.map((worker) => detachedFrozen({
|
|
4836
|
+
type: "settled",
|
|
4837
|
+
worker
|
|
4838
|
+
})), ...resumedFindings] : [];
|
|
4839
|
+
let resumeEventIndex = 0;
|
|
4840
|
+
let readyInFlight;
|
|
4841
|
+
return () => {
|
|
4842
|
+
if (resumeEventIndex >= resumeEvents.length) return Promise.resolve();
|
|
4843
|
+
if (readyInFlight) return readyInFlight;
|
|
4844
|
+
readyInFlight = (async () => {
|
|
4845
|
+
while (resumeEventIndex < resumeEvents.length) {
|
|
4846
|
+
const event = resumeEvents[resumeEventIndex];
|
|
4847
|
+
if (!event) break;
|
|
4848
|
+
await bus.publish(event);
|
|
4849
|
+
resumeEventIndex += 1;
|
|
4850
|
+
}
|
|
4851
|
+
})().finally(() => {
|
|
4852
|
+
readyInFlight = void 0;
|
|
4853
|
+
});
|
|
4854
|
+
return readyInFlight;
|
|
4855
|
+
};
|
|
4856
|
+
}
|
|
4857
|
+
// src/runtime/supervise/driver-control-acknowledgers.ts
|
|
4858
|
+
const SPAWN_JOURNAL_FILE = "spawn-journal.jsonl";
|
|
4859
|
+
function appendedLines(tail) {
|
|
4860
|
+
let size;
|
|
4861
|
+
try {
|
|
4862
|
+
size = statSync(tail.file).size;
|
|
4863
|
+
} catch {
|
|
4864
|
+
return;
|
|
4865
|
+
}
|
|
4866
|
+
if (size < tail.offset) {
|
|
4867
|
+
tail.offset = 0;
|
|
4868
|
+
tail.partial = "";
|
|
4869
|
+
tail.at.clear();
|
|
4870
|
+
}
|
|
4871
|
+
if (size === tail.offset) return void 0;
|
|
4872
|
+
const buf = Buffer.allocUnsafe(size - tail.offset);
|
|
4873
|
+
const fd = openSync(tail.file, "r");
|
|
4874
|
+
try {
|
|
4875
|
+
const got = readSync(fd, buf, 0, buf.length, tail.offset);
|
|
4876
|
+
tail.offset += got;
|
|
4877
|
+
const text = tail.partial + buf.subarray(0, got).toString("utf8");
|
|
4878
|
+
const parts = text.split("\n");
|
|
4879
|
+
tail.partial = text.endsWith("\n") ? "" : parts.pop() ?? "";
|
|
4880
|
+
if (text.endsWith("\n")) parts.pop();
|
|
4881
|
+
return parts;
|
|
4882
|
+
} finally {
|
|
4883
|
+
closeSync(fd);
|
|
4884
|
+
}
|
|
4885
|
+
}
|
|
4886
|
+
function indexDeaths(tail) {
|
|
4887
|
+
const lines = appendedLines(tail);
|
|
4888
|
+
if (lines === void 0) return false;
|
|
4889
|
+
let grew = false;
|
|
4890
|
+
for (const line of lines) {
|
|
4891
|
+
const trimmed = line.trim();
|
|
4892
|
+
if (!trimmed) continue;
|
|
4893
|
+
try {
|
|
4894
|
+
for (const event of spawnJournalRecordEvents(JSON.parse(trimmed))) {
|
|
4895
|
+
if (event === void 0) continue;
|
|
4896
|
+
if (!(event.kind === "settled" && event.status === "down" || event.kind === "cancelled") || typeof event.id !== "string" || typeof event.at !== "string") continue;
|
|
4897
|
+
const prev = tail.at.get(event.id);
|
|
4898
|
+
if (prev !== void 0 && prev >= event.at) continue;
|
|
4899
|
+
tail.at.set(event.id, event.at);
|
|
4900
|
+
grew = true;
|
|
4901
|
+
}
|
|
4902
|
+
} catch {}
|
|
4903
|
+
}
|
|
4904
|
+
return grew;
|
|
4905
|
+
}
|
|
4906
|
+
function descendantsSince(tail, nodeId, sinceIso) {
|
|
4907
|
+
indexDeaths(tail);
|
|
4908
|
+
const prefix = `${nodeId}:`;
|
|
4909
|
+
const ids = [...tail.at.keys()].filter((id) => id.startsWith(prefix) && (tail.at.get(id) ?? "") >= sinceIso);
|
|
4910
|
+
ids.sort();
|
|
4911
|
+
return ids;
|
|
4912
|
+
}
|
|
4913
|
+
/** Unknown ack lands before delivery. A crash can lose the steer; a restart must not deliver it twice. */
|
|
4914
|
+
function createSteerAcknowledger(deps) {
|
|
4915
|
+
const iso = () => new Date(deps.now()).toISOString();
|
|
4916
|
+
const awaiting = /* @__PURE__ */ new Map();
|
|
4917
|
+
const named = /* @__PURE__ */ new Map();
|
|
4918
|
+
const paused = () => {
|
|
4919
|
+
const pause = deps.rootPause?.();
|
|
4920
|
+
if (pause === void 0) return { why: "" };
|
|
4921
|
+
const left = pause.tokensLeft === void 0 ? "" : ` with ${pause.tokensLeft} tokens left`;
|
|
4922
|
+
return {
|
|
4923
|
+
pausedOn: pause,
|
|
4924
|
+
why: `; the root is paused on ${pause.stop}${left}`
|
|
4925
|
+
};
|
|
4926
|
+
};
|
|
4927
|
+
const queuedRoot = (request) => {
|
|
4928
|
+
const { pausedOn, why } = paused();
|
|
4929
|
+
const key = pausedOn?.stop ?? "";
|
|
4930
|
+
if (named.get(request.operationId) === key) return;
|
|
4931
|
+
named.set(request.operationId, key);
|
|
4932
|
+
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
4933
|
+
...base(request),
|
|
4934
|
+
effect: "unknown",
|
|
4935
|
+
observedAt: iso(),
|
|
4936
|
+
detail: `queued in the root inbox; no root turn has consumed it yet${why}`,
|
|
4937
|
+
...pausedOn === void 0 ? {} : { pausedOn }
|
|
4938
|
+
});
|
|
4939
|
+
};
|
|
4940
|
+
const answerRoot = (request, receipt) => {
|
|
4941
|
+
if (!awaiting.delete(request.operationId)) return;
|
|
4942
|
+
named.delete(request.operationId);
|
|
4943
|
+
const { pausedOn, why } = receipt.status === "consumed" ? { why: "" } : paused();
|
|
4944
|
+
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
4945
|
+
...base(request),
|
|
4946
|
+
...receipt.status === "consumed" ? {
|
|
4947
|
+
effect: "delivered",
|
|
4948
|
+
detail: `the root consumed the steer in ${receipt.attemptId}`
|
|
4949
|
+
} : {
|
|
4950
|
+
effect: "not_live",
|
|
4951
|
+
detail: `the root did not consume the steer: ${receipt.reason}${why}`
|
|
4952
|
+
},
|
|
4953
|
+
observedAt: iso(),
|
|
4954
|
+
...pausedOn === void 0 ? {} : { pausedOn }
|
|
4955
|
+
});
|
|
4956
|
+
};
|
|
4957
|
+
const base = (request) => ({
|
|
4958
|
+
schemaVersion: 1,
|
|
4959
|
+
operationId: request.operationId,
|
|
4960
|
+
requestDigest: request.requestDigest,
|
|
4961
|
+
worker: request.worker,
|
|
4962
|
+
requestedAt: request.at
|
|
4963
|
+
});
|
|
4964
|
+
let steerStamp = "";
|
|
4965
|
+
let steerIdle = false;
|
|
4966
|
+
const steerChanged = (phase) => {
|
|
4967
|
+
let stamp = "missing";
|
|
4968
|
+
try {
|
|
4969
|
+
const st = statSync(workerSteerRequestsDir(deps.dir), { bigint: true });
|
|
4970
|
+
stamp = `${st.dev}:${st.ino}:${st.mtimeNs}:${st.size}`;
|
|
4971
|
+
} catch {
|
|
4972
|
+
stamp = "missing";
|
|
4973
|
+
}
|
|
4974
|
+
const changed = stamp !== steerStamp;
|
|
4975
|
+
if (changed && phase !== "boundary") steerStamp = stamp;
|
|
4976
|
+
return changed;
|
|
4977
|
+
};
|
|
4978
|
+
return { async pass(phase) {
|
|
4979
|
+
if (phase === "turn") for (const request of awaiting.values()) queuedRoot(request);
|
|
4980
|
+
const changed = steerChanged(phase);
|
|
4981
|
+
if (phase !== "final" && !changed && steerIdle) return;
|
|
4982
|
+
for (const request of readWorkerSteerRequests(deps.dir)) {
|
|
4983
|
+
if (phase !== "final" && deps.signal?.aborted) {
|
|
4984
|
+
steerIdle = false;
|
|
4985
|
+
return;
|
|
4986
|
+
}
|
|
4987
|
+
const rootRequest = request.worker === deps.ownerId && deps.deliverRoot !== void 0;
|
|
4988
|
+
if (phase === "boundary" && !rootRequest) continue;
|
|
4989
|
+
if (!rootRequest && !isDirectChildNodeId(deps, request.worker)) continue;
|
|
4990
|
+
const queued = awaiting.get(request.operationId);
|
|
4991
|
+
if (phase === "final" && queued !== void 0) {
|
|
4992
|
+
answerRoot(queued, {
|
|
4993
|
+
status: "failed",
|
|
4994
|
+
messageId: request.operationId,
|
|
4995
|
+
cause: "closed",
|
|
4996
|
+
reason: "the run ended before a root turn read it"
|
|
4997
|
+
});
|
|
4998
|
+
continue;
|
|
4999
|
+
}
|
|
5000
|
+
if (readWorkerSteerAcknowledgement(deps.dir, request.operationId) !== void 0) continue;
|
|
5001
|
+
if (phase === "final") {
|
|
5002
|
+
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
5003
|
+
...base(request),
|
|
5004
|
+
effect: "not_live",
|
|
5005
|
+
observedAt: iso(),
|
|
5006
|
+
detail: "run ended before the steer was applied"
|
|
5007
|
+
});
|
|
5008
|
+
continue;
|
|
5009
|
+
}
|
|
5010
|
+
if (!claimWorkerSteerDelivery(deps.dir, {
|
|
5011
|
+
...base(request),
|
|
5012
|
+
effect: "unknown",
|
|
5013
|
+
observedAt: iso(),
|
|
5014
|
+
detail: "delivery admitted; outcome not yet known"
|
|
5015
|
+
})) continue;
|
|
5017
5016
|
try {
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5017
|
+
let outcome;
|
|
5018
|
+
if (rootRequest) {
|
|
5019
|
+
awaiting.set(request.operationId, request);
|
|
5020
|
+
const delivered = deps.deliverRoot({
|
|
5021
|
+
steer: request.message,
|
|
5022
|
+
interrupt: request.interrupt,
|
|
5023
|
+
messageId: request.operationId,
|
|
5024
|
+
receipt: (receipt) => answerRoot(request, receipt)
|
|
5025
|
+
});
|
|
5026
|
+
if (!delivered) awaiting.delete(request.operationId);
|
|
5027
|
+
outcome = {
|
|
5028
|
+
delivered,
|
|
5029
|
+
outcome: delivered ? "delivered" : "runtime-has-no-inbox"
|
|
5030
|
+
};
|
|
5031
|
+
} else outcome = await deps.coord.steerWorker(request.worker, request.message, { interrupt: request.interrupt });
|
|
5032
|
+
if (rootRequest && outcome.delivered) {
|
|
5033
|
+
if (awaiting.has(request.operationId)) queuedRoot(request);
|
|
5034
|
+
continue;
|
|
5035
|
+
}
|
|
5036
|
+
const effect = outcome.delivered ? "delivered" : outcome.outcome === "runtime-has-no-inbox" ? "unsupported" : outcome.outcome === "unknown-worker" || outcome.outcome === "already-settled" || outcome.outcome === "scope-stopped" ? "not_live" : "unknown";
|
|
5037
|
+
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
5038
|
+
...base(request),
|
|
5039
|
+
effect,
|
|
5040
|
+
observedAt: iso(),
|
|
5041
|
+
detail: rootRequest ? "the root exposes no accepting inbox at delivery time" : steerAcknowledgementDetail(outcome)
|
|
5042
|
+
});
|
|
5021
5043
|
} catch (error) {
|
|
5022
|
-
|
|
5023
|
-
|
|
5044
|
+
awaiting.delete(request.operationId);
|
|
5045
|
+
writeWorkerSteerAcknowledgement(deps.dir, {
|
|
5046
|
+
...base(request),
|
|
5047
|
+
effect: "unknown",
|
|
5048
|
+
observedAt: iso(),
|
|
5049
|
+
detail: "delivery outcome is unknown after a runtime error"
|
|
5050
|
+
});
|
|
5024
5051
|
}
|
|
5025
5052
|
}
|
|
5026
|
-
|
|
5027
|
-
}
|
|
5028
|
-
async function recordToolTiming(bus, tool, receivedAt, ok, value) {
|
|
5029
|
-
try {
|
|
5030
|
-
await bus.publish({
|
|
5031
|
-
type: "tool-timing",
|
|
5032
|
-
call: {
|
|
5033
|
-
tool,
|
|
5034
|
-
receivedAt,
|
|
5035
|
-
elapsedMs: Math.max(0, Date.now() - receivedAt),
|
|
5036
|
-
responseBytes: responseUtf8Bytes(ok ? value : errorText(value)),
|
|
5037
|
-
ok
|
|
5038
|
-
}
|
|
5039
|
-
}, { queue: false });
|
|
5040
|
-
} catch (error) {
|
|
5041
|
-
console.error("Runtime could not record coordination tool timing", {
|
|
5042
|
-
tool,
|
|
5043
|
-
error: error instanceof Error ? error.message : String(error)
|
|
5044
|
-
});
|
|
5045
|
-
}
|
|
5053
|
+
if (phase === "turn") steerIdle = true;
|
|
5054
|
+
} };
|
|
5046
5055
|
}
|
|
5047
|
-
function
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
return
|
|
5051
|
-
|
|
5052
|
-
return
|
|
5056
|
+
function steerAcknowledgementDetail(outcome) {
|
|
5057
|
+
switch (outcome.outcome) {
|
|
5058
|
+
case "delivered": return "the owning manager delivered the steer to the exact live worker";
|
|
5059
|
+
case "runtime-has-no-inbox": return "the exact worker does not expose a steer inbox";
|
|
5060
|
+
case "unknown-worker": return "the owning manager does not know the exact worker";
|
|
5061
|
+
case "already-settled": return "the exact worker settled before delivery";
|
|
5062
|
+
case "scope-stopped": return "the owning manager stopped before delivery";
|
|
5063
|
+
case "runtime-error": return "delivery outcome is unknown after a runtime error";
|
|
5053
5064
|
}
|
|
5054
5065
|
}
|
|
5055
|
-
function
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
const
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5069
|
-
|
|
5070
|
-
|
|
5071
|
-
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
5075
|
-
|
|
5076
|
-
|
|
5077
|
-
|
|
5078
|
-
|
|
5079
|
-
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
5092
|
-
|
|
5093
|
-
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5066
|
+
function createCancelAcknowledger(deps) {
|
|
5067
|
+
const tracked = /* @__PURE__ */ new Map();
|
|
5068
|
+
let runTracked;
|
|
5069
|
+
const abortIssuedAt = /* @__PURE__ */ new Map();
|
|
5070
|
+
const iso = () => new Date(deps.now()).toISOString();
|
|
5071
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
5072
|
+
const reconciling = /* @__PURE__ */ new Map();
|
|
5073
|
+
const regrowing = /* @__PURE__ */ new Set();
|
|
5074
|
+
let inboxBytes;
|
|
5075
|
+
const deaths = {
|
|
5076
|
+
file: join(deps.dir, SPAWN_JOURNAL_FILE),
|
|
5077
|
+
offset: 0,
|
|
5078
|
+
partial: "",
|
|
5079
|
+
at: /* @__PURE__ */ new Map()
|
|
5080
|
+
};
|
|
5081
|
+
const watch = (record) => {
|
|
5082
|
+
if (record.effect === "cancel_requested") reconciling.set(record.operationId, record);
|
|
5083
|
+
else reconciling.delete(record.operationId);
|
|
5084
|
+
if (record.effect === "cancelled" && abortIssuedAt.has(record.operationId)) regrowing.add(record.operationId);
|
|
5085
|
+
else regrowing.delete(record.operationId);
|
|
5086
|
+
};
|
|
5087
|
+
const write = (record) => {
|
|
5088
|
+
writeWorkerCancellation(deps.dir, record);
|
|
5089
|
+
tracked.set(record.operationId, record);
|
|
5090
|
+
watch(record);
|
|
5091
|
+
};
|
|
5092
|
+
const owned = (ref) => {
|
|
5093
|
+
if (isDirectChildNodeId(deps, ref)) return true;
|
|
5094
|
+
if (deps.controlScope !== "run") return false;
|
|
5095
|
+
return !ref.startsWith(`${deps.ownerId}:`) && ref !== deps.ownerId;
|
|
5096
|
+
};
|
|
5097
|
+
const deliveredTerminal = (id) => {
|
|
5098
|
+
const row = deps.coord.settled().find((w) => w.id === id);
|
|
5099
|
+
if (row !== void 0) return row.status;
|
|
5100
|
+
const node = deps.scope.view.nodes.find((n) => n.id === id);
|
|
5101
|
+
if (node === void 0) return void 0;
|
|
5102
|
+
if (node.status === "done") return "done";
|
|
5103
|
+
if (node.status === "failed" || node.status === "cancelled") return "down";
|
|
5104
|
+
};
|
|
5105
|
+
const apply = (request) => {
|
|
5106
|
+
const aborted = deps.coord.abortWorker(request.worker, request.reason ?? "cancel requested");
|
|
5107
|
+
const base = {
|
|
5108
|
+
operationId: request.operationId,
|
|
5109
|
+
worker: request.worker,
|
|
5110
|
+
requestedAt: request.at,
|
|
5111
|
+
observedAt: iso(),
|
|
5112
|
+
...request.reason === void 0 ? {} : { reason: request.reason }
|
|
5113
|
+
};
|
|
5114
|
+
if (aborted !== void 0) {
|
|
5115
|
+
abortIssuedAt.set(request.operationId, base.observedAt);
|
|
5116
|
+
write({
|
|
5117
|
+
...base,
|
|
5118
|
+
effect: "cancel_requested",
|
|
5119
|
+
workerId: aborted.id,
|
|
5120
|
+
detail: `abort issued to live worker '${aborted.label}' (${aborted.id}); termination not yet proven`,
|
|
5121
|
+
terminated: []
|
|
5122
|
+
});
|
|
5123
|
+
return;
|
|
5124
|
+
}
|
|
5125
|
+
const goneId = deps.scope.view.nodes.find((n) => (n.id === request.worker || n.label === request.worker) && isTerminalNodeStatus(n.status))?.id ?? deps.coord.settled().find((w) => w.id === request.worker)?.id;
|
|
5126
|
+
if (goneId !== void 0) write({
|
|
5127
|
+
...base,
|
|
5128
|
+
effect: "not_live",
|
|
5129
|
+
workerId: goneId,
|
|
5130
|
+
detail: `worker '${goneId}' had already settled before this operation was applied`,
|
|
5131
|
+
terminated: []
|
|
5132
|
+
});
|
|
5133
|
+
};
|
|
5134
|
+
/** Grows only: the worker, the record's ids, and subtree deaths at or after the abort. */
|
|
5135
|
+
const provenTerminated = (record, workerId) => {
|
|
5136
|
+
const since = abortIssuedAt.get(record.operationId) ?? record.observedAt;
|
|
5137
|
+
return [.../* @__PURE__ */ new Set([
|
|
5138
|
+
...record.terminated,
|
|
5139
|
+
workerId,
|
|
5140
|
+
...descendantsSince(deaths, workerId, since)
|
|
5141
|
+
])].sort();
|
|
5142
|
+
};
|
|
5143
|
+
const reconcile = (record) => {
|
|
5144
|
+
const workerId = record.workerId;
|
|
5145
|
+
if (workerId === void 0) return;
|
|
5146
|
+
const terminal = deliveredTerminal(workerId);
|
|
5147
|
+
if (terminal === void 0) return;
|
|
5148
|
+
if (terminal === "down") {
|
|
5149
|
+
write({
|
|
5150
|
+
...record,
|
|
5151
|
+
effect: "cancelled",
|
|
5152
|
+
observedAt: iso(),
|
|
5153
|
+
terminated: provenTerminated(record, workerId),
|
|
5154
|
+
detail: `worker '${workerId}' reached a terminal down state on the settle path`
|
|
5107
5155
|
});
|
|
5108
|
-
|
|
5109
|
-
}
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
|
|
5115
|
-
|
|
5116
|
-
|
|
5117
|
-
bus,
|
|
5118
|
-
journal,
|
|
5119
|
-
openWork: workers.openWork,
|
|
5120
|
-
driverAttempt: state.driverAttempt,
|
|
5121
|
-
lastRejection: state.lastRejection
|
|
5122
|
-
}),
|
|
5123
|
-
blocked: () => [...state.blockedReports],
|
|
5124
|
-
checkReads: () => state.checkReads,
|
|
5125
|
-
recordCheckRead: (read) => appendCheckRead(state, read),
|
|
5126
|
-
...peerMail ? { peerMail } : {}
|
|
5156
|
+
return;
|
|
5157
|
+
}
|
|
5158
|
+
write({
|
|
5159
|
+
...record,
|
|
5160
|
+
effect: "not_live",
|
|
5161
|
+
observedAt: iso(),
|
|
5162
|
+
terminated: [],
|
|
5163
|
+
detail: `worker '${workerId}' settled done despite the abort request; nothing was terminated`
|
|
5164
|
+
});
|
|
5127
5165
|
};
|
|
5128
|
-
|
|
5129
|
-
|
|
5130
|
-
|
|
5131
|
-
|
|
5132
|
-
|
|
5133
|
-
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
5166
|
+
const regrow = (record) => {
|
|
5167
|
+
const workerId = record.workerId;
|
|
5168
|
+
if (workerId === void 0 || !abortIssuedAt.has(record.operationId)) return;
|
|
5169
|
+
const terminated = provenTerminated(record, workerId);
|
|
5170
|
+
if (terminated.length > record.terminated.length) write({
|
|
5171
|
+
...record,
|
|
5172
|
+
observedAt: iso(),
|
|
5173
|
+
terminated
|
|
5174
|
+
});
|
|
5137
5175
|
};
|
|
5138
|
-
const
|
|
5139
|
-
|
|
5140
|
-
|
|
5141
|
-
|
|
5142
|
-
nodeOf,
|
|
5143
|
-
settleCommitted: settleNode,
|
|
5144
|
-
endInDoubt: (node, source) => routes.endInDoubt(node, source)
|
|
5145
|
-
});
|
|
5146
|
-
const routes = createRouteRouting({
|
|
5147
|
-
opts,
|
|
5148
|
-
bus,
|
|
5149
|
-
admitSpawn: (input) => admitSpawn(input),
|
|
5150
|
-
resolveContinuity,
|
|
5151
|
-
nodeOf,
|
|
5152
|
-
settleCommitted: settleNode,
|
|
5153
|
-
stop
|
|
5154
|
-
});
|
|
5155
|
-
return {
|
|
5156
|
-
maps,
|
|
5157
|
-
routes
|
|
5176
|
+
const passRun = () => {
|
|
5177
|
+
if (deps.controlScope !== "run" || deps.abortRun === void 0) return;
|
|
5178
|
+
if (runTracked !== void 0) return;
|
|
5179
|
+
runTracked = applyRunCancellation(deps.dir, deps.abortRun, iso);
|
|
5158
5180
|
};
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5166
|
-
}
|
|
5167
|
-
|
|
5168
|
-
|
|
5169
|
-
|
|
5170
|
-
|
|
5171
|
-
|
|
5172
|
-
|
|
5173
|
-
|
|
5174
|
-
|
|
5175
|
-
|
|
5176
|
-
};
|
|
5177
|
-
return {
|
|
5178
|
-
delivered: true,
|
|
5179
|
-
to: `parent manager question ${(await emitNewQuestion(addQuestion({
|
|
5180
|
-
from: workerId,
|
|
5181
|
-
level: asked.level,
|
|
5182
|
-
question: asked.question,
|
|
5183
|
-
reason: asked.reason,
|
|
5184
|
-
...asked.options ? { options: asked.options } : {},
|
|
5185
|
-
urgency: asked.urgency
|
|
5186
|
-
}, workerId))).id}`
|
|
5187
|
-
};
|
|
5188
|
-
});
|
|
5189
|
-
}
|
|
5190
|
-
/**
|
|
5191
|
-
* Let `observe_agent` and `read_journal` read a peer root's own record when the run enables peer
|
|
5192
|
-
* audit, then register this manager's tools with the peer registry. Mutates the two tools in place.
|
|
5193
|
-
*/
|
|
5194
|
-
function mountPeerAudit({ opts, tools, readJournal }) {
|
|
5195
|
-
for (const tool of tools) {
|
|
5196
|
-
if (tool.name !== "observe_agent" && tool.name !== "read_journal") continue;
|
|
5197
|
-
const ownHandler = tool.handler;
|
|
5198
|
-
const name = tool.name;
|
|
5199
|
-
const schema = tool.inputSchema;
|
|
5200
|
-
schema.properties = {
|
|
5201
|
-
...schema.properties,
|
|
5202
|
-
peerId: {
|
|
5203
|
-
type: "string",
|
|
5204
|
-
description: "Read a peer root's own record, using its workerId from read_mail.peers. Read-only; omit for your own tree."
|
|
5181
|
+
const ingest = () => {
|
|
5182
|
+
const file = workerCancelRequestsFile(deps.dir);
|
|
5183
|
+
let size;
|
|
5184
|
+
try {
|
|
5185
|
+
size = statSync(file).size;
|
|
5186
|
+
} catch {
|
|
5187
|
+
size = null;
|
|
5188
|
+
}
|
|
5189
|
+
if (size === inboxBytes) return;
|
|
5190
|
+
inboxBytes = size;
|
|
5191
|
+
for (const request of readWorkerCancelRequests(deps.dir)) {
|
|
5192
|
+
if (!owned(request.worker) || tracked.has(request.operationId) || waiting.has(request.operationId)) continue;
|
|
5193
|
+
const record = readWorkerCancellation(deps.dir, request.operationId);
|
|
5194
|
+
if (record === void 0) waiting.set(request.operationId, request);
|
|
5195
|
+
else {
|
|
5196
|
+
tracked.set(record.operationId, record);
|
|
5197
|
+
watch(record);
|
|
5205
5198
|
}
|
|
5206
|
-
};
|
|
5207
|
-
tool.handler = async (raw) => {
|
|
5208
|
-
const args = obj(raw);
|
|
5209
|
-
if (args.peerId === void 0) return ownHandler(raw);
|
|
5210
|
-
const peerId = str(args.peerId, "peerId");
|
|
5211
|
-
const { peerId: _peerId, ...readArgs } = args;
|
|
5212
|
-
return opts.peerAudit?.read(peerId, name, readArgs);
|
|
5213
|
-
};
|
|
5214
|
-
}
|
|
5215
|
-
opts.peerAudit.register(opts.scope.view.root, tools.map((tool) => tool.name === "read_journal" ? {
|
|
5216
|
-
...tool,
|
|
5217
|
-
handler: async (raw) => readJournal(raw, false)
|
|
5218
|
-
} : tool));
|
|
5219
|
-
}
|
|
5220
|
-
/**
|
|
5221
|
-
* Seed the settled ledger from a resumed scope and own the replay of its events onto the bus.
|
|
5222
|
-
* Replayed reviews remain findings. They cannot enter the completion pool or recursively
|
|
5223
|
-
* trigger another analyst, even when the resumed configuration changes its analyst routes.
|
|
5224
|
-
*/
|
|
5225
|
-
function createResumeReplay({ opts, bus, ledger, analysis, projectSettled }) {
|
|
5226
|
-
const { analystRuns, flushedAnalystRuns, analystRunFinding } = analysis;
|
|
5227
|
-
const resumedWorkers = [];
|
|
5228
|
-
const resumedFindings = [];
|
|
5229
|
-
for (const s of opts.scope.resume?.settled ?? []) {
|
|
5230
|
-
const analyst = analystRuns.get(s.handle.id);
|
|
5231
|
-
if (analyst) {
|
|
5232
|
-
resumedFindings.push(analystRunFinding(analyst, s));
|
|
5233
|
-
analystRuns.delete(s.handle.id);
|
|
5234
|
-
flushedAnalystRuns.add(s.handle.id);
|
|
5235
|
-
continue;
|
|
5236
5199
|
}
|
|
5237
|
-
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
|
|
5243
|
-
|
|
5244
|
-
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
|
|
5200
|
+
};
|
|
5201
|
+
const pass = (phase) => {
|
|
5202
|
+
if (phase === "turn") passRun();
|
|
5203
|
+
ingest();
|
|
5204
|
+
const pending = [...reconciling.values()];
|
|
5205
|
+
if (phase === "turn") for (const request of [...waiting.values()]) {
|
|
5206
|
+
waiting.delete(request.operationId);
|
|
5207
|
+
apply(request);
|
|
5208
|
+
if (!tracked.has(request.operationId)) waiting.set(request.operationId, request);
|
|
5209
|
+
}
|
|
5210
|
+
const grew = indexDeaths(deaths);
|
|
5211
|
+
for (const record of pending) {
|
|
5212
|
+
const current = tracked.get(record.operationId);
|
|
5213
|
+
if (current?.effect === "cancel_requested") reconcile(current);
|
|
5214
|
+
}
|
|
5215
|
+
if (!grew) return;
|
|
5216
|
+
for (const id of [...regrowing]) {
|
|
5217
|
+
const record = tracked.get(id);
|
|
5218
|
+
if (record !== void 0) regrow(record);
|
|
5219
|
+
}
|
|
5220
|
+
};
|
|
5221
|
+
return {
|
|
5222
|
+
pass,
|
|
5223
|
+
finish() {
|
|
5224
|
+
const runRequest = deps.controlScope === "run" && deps.abortRun !== void 0 ? readRunCancelRequest(deps.dir) : void 0;
|
|
5225
|
+
if (runRequest !== void 0 && readRunCancellation(deps.dir, runRequest.operationId) === void 0) writeRunCancellation(deps.dir, {
|
|
5226
|
+
operationId: runRequest.operationId,
|
|
5227
|
+
effect: "not_live",
|
|
5228
|
+
requestedAt: runRequest.at,
|
|
5229
|
+
observedAt: iso(),
|
|
5230
|
+
...runRequest.reason === void 0 ? {} : { reason: runRequest.reason },
|
|
5231
|
+
...runRequest.operator === void 0 ? {} : { operator: runRequest.operator },
|
|
5232
|
+
detail: "run ended before the request was applied"
|
|
5233
|
+
});
|
|
5234
|
+
for (const request of readWorkerCancelRequests(deps.dir)) {
|
|
5235
|
+
if (!owned(request.worker)) continue;
|
|
5236
|
+
const record = tracked.get(request.operationId) ?? readWorkerCancellation(deps.dir, request.operationId);
|
|
5237
|
+
if (record === void 0) {
|
|
5238
|
+
write({
|
|
5239
|
+
operationId: request.operationId,
|
|
5240
|
+
worker: request.worker,
|
|
5241
|
+
effect: "not_live",
|
|
5242
|
+
requestedAt: request.at,
|
|
5243
|
+
observedAt: iso(),
|
|
5244
|
+
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
5245
|
+
detail: "run ended before the request was applied",
|
|
5246
|
+
terminated: []
|
|
5247
|
+
});
|
|
5248
|
+
continue;
|
|
5249
|
+
}
|
|
5250
|
+
if (record.effect === "cancel_requested") write({
|
|
5251
|
+
...record,
|
|
5252
|
+
effect: "unknown",
|
|
5253
|
+
observedAt: iso(),
|
|
5254
|
+
detail: "abort issued; run ended before termination was observed"
|
|
5255
|
+
});
|
|
5256
5256
|
}
|
|
5257
|
-
}
|
|
5258
|
-
readyInFlight = void 0;
|
|
5259
|
-
});
|
|
5260
|
-
return readyInFlight;
|
|
5257
|
+
}
|
|
5261
5258
|
};
|
|
5262
5259
|
}
|
|
5263
|
-
|
|
5260
|
+
function isDirectChildNodeId(owner, ref) {
|
|
5261
|
+
return ref.startsWith(`${owner.ownerId}:s`) && /^s\d+$/.test(ref.slice(owner.ownerId.length + 1));
|
|
5262
|
+
}
|
|
5263
|
+
export { defaultToolDetectors as a, budgetOverspendText as c, createEventBus as d, createFileRunContext as f, createCoordinationToolsForManager as i, coordinationVerbNames as l, withRunContext as m, createSteerAcknowledger as n, watchTrace as o, createInMemoryRunContext as p, createCoordinationTools as r, downMessageRefusalReasons as s, createCancelAcknowledger as t, normalizeAnalyzeOnSettle as u };
|
|
5264
5264
|
|
|
5265
|
-
//# sourceMappingURL=
|
|
5265
|
+
//# sourceMappingURL=driver-control-acknowledgers-CJDYLJmW.js.map
|