anchor-ai-sdk 0.8.2 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -5
- package/dist/engine/budgets.d.ts +65 -2
- package/dist/engine/budgets.d.ts.map +1 -1
- package/dist/engine/budgets.js +76 -1
- package/dist/engine/budgets.js.map +1 -1
- package/dist/engine/dispatch.d.ts.map +1 -1
- package/dist/engine/dispatch.js +3 -2
- package/dist/engine/dispatch.js.map +1 -1
- package/dist/engine/events.d.ts +26 -2
- package/dist/engine/events.d.ts.map +1 -1
- package/dist/engine/guardrails.d.ts +7 -0
- package/dist/engine/guardrails.d.ts.map +1 -1
- package/dist/engine/guardrails.js +12 -0
- package/dist/engine/guardrails.js.map +1 -1
- package/dist/engine/loop.d.ts +1 -1
- package/dist/engine/loop.d.ts.map +1 -1
- package/dist/engine/loop.js +557 -204
- package/dist/engine/loop.js.map +1 -1
- package/dist/engine/revival.d.ts.map +1 -1
- package/dist/engine/revival.js +2 -1
- package/dist/engine/revival.js.map +1 -1
- package/dist/engine/supervision.d.ts +34 -0
- package/dist/engine/supervision.d.ts.map +1 -0
- package/dist/engine/supervision.js +72 -0
- package/dist/engine/supervision.js.map +1 -0
- package/dist/engine/types.d.ts +75 -2
- package/dist/engine/types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ledger/alignment.d.ts.map +1 -1
- package/dist/ledger/alignment.js +1 -0
- package/dist/ledger/alignment.js.map +1 -1
- package/dist/teams/delegate.d.ts +24 -5
- package/dist/teams/delegate.d.ts.map +1 -1
- package/dist/teams/delegate.js +136 -33
- package/dist/teams/delegate.js.map +1 -1
- package/dist/teams/index.d.ts +1 -0
- package/dist/teams/index.d.ts.map +1 -1
- package/dist/teams/index.js +1 -0
- package/dist/teams/index.js.map +1 -1
- package/dist/teams/steer.d.ts +40 -0
- package/dist/teams/steer.d.ts.map +1 -0
- package/dist/teams/steer.js +60 -0
- package/dist/teams/steer.js.map +1 -0
- package/dist/teams/types.d.ts +15 -1
- package/dist/teams/types.d.ts.map +1 -1
- package/dist/teams/types.js.map +1 -1
- package/dist/tools/types.d.ts +8 -0
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/package.json +1 -1
package/dist/engine/loop.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { createFinishTool } from "../tools/finish.js";
|
|
2
2
|
import { validateRepos } from "../repo.js";
|
|
3
|
-
import { BudgetTracker, DEFAULT_BUDGET_LIMITS, DEFAULT_MAX_OUTPUT_TOKENS, } from "./budgets.js";
|
|
3
|
+
import { BudgetTracker, DEFAULT_BUDGET_LIMITS, DEFAULT_CHILD_SOFT_CAP, DEFAULT_MAX_OUTPUT_TOKENS, } from "./budgets.js";
|
|
4
4
|
import { DEFAULT_TRUNCATED_REPLY_CHARS, DEFAULT_MAX_ASSISTANT_CHARS, elideReply, spillReply, } from "./elision.js";
|
|
5
5
|
import { compactConversation, compactConversationStructured, DEFAULT_COMPACTION, estimateTokens, renderCompactionHandoff, } from "./compaction.js";
|
|
6
6
|
import { assistantMessage, conversationHistory, } from "./context.js";
|
|
7
7
|
import { renderInboxTurn, } from "./inbox.js";
|
|
8
8
|
import { defineTool } from "../tools/types.js";
|
|
9
9
|
import { gitSnapshot } from "./snapshot.js";
|
|
10
|
-
import {
|
|
10
|
+
import { createTeamTools } from "../teams/delegate.js";
|
|
11
|
+
import { steerDirective } from "../teams/steer.js";
|
|
11
12
|
import { TraceFanout } from "../trace/sink.js";
|
|
12
13
|
import { budgetWarning, revivalBlock, warnPercent as revivalWarnPercent, } from "./revival.js";
|
|
13
14
|
import { phaseDisciplineBlock } from "./phase-discipline.js";
|
|
@@ -16,9 +17,85 @@ import { addRequirement, compileLedger, createLedger, ledgerGate, linkEvidence,
|
|
|
16
17
|
import { llmJudge } from "../verify/index.js";
|
|
17
18
|
import { dispatchToolCalls, } from "./dispatch.js";
|
|
18
19
|
import { mintOperationId, reconcilePendingOperations, settleFromResult, } from "./operations.js";
|
|
19
|
-
import { RepeatTracker, cappedReplyNudge, createCourseCorrect, emptyTurnNudge, proseCheckpoint as proseCheckpointMessage, repeatedCallNudge, silentNudge, verboseNudge, visibleOutputTokens, } from "./guardrails.js";
|
|
20
|
+
import { RepeatTracker, cappedReplyNudge, createCourseCorrect, emptyTurnNudge, proseCheckpoint as proseCheckpointMessage, repeatedCallNudge, silentNudge, verboseNudge, visibleOutputTokens, wrapUpNudge, } from "./guardrails.js";
|
|
21
|
+
import { CANCEL_GRACE, DEFAULT_CANCEL_GRACE_MS, DEFAULT_STALL_AFTER_MS, waitWithCancelGrace, } from "./supervision.js";
|
|
20
22
|
import { pollBackgroundJobs, renderBackgroundResult, renderLostJob, waitForBackgroundJobs, } from "./background.js";
|
|
21
23
|
export { userTurn } from "./types.js";
|
|
24
|
+
/**
|
|
25
|
+
* Ledger tools answer "what is the task", not "what did the work". Calling one
|
|
26
|
+
* must never be captured as evidence about the work inside the ledger it
|
|
27
|
+
* manages. `update_ledger` is the deprecated shim; the rest are its split
|
|
28
|
+
* successors.
|
|
29
|
+
*/
|
|
30
|
+
const LEDGER_TOOL_NAMES = new Set([
|
|
31
|
+
"create_task",
|
|
32
|
+
"finish",
|
|
33
|
+
"update_ledger",
|
|
34
|
+
"add_requirement",
|
|
35
|
+
"set_requirement_status",
|
|
36
|
+
"link_evidence",
|
|
37
|
+
"verify_requirement",
|
|
38
|
+
"set_next_step",
|
|
39
|
+
"add_failure",
|
|
40
|
+
"clear_failure",
|
|
41
|
+
]);
|
|
42
|
+
/** The child's most recent visible prose, for a budget-exhausted hand-back. */
|
|
43
|
+
function lastAssistantText(messages) {
|
|
44
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
45
|
+
const message = messages[index];
|
|
46
|
+
if (message.role === "assistant" &&
|
|
47
|
+
typeof message.content === "string" &&
|
|
48
|
+
message.content.trim()) {
|
|
49
|
+
return message.content.trim();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The last non-empty line of the child's most recent visible prose, capped for
|
|
56
|
+
* a progress record: what a wake-up message can quote as "it was doing X".
|
|
57
|
+
*/
|
|
58
|
+
function lastAssistantLine(messages, max = 200) {
|
|
59
|
+
const full = lastAssistantText(messages);
|
|
60
|
+
if (!full)
|
|
61
|
+
return "";
|
|
62
|
+
const line = full
|
|
63
|
+
.split("\n")
|
|
64
|
+
.map((row) => row.trim())
|
|
65
|
+
.filter(Boolean)
|
|
66
|
+
.pop() ?? "";
|
|
67
|
+
return line.length > max ? line.slice(0, max) : line;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Paths named by a turn's tool calls, for progress. Best-effort: an
|
|
71
|
+
* unparseable call contributes nothing, so this can never fail a run.
|
|
72
|
+
*/
|
|
73
|
+
function noteTouchedFiles(target, calls) {
|
|
74
|
+
for (const call of calls) {
|
|
75
|
+
try {
|
|
76
|
+
const parsed = call.arguments.trim()
|
|
77
|
+
? JSON.parse(call.arguments)
|
|
78
|
+
: {};
|
|
79
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
80
|
+
const path = parsed.path;
|
|
81
|
+
if (typeof path === "string" && path.trim())
|
|
82
|
+
target.add(path.trim());
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
/* an unparseable call is not a file path */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** "…, 3/20 steps, $0.42/$1.50" — the numbers a wrap-up nudge cites. */
|
|
91
|
+
function budgetLine(budget, steps) {
|
|
92
|
+
const parts = [`${steps}/${budget.limits.maxSteps} steps`];
|
|
93
|
+
if (budget.limits.maxWallClockMs !== undefined)
|
|
94
|
+
parts.push(`${Math.round(budget.wallClockMs() / 1000)}s/${Math.round(budget.limits.maxWallClockMs / 1000)}s`);
|
|
95
|
+
if (budget.costsKnown)
|
|
96
|
+
parts.push(`$${budget.costUsd.toFixed(2)}/$${budget.limits.maxUsd}`);
|
|
97
|
+
return parts.join(", ");
|
|
98
|
+
}
|
|
22
99
|
async function runOne(input, opts, chain = {}) {
|
|
23
100
|
const strategy = opts.strategy ?? opts.agent?.strategy;
|
|
24
101
|
if (!strategy)
|
|
@@ -38,12 +115,24 @@ async function runOne(input, opts, chain = {}) {
|
|
|
38
115
|
else
|
|
39
116
|
opts.signal.addEventListener("abort", abortFromCaller, { once: true });
|
|
40
117
|
}
|
|
118
|
+
// The signal every tool sees. It is the run's cancel signal plus, for a
|
|
119
|
+
// delegated child, its own wall-clock deadline: a tool call already in
|
|
120
|
+
// flight is aborted at the deadline, and the child concludes
|
|
121
|
+
// `budget_exhausted` with a partial hand-back. The run signal (used for the
|
|
122
|
+
// model call) stays separate, so a deadline never reads as a host cancel.
|
|
123
|
+
const toolController = new AbortController();
|
|
124
|
+
const toolSignal = toolController.signal;
|
|
125
|
+
const abortTools = () => toolController.abort();
|
|
126
|
+
if (signal.aborted)
|
|
127
|
+
toolController.abort();
|
|
128
|
+
else
|
|
129
|
+
signal.addEventListener("abort", abortTools, { once: true });
|
|
41
130
|
const timers = [];
|
|
42
131
|
const fanout = opts.traceSinks?.length
|
|
43
132
|
? new TraceFanout(opts.traceSinks)
|
|
44
133
|
: null;
|
|
45
134
|
let stopped = false;
|
|
46
|
-
/** Idempotent: stop the timers, unlink the
|
|
135
|
+
/** Idempotent: stop the timers, unlink the signals, flush sinks. */
|
|
47
136
|
const stopLifecycle = async () => {
|
|
48
137
|
if (stopped)
|
|
49
138
|
return;
|
|
@@ -51,6 +140,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
51
140
|
for (const timer of timers)
|
|
52
141
|
clearInterval(timer);
|
|
53
142
|
opts.signal?.removeEventListener("abort", abortFromCaller);
|
|
143
|
+
signal.removeEventListener("abort", abortTools);
|
|
54
144
|
if (fanout)
|
|
55
145
|
await fanout.flush();
|
|
56
146
|
};
|
|
@@ -61,6 +151,13 @@ async function runOne(input, opts, chain = {}) {
|
|
|
61
151
|
...(chain.worker ? { worker: chain.worker } : {}),
|
|
62
152
|
...(chain.role ? { role: chain.role } : {}),
|
|
63
153
|
};
|
|
154
|
+
// Activity bookkeeping for a delegated child's stall signal. Every event the
|
|
155
|
+
// child produces is activity; the one record this emits for a silent child
|
|
156
|
+
// is not.
|
|
157
|
+
let lastActivityAt = Date.now();
|
|
158
|
+
let stallReported = false;
|
|
159
|
+
let lastToolName;
|
|
160
|
+
let lastVerbName;
|
|
64
161
|
const emit = (event) => {
|
|
65
162
|
const attributed = Object.keys(traceAttribution).length > 0
|
|
66
163
|
? { ...event, ...traceAttribution }
|
|
@@ -72,6 +169,14 @@ async function runOne(input, opts, chain = {}) {
|
|
|
72
169
|
catch {
|
|
73
170
|
// A subscriber must never kill the run — same rule as sinks.
|
|
74
171
|
}
|
|
172
|
+
if (event.type === "progress" && event.stalled)
|
|
173
|
+
return;
|
|
174
|
+
lastActivityAt = Date.now();
|
|
175
|
+
stallReported = false;
|
|
176
|
+
if (event.type === "tool_call") {
|
|
177
|
+
lastToolName = event.name;
|
|
178
|
+
lastVerbName = event.verb ?? event.name;
|
|
179
|
+
}
|
|
75
180
|
};
|
|
76
181
|
if (opts.repos?.length) {
|
|
77
182
|
if (!opts.sandbox)
|
|
@@ -148,17 +253,19 @@ async function runOne(input, opts, chain = {}) {
|
|
|
148
253
|
let summary = prior?.summary;
|
|
149
254
|
let compaction = prior?.compaction;
|
|
150
255
|
const budget = chain.budget ?? new BudgetTracker(opts.budgets);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
256
|
+
const cancelGraceMs = opts.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
|
|
257
|
+
const stallAfterMs = opts.stallAfterMs === false
|
|
258
|
+
? false
|
|
259
|
+
: (opts.stallAfterMs ?? DEFAULT_STALL_AFTER_MS);
|
|
260
|
+
// A child's wall-clock budget must bite at its next tool boundary, not only
|
|
261
|
+
// at turn boundaries: give its tools a signal that aborts at the deadline,
|
|
262
|
+
// so a call already in flight is cut and no new call starts past it.
|
|
263
|
+
const wallClockLimit = budget.limits.maxWallClockMs;
|
|
264
|
+
if (chain.child && wallClockLimit !== undefined && wallClockLimit > 0) {
|
|
265
|
+
const remainingMs = Math.max(0, wallClockLimit - budget.wallClockMs());
|
|
266
|
+
const deadline = setTimeout(() => toolController.abort(), remainingMs);
|
|
267
|
+
deadline.unref?.();
|
|
268
|
+
timers.push(deadline);
|
|
162
269
|
}
|
|
163
270
|
// ---- Task contracts and the judge --------------------------------------
|
|
164
271
|
const verifierOn = opts.verifier !== undefined && opts.verifier !== false;
|
|
@@ -229,217 +336,319 @@ async function runOne(input, opts, chain = {}) {
|
|
|
229
336
|
return undefined;
|
|
230
337
|
}
|
|
231
338
|
};
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
339
|
+
// The task contract, one tool per operation. A single `update_ledger` with an
|
|
340
|
+
// `op` and every field anyone might need let models mix operations up: an
|
|
341
|
+
// "add" carrying `status`, `failure` and an existing id, repeated verbatim
|
|
342
|
+
// until the engine stalled the turn. Each tool below does one job and asks
|
|
343
|
+
// for only the fields that job needs. `update_ledger` stays as a deprecated
|
|
344
|
+
// shim for callers that still name it.
|
|
345
|
+
const runLedgerOp = async (op, input) => {
|
|
346
|
+
const dependencyError = (requirementId) => {
|
|
347
|
+
const requirement = ledger.requirements.find((item) => item.id === requirementId);
|
|
348
|
+
if (!requirement)
|
|
349
|
+
return `unknown requirement "${requirementId}"`;
|
|
350
|
+
const unmet = unmetDependencies(ledger, requirement, {
|
|
351
|
+
allowWaived: verifierConfig.allowWaived,
|
|
352
|
+
});
|
|
353
|
+
return unmet.length
|
|
354
|
+
? `${requirement.id} requires ${unmet.join(", ")}`
|
|
355
|
+
: undefined;
|
|
356
|
+
};
|
|
357
|
+
if (op === "add_requirement") {
|
|
358
|
+
const text = String(input.text ?? "").trim();
|
|
359
|
+
if (!text)
|
|
360
|
+
return {
|
|
361
|
+
ok: false,
|
|
362
|
+
content: 'add_requirement needs text: the requirement in one sentence, e.g. {"op":"add_requirement","text":"Threads can be filtered by label","dependsOn":["r2"]}',
|
|
363
|
+
};
|
|
364
|
+
if (input.id !== undefined && typeof input.id !== "string") {
|
|
365
|
+
return { ok: false, content: "id must be a string" };
|
|
366
|
+
}
|
|
367
|
+
if (input.dependsOn !== undefined && !Array.isArray(input.dependsOn)) {
|
|
368
|
+
return {
|
|
369
|
+
ok: false,
|
|
370
|
+
content: "dependsOn must be an array of requirement ids",
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
if (Array.isArray(input.dependsOn) &&
|
|
374
|
+
input.dependsOn.some((item) => typeof item !== "string")) {
|
|
375
|
+
return {
|
|
376
|
+
ok: false,
|
|
377
|
+
content: "dependsOn must be an array of requirement ids",
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
381
|
+
const requirement = addRequirement(ledger, {
|
|
382
|
+
text,
|
|
383
|
+
required: input.required !== false,
|
|
384
|
+
...(typeof input.id === "string" && input.id
|
|
385
|
+
? { id: input.id }
|
|
386
|
+
: {}),
|
|
387
|
+
...(typeof input.phase === "string" && input.phase
|
|
388
|
+
? { phase: input.phase }
|
|
389
|
+
: {}),
|
|
390
|
+
...(Array.isArray(input.dependsOn) && input.dependsOn.length
|
|
391
|
+
? { dependsOn: input.dependsOn }
|
|
392
|
+
: {}),
|
|
393
|
+
}, "agent");
|
|
394
|
+
return {
|
|
395
|
+
ok: true,
|
|
396
|
+
content: `added ${requirement.id}: ${requirement.text}`,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
return {
|
|
401
|
+
ok: false,
|
|
402
|
+
content: error instanceof Error ? error.message : String(error),
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (op === "link_evidence") {
|
|
407
|
+
const claim = String(input.claim ?? "").trim();
|
|
408
|
+
if (!claim) {
|
|
409
|
+
return {
|
|
410
|
+
ok: false,
|
|
411
|
+
content: "claim is required: explain why this evidence establishes the requirement",
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
linkEvidence(ledger, String(input.requirementId ?? ""), String(input.evidenceId ?? ""), claim);
|
|
415
|
+
return { ok: true, content: "evidence linked" };
|
|
416
|
+
}
|
|
417
|
+
if (op === "verify") {
|
|
418
|
+
const claim = String(input.claim ?? "").trim();
|
|
419
|
+
if (!claim) {
|
|
420
|
+
return {
|
|
421
|
+
ok: false,
|
|
422
|
+
content: "claim is required: explain why this evidence establishes the requirement",
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
const requirementId = String(input.requirementId ?? "");
|
|
426
|
+
const unmet = dependencyError(requirementId);
|
|
427
|
+
if (unmet)
|
|
428
|
+
return { ok: false, content: unmet };
|
|
429
|
+
linkEvidence(ledger, requirementId, String(input.evidenceId ?? ""), claim);
|
|
430
|
+
setRequirementStatus(ledger, requirementId, "verified");
|
|
431
|
+
return { ok: true, content: "evidence linked and requirement verified" };
|
|
432
|
+
}
|
|
433
|
+
if (op === "set_status") {
|
|
434
|
+
const status = String(input.status ?? "");
|
|
435
|
+
if (status === "superseded") {
|
|
436
|
+
return { ok: false, content: "use a user revision to supersede" };
|
|
437
|
+
}
|
|
438
|
+
const requirementId = String(input.requirementId ?? "");
|
|
439
|
+
if (status === "verified" || status === "waived") {
|
|
440
|
+
const unmet = dependencyError(requirementId);
|
|
441
|
+
if (unmet)
|
|
442
|
+
return { ok: false, content: unmet };
|
|
443
|
+
}
|
|
444
|
+
if (status === "verified") {
|
|
445
|
+
const requirement = ledger.requirements.find((item) => item.id === requirementId);
|
|
446
|
+
if (!requirement || requirement.evidenceIds.length === 0) {
|
|
447
|
+
return {
|
|
448
|
+
ok: false,
|
|
449
|
+
content: "link evidence to this requirement before marking it verified",
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
setRequirementStatus(ledger, requirementId, status);
|
|
454
|
+
return { ok: true, content: `status set to ${status}` };
|
|
455
|
+
}
|
|
456
|
+
if (op === "set_next_step") {
|
|
457
|
+
ledger.nextStep = String(input.text ?? "");
|
|
458
|
+
return { ok: true, content: "next step recorded" };
|
|
459
|
+
}
|
|
460
|
+
if (op === "add_failure") {
|
|
461
|
+
const failure = String(input.failure ?? "").trim();
|
|
462
|
+
if (!failure)
|
|
463
|
+
return {
|
|
464
|
+
ok: false,
|
|
465
|
+
content: 'add_failure needs failure: what failed, in words, e.g. {"op":"add_failure","failure":"Migration fails on an empty table"}',
|
|
466
|
+
};
|
|
467
|
+
ledger.openFailures.push(failure);
|
|
468
|
+
return { ok: true, content: "failure recorded" };
|
|
469
|
+
}
|
|
470
|
+
if (op === "clear_failure") {
|
|
471
|
+
const failure = String(input.failure ?? "");
|
|
472
|
+
ledger.openFailures = ledger.openFailures.filter((item) => item !== failure);
|
|
473
|
+
return { ok: true, content: "failure cleared" };
|
|
474
|
+
}
|
|
475
|
+
return { ok: false, content: `unknown ledger op "${op}"` };
|
|
476
|
+
};
|
|
477
|
+
const requirementProps = {
|
|
478
|
+
requirementId: {
|
|
479
|
+
type: "string",
|
|
480
|
+
description: "The existing requirement, e.g. r2.",
|
|
481
|
+
},
|
|
482
|
+
evidenceId: {
|
|
483
|
+
type: "string",
|
|
484
|
+
description: "An evidence id from a tool result. Never invented.",
|
|
485
|
+
},
|
|
486
|
+
claim: {
|
|
487
|
+
type: "string",
|
|
488
|
+
description: "Why this evidence establishes the requirement, in one sentence.",
|
|
489
|
+
},
|
|
490
|
+
};
|
|
491
|
+
const ledgerTools = () => {
|
|
492
|
+
const install = (tool, name) => {
|
|
493
|
+
available.set(name, tool);
|
|
494
|
+
return tool;
|
|
495
|
+
};
|
|
496
|
+
install(defineTool({
|
|
497
|
+
name: "add_requirement",
|
|
498
|
+
description: "Add one requirement to the task contract. Use this only to add; to change an existing one use set_requirement_status, link_evidence, verify_requirement or add_failure.",
|
|
242
499
|
parameters: {
|
|
243
500
|
type: "object",
|
|
244
501
|
properties: {
|
|
245
|
-
op: {
|
|
246
|
-
type: "string",
|
|
247
|
-
enum: [
|
|
248
|
-
"add_requirement",
|
|
249
|
-
"link_evidence",
|
|
250
|
-
"verify",
|
|
251
|
-
"set_status",
|
|
252
|
-
"set_next_step",
|
|
253
|
-
"add_failure",
|
|
254
|
-
"clear_failure",
|
|
255
|
-
],
|
|
256
|
-
},
|
|
257
502
|
text: {
|
|
258
503
|
type: "string",
|
|
259
|
-
description: "
|
|
260
|
-
},
|
|
261
|
-
required: {
|
|
262
|
-
type: "boolean",
|
|
263
|
-
description: "add_requirement: false for a nice-to-have. Default true.",
|
|
504
|
+
description: "What must be true, in one sentence.",
|
|
264
505
|
},
|
|
265
506
|
id: {
|
|
266
507
|
type: "string",
|
|
267
|
-
description: "
|
|
508
|
+
description: "The new requirement's id (e.g. r3). Omit for the next one.",
|
|
268
509
|
},
|
|
269
510
|
phase: {
|
|
270
511
|
type: "string",
|
|
271
|
-
description: "
|
|
512
|
+
description: "The phase that satisfies it.",
|
|
272
513
|
},
|
|
273
514
|
dependsOn: {
|
|
274
515
|
type: "array",
|
|
275
516
|
items: { type: "string" },
|
|
276
|
-
description: "
|
|
517
|
+
description: "Ids of requirements that must be met first.",
|
|
277
518
|
},
|
|
278
|
-
|
|
519
|
+
required: {
|
|
520
|
+
type: "boolean",
|
|
521
|
+
description: "false for a nice-to-have. Default true.",
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
required: ["text"],
|
|
525
|
+
additionalProperties: false,
|
|
526
|
+
},
|
|
527
|
+
}, (input) => runLedgerOp("add_requirement", input), { verb: "Adding a requirement" }), "add_requirement");
|
|
528
|
+
install(defineTool({
|
|
529
|
+
name: "set_requirement_status",
|
|
530
|
+
description: "Change an existing requirement's status. Marking one verified needs evidence linked first.",
|
|
531
|
+
parameters: {
|
|
532
|
+
type: "object",
|
|
533
|
+
properties: {
|
|
534
|
+
requirementId: requirementProps.requirementId,
|
|
535
|
+
status: {
|
|
279
536
|
type: "string",
|
|
280
|
-
|
|
537
|
+
enum: ["open", "in_progress", "verified", "blocked", "waived"],
|
|
538
|
+
description: "The requirement's new status.",
|
|
281
539
|
},
|
|
282
|
-
|
|
540
|
+
},
|
|
541
|
+
required: ["requirementId", "status"],
|
|
542
|
+
additionalProperties: false,
|
|
543
|
+
},
|
|
544
|
+
}, (input) => runLedgerOp("set_status", input), { verb: "Setting a requirement's status" }), "set_requirement_status");
|
|
545
|
+
install(defineTool({
|
|
546
|
+
name: "link_evidence",
|
|
547
|
+
description: "Attach a tool result to a requirement, with a sentence saying why it shows it.",
|
|
548
|
+
parameters: {
|
|
549
|
+
type: "object",
|
|
550
|
+
properties: requirementProps,
|
|
551
|
+
required: ["requirementId", "evidenceId", "claim"],
|
|
552
|
+
additionalProperties: false,
|
|
553
|
+
},
|
|
554
|
+
}, (input) => runLedgerOp("link_evidence", input), { verb: "Linking evidence" }), "link_evidence");
|
|
555
|
+
install(defineTool({
|
|
556
|
+
name: "verify_requirement",
|
|
557
|
+
description: "Link a tool result to a requirement and mark it verified, in one step.",
|
|
558
|
+
parameters: {
|
|
559
|
+
type: "object",
|
|
560
|
+
properties: requirementProps,
|
|
561
|
+
required: ["requirementId", "evidenceId", "claim"],
|
|
562
|
+
additionalProperties: false,
|
|
563
|
+
},
|
|
564
|
+
}, (input) => runLedgerOp("verify", input), { verb: "Verifying a requirement" }), "verify_requirement");
|
|
565
|
+
install(defineTool({
|
|
566
|
+
name: "set_next_step",
|
|
567
|
+
description: "Record the next step you are about to take.",
|
|
568
|
+
parameters: {
|
|
569
|
+
type: "object",
|
|
570
|
+
properties: {
|
|
571
|
+
text: { type: "string", description: "The next step." },
|
|
572
|
+
},
|
|
573
|
+
required: ["text"],
|
|
574
|
+
additionalProperties: false,
|
|
575
|
+
},
|
|
576
|
+
}, (input) => runLedgerOp("set_next_step", input), { verb: "Recording the next step" }), "set_next_step");
|
|
577
|
+
install(defineTool({
|
|
578
|
+
name: "add_failure",
|
|
579
|
+
description: "Record something that failed and still needs fixing.",
|
|
580
|
+
parameters: {
|
|
581
|
+
type: "object",
|
|
582
|
+
properties: {
|
|
583
|
+
failure: { type: "string", description: "What failed, in words." },
|
|
584
|
+
},
|
|
585
|
+
required: ["failure"],
|
|
586
|
+
additionalProperties: false,
|
|
587
|
+
},
|
|
588
|
+
}, (input) => runLedgerOp("add_failure", input), { verb: "Recording a failure" }), "add_failure");
|
|
589
|
+
install(defineTool({
|
|
590
|
+
name: "clear_failure",
|
|
591
|
+
description: "Clear a failure once it is fixed.",
|
|
592
|
+
parameters: {
|
|
593
|
+
type: "object",
|
|
594
|
+
properties: {
|
|
595
|
+
failure: {
|
|
283
596
|
type: "string",
|
|
284
|
-
description: "
|
|
597
|
+
description: "The recorded failure, word for word.",
|
|
285
598
|
},
|
|
286
|
-
|
|
599
|
+
},
|
|
600
|
+
required: ["failure"],
|
|
601
|
+
additionalProperties: false,
|
|
602
|
+
},
|
|
603
|
+
}, (input) => runLedgerOp("clear_failure", input), { verb: "Clearing a failure" }), "clear_failure");
|
|
604
|
+
// Deprecated: the same operations, by name, with one open field list.
|
|
605
|
+
const shim = defineTool({
|
|
606
|
+
name: "update_ledger",
|
|
607
|
+
description: "Deprecated — prefer add_requirement, set_requirement_status, link_evidence, verify_requirement, set_next_step, add_failure and clear_failure; each does one job with only the fields it needs. Kept for callers that still name it: add_requirement — text; link_evidence / verify — requirementId, evidenceId, claim; set_status — requirementId, status; set_next_step — text; add_failure / clear_failure — failure.",
|
|
608
|
+
parameters: {
|
|
609
|
+
type: "object",
|
|
610
|
+
properties: {
|
|
611
|
+
op: {
|
|
287
612
|
type: "string",
|
|
288
|
-
|
|
613
|
+
enum: [
|
|
614
|
+
"add_requirement",
|
|
615
|
+
"link_evidence",
|
|
616
|
+
"verify",
|
|
617
|
+
"set_status",
|
|
618
|
+
"set_next_step",
|
|
619
|
+
"add_failure",
|
|
620
|
+
"clear_failure",
|
|
621
|
+
],
|
|
289
622
|
},
|
|
623
|
+
text: { type: "string" },
|
|
624
|
+
required: { type: "boolean" },
|
|
625
|
+
id: { type: "string" },
|
|
626
|
+
phase: { type: "string" },
|
|
627
|
+
dependsOn: { type: "array", items: { type: "string" } },
|
|
628
|
+
requirementId: { type: "string" },
|
|
629
|
+
evidenceId: { type: "string" },
|
|
630
|
+
claim: { type: "string" },
|
|
290
631
|
status: {
|
|
291
632
|
type: "string",
|
|
292
633
|
enum: ["open", "in_progress", "verified", "blocked", "waived"],
|
|
293
|
-
description: "set_status: the requirement's new status.",
|
|
294
|
-
},
|
|
295
|
-
failure: {
|
|
296
|
-
type: "string",
|
|
297
|
-
description: "add_failure, clear_failure: the failure, in words. Only for those ops.",
|
|
298
634
|
},
|
|
635
|
+
failure: { type: "string" },
|
|
299
636
|
},
|
|
300
637
|
required: ["op"],
|
|
301
638
|
additionalProperties: false,
|
|
302
639
|
},
|
|
303
640
|
}, async (input) => {
|
|
304
|
-
const
|
|
641
|
+
const raw = input;
|
|
642
|
+
const op = String(raw.op ?? "") || inferLedgerOp(raw);
|
|
305
643
|
if (!op)
|
|
306
644
|
return {
|
|
307
645
|
ok: false,
|
|
308
|
-
content: 'Say which op:
|
|
646
|
+
content: 'Say which op, or call the focused tool: add_requirement {"text":"…"}, set_requirement_status {"requirementId":"r2","status":"blocked"}, add_failure {"failure":"…"}, set_next_step {"text":"…"}.',
|
|
309
647
|
};
|
|
310
|
-
|
|
311
|
-
const requirement = ledger.requirements.find((item) => item.id === requirementId);
|
|
312
|
-
if (!requirement)
|
|
313
|
-
return `unknown requirement "${requirementId}"`;
|
|
314
|
-
const unmet = unmetDependencies(ledger, requirement, {
|
|
315
|
-
allowWaived: verifierConfig.allowWaived,
|
|
316
|
-
});
|
|
317
|
-
return unmet.length
|
|
318
|
-
? `${requirement.id} requires ${unmet.join(", ")}`
|
|
319
|
-
: undefined;
|
|
320
|
-
};
|
|
321
|
-
if (op === "add_requirement") {
|
|
322
|
-
const text = String(input.text ?? "").trim();
|
|
323
|
-
if (!text)
|
|
324
|
-
return {
|
|
325
|
-
ok: false,
|
|
326
|
-
content: 'add_requirement needs text: the requirement in one sentence, e.g. {"op":"add_requirement","text":"Threads can be filtered by label","dependsOn":["r2"]}',
|
|
327
|
-
};
|
|
328
|
-
if (input.id !== undefined && typeof input.id !== "string") {
|
|
329
|
-
return { ok: false, content: "id must be a string" };
|
|
330
|
-
}
|
|
331
|
-
if (input.dependsOn !== undefined && !Array.isArray(input.dependsOn)) {
|
|
332
|
-
return {
|
|
333
|
-
ok: false,
|
|
334
|
-
content: "dependsOn must be an array of requirement ids",
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
if (Array.isArray(input.dependsOn) &&
|
|
338
|
-
input.dependsOn.some((item) => typeof item !== "string")) {
|
|
339
|
-
return {
|
|
340
|
-
ok: false,
|
|
341
|
-
content: "dependsOn must be an array of requirement ids",
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
try {
|
|
345
|
-
const requirement = addRequirement(ledger, {
|
|
346
|
-
text,
|
|
347
|
-
required: input.required !== false,
|
|
348
|
-
...(typeof input.id === "string" && input.id
|
|
349
|
-
? { id: input.id }
|
|
350
|
-
: {}),
|
|
351
|
-
...(typeof input.phase === "string" && input.phase
|
|
352
|
-
? { phase: input.phase }
|
|
353
|
-
: {}),
|
|
354
|
-
...(Array.isArray(input.dependsOn) && input.dependsOn.length
|
|
355
|
-
? { dependsOn: input.dependsOn }
|
|
356
|
-
: {}),
|
|
357
|
-
}, "agent");
|
|
358
|
-
return {
|
|
359
|
-
ok: true,
|
|
360
|
-
content: `added ${requirement.id}: ${requirement.text}`,
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
catch (error) {
|
|
364
|
-
return {
|
|
365
|
-
ok: false,
|
|
366
|
-
content: error instanceof Error ? error.message : String(error),
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
if (op === "link_evidence") {
|
|
371
|
-
const claim = String(input.claim ?? "").trim();
|
|
372
|
-
if (!claim) {
|
|
373
|
-
return {
|
|
374
|
-
ok: false,
|
|
375
|
-
content: "claim is required: explain why this evidence establishes the requirement",
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
linkEvidence(ledger, String(input.requirementId ?? ""), String(input.evidenceId ?? ""), claim);
|
|
379
|
-
return { ok: true, content: "evidence linked" };
|
|
380
|
-
}
|
|
381
|
-
if (op === "verify") {
|
|
382
|
-
const claim = String(input.claim ?? "").trim();
|
|
383
|
-
if (!claim) {
|
|
384
|
-
return {
|
|
385
|
-
ok: false,
|
|
386
|
-
content: "claim is required: explain why this evidence establishes the requirement",
|
|
387
|
-
};
|
|
388
|
-
}
|
|
389
|
-
const requirementId = String(input.requirementId ?? "");
|
|
390
|
-
const unmet = dependencyError(requirementId);
|
|
391
|
-
if (unmet)
|
|
392
|
-
return { ok: false, content: unmet };
|
|
393
|
-
linkEvidence(ledger, requirementId, String(input.evidenceId ?? ""), claim);
|
|
394
|
-
setRequirementStatus(ledger, requirementId, "verified");
|
|
395
|
-
return { ok: true, content: "evidence linked and requirement verified" };
|
|
396
|
-
}
|
|
397
|
-
if (op === "set_status") {
|
|
398
|
-
const status = String(input.status ?? "");
|
|
399
|
-
if (status === "superseded") {
|
|
400
|
-
return { ok: false, content: "use a user revision to supersede" };
|
|
401
|
-
}
|
|
402
|
-
const requirementId = String(input.requirementId ?? "");
|
|
403
|
-
if (status === "verified" || status === "waived") {
|
|
404
|
-
const unmet = dependencyError(requirementId);
|
|
405
|
-
if (unmet)
|
|
406
|
-
return { ok: false, content: unmet };
|
|
407
|
-
}
|
|
408
|
-
if (status === "verified") {
|
|
409
|
-
const requirement = ledger.requirements.find((item) => item.id === requirementId);
|
|
410
|
-
if (!requirement || requirement.evidenceIds.length === 0) {
|
|
411
|
-
return {
|
|
412
|
-
ok: false,
|
|
413
|
-
content: "link evidence to this requirement before marking it verified",
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
setRequirementStatus(ledger, requirementId, status);
|
|
418
|
-
return { ok: true, content: `status set to ${status}` };
|
|
419
|
-
}
|
|
420
|
-
if (op === "set_next_step") {
|
|
421
|
-
ledger.nextStep = String(input.text ?? "");
|
|
422
|
-
return { ok: true, content: "next step recorded" };
|
|
423
|
-
}
|
|
424
|
-
if (op === "add_failure") {
|
|
425
|
-
const failure = String(input.failure ?? "").trim();
|
|
426
|
-
if (!failure)
|
|
427
|
-
return {
|
|
428
|
-
ok: false,
|
|
429
|
-
content: 'add_failure needs failure: what failed, in words, e.g. {"op":"add_failure","failure":"Migration fails on an empty table"}',
|
|
430
|
-
};
|
|
431
|
-
ledger.openFailures.push(failure);
|
|
432
|
-
return { ok: true, content: "failure recorded" };
|
|
433
|
-
}
|
|
434
|
-
if (op === "clear_failure") {
|
|
435
|
-
const failure = String(input.failure ?? "");
|
|
436
|
-
ledger.openFailures = ledger.openFailures.filter((item) => item !== failure);
|
|
437
|
-
return { ok: true, content: "failure cleared" };
|
|
438
|
-
}
|
|
439
|
-
return { ok: false, content: `unknown ledger op "${op}"` };
|
|
648
|
+
return runLedgerOp(op, raw);
|
|
440
649
|
}, { verb: "Updating the progress ledger" });
|
|
441
|
-
|
|
442
|
-
return
|
|
650
|
+
install(shim, "update_ledger");
|
|
651
|
+
return shim;
|
|
443
652
|
};
|
|
444
653
|
const installCompletionGate = () => {
|
|
445
654
|
completionGate = async (summaryText, success) => {
|
|
@@ -474,7 +683,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
474
683
|
`missingEvidence: ${structural.missingEvidence.join(", ") || "none"}`,
|
|
475
684
|
`unsatisfiedDependencies: ${structural.unsatisfiedDependencies.join(" | ") || "none"}`,
|
|
476
685
|
`failures: ${structural.failures.join(" | ") || "none"}`,
|
|
477
|
-
"Attach evidence to each requirement with
|
|
686
|
+
"Attach evidence to each requirement with link_evidence or verify_requirement, resolve failures, and try again.",
|
|
478
687
|
].join("\n"),
|
|
479
688
|
};
|
|
480
689
|
}
|
|
@@ -524,7 +733,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
524
733
|
ledger = next;
|
|
525
734
|
phaseRejections = 0;
|
|
526
735
|
phaseEvidence = [];
|
|
527
|
-
|
|
736
|
+
ledgerTools();
|
|
528
737
|
installCompletionGate();
|
|
529
738
|
};
|
|
530
739
|
if (verifierOn && ledger)
|
|
@@ -577,7 +786,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
577
786
|
renderLedger(ledger, {
|
|
578
787
|
allowWaived: verifierConfig.allowWaived,
|
|
579
788
|
}),
|
|
580
|
-
"Use
|
|
789
|
+
"Use link_evidence and verify_requirement for each requirement. Do not claim completion while a required item is open or lacks evidence.",
|
|
581
790
|
].join("\n\n")
|
|
582
791
|
: undefined,
|
|
583
792
|
stability: "turn",
|
|
@@ -689,6 +898,32 @@ async function runOne(input, opts, chain = {}) {
|
|
|
689
898
|
let silentToolTurns = 0;
|
|
690
899
|
let steps = 0;
|
|
691
900
|
const stepsBefore = chain.stepsBefore ?? 0;
|
|
901
|
+
// ---- Delegated subagents ------------------------------------------------
|
|
902
|
+
// Registered here, after the step counters exist: a child's derived budget
|
|
903
|
+
// is computed from what the leader has left at the moment it delegates.
|
|
904
|
+
if (opts.team && Object.keys(opts.team.members).length > 0) {
|
|
905
|
+
const remaining = () => ({
|
|
906
|
+
steps: Math.max(0, budget.limits.maxSteps - stepsBefore - steps),
|
|
907
|
+
...(budget.limits.maxWallClockMs !== undefined
|
|
908
|
+
? { wallClockMs: Math.max(0, budget.limits.maxWallClockMs - budget.wallClockMs()) }
|
|
909
|
+
: {}),
|
|
910
|
+
usd: budget.costsKnown
|
|
911
|
+
? Math.max(0, budget.limits.maxUsd - budget.costUsd)
|
|
912
|
+
: budget.limits.maxUsd,
|
|
913
|
+
});
|
|
914
|
+
const teamTools = createTeamTools({
|
|
915
|
+
team: opts.team,
|
|
916
|
+
parent: opts,
|
|
917
|
+
budget,
|
|
918
|
+
remaining,
|
|
919
|
+
leaderName: strategy.name,
|
|
920
|
+
emit,
|
|
921
|
+
signal,
|
|
922
|
+
runChild: (input, childOpts, link) => runOne(input, childOpts, link),
|
|
923
|
+
});
|
|
924
|
+
available.set("delegate", teamTools.delegate);
|
|
925
|
+
available.set("steer_worker", teamTools.steer);
|
|
926
|
+
}
|
|
692
927
|
// Recovery for tools that declare an external effect. Scope defaults to the
|
|
693
928
|
// thread; a store without either is a wiring bug, not a silent no-op.
|
|
694
929
|
const operations = opts.operations;
|
|
@@ -787,6 +1022,11 @@ async function runOne(input, opts, chain = {}) {
|
|
|
787
1022
|
// An empty turn (no text, no tool call) gets one correction. The flag is
|
|
788
1023
|
// how the next empty turn is recognized as "after the advisory."
|
|
789
1024
|
let emptyNudged = false;
|
|
1025
|
+
// A delegated child is told to wrap up once, at its soft cap. The hard cap
|
|
1026
|
+
// still ends the loop; the flag keeps the directive one-shot.
|
|
1027
|
+
let softCapNudged = false;
|
|
1028
|
+
/** Files the child has named in its tool calls, for progress. */
|
|
1029
|
+
const touchedFiles = new Set();
|
|
790
1030
|
const proseCheckpoint = opts.guardrails?.proseCheckpoint ?? true;
|
|
791
1031
|
// The shared mechanic lives in guardrails.ts; the policy (when a correction
|
|
792
1032
|
// fires, and when it stops) stays here.
|
|
@@ -800,6 +1040,70 @@ async function runOne(input, opts, chain = {}) {
|
|
|
800
1040
|
pendingProseCheck = true;
|
|
801
1041
|
},
|
|
802
1042
|
});
|
|
1043
|
+
/**
|
|
1044
|
+
* The compact record a host sees while a delegated child runs. One shape for
|
|
1045
|
+
* the per-turn progress and for the stall signal, so a supervisor reads the
|
|
1046
|
+
* same fields either way.
|
|
1047
|
+
*/
|
|
1048
|
+
const emitProgress = (extra = {}) => {
|
|
1049
|
+
if (!chain.child || !chain.worker)
|
|
1050
|
+
return;
|
|
1051
|
+
const filesTouched = touchedFiles.size
|
|
1052
|
+
? [...touchedFiles].slice(0, 20)
|
|
1053
|
+
: undefined;
|
|
1054
|
+
const lastText = lastAssistantLine(messages);
|
|
1055
|
+
const progress = {
|
|
1056
|
+
worker: chain.worker,
|
|
1057
|
+
agent: chain.agent ?? strategy.name,
|
|
1058
|
+
role: chain.role ?? "worker",
|
|
1059
|
+
steps,
|
|
1060
|
+
budgetUsed: budget.usedFraction(stepsBefore + steps),
|
|
1061
|
+
...(lastToolName ? { lastTool: lastToolName } : {}),
|
|
1062
|
+
...(lastVerbName ? { lastVerb: lastVerbName } : {}),
|
|
1063
|
+
...(lastText ? { lastText } : {}),
|
|
1064
|
+
...(filesTouched ? { filesTouched } : {}),
|
|
1065
|
+
...(extra.stalled ? { stalled: true } : {}),
|
|
1066
|
+
...(extra.stalledForMs !== undefined
|
|
1067
|
+
? { stalledForMs: extra.stalledForMs }
|
|
1068
|
+
: {}),
|
|
1069
|
+
steer: (value) => chain.steer?.push(value) ?? false,
|
|
1070
|
+
nudge: (value) => chain.steer?.push(value) ?? false,
|
|
1071
|
+
};
|
|
1072
|
+
emit({
|
|
1073
|
+
type: "progress",
|
|
1074
|
+
worker: progress.worker,
|
|
1075
|
+
steps: progress.steps,
|
|
1076
|
+
budgetUsed: progress.budgetUsed,
|
|
1077
|
+
...(progress.lastTool ? { lastTool: progress.lastTool } : {}),
|
|
1078
|
+
...(progress.lastVerb ? { lastVerb: progress.lastVerb } : {}),
|
|
1079
|
+
...(progress.lastText ? { lastText: progress.lastText } : {}),
|
|
1080
|
+
...(progress.filesTouched ? { filesTouched: progress.filesTouched } : {}),
|
|
1081
|
+
...(progress.stalled ? { stalled: true } : {}),
|
|
1082
|
+
...(progress.stalledForMs !== undefined
|
|
1083
|
+
? { stalledForMs: progress.stalledForMs }
|
|
1084
|
+
: {}),
|
|
1085
|
+
});
|
|
1086
|
+
try {
|
|
1087
|
+
opts.onProgress?.(progress);
|
|
1088
|
+
}
|
|
1089
|
+
catch {
|
|
1090
|
+
// A consumer callback must never kill the run.
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
// A child that produces no event for `stallAfterMs` is reported ONCE; any
|
|
1094
|
+
// real activity resets the window. The engine neither cancels nor nudges —
|
|
1095
|
+
// the supervisor decides.
|
|
1096
|
+
if (chain.child && chain.worker && stallAfterMs !== false) {
|
|
1097
|
+
const tick = setInterval(() => {
|
|
1098
|
+
const idle = Date.now() - lastActivityAt;
|
|
1099
|
+
if (idle < stallAfterMs || stallReported)
|
|
1100
|
+
return;
|
|
1101
|
+
stallReported = true;
|
|
1102
|
+
emitProgress({ stalled: true, stalledForMs: idle });
|
|
1103
|
+
}, stallAfterMs);
|
|
1104
|
+
tick.unref?.();
|
|
1105
|
+
timers.push(tick);
|
|
1106
|
+
}
|
|
803
1107
|
let checkpointRef;
|
|
804
1108
|
let pauseRequested = false;
|
|
805
1109
|
if (phaseOn) {
|
|
@@ -998,7 +1302,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
998
1302
|
if (ledger) {
|
|
999
1303
|
return {
|
|
1000
1304
|
ok: false,
|
|
1001
|
-
content: "the contract is already active; use
|
|
1305
|
+
content: "the contract is already active; use set_requirement_status or add_requirement to change it",
|
|
1002
1306
|
};
|
|
1003
1307
|
}
|
|
1004
1308
|
const goal = String(input.goal ?? "").trim();
|
|
@@ -1099,7 +1403,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1099
1403
|
content: [
|
|
1100
1404
|
`Contract created: ${next.goal}`,
|
|
1101
1405
|
...next.requirements.map((item) => `${item.id}: ${item.text} (phase ${item.phase ?? "any"})`),
|
|
1102
|
-
"Use
|
|
1406
|
+
"Use link_evidence or verify_requirement to attach evidence with a claim and verify each requirement.",
|
|
1103
1407
|
].join("\n"),
|
|
1104
1408
|
// Identifiers only: the ledger itself is emitted on task_created
|
|
1105
1409
|
// and must never ride a tool result, which is captured as evidence
|
|
@@ -1404,6 +1708,31 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1404
1708
|
});
|
|
1405
1709
|
}
|
|
1406
1710
|
}
|
|
1711
|
+
// Leader directives land here, at the boundary, as ordinary runtime
|
|
1712
|
+
// messages in the child's own stream — never a tool result, so they
|
|
1713
|
+
// cannot forge evidence.
|
|
1714
|
+
if (chain.steer) {
|
|
1715
|
+
for (const directive of chain.steer.drain()) {
|
|
1716
|
+
messages.push({
|
|
1717
|
+
role: "user",
|
|
1718
|
+
origin: "engine",
|
|
1719
|
+
content: steerDirective(directive),
|
|
1720
|
+
});
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
// Soft cap: a child is told to wrap up at 80% of its own budget, once.
|
|
1724
|
+
// It is a nudge, not a stop — the child can still hand back an answer.
|
|
1725
|
+
if (chain.child &&
|
|
1726
|
+
!softCapNudged &&
|
|
1727
|
+
budget.usedFraction(stepsBefore + steps) >= DEFAULT_CHILD_SOFT_CAP) {
|
|
1728
|
+
softCapNudged = true;
|
|
1729
|
+
await courseCorrect({
|
|
1730
|
+
kind: "child_wrap_up",
|
|
1731
|
+
detail: `step ${steps}: child reached ${Math.round(DEFAULT_CHILD_SOFT_CAP * 100)}% of its budget ` +
|
|
1732
|
+
`(${budgetLine(budget, stepsBefore + steps)}) — told to wrap up`,
|
|
1733
|
+
content: wrapUpNudge(Math.max(0, budget.limits.maxSteps - stepsBefore - steps), budgetLine(budget, stepsBefore + steps)),
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1407
1736
|
const over = budget.exceeded(stepsBefore + steps);
|
|
1408
1737
|
if (over) {
|
|
1409
1738
|
emit({
|
|
@@ -1411,6 +1740,15 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1411
1740
|
kind: "budget_exceeded",
|
|
1412
1741
|
detail: over.detail,
|
|
1413
1742
|
});
|
|
1743
|
+
// A child out of its OWN budget hands back what it has. The leader's
|
|
1744
|
+
// run continues; a worker hitting its cap is not the leader's failure.
|
|
1745
|
+
if (chain.child) {
|
|
1746
|
+
return conclude("budget_exhausted", {
|
|
1747
|
+
ok: false,
|
|
1748
|
+
summary: lastAssistantText(messages),
|
|
1749
|
+
error: over.detail,
|
|
1750
|
+
});
|
|
1751
|
+
}
|
|
1414
1752
|
return conclude(over.kind === "steps" ? "max_steps" : "budget_exceeded", { ok: false, error: over.detail });
|
|
1415
1753
|
}
|
|
1416
1754
|
if (revivalOn && !revivalWarned) {
|
|
@@ -1533,7 +1871,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1533
1871
|
steps++;
|
|
1534
1872
|
emit({ type: "llm_call_started", phase, step: steps });
|
|
1535
1873
|
const modelMessages = forModel();
|
|
1536
|
-
const response = await opts.llm.stream({
|
|
1874
|
+
const response = await waitWithCancelGrace(opts.llm.stream({
|
|
1537
1875
|
messages: modelMessages,
|
|
1538
1876
|
cacheBreakpoints: cacheBreakpointsFor(modelMessages),
|
|
1539
1877
|
tools: [...available.values()].map((tool) => ({
|
|
@@ -1551,7 +1889,12 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1551
1889
|
}, (text) => emit({ type: "llm_text_delta", text }), {
|
|
1552
1890
|
signal,
|
|
1553
1891
|
onReasoning: (text) => emit({ type: "llm_reasoning_delta", text }),
|
|
1554
|
-
});
|
|
1892
|
+
}), signal, cancelGraceMs);
|
|
1893
|
+
if (response === CANCEL_GRACE)
|
|
1894
|
+
return conclude("cancelled", {
|
|
1895
|
+
ok: false,
|
|
1896
|
+
error: "cancelled by signal",
|
|
1897
|
+
});
|
|
1555
1898
|
budget.record(response.usage);
|
|
1556
1899
|
emit({
|
|
1557
1900
|
type: "llm_call_finished",
|
|
@@ -1702,7 +2045,7 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1702
2045
|
pendingProseCheck = false;
|
|
1703
2046
|
let declared;
|
|
1704
2047
|
let runaway = false;
|
|
1705
|
-
const
|
|
2048
|
+
const dispatched = await waitWithCancelGrace(dispatchToolCalls({
|
|
1706
2049
|
calls: response.toolCalls,
|
|
1707
2050
|
available,
|
|
1708
2051
|
steps,
|
|
@@ -1716,15 +2059,12 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1716
2059
|
emitBackground,
|
|
1717
2060
|
...(operationRuntime ? { operations: operationRuntime } : {}),
|
|
1718
2061
|
onMissingJournal,
|
|
1719
|
-
signal,
|
|
2062
|
+
signal: toolSignal,
|
|
1720
2063
|
pauseRequested: () => pauseRequested,
|
|
1721
2064
|
onToolResult: (call, result) => {
|
|
1722
2065
|
// Contract tools describe the ledger; they are not evidence about
|
|
1723
2066
|
// the work and must not be recorded into the ledger they manage.
|
|
1724
|
-
if (!ledger ||
|
|
1725
|
-
call.name === "finish" ||
|
|
1726
|
-
call.name === "update_ledger" ||
|
|
1727
|
-
call.name === "create_task") {
|
|
2067
|
+
if (!ledger || LEDGER_TOOL_NAMES.has(call.name)) {
|
|
1728
2068
|
return;
|
|
1729
2069
|
}
|
|
1730
2070
|
const evidenceRef = recordEvidence(ledger, {
|
|
@@ -1736,11 +2076,24 @@ async function runOne(input, opts, chain = {}) {
|
|
|
1736
2076
|
});
|
|
1737
2077
|
phaseEvidence.push(evidenceRef);
|
|
1738
2078
|
},
|
|
1739
|
-
});
|
|
2079
|
+
}), signal, cancelGraceMs);
|
|
2080
|
+
if (dispatched === CANCEL_GRACE)
|
|
2081
|
+
return conclude("cancelled", {
|
|
2082
|
+
ok: false,
|
|
2083
|
+
error: "cancelled by signal",
|
|
2084
|
+
});
|
|
2085
|
+
const outcome = dispatched;
|
|
1740
2086
|
runaway = outcome.runaway;
|
|
1741
2087
|
declared = outcome.declared;
|
|
1742
2088
|
outstanding.push(...outcome.jobs);
|
|
1743
2089
|
pendingSettlements.push(...outcome.settlements);
|
|
2090
|
+
// Progress for a delegated child: the leader's `delegate` call is still
|
|
2091
|
+
// open, so this is how a host sees the work (and may steer it). One
|
|
2092
|
+
// compact record per turn — never the child's transcript.
|
|
2093
|
+
if (chain.child && chain.worker) {
|
|
2094
|
+
noteTouchedFiles(touchedFiles, response.toolCalls);
|
|
2095
|
+
emitProgress();
|
|
2096
|
+
}
|
|
1744
2097
|
// Materialization advisory (runtime-only, never persisted): a reasoning
|
|
1745
2098
|
// model's hidden chain is stateless between calls, so after consecutive
|
|
1746
2099
|
// turns that only call tools, nothing it understood is visible — and
|