@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.43
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 +21 -0
- package/README.md +8 -7
- package/dist/console/assets/index-BrcDSBD8.css +1 -0
- package/dist/console/assets/{index-DYJ_wj27.js → index-Bz6IWncl.js} +186 -186
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +0 -4
- package/dist/import-sources.js +25 -5
- package/dist/learn/audit.d.ts +123 -0
- package/dist/learn/audit.js +159 -0
- package/dist/learn/compile.d.ts +50 -74
- package/dist/learn/compile.js +90 -124
- package/dist/learn/folder.d.ts +9 -0
- package/dist/learn/folder.js +13 -2
- package/dist/learn/promote.d.ts +86 -200
- package/dist/learn/promote.js +57 -183
- package/dist/learn/replay-calls.d.ts +5 -0
- package/dist/learn/replay-calls.js +12 -1
- package/dist/learn/secrets.d.ts +8 -0
- package/dist/learn/secrets.js +12 -0
- package/dist/learn/skills.js +2 -4
- package/dist/learn/workflow-nodes.d.ts +1 -2
- package/dist/learn/workflow-nodes.js +2 -3
- package/dist/learned-nodes.d.ts +9 -34
- package/dist/learned-nodes.js +11 -23
- package/dist/learned-workflow.d.ts +6 -8
- package/dist/learned-workflow.js +18 -57
- package/dist/learning-batch.d.ts +13 -5
- package/dist/learning-batch.js +34 -8
- package/dist/learning-cost.d.ts +11 -4
- package/dist/learning-cost.js +4 -2
- package/dist/learning-routes.js +1 -1
- package/dist/learning-setting.d.ts +16 -1
- package/dist/learning-setting.js +34 -2
- package/dist/openapi.js +95 -55
- package/dist/run-launch.d.ts +6 -3
- package/dist/run-launch.js +2 -0
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/runner/adapter-loop.d.ts +4 -0
- package/dist/runner/adapter-loop.js +17 -2
- package/dist/runner/adapter-run-spec.js +16 -5
- package/dist/runner/audit.d.ts +64 -0
- package/dist/runner/audit.js +338 -0
- package/dist/runner/beside.js +1 -1
- package/dist/runner/cli-run-spec.js +15 -5
- package/dist/runner/feedback-round.js +1 -4
- package/dist/runner/harness-loops.js +1 -15
- package/dist/runner/journal-kinds.d.ts +0 -7
- package/dist/runner/journal-kinds.js +0 -7
- package/dist/runner/learning-dispatch.d.ts +0 -16
- package/dist/runner/learning-dispatch.js +4 -47
- package/dist/runner/learning-end.d.ts +52 -13
- package/dist/runner/learning-end.js +124 -44
- package/dist/runner/learning-factory.d.ts +1 -1
- package/dist/runner/learning-factory.js +1 -4
- package/dist/runner/learning-loop.d.ts +2 -38
- package/dist/runner/learning-loop.js +8 -116
- package/dist/runner/main.js +1 -1
- package/dist/runner/promotion.d.ts +50 -54
- package/dist/runner/promotion.js +191 -583
- package/dist/runner/reflect-hook.d.ts +10 -0
- package/dist/runner/reflect-hook.js +6 -0
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +17 -12
- package/dist/server.js +61 -16
- package/dist/store/sqlite/store.js +1 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store-reads/learning.d.ts +17 -6
- package/dist/store-reads/learning.js +36 -23
- package/dist/store-reads/loop.d.ts +4 -39
- package/dist/store-reads/loop.js +10 -79
- package/dist/store-view.js +12 -2
- package/dist/workspace/run-tools.d.ts +1 -1
- package/dist/workspace/run-tools.js +14 -3
- package/package.json +9 -9
- package/dist/console/assets/index-C3gNPz58.css +0 -1
- package/dist/learn/general.d.ts +0 -69
- package/dist/learn/general.js +0 -75
- package/dist/learn/refit.d.ts +0 -48
- package/dist/learn/refit.js +0 -264
- package/dist/runner/step-guard.d.ts +0 -62
- package/dist/runner/step-guard.js +0 -93
package/dist/runner/promotion.js
CHANGED
|
@@ -6,17 +6,15 @@ import { uuidv7 } from "../runs-over-store.js";
|
|
|
6
6
|
import { FINAL_STATES, RunFinal, StoreConstraint } from "../store/store.js";
|
|
7
7
|
import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
|
|
8
8
|
import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
|
|
9
|
-
import { recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
|
|
9
|
+
import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
|
|
10
10
|
import { isObject } from "../validate.js";
|
|
11
|
-
import { lastOwnRuns } from "../learn/compile.js";
|
|
12
|
-
import {
|
|
11
|
+
import { agentRun, lastOwnRuns, newCompileAttempt } from "../learn/compile.js";
|
|
12
|
+
import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, promotionOf, promotionsOf, recordPromotion, replayingOf, sameAnswer, skippedToolsOf } from "../learn/promote.js";
|
|
13
13
|
import { sendCommand } from "./commands.js";
|
|
14
14
|
import { ClaimRefused } from "./loop-contract.js";
|
|
15
15
|
import { readSnapshot } from "../learn/folder.js";
|
|
16
|
-
import { refitGuards, refitRowsOf, scoreRows } from "../learn/refit.js";
|
|
17
16
|
import { fits, laidFor, servedOf, workflowDigest } from "./workflow-first.js";
|
|
18
|
-
import {
|
|
19
|
-
import { recordOnly } from "../learn/promote.js";
|
|
17
|
+
import { excerptShown } from "../learn/secrets.js";
|
|
20
18
|
import { workflowsAt } from "./learning-seed.js";
|
|
21
19
|
/** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
|
|
22
20
|
* the replay is decided without it. */
|
|
@@ -24,27 +22,13 @@ export const REPLAY_DEADLINE_MS = 60 * 60 * 1000;
|
|
|
24
22
|
/** A reserved replay run still not created this long after its record was reserved is a launch that was interrupted (the
|
|
25
23
|
* reserving claim crashed, or its create failed): the next claim creates it (relaunch). Before then it is pending. */
|
|
26
24
|
export const REPLAY_LAUNCH_GRACE_MS = 5 * 60 * 1000;
|
|
27
|
-
/** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
* the workflow an earlier claim of this run served (`kept`, from its journal: none on a first claim). */
|
|
25
|
+
/** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
|
|
26
|
+
* from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
|
|
27
|
+
* claim of this run served (`kept`, from its journal: none on a first claim). */
|
|
31
28
|
export function claimPromotion(deps) {
|
|
32
|
-
const seed = deps.launch.learning?.seed;
|
|
33
29
|
return {
|
|
34
30
|
...deps,
|
|
35
31
|
kept: async () => (deps.runId ? servedOf(await runEntries(deps.store, deps.runId, deps.context).catch(() => [])) : undefined),
|
|
36
|
-
commit: async (files, reason, id) => {
|
|
37
|
-
const folder = deps.folder();
|
|
38
|
-
try {
|
|
39
|
-
const done = await learningCommit(folder.workspace, { kind: "merge", runId: id, reason, files, graded: {}, ...(seed ? { seed } : {}) });
|
|
40
|
-
if (!done.ok)
|
|
41
|
-
deps.log(`workflow-first: a refit could not be written (${done.reason})`);
|
|
42
|
-
return done.ok ? done.commit : null;
|
|
43
|
-
}
|
|
44
|
-
finally {
|
|
45
|
-
await folder.end();
|
|
46
|
-
}
|
|
47
|
-
},
|
|
48
32
|
champion: async (name, commit) => (await workflowsAt({ folder: deps.folder, shown: deps.shown }, commit)).find((one) => one.name === name),
|
|
49
33
|
newest: async (name) => {
|
|
50
34
|
const folder = deps.folder();
|
|
@@ -72,29 +56,27 @@ export async function replayClaimed(store, agentId, runId, launch, choice) {
|
|
|
72
56
|
const { workflow, digest } = launch.replay;
|
|
73
57
|
const record = promotionOf(await promotionsOf(store.settings, agentId), workflow, digest);
|
|
74
58
|
if (record && record.decided !== "replaying")
|
|
75
|
-
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "
|
|
59
|
+
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "promote" ? "promoted already" : "held already"}.`);
|
|
76
60
|
if (record && !record.runs?.includes(runId))
|
|
77
61
|
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision replays again${record.replay_id ? ` (replay ${record.replay_id})` : ""}, and this run is not one of its runs.`);
|
|
78
62
|
if (choice.serve?.replay !== true || choice.serve.name !== workflow)
|
|
79
63
|
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: its claim laid no workflow by that name at that digest. The agent was not asked.`);
|
|
80
64
|
}
|
|
81
|
-
/** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays
|
|
82
|
-
*
|
|
83
|
-
* the laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's,
|
|
84
|
-
* as laid. */
|
|
65
|
+
/** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays, or none by that name when the
|
|
66
|
+
* laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's, as laid. */
|
|
85
67
|
export function replayLaid(launch, laid) {
|
|
86
68
|
if (!launch.replay)
|
|
87
69
|
return [...laid];
|
|
88
70
|
const { workflow, digest } = launch.replay;
|
|
89
|
-
return laid.
|
|
71
|
+
return laid.filter((one) => one.name !== workflow || workflowDigest(one) === digest);
|
|
90
72
|
}
|
|
91
73
|
/** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
|
|
92
74
|
* revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
|
|
93
75
|
* champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
|
|
94
76
|
* text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
|
|
95
|
-
* promoted yet, or the champion held): a revision replaying,
|
|
96
|
-
*
|
|
97
|
-
*
|
|
77
|
+
* promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
|
|
78
|
+
* in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
|
|
79
|
+
* laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
|
|
98
80
|
export async function toolFlowsFor(deps, launch, laid, choice) {
|
|
99
81
|
const chosen = laidFor(laid, choice);
|
|
100
82
|
if (launch.replay || !chosen.length)
|
|
@@ -136,10 +118,10 @@ const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.lea
|
|
|
136
118
|
const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
|
|
137
119
|
/** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
|
|
138
120
|
* this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
|
|
139
|
-
* revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
121
|
+
* revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its check moved on (decide:
|
|
122
|
+
* started, or settled once its runs ended), and then servingNow alone says who serves: the champion (championOf), the
|
|
123
|
+
* laid text when it is the champion, its own text read from its record's commit when not; undefined when none serves
|
|
124
|
+
* (the agent takes the run). A digest's own record never says it serves. */
|
|
143
125
|
export const promotionGate = (deps) => {
|
|
144
126
|
const failed = (workflow, error) => {
|
|
145
127
|
// A promotion that could not be read or written leaves the run to its agent: never a workflow served unchecked.
|
|
@@ -158,7 +140,7 @@ export const promotionGate = (deps) => {
|
|
|
158
140
|
return failed(workflow, error);
|
|
159
141
|
}
|
|
160
142
|
};
|
|
161
|
-
// The champion alone, for a laid revision that does not take the run's input (workflowFirstOf): nothing
|
|
143
|
+
// The champion alone, for a laid revision that does not take the run's input (workflowFirstOf): nothing is checked.
|
|
162
144
|
const champion = async (workflow, digest) => {
|
|
163
145
|
try {
|
|
164
146
|
const kept = await keptFor(deps, workflow, digest);
|
|
@@ -172,12 +154,9 @@ export const promotionGate = (deps) => {
|
|
|
172
154
|
};
|
|
173
155
|
/** Who serves `workflow` now, the one answer every serving path asks: its champion (championOf, read fresh from the
|
|
174
156
|
* records), never a digest's own record, so a revision promoted before another was (or before the champion was held)
|
|
175
|
-
* never serves again. The laid revision at `digest` when it is the champion
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
* with no refit (a refit written now would land over the laid revision on the folder's main). With the champion's
|
|
179
|
-
* promotion (its since), which the run keeps (WorkflowFirst.promotion). Undefined when none serves: none promoted, the
|
|
180
|
-
* champion held, or its text cannot be read (the agent takes the run). */
|
|
157
|
+
* never serves again. The laid revision at `digest` when it is the champion; `laid` false: it is not asked (the laid text
|
|
158
|
+
* does not take the input). Another champion: its text at its record's commit (its digest checked). Undefined when none
|
|
159
|
+
* serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
|
|
181
160
|
async function servingNow(deps, workflow, digest, laid) {
|
|
182
161
|
const records = await promotionsOf(deps.store.settings, deps.agentId);
|
|
183
162
|
const champion = championOf(records, workflow.name);
|
|
@@ -187,12 +166,8 @@ async function servingNow(deps, workflow, digest, laid) {
|
|
|
187
166
|
deps.log(`workflow-first: ${workflow.name} at ${digest} was promoted, but the revision promoted after it is held; no revision serves, the agent takes this run`);
|
|
188
167
|
return undefined;
|
|
189
168
|
}
|
|
190
|
-
const serving = (text, under) => (under ? { workflow: text, ...(under.since !== undefined ? { promotion: under.since } : {}) } : undefined);
|
|
191
|
-
// A champion its check promoted serves as it is: it was decided once on the agent's own answers, and no grade, refit or
|
|
192
|
-
// second replay ever moves it (a hold or its owner does).
|
|
193
|
-
const kept = (text, under) => (under.source === "check" ? Promise.resolve(under) : stillServing(deps, text, under.digest, under));
|
|
194
169
|
if (champion.digest === digest)
|
|
195
|
-
return laid ?
|
|
170
|
+
return laid ? { workflow } : undefined;
|
|
196
171
|
if (!deps.champion)
|
|
197
172
|
return undefined;
|
|
198
173
|
const text = champion.commit ? await deps.champion(workflow.name, champion.commit).catch(() => undefined) : undefined;
|
|
@@ -200,11 +175,8 @@ async function servingNow(deps, workflow, digest, laid) {
|
|
|
200
175
|
deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} could not be read from its learning commit; the agent takes this run`);
|
|
201
176
|
return undefined;
|
|
202
177
|
}
|
|
203
|
-
const under = champion.source === "check" ? champion : await stillServing({ ...deps, commit: undefined }, text, champion.digest, champion);
|
|
204
|
-
if (!under)
|
|
205
|
-
return undefined;
|
|
206
178
|
deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} serves this run while ${digest} ${own?.decided === "promote" ? "is a revision promoted before it" : "is not promoted"}`);
|
|
207
|
-
return
|
|
179
|
+
return { workflow: text };
|
|
208
180
|
}
|
|
209
181
|
/** A run already executing keeps its revision: when an earlier claim of it served `workflow` first (its WORKFLOW_FIRST
|
|
210
182
|
* entry, answered or handed back: `deps.kept`), a re-claim serves the same digest, whoever the champion is now (the loop
|
|
@@ -216,7 +188,7 @@ async function keptFor(deps, workflow, digest) {
|
|
|
216
188
|
if (!kept || kept.workflow !== workflow.name || !kept.digest)
|
|
217
189
|
return undefined;
|
|
218
190
|
if (kept.digest !== digest) {
|
|
219
|
-
// Its newest record naming a commit
|
|
191
|
+
// Its newest record naming a commit.
|
|
220
192
|
const record = (await promotionsOf(deps.store.settings, deps.agentId)).findLast((one) => one.workflow === workflow.name && one.digest === kept.digest && one.commit);
|
|
221
193
|
const text = record?.commit && deps.champion ? await deps.champion(workflow.name, record.commit).catch(() => undefined) : undefined;
|
|
222
194
|
if (text && workflowDigest(text) === kept.digest) {
|
|
@@ -227,12 +199,10 @@ async function keptFor(deps, workflow, digest) {
|
|
|
227
199
|
deps.log(`workflow-first: ${workflow.name} at ${kept.digest} served this run on an earlier claim; it keeps that revision${kept.digest === digest ? "" : ` (its text could not be read: the laid ${digest} stands in, the kept outcome recovered as it is)`}`);
|
|
228
200
|
return workflow;
|
|
229
201
|
}
|
|
230
|
-
/** Moves the laid revision's
|
|
231
|
-
*
|
|
232
|
-
* started. It decides nothing about who serves (servingNow does). */
|
|
202
|
+
/** Moves the laid revision's check on: a new digest is checked (startCheck), a replaying one settled once its runs ended
|
|
203
|
+
* (after finishing a launch that was interrupted). It decides nothing about who serves (servingNow does). */
|
|
233
204
|
async function decide(deps, workflow, digest) {
|
|
234
205
|
const { store, agentId, log } = deps;
|
|
235
|
-
const now = deps.now ?? Date.now;
|
|
236
206
|
const record = promotionOf(await promotionsOf(store.settings, agentId), workflow.name, digest);
|
|
237
207
|
if (record?.decided === "promote")
|
|
238
208
|
return;
|
|
@@ -240,78 +210,13 @@ async function decide(deps, workflow, digest) {
|
|
|
240
210
|
log(`workflow-first: ${workflow.name} at ${digest} is held (${record.reason}); it does not serve this run`);
|
|
241
211
|
return;
|
|
242
212
|
}
|
|
243
|
-
if (record?.decided === "skipped") {
|
|
244
|
-
log(`workflow-first: ${workflow.name} at ${digest} was skipped (${record.reason}); it does not serve this run`);
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
213
|
if (record?.decided === "replaying") {
|
|
248
214
|
await relaunch(deps, workflow, digest, record);
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
log(`workflow-first: ${workflow.name} at ${digest} is ${record.source === "check" ? `being checked on ${record.runs?.length ?? 0} of the agent's inputs` : `replaying on ${plural(record.runs?.length ?? 0, "graded input")}`}; it does not serve this run`);
|
|
215
|
+
if (!(await settleCheck(deps, workflow, digest, record)))
|
|
216
|
+
log(`workflow-first: ${workflow.name} at ${digest} is being checked on ${record.runs?.length ?? 0} of the agent's inputs; it does not serve this run`);
|
|
252
217
|
return;
|
|
253
218
|
}
|
|
254
|
-
|
|
255
|
-
// rival settled, no dry-run promote. Only a revision a replay's queue holds already moves as it did.
|
|
256
|
-
if (!record)
|
|
257
|
-
return startCheck(deps, workflow, digest);
|
|
258
|
-
// A new revision, or a queued one. One replay at a time, and a running replay finishes: the laid one moves only when it
|
|
259
|
-
// is the newest revision (the one the learning folder's main holds now); a run pinned to an older commit lays an older
|
|
260
|
-
// text and starts nothing, whenever it was launched (a queued one it lays is skipped for the newest). With the records at
|
|
261
|
-
// the trim's cap a revision with none may be one whose record the trim dropped (a skipped or held one): it starts only
|
|
262
|
-
// when it is the newest too, so a skipped draft never replays once its record is gone. `seen`, the queue as read before
|
|
263
|
-
// the newest check: every queue change below (queued, skips, a start) is one guarded write kept only while the queue
|
|
264
|
-
// is still that (sameQueue), so a claim that read an older main never skips a newer revision a later claim queued
|
|
265
|
-
// meanwhile.
|
|
266
|
-
const seen = await promotionsOf(store.settings, agentId);
|
|
267
|
-
let records = seen;
|
|
268
|
-
const ahead = [...replayingOf(records, workflow.name, digest), ...replayingOf(records, workflow.name, digest, "queued")];
|
|
269
|
-
const trimmed = records.length >= PROMOTIONS_KEPT;
|
|
270
|
-
if (ahead.length || record || trimmed) {
|
|
271
|
-
const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
|
|
272
|
-
if (newest !== digest && (ahead.length || record || newest !== undefined)) {
|
|
273
|
-
if (record && newest !== undefined)
|
|
274
|
-
await skip(deps, record, newest);
|
|
275
|
-
else
|
|
276
|
-
log(`workflow-first: ${workflow.name} at ${digest} is not the learning folder's newest revision of it (${newest ?? "unknown"})${ahead[0] ? `, and ${ahead[0].digest} ${ahead[0].decided === "replaying" ? "replays" : "is queued"}` : ""}; it does not serve this run`);
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
// The replay at work finishes: decided here once its runs ended (its verdict stands), never cancelled. While it
|
|
280
|
-
// runs, the laid revision is queued behind it.
|
|
281
|
-
for (const rival of replayingOf(records, workflow.name, digest))
|
|
282
|
-
await settleRival(deps, workflow.name, rival);
|
|
283
|
-
records = await promotionsOf(store.settings, agentId);
|
|
284
|
-
const running = replayingOf(records, workflow.name, digest)[0];
|
|
285
|
-
if (running)
|
|
286
|
-
return enqueue(deps, workflow, digest, record, running, seen);
|
|
287
|
-
}
|
|
288
|
-
// Its replay starts now, and only the newest queued revision replays next: any queued before it is skipped in the same
|
|
289
|
-
// write, and says so. Kept while its record is still none (or still the queued one read here) and the queue is still seen.
|
|
290
|
-
const older = replayingOf(seen, workflow.name, digest, "queued");
|
|
291
|
-
const skips = older.map((one) => skippedFor(deps, one, digest));
|
|
292
|
-
const fresh = (was, items) => ownStill(record)(was) && sameQueue(items, seen, workflow.name, digest);
|
|
293
|
-
const after = record ? `, queued since ${record.at} behind another revision's replay` : "";
|
|
294
|
-
const skipped = () => { for (const one of older)
|
|
295
|
-
log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${skips[0].reason}`); };
|
|
296
|
-
// No replay of it yet, nothing owed, so the agent's newest REPLAY_INPUTS (the one picker, inputsFor).
|
|
297
|
-
const { graded } = await inputsFor(deps, workflow, digest, records, "held");
|
|
298
|
-
if (graded.length < REPLAY_MIN) {
|
|
299
|
-
const reason = graded.length ? `${plural(graded.length, "graded input")} it fits, fewer than ${REPLAY_MIN}: promoted on its passing dry run` : `no graded input it fits: promoted on its passing dry run`;
|
|
300
|
-
const kept = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "promote", source: "dry_run", reason, ...seedOf(deps) }, fresh, skips);
|
|
301
|
-
if (kept.won) {
|
|
302
|
-
skipped();
|
|
303
|
-
log(`workflow-first: ${workflow.name} at ${digest}: ${reason}`);
|
|
304
|
-
}
|
|
305
|
-
return;
|
|
306
|
-
}
|
|
307
|
-
const reserved = await reserve(deps, workflow, digest, gradedRuns(graded), `replaying on the agent's last ${plural(graded.length, "graded input")} it fits${after}`, fresh, [], skips);
|
|
308
|
-
if (!reserved.won) {
|
|
309
|
-
const rival = replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest)[0];
|
|
310
|
-
log(`workflow-first: ${workflow.name} at ${digest}: ${rival ? `${rival.digest} began replaying first` : "the queue moved since this claim read it (a claim that read a newer revision acted first)"}; it does not serve this run`);
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
skipped();
|
|
314
|
-
log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "next" : "new"}: replaying it on the agent's last ${plural(graded.length, "graded input")} before it serves`);
|
|
219
|
+
return startCheck(deps, workflow, digest);
|
|
315
220
|
}
|
|
316
221
|
/** The loop's numbers (learning-setting.ts) of the revision the claim runs: its definition's `learning`, each one it
|
|
317
222
|
* leaves out at its default (a revision that cannot be read: every default). */
|
|
@@ -325,21 +230,48 @@ async function loopOfRevision(deps) {
|
|
|
325
230
|
}
|
|
326
231
|
}
|
|
327
232
|
/** Which check of a compile a new revision's is: 2 when the workflow's newest record of another revision is a first
|
|
328
|
-
* check's hold (this revision is its one recompile), else 1. A
|
|
329
|
-
* check's hold: it spends no recompile.
|
|
233
|
+
* check's hold or an audit's hold, or a first compile's failed draft (this revision is its one recompile), else 1. A
|
|
234
|
+
* stop with nothing checked (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first
|
|
235
|
+
* revision after a first compile whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that
|
|
236
|
+
* compile's recompile too. */
|
|
330
237
|
function attemptOf(records, name, digest) {
|
|
331
238
|
const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
*
|
|
340
|
-
|
|
239
|
+
if (!before)
|
|
240
|
+
return newCompileAttempt(records.filter((one) => one.digest !== digest));
|
|
241
|
+
if (before.decided !== "hold")
|
|
242
|
+
return 1;
|
|
243
|
+
return before.audit ? (before.audit.stopped ? 1 : 2) : before.check?.attempt === 1 && !before.check.stopped ? 2 : 1;
|
|
244
|
+
}
|
|
245
|
+
/** The shadow runs a recompile's check runs on beside the agent's last runs: the disagreeing audit rows the workflow's
|
|
246
|
+
* newest audit hold names (a grade's row has no answer of the agent's to check against), when that hold is the
|
|
247
|
+
* workflow's newest record of another revision. */
|
|
248
|
+
function auditInputsOf(records, name, digest) {
|
|
249
|
+
const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
|
|
250
|
+
if (before?.decided !== "hold" || !before.audit || before.audit.stopped)
|
|
251
|
+
return [];
|
|
252
|
+
return before.audit.disagreements.filter((one) => !one.graded && one.agent !== null).map((one) => one.run);
|
|
253
|
+
}
|
|
254
|
+
/** An agent run a check may read its input from: a completed run of its own (agentRun: no learned workflow answered it
|
|
255
|
+
* alone, and it is no replay), neither archived nor imported, and never the claimed run (lastOwnRuns' own rule). */
|
|
256
|
+
const checkable = (deps, row) => row.id !== deps.runId && agentRun(row) && row.archivedAt === null && !row.importedFrom;
|
|
257
|
+
/** The inputs a check runs its draft on: the agent's runs `pick.of` names (a check's own, asked again; each still
|
|
258
|
+
* checkable), then the agent's last `pick.n` completed runs of its own (lastOwnRuns: never the claimed run, an archived
|
|
259
|
+
* or imported one), newest first, picked before anything else limits them: runs its workflow served since, however many,
|
|
260
|
+
* never push them out of the read. And `audited`: an audit hold's disagreeing shadow runs (auditInputsOf), each ended.
|
|
261
|
+
* Of those, the ones whose input `workflow` takes (fits), each with its launch read back; one with an uploaded file is
|
|
262
|
+
* never an input. With how many of the agent's runs it looked at (`looked`) and why each it looked at is no input
|
|
263
|
+
* (`unfit`, `files`). */
|
|
264
|
+
async function checkInputs(deps, workflow, pick, audited = []) {
|
|
341
265
|
const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
|
|
342
|
-
const
|
|
266
|
+
const named = (await Promise.all(pick.of.map((id) => deps.store.runs.get(id)))).filter((row) => row !== undefined && checkable(deps, row));
|
|
267
|
+
const last = pick.n ? await lastOwnRuns(deps.store, deps.agentId, pick.n + pick.of.length, deps.runId) : [];
|
|
268
|
+
const own = [...named, ...last.filter((row) => !pick.of.includes(row.id)).slice(0, pick.n)];
|
|
269
|
+
// And an audit hold's disagreeing shadow runs: the agent's answers the recompile must say too.
|
|
270
|
+
for (const id of audited) {
|
|
271
|
+
const row = await deps.store.runs.get(id);
|
|
272
|
+
if (row && row.state === "ended" && !own.some((one) => one.id === id))
|
|
273
|
+
own.push(row);
|
|
274
|
+
}
|
|
343
275
|
const out = [];
|
|
344
276
|
let files = 0;
|
|
345
277
|
for (const row of own) {
|
|
@@ -367,17 +299,17 @@ async function startCheck(deps, workflow, digest) {
|
|
|
367
299
|
}
|
|
368
300
|
// One check at a time, and one at work finishes: decided here once its runs ended (its verdict stands), never
|
|
369
301
|
// cancelled. While it runs, this revision waits, recording nothing: the claim after it is decided starts this one.
|
|
370
|
-
for (const
|
|
371
|
-
await
|
|
302
|
+
for (const ahead of replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest))
|
|
303
|
+
await settleAhead(deps, workflow.name, ahead);
|
|
372
304
|
const records = await promotionsOf(store.settings, agentId);
|
|
373
305
|
const rival = replayingOf(records, workflow.name, digest)[0];
|
|
374
306
|
if (rival) {
|
|
375
|
-
log(`workflow-first: ${workflow.name} at ${digest} waits: ${rival.digest} is
|
|
307
|
+
log(`workflow-first: ${workflow.name} at ${digest} waits: ${rival.digest} is being checked (one check at a time); it does not serve this run`);
|
|
376
308
|
return;
|
|
377
309
|
}
|
|
378
310
|
const loop = await loopOfRevision(deps);
|
|
379
311
|
const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, workflow.name, digest) };
|
|
380
|
-
const { inputs, looked, unfit, files } = await checkInputs(deps, workflow, loop.compile_after);
|
|
312
|
+
const { inputs, looked, unfit, files } = await checkInputs(deps, workflow, { of: [], n: loop.compile_after }, auditInputsOf(records, workflow.name, digest));
|
|
381
313
|
if (!inputs.length) {
|
|
382
314
|
// Nothing of the agent's to check it on (a workflow landed before any run it fits): never promoted unchecked. It
|
|
383
315
|
// stops, its record naming why (the compile's draft error), and asks no recompile: a revision would have nothing to be
|
|
@@ -389,7 +321,7 @@ async function startCheck(deps, workflow, digest) {
|
|
|
389
321
|
return;
|
|
390
322
|
}
|
|
391
323
|
const said = `checking it on ${plural(inputs.length, "input")} of the agent's last ${plural(bar.compile_after, "completed run")} against its own answers`;
|
|
392
|
-
const reserved = await reserve(deps, workflow, digest, inputs, said, (was) => was === undefined,
|
|
324
|
+
const reserved = await reserve(deps, workflow, digest, inputs, said, (was) => was === undefined, bar);
|
|
393
325
|
if (!reserved.won) {
|
|
394
326
|
log(`workflow-first: ${workflow.name} at ${digest}: another claim's decision on it came first; it does not serve this run`);
|
|
395
327
|
return;
|
|
@@ -405,20 +337,29 @@ export const NOTHING_TO_CHECK = "nothing to check it on";
|
|
|
405
337
|
* (attemptOf). Kept only while `still` holds of the digest's record (the one write). */
|
|
406
338
|
async function stopUnchecked(deps, name, digest, bar, why, still, check = {}, extra = {}) {
|
|
407
339
|
const reason = `${NOTHING_TO_CHECK}: ${why}. It is not promoted, and it stops: nothing compiles again until a hold or its owner acts`;
|
|
408
|
-
const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold",
|
|
340
|
+
const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason, check: { ...bar, n: 0, agreed: 0, alone: 0, of: [], ...check, stopped: true }, ...seedOf(deps), ...extra }, still);
|
|
409
341
|
if (decided.won)
|
|
410
342
|
deps.log(`workflow-first: ${name} at ${digest} stopped: ${reason}`);
|
|
411
343
|
return decided;
|
|
412
344
|
}
|
|
413
|
-
/**
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
|
|
345
|
+
/** Decides `ahead`, the check at work for a revision older than the laid (newest) one, as a claim laying it would
|
|
346
|
+
* (relaunch, then settleCheck) once its runs ended: its text read at its record's commit, its verdict standing (promote
|
|
347
|
+
* or hold) though a newer revision waits. Left replaying while a run of it is at work, or when its text cannot be read
|
|
348
|
+
* (its read, replayView, decides it then). */
|
|
349
|
+
async function settleAhead(deps, name, ahead) {
|
|
350
|
+
const text = ahead.commit && deps.champion ? await deps.champion(name, ahead.commit).catch(() => undefined) : undefined;
|
|
351
|
+
if (text === undefined || workflowDigest(text) !== ahead.digest) {
|
|
352
|
+
deps.log(`workflow-first: ${name} at ${ahead.digest} is being checked, and its text could not be read from its learning commit to decide it at this claim`);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
await relaunch(deps, text, ahead.digest, ahead);
|
|
356
|
+
await settleCheck(deps, text, ahead.digest, ahead);
|
|
357
|
+
}
|
|
418
358
|
/** A check's rows, once every replay run ended (or REPLAY_DEADLINE_MS passed); undefined while one is at work or not
|
|
419
359
|
* created yet. One row per reserved input, so every one counts: a run not ended by the deadline failed, and so did one
|
|
420
360
|
* never created by then (`unstarted`: the server stopped after reserving it, say), its input read from the agent's run
|
|
421
|
-
* the record names for it. With what its runs cost,
|
|
361
|
+
* the record names for it. With what its runs cost, the rows' outcomes (one per row, the never created failed), and how
|
|
362
|
+
* many were never created by the deadline.
|
|
422
363
|
* No grade is read: the label is the agent's own recorded answer. */
|
|
423
364
|
async function checkRows(deps, record) {
|
|
424
365
|
const { store, context } = deps;
|
|
@@ -435,20 +376,23 @@ async function checkRows(deps, record) {
|
|
|
435
376
|
// Never created (or its launch unreadable): a failed input, never left out of n.
|
|
436
377
|
const of = reservedOf;
|
|
437
378
|
const from = of ? await store.runs.launch(of).then((one) => readLaunchBody(one.body), () => undefined) : undefined;
|
|
438
|
-
rows.push({ of: of ?? record.runs[i], input: from ? inputText(from.input) : "", agent: of ? await answerOf(store, of, context) : null, outcome: "failed", answer: null,
|
|
379
|
+
rows.push({ of: of ?? record.runs[i], input: from ? inputText(from.input) : "", agent: of ? await answerOf(store, of, context) : null, outcome: "failed", answer: null, ...(run ? {} : { unstarted: true }) });
|
|
439
380
|
continue;
|
|
440
381
|
}
|
|
441
382
|
const outcome = outcomeOf(run);
|
|
442
383
|
const stoppedAt = outcome === "skipped_write" ? metricsOf(run).replay?.skipped : undefined;
|
|
443
|
-
const guards = metricsOf(run).guards;
|
|
444
384
|
rows.push({
|
|
445
|
-
of: replayed, input: inputText(launch.input), agent: await answerOf(store, replayed, context), outcome,
|
|
385
|
+
of: replayed, input: inputText(launch.input), agent: await answerOf(store, replayed, context), outcome,
|
|
446
386
|
answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
|
|
447
387
|
...(outcome === "handed_back" ? { escalated: (await handedBackOf(store, run.id, context)) ?? "" } : {}),
|
|
448
388
|
...(stoppedAt ? { skipped: stoppedAt } : {}),
|
|
449
389
|
});
|
|
450
390
|
}
|
|
451
|
-
|
|
391
|
+
// The outcomes are the rows', so they add up to its n: a reserved run never created is a failed input there too.
|
|
392
|
+
const outcomes = { ...NO_OUTCOMES };
|
|
393
|
+
for (const row of rows)
|
|
394
|
+
outcomes[row.outcome] += 1;
|
|
395
|
+
return { rows, cost: replayCost(runs, late), outcomes, unstarted: rows.filter((row) => row.unstarted).length };
|
|
452
396
|
}
|
|
453
397
|
/** A run's input as a check's disagreement shows it: its text, else its JSON. */
|
|
454
398
|
const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input) ?? "");
|
|
@@ -469,7 +413,7 @@ async function settleCheck(deps, workflow, digest, record) {
|
|
|
469
413
|
if (!read)
|
|
470
414
|
return undefined;
|
|
471
415
|
const bar = record.check ?? { ...(await loopOfRevision(deps)), attempt: 1 };
|
|
472
|
-
const decided = await decideCheck(deps, name, digest, bar, read,
|
|
416
|
+
const decided = await decideCheck(deps, name, digest, bar, read, (was) => sameReplay(was, record), { ...(record.runs ? { runs: record.runs } : {}), ...(record.replay_id ? { replay_id: record.replay_id } : {}), ...(record.commit ? { commit: record.commit } : {}) });
|
|
473
417
|
if (decided.won) {
|
|
474
418
|
const cancelled = await cancelUnended(deps, record);
|
|
475
419
|
if (cancelled)
|
|
@@ -478,33 +422,24 @@ async function settleCheck(deps, workflow, digest, record) {
|
|
|
478
422
|
return decided.record?.decided === "replaying" ? undefined : decided.record;
|
|
479
423
|
}
|
|
480
424
|
/** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
|
|
481
|
-
* with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate
|
|
482
|
-
* step
|
|
483
|
-
*
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
export async function decideCheck(deps, name, digest, bar, read,
|
|
425
|
+
* with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate and no
|
|
426
|
+
* failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
|
|
427
|
+
* agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
|
|
428
|
+
* nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
|
|
429
|
+
* (the one write: of two claims at once, one decides). */
|
|
430
|
+
export async function decideCheck(deps, name, digest, bar, read, still, extra) {
|
|
487
431
|
const now = deps.now ?? Date.now;
|
|
488
432
|
const ran = read.rows.filter((row) => row.outcome !== "skipped_write");
|
|
489
|
-
const alone = (row) => row.outcome === "answered"
|
|
433
|
+
const alone = (row) => row.outcome === "answered";
|
|
490
434
|
const agrees = (row) => alone(row) && sameAnswer(row.answer, row.agent);
|
|
491
435
|
const score = { n: ran.length, agreed: ran.filter(agrees).length, alone: ran.filter(alone).length };
|
|
492
436
|
const ok = checkPasses(score, bar);
|
|
493
|
-
// Each text is cut of the host's secrets whole, then shortened
|
|
494
|
-
// its prefix, which no redactor matches.
|
|
437
|
+
// Each text is cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown).
|
|
495
438
|
const shown = await deps.shown();
|
|
496
|
-
const cut = (text) =>
|
|
497
|
-
const clean = shown.text(text);
|
|
498
|
-
return clean.length > CHECK_TEXT_MAX ? `${clean.slice(0, CHECK_TEXT_MAX)}…` : clean;
|
|
499
|
-
};
|
|
500
|
-
// An input it answered that a guard (or a recorded escalate) hands back when serving is a hand-back, named by its step.
|
|
501
|
-
const servedBack = (row) => {
|
|
502
|
-
const guard = handsBackAt(row, thresholds);
|
|
503
|
-
return guard ? `step ${guard.node} hands it back when serving (${guard.signal === "escalate" ? "its escalate fired" : `p ${guard.p ?? "unknown"} under ${thresholds.get(guard.node) ?? guard.threshold}`})` : undefined;
|
|
504
|
-
};
|
|
439
|
+
const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
|
|
505
440
|
const disagreements = ran.filter((row) => !agrees(row)).map((row) => ({
|
|
506
441
|
run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
|
|
507
|
-
...(row.outcome === "answered" ?
|
|
442
|
+
...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
|
|
508
443
|
}));
|
|
509
444
|
const stopped = !ok && bar.attempt === 2;
|
|
510
445
|
const pct = (value) => `${(value * 100).toFixed(1)}%`;
|
|
@@ -514,111 +449,43 @@ export async function decideCheck(deps, name, digest, bar, read, thresholds, sti
|
|
|
514
449
|
const tools = skippedToolsOf(read.rows);
|
|
515
450
|
const { skipped_write: skipped, failed } = read.outcomes;
|
|
516
451
|
const { hint, why: skipWhy } = skipWordsOf(tools, skipped);
|
|
517
|
-
const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(tools.length ? { skipped_tools: tools } : {}) };
|
|
452
|
+
const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}) };
|
|
518
453
|
// Every input skipped at a write (each reserved input counts: one never created or never ended failed, so this is the
|
|
519
454
|
// only way to none): nothing to check it on, so it stops, never promoted unchecked, and asks no recompile.
|
|
520
455
|
if (!score.n) {
|
|
521
456
|
const why = skipped ? `${plural(skipped, "input")} skipped because ${hint ? skipWhy : `each ${SKIPPED_WRITE} (a check never runs a write)`}` : "it ran on no input";
|
|
522
457
|
return stopUnchecked(deps, name, digest, bar, why, still, numbers, extra);
|
|
523
458
|
}
|
|
524
|
-
|
|
525
|
-
const
|
|
459
|
+
// A run never created is a failed outcome too, said once: as never started.
|
|
460
|
+
const ranFailed = failed - read.unstarted;
|
|
461
|
+
const aside = [...(ranFailed ? [`${ranFailed} failed: a step failed, or it was still at work at the check's deadline`] : []), ...(skipped ? [`${skipped} skipped: ${skipWhy}`] : []), ...(read.unstarted ? [`${read.unstarted} never started by the check's deadline (the server stopped after reserving it, say), each a failed input`] : [])].join("; ");
|
|
462
|
+
// Every input reserved and none started (a launch interrupted before its first run existed): each counts failed in n,
|
|
463
|
+
// and the words say none ran.
|
|
464
|
+
const said = read.unstarted === score.n
|
|
465
|
+
? `none of its ${plural(score.n, "check run")} started by the check's deadline (its launch was interrupted: the server stopped after reserving it, say): nothing was checked`
|
|
466
|
+
: `checked on ${score.n} of the agent's inputs: answered ${score.alone} alone (${pct(shares.alone)}, the bar ${pct(bar.alone_min)}), and ${score.agreed} of those said what the agent said (${pct(shares.agreement)}, the bar ${pct(bar.agree_min)})${aside ? ` (${aside})` : ""}`;
|
|
526
467
|
const reason = ok ? `${said}: promoted` : stopped ? `${said}: held, and this was the recompile's check, so it stops: nothing compiles again until a hold or its owner acts` : `${said}: held; the agent's next run recompiles it once with the inputs it did not agree on`;
|
|
527
468
|
const check = { ...bar, ...score, ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}) };
|
|
528
|
-
const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold",
|
|
469
|
+
const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold", reason, check, ...seedOf(deps), ...extra }, still);
|
|
529
470
|
if (decided.won)
|
|
530
471
|
deps.log(`workflow-first: ${name} at ${digest} ${ok ? "promoted" : "held"}: ${reason}`);
|
|
531
472
|
return decided;
|
|
532
473
|
}
|
|
533
|
-
/**
|
|
534
|
-
* queued record. */
|
|
535
|
-
const ownStill = (record) => (was) => (record ? was?.decided === "queued" && was.at === record.at : was === undefined);
|
|
536
|
-
/** The revisions of `name` other than `digest` queued in `records`, each by digest and when it was queued. */
|
|
537
|
-
const queueOf = (records, name, digest) => replayingOf(records, name, digest, "queued").map((one) => `${one.digest}@${one.at}`).sort().join(",");
|
|
538
|
-
/** Whether the queue in `items` (now, in the guarded write) is still the one in `seen` (read before the claim's newest
|
|
539
|
-
* check). Main only moves on, so a claim whose newest check read an older main read the records before any claim that
|
|
540
|
-
* read the newer main acted: when one did (queued its revision, skipped or started the one queued), the queue moved,
|
|
541
|
-
* and the stale claim's write is refused. A refused claim that was the newest after all (two read the same queue)
|
|
542
|
-
* changes nothing either; the next claim of the newest revision, which every new run lays, makes the change. */
|
|
543
|
-
const sameQueue = (items, seen, name, digest) => queueOf(items, name, digest) === queueOf(seen, name, digest);
|
|
544
|
-
/** Queues `workflow` at `digest`, the newest revision, behind `running`, the replay at work (a record of it already
|
|
545
|
-
* queued is left as it is), and skips each revision queued before it (only the newest queued one replays next), in one
|
|
546
|
-
* guarded write: kept only while its own record is still the one read and the queue is still `seen` (sameQueue). */
|
|
547
|
-
async function enqueue(deps, workflow, digest, record, running, seen) {
|
|
548
|
-
const { store, agentId, log } = deps;
|
|
549
|
-
const now = deps.now ?? Date.now;
|
|
550
|
-
const behind = `${running.digest}'s replay on ${plural(running.runs?.length ?? 0, "graded input")}`;
|
|
551
|
-
const reason = `queued behind ${behind}: a running replay finishes; the newest revision queued meanwhile replays next`;
|
|
552
|
-
const older = replayingOf(seen, workflow.name, digest, "queued");
|
|
553
|
-
const writes = [...(record ? [] : [{ workflow: workflow.name, digest, at: iso(now()), decided: "queued", source: "replay", reason, ...seedOf(deps) }]), ...older.map((one) => skippedFor(deps, one, digest))];
|
|
554
|
-
if (!writes.length) {
|
|
555
|
-
log(`workflow-first: ${workflow.name} at ${digest} is queued behind ${behind}; it does not serve this run`);
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
const kept = await recordPromotion(store.settings, agentId, writes[0], (_, items) => ownStill(record)(promotionOf(items, workflow.name, digest)) && sameQueue(items, seen, workflow.name, digest), writes.slice(1));
|
|
559
|
-
if (!kept.won) {
|
|
560
|
-
log(`workflow-first: ${workflow.name} at ${digest}: the queue moved since this claim read it (a claim that read a newer revision acted first); this claim changes nothing, and it does not serve this run`);
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
log(`workflow-first: ${workflow.name} at ${digest} is ${record ? "queued" : "new: queued"} behind ${behind}; it replays once that one is decided`);
|
|
564
|
-
for (const one of older)
|
|
565
|
-
log(`workflow-first: ${one.workflow} at ${one.digest} skipped: ${writes.at(-1).reason}`);
|
|
566
|
-
}
|
|
567
|
-
/** `record`, a revision queued behind another's replay, skipped for `by`, a newer revision that came before its replay
|
|
568
|
-
* could start: it never replays and never serves. Never silent: the record names `by` and says why. */
|
|
569
|
-
function skippedFor(deps, record, by) {
|
|
570
|
-
const now = deps.now ?? Date.now;
|
|
571
|
-
const reason = `a newer draft ${by} arrived before its replay could start: only the newest queued revision replays next`;
|
|
572
|
-
return { workflow: record.workflow, digest: record.digest, at: iso(now()), decided: "skipped", source: "replay", reason, skipped_by: by, ...(record.commit ? { commit: record.commit } : {}) };
|
|
573
|
-
}
|
|
574
|
-
/** Skips the laid revision's own queued `record` for `by`, the newest revision (its claim laid an older text): kept only
|
|
575
|
-
* while it is still that queued record. */
|
|
576
|
-
async function skip(deps, record, by) {
|
|
577
|
-
const one = skippedFor(deps, record, by);
|
|
578
|
-
const kept = await recordPromotion(deps.store.settings, deps.agentId, one, (was) => was?.decided === "queued" && was.at === record.at);
|
|
579
|
-
if (kept.won)
|
|
580
|
-
deps.log(`workflow-first: ${record.workflow} at ${record.digest} skipped: ${one.reason}`);
|
|
581
|
-
}
|
|
582
|
-
/** Decides `running`, the replay at work ahead of the laid (newest) revision, as a claim laying it would (relaunch, then
|
|
583
|
-
* settle) once its runs ended: its text read at its record's commit, its verdict standing (promote or hold) though a
|
|
584
|
-
* newer revision waits. No refit is written from it: the folder's main holds the newer revision, and a refit would land
|
|
585
|
-
* over it. Left replaying while a run of it is at work, or when its text cannot be read (its read, replayView, decides
|
|
586
|
-
* it then). */
|
|
587
|
-
async function settleRival(deps, name, running) {
|
|
588
|
-
const text = running.commit && deps.champion ? await deps.champion(name, running.commit).catch(() => undefined) : undefined;
|
|
589
|
-
const readable = text !== undefined && workflowDigest(text) === running.digest;
|
|
590
|
-
const ports = { ...deps, commit: undefined };
|
|
591
|
-
if (!readable) {
|
|
592
|
-
deps.log(`workflow-first: ${name} at ${running.digest} replays, and its text could not be read from its learning commit to decide it at this claim`);
|
|
593
|
-
return;
|
|
594
|
-
}
|
|
595
|
-
await relaunch(ports, text, running.digest, running);
|
|
596
|
-
// A check ahead (source check) is decided on its runs and the agent's answers, its guards at the text's thresholds.
|
|
597
|
-
if (running.source === "check") {
|
|
598
|
-
await settleCheck(ports, text, running.digest, running);
|
|
599
|
-
return;
|
|
600
|
-
}
|
|
601
|
-
const decided = await settle(ports, text, running.digest, running);
|
|
602
|
-
if (decided?.decided === "hold")
|
|
603
|
-
deps.log(`workflow-first: ${name} at ${running.digest} held with a newer revision waiting: no refit of it is written`);
|
|
604
|
-
}
|
|
605
|
-
/** Reserves a replay of `workflow` at `digest` on `graded`, then starts its runs: its replaying record names the replay
|
|
474
|
+
/** Reserves a check of `workflow` at `digest` on `inputs`, then starts its runs: its replaying record names the replay
|
|
606
475
|
* runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
|
|
607
476
|
* now and no other revision of the workflow replays, in the one guarded write. Only the writer that kept it starts them:
|
|
608
|
-
* a claim of the same digest, or of another revision, or a person's ask, at once, starts none. A claim's (
|
|
609
|
-
* person's (askReplay) are this one reservation.
|
|
610
|
-
|
|
611
|
-
async function reserve(deps, workflow, digest, inputs, reason, still, owed = [], also = [], check) {
|
|
477
|
+
* a claim of the same digest, or of another revision, or a person's ask, at once, starts none. A claim's (startCheck) and
|
|
478
|
+
* a person's (askReplay) are this one reservation. */
|
|
479
|
+
async function reserve(deps, workflow, digest, inputs, reason, still, check) {
|
|
612
480
|
const now = deps.now ?? Date.now;
|
|
613
481
|
const ids = inputs.map(() => uuidv7());
|
|
614
482
|
const launch = replayLaunchOf(deps);
|
|
615
|
-
const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying",
|
|
483
|
+
const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying", reason, runs: ids, inputs: inputs.map((one) => one.run), replay_id: uuidv7(), launch, ...seedOf(deps), check }, (was, items) => still(was) && replayingOf(items, workflow.name, digest).length === 0);
|
|
616
484
|
if (reserved.won)
|
|
617
485
|
for (const [i, one] of inputs.entries())
|
|
618
486
|
await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
|
|
619
487
|
return reserved;
|
|
620
488
|
}
|
|
621
|
-
const gradedRuns = (inputs) => inputs.map((one) => ({ run: one.grade.run, launch: one.launch }));
|
|
622
489
|
/** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
|
|
623
490
|
* `deps.launch` as a replay run takes it (a claim's claimed run's; a person's ask makes one now), the revision it runs,
|
|
624
491
|
* and the claimed run as the one whose per_run MCP credentials its runs are handed, when the server can seal them. A
|
|
@@ -648,7 +515,7 @@ function replayLaunchOf(deps) {
|
|
|
648
515
|
* be replayed again), are not: an older replay's late decision never lands over a newer one. */
|
|
649
516
|
const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
|
|
650
517
|
/** Cancels each of `record`'s replay runs not ended, as a person's cancel is (an in-flight one stops, what it spent booked
|
|
651
|
-
* on its row): once its
|
|
518
|
+
* on its row): once its check is decided with runs still at work (past its deadline). How many were sent their cancel. The
|
|
652
519
|
* record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose
|
|
653
520
|
* claim refuses it (replayClaimed: its revision no longer replays), so each cancel is tried and a failed one only logged. */
|
|
654
521
|
async function cancelUnended(deps, record) {
|
|
@@ -669,58 +536,6 @@ async function cancelUnended(deps, record) {
|
|
|
669
536
|
}
|
|
670
537
|
return cancelled;
|
|
671
538
|
}
|
|
672
|
-
/** The paths a graded run a replay runs on took: the agent's (`agent`, or `handed_back`: the agent finished it), or a
|
|
673
|
-
* learned workflow's alone (`workflow`). Each has a recorded answer (the run's final answer, whoever wrote it) and its
|
|
674
|
-
* grade, which is what a replay scores against (answerCorrect); the path says only whose answer it was (agentRight: on a
|
|
675
|
-
* `workflow` run graded wrong the agent counts right); a replay run never is one. */
|
|
676
|
-
const REPLAYABLE = new Set(["agent", "handed_back", "workflow"]);
|
|
677
|
-
/** The agent's graded runs a replay runs on (REPLAYABLE), newest first: the runs `pick.of` names, then the newest
|
|
678
|
-
* `pick.n` (a run both name is taken once). Each with a launch read back, no uploaded file, an input `workflow` fits,
|
|
679
|
-
* never the run being claimed, nor an archived or imported one. */
|
|
680
|
-
async function gradedInputs(deps, workflow, pick) {
|
|
681
|
-
const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
|
|
682
|
-
const out = [];
|
|
683
|
-
const of = new Set(pick.of);
|
|
684
|
-
let newest = 0;
|
|
685
|
-
let named = 0;
|
|
686
|
-
const grades = (await gradesOf(deps.store.settings, deps.agentId)).filter((grade) => REPLAYABLE.has(grade.path));
|
|
687
|
-
for (const grade of grades.reverse()) {
|
|
688
|
-
if (newest >= pick.n && named >= of.size)
|
|
689
|
-
break;
|
|
690
|
-
const asked = of.has(grade.run);
|
|
691
|
-
if ((!asked && newest >= pick.n) || grade.run === deps.runId)
|
|
692
|
-
continue;
|
|
693
|
-
const row = await deps.store.runs.get(grade.run);
|
|
694
|
-
if (!row || row.archivedAt !== null || row.importedFrom)
|
|
695
|
-
continue;
|
|
696
|
-
const launch = await deps.store.runs.launch(grade.run).then((one) => readLaunchBody(one.body), () => undefined);
|
|
697
|
-
if (!launch || launch.files?.length || launch.replay || !fits(workflow, launch.input, resolveSchemaForWorkflow))
|
|
698
|
-
continue;
|
|
699
|
-
out.push({ grade, launch });
|
|
700
|
-
if (asked)
|
|
701
|
-
named += 1;
|
|
702
|
-
if (newest < pick.n)
|
|
703
|
-
newest += 1;
|
|
704
|
-
}
|
|
705
|
-
return out;
|
|
706
|
-
}
|
|
707
|
-
/** What a replay of a revision owes before it may promote it: the served runs graded wrong it was held on
|
|
708
|
-
* (PromotionRecord.held_on), none when `record` owes none. Its replay puts each among its inputs (inputsFor), and its
|
|
709
|
-
* settle holds a replay that did not answer or hand back on each. */
|
|
710
|
-
const heldOn = (record) => record?.held_on ?? [];
|
|
711
|
-
/** The graded inputs a replay of `workflow` at `digest` runs on (gradedInputs), the one picker of both starts: always the
|
|
712
|
-
* served runs graded wrong its newest record holds it on (heldOn), then `held`, the inputs of its newest record that
|
|
713
|
-
* names any (a replay's), else, with none and nothing owed, the agent's newest REPLAY_INPUTS; or a number, the agent's
|
|
714
|
-
* newest that many. A claim's start (decide) is `held` on a revision with no record: the newest REPLAY_INPUTS. `owed`:
|
|
715
|
-
* the held runs among the picked; `named`: how many runs the records named (owed or decided on), picked or not. */
|
|
716
|
-
async function inputsFor(deps, workflow, digest, records, inputs) {
|
|
717
|
-
const held = heldOn(promotionOf(records, workflow.name, digest));
|
|
718
|
-
const last = inputs === "held" ? records.findLast((one) => one.workflow === workflow.name && one.digest === digest && (one.inputs?.length || one.replay?.of.length)) : undefined;
|
|
719
|
-
const of = [...new Set([...held, ...(last ? (last.inputs ?? last.replay.of) : [])])];
|
|
720
|
-
const n = typeof inputs === "number" ? inputs : of.length ? 0 : REPLAY_INPUTS;
|
|
721
|
-
const graded = await gradedInputs(deps, workflow, { of, n });
|
|
722
|
-
return { graded, owed: graded.filter((one) => held.includes(one.grade.run)).map((one) => one.grade.run), named: of.length };
|
|
723
|
-
}
|
|
724
539
|
/** The per_run MCP credentials run `launch.handed_from` was handed (its launch's sealed column, opened under the seal
|
|
725
540
|
* key), sealed for the replay run `id` alone, as the server's start seals a run's mcp_auth (store/seal.ts
|
|
726
541
|
* sealRunMcpAuth): the replay's claim reads them where any run's claim does (runner/mcp-claim.ts). None when the replay
|
|
@@ -734,7 +549,7 @@ async function handedTo(deps, launch, id) {
|
|
|
734
549
|
const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
|
|
735
550
|
return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
|
|
736
551
|
}
|
|
737
|
-
/** Starts the replay of `workflow` at `digest` on
|
|
552
|
+
/** Starts the replay of `workflow` at `digest` on agent run `of` (its launch `from`) as run `id` (the id its reserved
|
|
738
553
|
* record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
|
|
739
554
|
* handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
|
|
740
555
|
* relaunch and the reserving claim at once), and it is left to that one. */
|
|
@@ -756,10 +571,10 @@ async function startReplay(deps, workflow, digest, of, from, id, launch) {
|
|
|
756
571
|
}
|
|
757
572
|
}
|
|
758
573
|
/** Finishes a launch that was interrupted: `record`'s reserved replay runs still not created REPLAY_LAUNCH_GRACE_MS after
|
|
759
|
-
* its reservation (and before its deadline) are created now, each under its reserved id on the
|
|
574
|
+
* its reservation (and before its deadline) are created now, each under its reserved id on the agent run its record
|
|
760
575
|
* names for it (`inputs`), with the launch the record chose when it was reserved (`launch`: its model, revision and
|
|
761
|
-
* handed credentials, an owner's replay none), never this claim's: one
|
|
762
|
-
*
|
|
576
|
+
* handed credentials, an owner's replay none), never this claim's: one check runs on one set of settings. One whose
|
|
577
|
+
* agent run's launch can no longer be read stays missing: past the deadline it is counted as never started. How many
|
|
763
578
|
* this claim created. */
|
|
764
579
|
async function relaunch(deps, workflow, digest, record) {
|
|
765
580
|
const { store } = deps;
|
|
@@ -777,29 +592,33 @@ async function relaunch(deps, workflow, digest, record) {
|
|
|
777
592
|
made += 1;
|
|
778
593
|
}
|
|
779
594
|
if (made)
|
|
780
|
-
deps.log(`workflow-first: ${workflow.name} at ${digest}: its
|
|
595
|
+
deps.log(`workflow-first: ${workflow.name} at ${digest}: its check's launch was interrupted; ${plural(made, "replay run")} it reserved started now`);
|
|
781
596
|
return made;
|
|
782
597
|
}
|
|
783
|
-
/** A run's final answer, whole (its last final answer row that is not its end-of-run turn's), or null: none,
|
|
784
|
-
* record could not be read
|
|
785
|
-
|
|
598
|
+
/** A run's final answer row, its text whole (its last final answer row that is not its end-of-run turn's), or null: none,
|
|
599
|
+
* or its record could not be read. `turn`: the row of that id instead (the answer an audit is of, runner/audit.ts), so an
|
|
600
|
+
* answer a follow-up gave since is never read for it. */
|
|
601
|
+
export async function answerRowOf(store, runId, context, turn) {
|
|
786
602
|
try {
|
|
787
603
|
const rows = await runTimeline(store, runId, context, { settled: true, caps: { text: Number.POSITIVE_INFINITY } });
|
|
788
|
-
|
|
604
|
+
const row = rows.findLast((one) => one.kind === "final_answer" && one.agent_label !== LEARNING_LABEL && (turn === undefined || one.id === turn));
|
|
605
|
+
return typeof row?.text === "string" ? { id: row.id, text: row.text } : null;
|
|
789
606
|
}
|
|
790
607
|
catch {
|
|
791
608
|
return null;
|
|
792
609
|
}
|
|
793
610
|
}
|
|
611
|
+
/** A run's final answer, whole (answerRowOf's text; `turn`: that row's), or null. */
|
|
612
|
+
export const answerOf = async (store, runId, context, turn) => (await answerRowOf(store, runId, context, turn))?.text ?? null;
|
|
794
613
|
const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
|
|
795
614
|
/** What a replay run did, read from its row alone: answered, handed back or skipped at a write once it ended as such; any
|
|
796
|
-
* other end, or one not ended (past the
|
|
615
|
+
* other end, or one not ended (past the check's deadline), failed: no evidence either way. */
|
|
797
616
|
const outcomeOf = (run) => {
|
|
798
617
|
const m = metricsOf(run);
|
|
799
618
|
return run.state === "ended" && (m.replay?.outcome === "answered" || m.replay?.outcome === "handed_back" || m.replay?.outcome === "skipped_write") ? m.replay.outcome : "failed";
|
|
800
619
|
};
|
|
801
620
|
const NO_OUTCOMES = { answered: 0, handed_back: 0, failed: 0, skipped_write: 0 };
|
|
802
|
-
/** How many of a
|
|
621
|
+
/** How many of a check's runs ended each way so far (ReplayOutcomes): one not ended counts only past the deadline
|
|
803
622
|
* (`late`), as failed; one never created, nothing. */
|
|
804
623
|
function outcomesOf(runs, late) {
|
|
805
624
|
const counts = { ...NO_OUTCOMES };
|
|
@@ -809,7 +628,7 @@ function outcomesOf(runs, late) {
|
|
|
809
628
|
return counts;
|
|
810
629
|
}
|
|
811
630
|
/** What `record`'s replay runs cost together, at `now`: null while one's is unknown (one not created yet before the
|
|
812
|
-
* deadline, one not ended, one ended with no cost)
|
|
631
|
+
* deadline, one not ended, one ended with no cost); a run never created by the deadline spent nothing. */
|
|
813
632
|
function replayCost(runs, late) {
|
|
814
633
|
let cost = 0;
|
|
815
634
|
for (const run of runs) {
|
|
@@ -824,44 +643,6 @@ function replayCost(runs, late) {
|
|
|
824
643
|
}
|
|
825
644
|
return Math.round(cost * 1e6) / 1e6;
|
|
826
645
|
}
|
|
827
|
-
/** The replay's rows, once every replay run ended (or REPLAY_DEADLINE_MS passed: one not ended is failed, no evidence);
|
|
828
|
-
* undefined while one is at work or not created yet (its record is reserved before its runs are created: a run missing
|
|
829
|
-
* is a launch still under way, or one a later claim relaunches). With the rows it scores (`scored`, refitRowsOf: the ones
|
|
830
|
-
* its workflow answered or handed back), what the replay runs cost (replayCost), its runs' outcomes (outcomesOf), and how
|
|
831
|
-
* many reserved runs were never created by the deadline (`unstarted`). `partial`: the rows of the runs ended so far, at
|
|
832
|
-
* any time (a replay's read while it runs). A row needs its graded run's grade (what it is scored against): a run whose
|
|
833
|
-
* grade the agent's newer grades rolled out of those kept has none, and is counted (`outcomes`) but not scored. */
|
|
834
|
-
async function replayRows(deps, record, partial = false) {
|
|
835
|
-
const { store, context } = deps;
|
|
836
|
-
const now = (deps.now ?? Date.now)();
|
|
837
|
-
const grades = new Map((await gradesOf(store.settings, deps.agentId)).map((grade) => [grade.run, grade]));
|
|
838
|
-
const runs = await Promise.all((record.runs ?? []).map((id) => store.runs.get(id)));
|
|
839
|
-
const late = now - Date.parse(record.at) > REPLAY_DEADLINE_MS;
|
|
840
|
-
if (!late && !partial && runs.some((row) => !row || !FINAL_STATES.includes(row.state)))
|
|
841
|
-
return undefined;
|
|
842
|
-
const rows = [];
|
|
843
|
-
for (const run of runs) {
|
|
844
|
-
if (!run || (partial && !late && !FINAL_STATES.includes(run.state)))
|
|
845
|
-
continue;
|
|
846
|
-
const launch = await store.runs.launch(run.id).then((one) => readLaunchBody(one.body), () => undefined);
|
|
847
|
-
const of = launch?.replay?.of;
|
|
848
|
-
const grade = of ? grades.get(of) : undefined;
|
|
849
|
-
if (!of || !grade)
|
|
850
|
-
continue;
|
|
851
|
-
const m = metricsOf(run);
|
|
852
|
-
const outcome = outcomeOf(run);
|
|
853
|
-
const stoppedAt = outcome === "skipped_write" ? m.replay?.skipped : undefined;
|
|
854
|
-
rows.push({
|
|
855
|
-
of,
|
|
856
|
-
recorded: { answer: await answerOf(store, of, context), correct: grade.correct, path: grade.path, ...(grade.expected ? { expected: grade.expected } : {}) },
|
|
857
|
-
outcome,
|
|
858
|
-
...(stoppedAt ? { skipped: stoppedAt } : {}),
|
|
859
|
-
answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
|
|
860
|
-
guards: Array.isArray(m.guards) ? m.guards : [],
|
|
861
|
-
});
|
|
862
|
-
}
|
|
863
|
-
return { rows, scored: refitRowsOf(rows), cost: replayCost(runs, late), outcomes: outcomesOf(runs, late), unstarted: runs.filter((row) => !row).length };
|
|
864
|
-
}
|
|
865
646
|
/** Why `skipped` inputs of a replay were skipped, in one phrase (`why`): the MCP tools among `tools` its server listed
|
|
866
647
|
* with no readOnlyHint, named (`hint`: the server may only lack the hint), with the rest in the recording's words;
|
|
867
648
|
* with none of those, the recording's words alone (SKIPPED_WRITE). */
|
|
@@ -871,159 +652,6 @@ function skipWordsOf(tools, skipped) {
|
|
|
871
652
|
const hint = unmarked.length ? unmarkedWords(unmarked.map((one) => toolWord(one.tool))) : undefined;
|
|
872
653
|
return { hint, why: !hint ? SKIPPED_WRITE : writes ? `${hint} (${writes} more ${writes === 1 ? "needs" : "need"} a write the recording doesn't have)` : hint };
|
|
873
654
|
}
|
|
874
|
-
/** A replaying digest's decision, once its replay runs ended: promote within the bar when it answered alone at least once,
|
|
875
|
-
* else hold, then one refit (of its guards and recorded escalates). Undefined while a replay run is at work. */
|
|
876
|
-
async function settle(deps, workflow, digest, record) {
|
|
877
|
-
const { store, agentId, log } = deps;
|
|
878
|
-
const now = deps.now ?? Date.now;
|
|
879
|
-
const read = await replayRows(deps, record);
|
|
880
|
-
if (!read)
|
|
881
|
-
return undefined;
|
|
882
|
-
// Scored: the inputs the workflow answered or handed back on. One it failed on (a node failed: a credential or a tool the
|
|
883
|
-
// replay ran without, say) is no evidence either way, never the agent's answer in its name.
|
|
884
|
-
// Skipped: the inputs whose workflow needed a write the graded run's recording does not have (learn/replay-calls.ts): a
|
|
885
|
-
// replay never runs one, so they are no evidence either, and never wrong.
|
|
886
|
-
const scored = read.scored;
|
|
887
|
-
const thresholds = thresholdsOf(workflow.workflow);
|
|
888
|
-
const score = scoreRows(scored, thresholds);
|
|
889
|
-
// A revision held on served runs graded wrong promotes only once its replay answered (or handed back) on each of them,
|
|
890
|
-
// and is within the bar on them alone (the one scorer over their rows; a hand-back on each is the agent's, right): a
|
|
891
|
-
// pass on other inputs never puts it back, nor pays for repeating the wrong answers it was held on.
|
|
892
|
-
const owedRuns = heldOn(record);
|
|
893
|
-
const unanswered = owedRuns.filter((run) => !read.rows.some((row) => row.of === run && (row.outcome === "answered" || row.outcome === "handed_back")));
|
|
894
|
-
const owedScore = owedRuns.length ? scoreRows(scored.filter((row) => row.of !== undefined && owedRuns.includes(row.of)), thresholds) : undefined;
|
|
895
|
-
const owedWrong = owedScore !== undefined && owedScore.n > 0 && !withinBar(owedScore);
|
|
896
|
-
const passed = scored.length >= REPLAY_MIN && clears(score);
|
|
897
|
-
const ok = passed && !unanswered.length && !owedWrong;
|
|
898
|
-
const pts = (value) => `${(value * 100).toFixed(1)}%`;
|
|
899
|
-
// Its runs' outcomes, the one count the record keeps (a run whose grade rolled out of those kept counts too).
|
|
900
|
-
const { skipped_write: skipped, failed } = read.outcomes;
|
|
901
|
-
const ended = Object.values(read.outcomes).reduce((sum, one) => sum + one, 0);
|
|
902
|
-
// Inputs stopped at an MCP tool its server listed with no readOnlyHint: the hold names those tools (the server may only
|
|
903
|
-
// lack the hint); any other skip (a destructive tool, a built-in write) keeps the recording's words.
|
|
904
|
-
const tools = skippedToolsOf(read.rows);
|
|
905
|
-
const { hint, why: skipWhy } = skipWordsOf(tools, skipped);
|
|
906
|
-
const aside = [...(failed ? [`${failed} failed: a step failed, no evidence either way`] : []), ...(skipped ? [`${skipped} skipped: ${skipWhy}`] : []),
|
|
907
|
-
...(read.unstarted ? [`${read.unstarted} never started by the replay's deadline`] : [])].join("; ");
|
|
908
|
-
const said = `on ${plural(score.n, "graded input")}: the workflow ${pts(score.wf_acc)} (${score.handed_back} handed back, the agent's answer), the agent ${pts(score.agent_acc)}, ${score.delta >= 0 ? "+" : ""}${(score.delta * 100).toFixed(1)} pts${aside ? ` (${aside})` : ""}`;
|
|
909
|
-
const reserved = record.runs?.length ?? 0;
|
|
910
|
-
const reason = reserved && read.unstarted === reserved
|
|
911
|
-
? `none of its ${plural(reserved, "replay run")} started by the replay's deadline (its launch was interrupted: the server stopped after reserving it, say): nothing was replayed; start it again with POST .../learning/workflows/${workflow.name}/revisions/${digest}/replays`
|
|
912
|
-
: ended && skipped === ended
|
|
913
|
-
? hint ? `nothing was replayed on its ${plural(skipped, "graded input")}: ${skipWhy}` : `every one of its ${plural(skipped, "graded input")} ${SKIPPED_WRITE}: a replay never runs a write, so nothing was replayed`
|
|
914
|
-
: scored.length < REPLAY_MIN
|
|
915
|
-
? `only ${plural(scored.length, "replay")} answered or handed back${aside ? ` (${aside})` : ""}, fewer than ${REPLAY_MIN}`
|
|
916
|
-
: passed && unanswered.length ? `replayed ${said}, but it did not answer on ${plural(unanswered.length, "graded run")} it was held on (its held_on): it serves again only once a replay answers on them`
|
|
917
|
-
: passed && owedScore && owedWrong ? `replayed ${said}, but on the ${plural(owedScore.n, "graded run")} it was held on the workflow ${pts(owedScore.wf_acc)}, the agent ${pts(owedScore.agent_acc)}: more than ${PROMOTE_BAR * 100} pts under; it serves again only once it answers them right`
|
|
918
|
-
: ok ? `replayed ${said}: within ${PROMOTE_BAR * 100} pts`
|
|
919
|
-
: !answersAlone(score) ? `it handed back every one of its ${plural(score.n, "replayed input")}: it would never answer alone (${said})`
|
|
920
|
-
: `replayed ${said}: more than ${PROMOTE_BAR * 100} pts under the agent`;
|
|
921
|
-
// Promoted: named by the agent's newest grade (`since`), which every run it serves keeps, so a revision that served
|
|
922
|
-
// before (promoted, held, now replayed again) is checked only on the runs this promotion served, never again on the
|
|
923
|
-
// ones it was held on. Held: it still owes the runs it was held on.
|
|
924
|
-
const since = ok ? Math.max(0, ...(await gradesOf(store.settings, agentId)).map((grade) => grade.seq ?? 0)) : undefined;
|
|
925
|
-
const owed = heldOn(record);
|
|
926
|
-
const decided = await recordPromotion(store.settings, agentId, {
|
|
927
|
-
workflow: workflow.name, digest, at: iso(now()), decided: ok ? "promote" : "hold", source: "replay", reason,
|
|
928
|
-
replay: { ...score, of: read.rows.map((row) => row.of), cost_usd: read.cost, skipped_tools: tools, outcomes: read.outcomes }, ...(record.runs ? { runs: record.runs } : {}),
|
|
929
|
-
...(record.commit ? { commit: record.commit } : seedOf(deps)), ...(record.replay_id ? { replay_id: record.replay_id } : {}),
|
|
930
|
-
...(since !== undefined ? { since } : owed.length ? { held_on: owed } : {}),
|
|
931
|
-
}, (was) => sameReplay(was, record));
|
|
932
|
-
// Another claim's decision came first: it logs, cancels and refits; this one reads it.
|
|
933
|
-
if (!decided.won)
|
|
934
|
-
return decided.record?.decided === "replaying" ? undefined : decided.record;
|
|
935
|
-
log(`workflow-first: ${workflow.name} at ${digest} ${ok ? "promoted" : "held"}: ${reason}`);
|
|
936
|
-
// Decided past its deadline with runs still at work: they are cancelled, never left spending on a decided replay.
|
|
937
|
-
const cancelled = await cancelUnended(deps, record);
|
|
938
|
-
if (cancelled)
|
|
939
|
-
log(`workflow-first: ${workflow.name} at ${digest}: ${plural(cancelled, "replay run")} still at work past the replay's deadline cancelled`);
|
|
940
|
-
if (!ok && scored.length >= REPLAY_MIN && !unanswered.length && !owedWrong) {
|
|
941
|
-
// Held: one refit over the replay's scored rows (each step's p known: its guards read record-only, its judge-driven
|
|
942
|
-
// escalates recorded). One with neither changes nothing. Never one that still owes runs it was held on: a refit is
|
|
943
|
-
// promoted on all its rows, and they did not answer on those, or answered them under the bar.
|
|
944
|
-
await refitAndWrite(deps, workflow, digest, scored, "its replay held it");
|
|
945
|
-
}
|
|
946
|
-
return decided.record;
|
|
947
|
-
}
|
|
948
|
-
/** A serving digest, checked once per REFIT_EVERY more graded runs it served: its thresholds refit over those runs and its
|
|
949
|
-
* replay's rows (a new revision when they move and still clear the bar), and held when its graded runs' accuracy fell
|
|
950
|
-
* more than PROMOTE_BAR under the agent's. The promotion it serves this run under (`record`, or the digest's newer
|
|
951
|
-
* promotion when one replaced it meanwhile), undefined when it does not serve it. */
|
|
952
|
-
async function stillServing(deps, workflow, digest, record) {
|
|
953
|
-
const { store, agentId, log } = deps;
|
|
954
|
-
const now = deps.now ?? Date.now;
|
|
955
|
-
const grades = await gradesOf(store.settings, agentId);
|
|
956
|
-
// Only the grades of runs this promotion served (each keeps its `since`, Grade.promotion): promoted again after a hold,
|
|
957
|
-
// never the ones it was held on, nor a run served under the promotion before and graded after this one.
|
|
958
|
-
const served = grades.filter((grade) => grade.workflow === workflow.name && grade.digest === digest && (grade.path === "workflow" || grade.path === "handed_back") && grade.promotion === record.since);
|
|
959
|
-
// Each write is kept only while the promotion this check read is still the digest's (the same since): a check that read
|
|
960
|
-
// an older one, replaced meanwhile (held, replayed and promoted again), writes nothing over the newer one.
|
|
961
|
-
const same = (was) => was?.decided === "promote" && was.since === record.since;
|
|
962
|
-
// New since the last check: by seq (putGrade), a cursor the trim of the kept grades never moves back.
|
|
963
|
-
const checked = record.checked ?? 0;
|
|
964
|
-
const through = Math.max(checked, ...served.map((grade) => grade.seq ?? 0));
|
|
965
|
-
if (served.filter((grade) => (grade.seq ?? 0) > checked).length < REFIT_EVERY)
|
|
966
|
-
return record;
|
|
967
|
-
const promoted = (one) => (one?.decided === "promote" ? one : undefined);
|
|
968
|
-
// The agent's accuracy by hand: its newest graded runs on the agent path, else the replay's.
|
|
969
|
-
const byHand = grades.filter((grade) => grade.path === "agent").slice(-REPLAY_INPUTS);
|
|
970
|
-
const agentAcc = byHand.length ? byHand.filter((grade) => grade.correct).length / byHand.length : record.replay?.agent_acc;
|
|
971
|
-
// Marked checked at this count first, so two claims never check the same window twice.
|
|
972
|
-
// Only the claim whose write marked it refits: one that lost the write reads the winner's record back, the same cursor.
|
|
973
|
-
const marked = await recordPromotion(store.settings, agentId, { ...record, at: iso(now()), checked: through }, (was) => same(was) && (was?.checked ?? 0) === checked);
|
|
974
|
-
if (!marked.won || agentAcc === undefined)
|
|
975
|
-
return promoted(marked.record);
|
|
976
|
-
const rows = [];
|
|
977
|
-
for (const grade of served) {
|
|
978
|
-
const run = await store.runs.get(grade.run);
|
|
979
|
-
const m = metricsOf(run);
|
|
980
|
-
const guards = Array.isArray(m.guards) ? m.guards : [];
|
|
981
|
-
rows.push(grade.path === "workflow" ? { guards, answered: true, wfCorrect: grade.correct, agentCorrect: agentAcc } : { guards, answered: false, wfCorrect: null, agentCorrect: grade.correct ? 1 : 0 });
|
|
982
|
-
}
|
|
983
|
-
const replayed = record.source === "replay" && record.runs?.length ? (await replayRows(deps, record))?.scored ?? [] : [];
|
|
984
|
-
const wrote = await refitAndWrite(deps, workflow, digest, [...rows, ...replayed], `${plural(served.length, "graded run")} it served`);
|
|
985
|
-
// What actually happened on the served runs: the recorded grades (a workflow-path grade is the workflow's answer, a
|
|
986
|
-
// handed-back one the agent's). Recorded, not rescored: the guards on a run may belong to other workflows the agent called
|
|
987
|
-
// after a hand-back, and rescoring over them would count a right answer as a hand-back at the agent's accuracy.
|
|
988
|
-
const servedAcc = served.filter((grade) => grade.correct).length / served.length;
|
|
989
|
-
if (!wrote && servedAcc < agentAcc - PROMOTE_BAR - 1e-9) {
|
|
990
|
-
const reason = `${plural(served.length, "graded run")} it served were right ${(servedAcc * 100).toFixed(1)}% of the time, more than ${PROMOTE_BAR * 100} pts under the agent's ${(agentAcc * 100).toFixed(1)}% by hand`;
|
|
991
|
-
// It keeps the served runs graded wrong it was held on, newest first: its next replay owes them (heldOn).
|
|
992
|
-
const wrong = served.filter((grade) => !grade.correct).map((grade) => grade.run).reverse().slice(0, REPLAY_INPUTS);
|
|
993
|
-
const held = await recordPromotion(store.settings, agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "hold", source: "graded", reason, held_on: wrong }, same);
|
|
994
|
-
if (held.won)
|
|
995
|
-
log(`workflow-first: ${workflow.name} at ${digest} held: ${reason}`);
|
|
996
|
-
return promoted(held.record);
|
|
997
|
-
}
|
|
998
|
-
return marked.record;
|
|
999
|
-
}
|
|
1000
|
-
/** One refit of `workflow` over `rows`; when it moves a guard and the rows clear the bar at the new thresholds, the new
|
|
1001
|
-
* text is written as a new revision (a merge from the claim's seed) and promoted with the rows' numbers. True when one
|
|
1002
|
-
* was written. */
|
|
1003
|
-
async function refitAndWrite(deps, workflow, digest, rows, why) {
|
|
1004
|
-
if (!deps.commit || rows.length < REPLAY_MIN)
|
|
1005
|
-
return false;
|
|
1006
|
-
const now = deps.now ?? Date.now;
|
|
1007
|
-
const refit = refitGuards(workflow.workflow, rows, iso(now()));
|
|
1008
|
-
if (!refit.text || !clears(refit))
|
|
1009
|
-
return false;
|
|
1010
|
-
const next = workflowDigest({ workflow: refit.text });
|
|
1011
|
-
const moved = refit.guards.map((one) => (one.escalate ? `${one.node} escalate off` : one.threshold === null ? `${one.node} guard off` : `${one.node} ${one.was} -> ${one.threshold}${one.fit ? " (fit)" : ""}`)).join(", ");
|
|
1012
|
-
const reason = `refit ${workflow.name}'s guards over ${why} (${plural(rows.length, "row")}): ${moved}`;
|
|
1013
|
-
const landed = await deps.commit([{ path: `workflows/${workflow.name}/workflow.json`, text: refit.text }], reason, `refit-${digest}-${next}`);
|
|
1014
|
-
if (landed === null) {
|
|
1015
|
-
deps.log(`workflow-first: ${workflow.name}'s refit did not land on its learning folder; it keeps its thresholds`);
|
|
1016
|
-
return false;
|
|
1017
|
-
}
|
|
1018
|
-
await recordPromotion(deps.store.settings, deps.agentId, {
|
|
1019
|
-
workflow: workflow.name, digest: next, at: iso(now()), decided: "promote", source: "refit",
|
|
1020
|
-
reason: `${reason}: the workflow ${(refit.wf_acc * 100).toFixed(1)}%, the agent ${(refit.agent_acc * 100).toFixed(1)}% on those rows`,
|
|
1021
|
-
replay: { ...scoreOf(refit), of: rows.flatMap((row) => (row.of === undefined ? [] : [row.of])) },
|
|
1022
|
-
refit: { from: digest, guards: refit.guards }, commit: landed,
|
|
1023
|
-
}, (was) => was === undefined);
|
|
1024
|
-
deps.log(`workflow-first: ${reason}; the new revision (${next}) serves from the next run`);
|
|
1025
|
-
return true;
|
|
1026
|
-
}
|
|
1027
655
|
/** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
|
|
1028
656
|
* replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
|
|
1029
657
|
export class ReplayRefused extends Error {
|
|
@@ -1056,15 +684,21 @@ async function revisionOf(ask, records, name, digest) {
|
|
|
1056
684
|
}
|
|
1057
685
|
return { named: onMain || records.some((one) => one.workflow === name) };
|
|
1058
686
|
}
|
|
1059
|
-
/**
|
|
1060
|
-
*
|
|
1061
|
-
*
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
687
|
+
/** The agent runs `name` at `digest` was last checked on: its newest record that names them, a decided
|
|
688
|
+
* check's `check.of` or a reservation's `inputs`. A check's reservation leaves the kept history (trimPromotions) while
|
|
689
|
+
* its decision stays, so the decision's own list is read first. Undefined when no record names any. */
|
|
690
|
+
function heldInputsOf(records, name, digest) {
|
|
691
|
+
const checked = (one) => (one.decided !== "replaying" && one.check?.of?.length ? one.check.of : undefined);
|
|
692
|
+
const last = records.findLast((one) => one.workflow === name && one.digest === digest && (checked(one) ?? one.inputs)?.length);
|
|
693
|
+
return last && (checked(last) ?? last.inputs);
|
|
694
|
+
}
|
|
695
|
+
/** A check of `name` at `digest` a person asked for: the claim path's check (reserve, startReplay), on `inputs`: `held`,
|
|
696
|
+
* the agent runs its last check ran on (else, with none, the agent's last compile_after completed runs), or a number,
|
|
697
|
+
* the agent's newest that many (each a completed run of its own the workflow fits). Its runs end as a claim's do, and it
|
|
698
|
+
* is decided by settleCheck: at a claim that lays the revision, or at its read (replayView). Refused (ReplayRefused): no
|
|
699
|
+
* such workflow or revision; one replaying already, or another revision of it replaying (one at a time); a promoted one
|
|
700
|
+
* (it serves already); no input it fits (nothing is reserved); an agent that does not learn here. The replay's id and
|
|
701
|
+
* its inputs. */
|
|
1068
702
|
export async function askReplay(ask, name, digest, inputs) {
|
|
1069
703
|
const records = await promotionsOf(ask.store.settings, ask.agentId);
|
|
1070
704
|
const found = await revisionOf(ask, records, name, digest);
|
|
@@ -1077,29 +711,31 @@ export async function askReplay(ask, name, digest, inputs) {
|
|
|
1077
711
|
throw new ReplayRefused("conflict", `${name} at ${digest} is promoted: it serves already. A replay checks a revision that does not serve yet, or was held.`);
|
|
1078
712
|
const rival = replayingOf(records, name, digest)[0];
|
|
1079
713
|
if (rival)
|
|
1080
|
-
throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow
|
|
1081
|
-
const
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
}
|
|
1087
|
-
|
|
714
|
+
throw new ReplayRefused("conflict", `${name} at ${rival.digest} is replaying: one revision of a workflow is checked at a time, and a running check finishes. Ask again once it ends.`);
|
|
715
|
+
const last = inputs === "held" ? heldInputsOf(records, name, digest) : undefined;
|
|
716
|
+
// The agent's own numbers (its current revision's definition, the one its replay runs launch on): with no earlier
|
|
717
|
+
// check, its last compile_after completed runs, as the claim's check picks them (startCheck), never the default's.
|
|
718
|
+
const current = (await ask.store.agents.get(ask.agentId).catch(() => undefined))?.currentRevision;
|
|
719
|
+
const loop = current ? await loopOfRevision({ store: ask.store, revisionId: current }) : loopOf(undefined);
|
|
720
|
+
const { inputs: picked } = await checkInputs({ store: ask.store, agentId: ask.agentId }, found.workflow, { of: last ?? [], n: typeof inputs === "number" ? inputs : last ? 0 : loop.compile_after });
|
|
721
|
+
if (!picked.length)
|
|
722
|
+
throw new ReplayRefused("conflict", `${name} at ${digest} has no input to replay on: none of ${typeof inputs === "number" ? `the agent's newest ${plural(inputs, "completed run")}` : last ? "the runs it was last checked on" : "the agent's last completed runs"} has an input it fits. Nothing was started.`);
|
|
723
|
+
const { launch, revisionId } = await ask.launchOf(picked[0].launch.input);
|
|
1088
724
|
if (!launch.learning || launch.learning.notesOnly)
|
|
1089
725
|
throw new ReplayRefused("conflict", `A replay runs ${name} as a run of the agent that learns does, and the agent's runs do not take learned workflows here (its learning is off, notes only, or this server's is off).`);
|
|
1090
726
|
const deps = { store: ask.store, agentId: ask.agentId, revisionId, launch: { ...launch, learning: { ...launch.learning, seed: found.commit } }, context: ask.context, log: ask.log, shown: ask.shown, ...(ask.now ? { now: ask.now } : {}) };
|
|
1091
|
-
const
|
|
727
|
+
const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, name, digest) };
|
|
728
|
+
const said = `checking it on ${plural(picked.length, "input")} of the agent's own runs, as its owner asked`;
|
|
1092
729
|
// Kept only while the revision's newest record is still the one read here: each record write stamps a new `at`.
|
|
1093
|
-
const reserved = await reserve(deps, found.workflow, digest,
|
|
730
|
+
const reserved = await reserve(deps, found.workflow, digest, picked, said, (was) => was?.at === own?.at && was?.decided === own?.decided, bar);
|
|
1094
731
|
if (!reserved.won || !reserved.record?.replay_id)
|
|
1095
732
|
throw new ReplayRefused("conflict", `${name} at ${digest} changed while this replay was asked for (another replay or decision came first): read its promotions and ask again.`);
|
|
1096
733
|
ask.log(`workflow-first: ${name} at ${digest}: ${said}`);
|
|
1097
|
-
return { replay: reserved.record.replay_id, inputs:
|
|
734
|
+
return { replay: reserved.record.replay_id, inputs: picked.length };
|
|
1098
735
|
}
|
|
736
|
+
const NO_SCORE = { n: 0, agree: 0, agent_acc: 0, wf_acc: 0, delta: 0, handed_back: 0 };
|
|
1099
737
|
/** A check's replay as its read answers it (replayView): decided, its record's numbers (CheckRecord), else its runs ended
|
|
1100
|
-
* so far.
|
|
1101
|
-
* answered alone as the agent did, `agent_acc` 1, `wf_acc` those plus the ones handed back (a hand-back is the agent's
|
|
1102
|
-
* answer), over the inputs it ran on. */
|
|
738
|
+
* so far. */
|
|
1103
739
|
async function checkView(ask, record, id, name, digest) {
|
|
1104
740
|
const inputs = record.runs?.length ?? 0;
|
|
1105
741
|
const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
|
|
@@ -1108,64 +744,42 @@ async function checkView(ask, record, id, name, digest) {
|
|
|
1108
744
|
const n = check.n ?? 0;
|
|
1109
745
|
const handedBack = check.outcomes.handed_back;
|
|
1110
746
|
const wf = n ? Math.round(((check.agreed ?? 0) + handedBack) / n * 1e4) / 1e4 : 0;
|
|
1111
|
-
const neverStarted = inputs > 0 &&
|
|
747
|
+
const neverStarted = inputs > 0 && check.unstarted === inputs;
|
|
1112
748
|
return { replay: id, workflow: name, digest, status: neverStarted ? "failed" : "done", inputs, outcomes: check.outcomes, score: { n, agree: check.agreed ?? 0, agent_acc: n ? 1 : 0, wf_acc: wf, delta: n ? Math.round((wf - 1) * 1e4) / 1e4 : 0, handed_back: handedBack }, cost_usd: check.cost_usd ?? null, decided, reason: record.reason };
|
|
1113
749
|
}
|
|
1114
750
|
const runs = await Promise.all((record.runs ?? []).map((run) => ask.store.runs.get(run)));
|
|
1115
|
-
return { replay: id, workflow: name, digest, status: decided ? "done" : "running", inputs, outcomes: outcomesOf(runs, false), score:
|
|
751
|
+
return { replay: id, workflow: name, digest, status: decided ? "done" : "running", inputs, outcomes: outcomesOf(runs, false), score: NO_SCORE, cost_usd: replayCost(runs, false), ...(decided ? { decided, reason: record.reason } : {}) };
|
|
1116
752
|
}
|
|
1117
753
|
/** The claim's ports a replay's read settles it through (replayView), with the launch its record chose when it was
|
|
1118
|
-
* reserved (PromotionRecord.launch, the one every replay run of it runs with): its revision, and its learning commit
|
|
1119
|
-
*
|
|
754
|
+
* reserved (PromotionRecord.launch, the one every replay run of it runs with): its revision, and its learning commit.
|
|
755
|
+
* Undefined when that launch cannot be read. */
|
|
1120
756
|
function readPorts(ask, launch) {
|
|
1121
757
|
const body = readLaunchBody(launch.body);
|
|
1122
758
|
return body ? claimPromotion({ ...ask, revisionId: launch.revision, launch: body }) : undefined;
|
|
1123
759
|
}
|
|
1124
|
-
/** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (
|
|
1125
|
-
*
|
|
1126
|
-
*
|
|
1127
|
-
*
|
|
1128
|
-
*
|
|
760
|
+
/** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (settleCheck) once its runs
|
|
761
|
+
* ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose launch was
|
|
762
|
+
* interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as failed, its
|
|
763
|
+
* reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim lays (an
|
|
764
|
+
* older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
|
|
1129
765
|
* (missing) when the agent has no such replay. */
|
|
1130
766
|
export async function replayView(ask, name, digest, id) {
|
|
1131
767
|
const find = async () => (await promotionsOf(ask.store.settings, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
|
|
1132
768
|
let record = await find();
|
|
1133
769
|
if (!record)
|
|
1134
770
|
throw new ReplayRefused("missing", `${name} at ${digest} has no replay ${id}.`);
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
await (record.source === "check" ? settleCheck(ports, text, digest, record) : settle(ports, text, digest, record));
|
|
1144
|
-
record = (await find()) ?? record;
|
|
1145
|
-
}
|
|
1146
|
-
if (record.source === "check")
|
|
1147
|
-
return checkView(ask, record, id, name, digest);
|
|
1148
|
-
// Only a replaying, promote or hold record carries a replay's id.
|
|
1149
|
-
const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
|
|
1150
|
-
const inputs = record.runs?.length ?? 0;
|
|
1151
|
-
const said = decided ? { decided, reason: record.reason } : {};
|
|
1152
|
-
const kept = record.replay && decided ? record.replay : undefined;
|
|
1153
|
-
if (kept) {
|
|
1154
|
-
// Decided: its record's numbers alone. With not one of its reserved runs ever created (none counted: a decided
|
|
1155
|
-
// replay counted every run there was, and none is created after), nothing was replayed (settle's reason says so).
|
|
1156
|
-
const outcomes = kept.outcomes ?? NO_OUTCOMES;
|
|
1157
|
-
const neverStarted = inputs > 0 && Object.values(outcomes).every((count) => count === 0);
|
|
1158
|
-
return { replay: id, workflow: name, digest, status: neverStarted ? "failed" : "done", inputs, outcomes, score: scoreOf(kept), cost_usd: kept.cost_usd ?? null, ...said };
|
|
771
|
+
if (record.decided === "replaying" && record.commit && record.launch) {
|
|
772
|
+
const text = (await workflowsAt(ask, record.commit).catch(() => [])).find((one) => one.name === name && workflowDigest(one) === digest);
|
|
773
|
+
const ports = text ? readPorts(ask, record.launch) : undefined;
|
|
774
|
+
if (ports && text) {
|
|
775
|
+
// Read back by its id: whatever settled it (this read, a claim, another read), never another replay's record.
|
|
776
|
+
await settleCheck(ports, text, digest, record);
|
|
777
|
+
record = (await find()) ?? record;
|
|
778
|
+
}
|
|
1159
779
|
}
|
|
1160
|
-
|
|
1161
|
-
text ??= await textOf(record);
|
|
1162
|
-
return {
|
|
1163
|
-
replay: id, workflow: name, digest, status: decided === undefined ? "running" : "done", inputs,
|
|
1164
|
-
outcomes: read?.outcomes ?? NO_OUTCOMES,
|
|
1165
|
-
score: scoreRows(read?.scored ?? [], text ? thresholdsOf(text.workflow) : new Map()), cost_usd: read?.cost ?? null, ...said,
|
|
1166
|
-
};
|
|
780
|
+
return checkView(ask, record, id, name, digest);
|
|
1167
781
|
}
|
|
1168
|
-
/** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the
|
|
782
|
+
/** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
|
|
1169
783
|
* (a CLI's record shaped as pi's), and each tool classed by the claim's MCP pin (`runId`'s, its servers' annotations as
|
|
1170
784
|
* they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one:
|
|
1171
785
|
* every write is then skipped, never run. */
|
|
@@ -1175,12 +789,6 @@ export async function replayCallsFor(store, runId, launch, context) {
|
|
|
1175
789
|
const entries = await runEntries(store, launch.replay.of, context).catch(() => []);
|
|
1176
790
|
const recorded = recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
|
|
1177
791
|
const pin = (await store.mcp.pin(runId).catch(() => undefined))?.body;
|
|
1178
|
-
const annotations = (
|
|
1179
|
-
const named = /^mcp:([^/]+)\/(.+)$/.exec(tool);
|
|
1180
|
-
const server = named && pin && Object.hasOwn(pin, named[1]) ? pin[named[1]] : undefined;
|
|
1181
|
-
const listed = server?.tools.find((one) => one.name === named[2]);
|
|
1182
|
-
// Listed with none: `{}`, so a tool its server left unannotated reads unmarked, never as one it does not list.
|
|
1183
|
-
return listed ? (listed.annotations ?? {}) : undefined;
|
|
1184
|
-
};
|
|
792
|
+
const annotations = pinAnnotations(pin);
|
|
1185
793
|
return replayCalls(recorded, (tool) => toolClassOf(tool, annotations));
|
|
1186
794
|
}
|