@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44
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 +126 -0
- package/README.md +221 -31
- package/dist/cli.js +42 -8
- package/dist/composio-preset.d.ts +4 -3
- package/dist/composio-preset.js +12 -4
- package/dist/composio-triggers.d.ts +20 -2
- package/dist/composio-triggers.js +183 -17
- package/dist/computer-lost.d.ts +11 -0
- package/dist/computer-lost.js +19 -0
- package/dist/computer-record.d.ts +10 -2
- package/dist/computer-record.js +50 -18
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +2 -2
- package/dist/console/assets/index-BUktRvS-.css +1 -0
- package/dist/console/assets/index-nB9kTfIN.js +711 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +0 -4
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +3 -0
- package/dist/harness-table.d.ts +51 -3
- package/dist/harness-table.js +101 -13
- package/dist/harness.d.ts +18 -1
- package/dist/harness.js +21 -9
- package/dist/host.d.ts +12 -10
- package/dist/host.js +18 -16
- package/dist/import-sources.js +25 -5
- package/dist/import-worker.d.ts +3 -0
- package/dist/import-worker.js +7 -5
- package/dist/import.d.ts +22 -1
- package/dist/import.js +141 -28
- package/dist/learn/audit.d.ts +123 -0
- package/dist/learn/audit.js +159 -0
- package/dist/learn/check.d.ts +3 -0
- package/dist/learn/check.js +1 -1
- package/dist/learn/compile.d.ts +50 -74
- package/dist/learn/compile.js +90 -124
- package/dist/learn/delete.d.ts +17 -0
- package/dist/learn/delete.js +44 -0
- package/dist/learn/folder.d.ts +9 -0
- package/dist/learn/folder.js +13 -2
- package/dist/learn/promote.d.ts +92 -200
- package/dist/learn/promote.js +65 -187
- 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.d.ts +4 -0
- package/dist/learn/skills.js +19 -5
- package/dist/learn/workflow-nodes.d.ts +23 -3
- package/dist/learn/workflow-nodes.js +30 -12
- 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 +111 -4
- package/dist/learning-cost.js +120 -3
- package/dist/learning-evals.d.ts +2 -0
- package/dist/learning-evals.js +4 -3
- package/dist/learning-routes.d.ts +8 -0
- package/dist/learning-routes.js +18 -1
- package/dist/learning-setting.d.ts +16 -1
- package/dist/learning-setting.js +34 -2
- package/dist/learning.d.ts +1 -1
- package/dist/listen-first.d.ts +30 -0
- package/dist/listen-first.js +115 -0
- package/dist/llms.txt +2 -1
- package/dist/mcp-servers-store.d.ts +12 -12
- package/dist/model.d.ts +8 -4
- package/dist/model.js +16 -8
- package/dist/openapi.js +203 -87
- package/dist/owner.d.ts +8 -0
- package/dist/owner.js +11 -0
- package/dist/paid-calls.d.ts +6 -0
- package/dist/paid-calls.js +11 -1
- package/dist/place.d.ts +8 -3
- package/dist/place.js +13 -9
- package/dist/provider.js +15 -1
- 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/run-model-key.d.ts +64 -0
- package/dist/run-model-key.js +147 -0
- package/dist/runner/adapter-loop.d.ts +10 -0
- package/dist/runner/adapter-loop.js +26 -4
- package/dist/runner/adapter-run-spec.d.ts +6 -3
- package/dist/runner/adapter-run-spec.js +83 -25
- package/dist/runner/adapters/index.d.ts +4 -2
- package/dist/runner/adapters/index.js +13 -4
- package/dist/runner/audit.d.ts +68 -0
- package/dist/runner/audit.js +349 -0
- package/dist/runner/beside.d.ts +2 -1
- package/dist/runner/beside.js +6 -3
- package/dist/runner/claim-secrets.d.ts +49 -0
- package/dist/runner/claim-secrets.js +110 -1
- package/dist/runner/cli-run-spec.d.ts +2 -1
- package/dist/runner/cli-run-spec.js +44 -15
- package/dist/runner/commands.d.ts +3 -6
- package/dist/runner/feedback-round.d.ts +3 -2
- package/dist/runner/feedback-round.js +8 -7
- package/dist/runner/harness-loops.js +31 -23
- package/dist/runner/journal-kinds.d.ts +5 -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 +55 -13
- package/dist/runner/learning-end.js +128 -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/loop-contract.d.ts +6 -0
- package/dist/runner/loop-contract.js +4 -0
- package/dist/runner/loop.js +6 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +25 -8
- package/dist/runner/memory-claim.d.ts +9 -6
- package/dist/runner/memory-claim.js +12 -9
- package/dist/runner/promotion.d.ts +55 -54
- package/dist/runner/promotion.js +232 -585
- package/dist/runner/reflect-hook.d.ts +14 -0
- package/dist/runner/reflect-hook.js +28 -3
- package/dist/runner/runner.js +57 -4
- package/dist/runner/store-secrets.js +9 -5
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +17 -12
- package/dist/runner/workflow-spec.js +10 -2
- package/dist/runs-over-store.d.ts +5 -4
- package/dist/runs-over-store.js +13 -3
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +64 -50
- package/dist/server.js +516 -134
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/seal.d.ts +20 -2
- package/dist/store/seal.js +24 -8
- package/dist/store/sqlite/run-launch.d.ts +4 -1
- package/dist/store/sqlite/run-launch.js +12 -0
- package/dist/store/sqlite/store.d.ts +3 -2
- package/dist/store/sqlite/store.js +119 -16
- package/dist/store/store.d.ts +41 -3
- package/dist/store-reads/analytics.js +11 -1
- package/dist/store-reads/learning.d.ts +57 -7
- package/dist/store-reads/learning.js +194 -28
- package/dist/store-reads/loop.d.ts +4 -39
- package/dist/store-reads/loop.js +10 -79
- package/dist/store-reads/stats.js +13 -3
- package/dist/store-view.d.ts +5 -1
- package/dist/store-view.js +12 -1
- package/dist/telemetry.d.ts +59 -0
- package/dist/telemetry.js +153 -0
- package/dist/tool-keys-store.d.ts +1 -1
- package/dist/tool-keys.d.ts +2 -2
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +11 -11
- package/dist/tools.js +18 -5
- package/dist/trigger-adapter.d.ts +3 -0
- package/dist/trigger-adapters.d.ts +4 -0
- package/dist/trigger-adapters.js +13 -0
- package/dist/trigger-composio.d.ts +58 -1
- package/dist/trigger-composio.js +160 -6
- package/dist/triggers.d.ts +4 -0
- package/dist/triggers.js +22 -3
- package/dist/validate.d.ts +11 -7
- package/dist/validate.js +8 -7
- package/dist/workspace/computer-for-claim.d.ts +15 -5
- package/dist/workspace/computer-for-claim.js +228 -32
- package/dist/workspace/resolve-computer.d.ts +8 -2
- package/dist/workspace/resolve-computer.js +1 -1
- package/dist/workspace/run-tools.d.ts +1 -1
- package/dist/workspace/run-tools.js +14 -3
- package/package.json +10 -9
- package/dist/console/assets/index-C3gNPz58.css +0 -1
- package/dist/console/assets/index-DYJ_wj27.js +0 -711
- 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,16 @@ 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 {
|
|
17
|
+
import { excerptShown } from "../learn/secrets.js";
|
|
18
|
+
import { dslRefusalOf } from "../learn/skills.js";
|
|
20
19
|
import { workflowsAt } from "./learning-seed.js";
|
|
21
20
|
/** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
|
|
22
21
|
* the replay is decided without it. */
|
|
@@ -24,27 +23,13 @@ export const REPLAY_DEADLINE_MS = 60 * 60 * 1000;
|
|
|
24
23
|
/** A reserved replay run still not created this long after its record was reserved is a launch that was interrupted (the
|
|
25
24
|
* reserving claim crashed, or its create failed): the next claim creates it (relaunch). Before then it is pending. */
|
|
26
25
|
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). */
|
|
26
|
+
/** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
|
|
27
|
+
* 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
|
|
28
|
+
* claim of this run served (`kept`, from its journal: none on a first claim). */
|
|
31
29
|
export function claimPromotion(deps) {
|
|
32
|
-
const seed = deps.launch.learning?.seed;
|
|
33
30
|
return {
|
|
34
31
|
...deps,
|
|
35
32
|
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
33
|
champion: async (name, commit) => (await workflowsAt({ folder: deps.folder, shown: deps.shown }, commit)).find((one) => one.name === name),
|
|
49
34
|
newest: async (name) => {
|
|
50
35
|
const folder = deps.folder();
|
|
@@ -72,29 +57,27 @@ export async function replayClaimed(store, agentId, runId, launch, choice) {
|
|
|
72
57
|
const { workflow, digest } = launch.replay;
|
|
73
58
|
const record = promotionOf(await promotionsOf(store.settings, agentId), workflow, digest);
|
|
74
59
|
if (record && record.decided !== "replaying")
|
|
75
|
-
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "
|
|
60
|
+
throw new ClaimRefused(`This replay of ${workflow} at ${digest} did not run: that revision is ${record.decided === "promote" ? "promoted already" : "held already"}.`);
|
|
76
61
|
if (record && !record.runs?.includes(runId))
|
|
77
62
|
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
63
|
if (choice.serve?.replay !== true || choice.serve.name !== workflow)
|
|
79
64
|
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
65
|
}
|
|
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. */
|
|
66
|
+
/** The workflows a replay run's claim lays (`laid`, the seed lay's): the one it replays, or none by that name when the
|
|
67
|
+
* laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's, as laid. */
|
|
85
68
|
export function replayLaid(launch, laid) {
|
|
86
69
|
if (!launch.replay)
|
|
87
70
|
return [...laid];
|
|
88
71
|
const { workflow, digest } = launch.replay;
|
|
89
|
-
return laid.
|
|
72
|
+
return laid.filter((one) => one.name !== workflow || workflowDigest(one) === digest);
|
|
90
73
|
}
|
|
91
74
|
/** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
|
|
92
75
|
* revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
|
|
93
76
|
* champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
|
|
94
77
|
* 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
|
-
*
|
|
78
|
+
* promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
|
|
79
|
+
* 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
|
|
80
|
+
* laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
|
|
98
81
|
export async function toolFlowsFor(deps, launch, laid, choice) {
|
|
99
82
|
const chosen = laidFor(laid, choice);
|
|
100
83
|
if (launch.replay || !chosen.length)
|
|
@@ -136,10 +119,10 @@ const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.lea
|
|
|
136
119
|
const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
|
|
137
120
|
/** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
|
|
138
121
|
* 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
|
-
*
|
|
122
|
+
* revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its check moved on (decide:
|
|
123
|
+
* started, or settled once its runs ended), and then servingNow alone says who serves: the champion (championOf), the
|
|
124
|
+
* laid text when it is the champion, its own text read from its record's commit when not; undefined when none serves
|
|
125
|
+
* (the agent takes the run). A digest's own record never says it serves. */
|
|
143
126
|
export const promotionGate = (deps) => {
|
|
144
127
|
const failed = (workflow, error) => {
|
|
145
128
|
// A promotion that could not be read or written leaves the run to its agent: never a workflow served unchecked.
|
|
@@ -152,17 +135,17 @@ export const promotionGate = (deps) => {
|
|
|
152
135
|
if (kept)
|
|
153
136
|
return { workflow: kept };
|
|
154
137
|
await decide(deps, workflow, digest);
|
|
155
|
-
return await servingNow(deps, workflow, digest, true);
|
|
138
|
+
return await holdRefused(deps, await servingNow(deps, workflow, digest, true));
|
|
156
139
|
}
|
|
157
140
|
catch (error) {
|
|
158
141
|
return failed(workflow, error);
|
|
159
142
|
}
|
|
160
143
|
};
|
|
161
|
-
// The champion alone, for a laid revision that does not take the run's input (workflowFirstOf): nothing
|
|
144
|
+
// The champion alone, for a laid revision that does not take the run's input (workflowFirstOf): nothing is checked.
|
|
162
145
|
const champion = async (workflow, digest) => {
|
|
163
146
|
try {
|
|
164
147
|
const kept = await keptFor(deps, workflow, digest);
|
|
165
|
-
return kept ? { workflow: kept } : await servingNow(deps, workflow, digest, false);
|
|
148
|
+
return kept ? { workflow: kept } : await holdRefused(deps, await servingNow(deps, workflow, digest, false));
|
|
166
149
|
}
|
|
167
150
|
catch (error) {
|
|
168
151
|
return failed(workflow, error);
|
|
@@ -172,12 +155,9 @@ export const promotionGate = (deps) => {
|
|
|
172
155
|
};
|
|
173
156
|
/** Who serves `workflow` now, the one answer every serving path asks: its champion (championOf, read fresh from the
|
|
174
157
|
* 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). */
|
|
158
|
+
* never serves again. The laid revision at `digest` when it is the champion; `laid` false: it is not asked (the laid text
|
|
159
|
+
* does not take the input). Another champion: its text at its record's commit (its digest checked). Undefined when none
|
|
160
|
+
* serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
|
|
181
161
|
async function servingNow(deps, workflow, digest, laid) {
|
|
182
162
|
const records = await promotionsOf(deps.store.settings, deps.agentId);
|
|
183
163
|
const champion = championOf(records, workflow.name);
|
|
@@ -187,12 +167,8 @@ async function servingNow(deps, workflow, digest, laid) {
|
|
|
187
167
|
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
168
|
return undefined;
|
|
189
169
|
}
|
|
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
170
|
if (champion.digest === digest)
|
|
195
|
-
return laid ?
|
|
171
|
+
return laid ? { workflow } : undefined;
|
|
196
172
|
if (!deps.champion)
|
|
197
173
|
return undefined;
|
|
198
174
|
const text = champion.commit ? await deps.champion(workflow.name, champion.commit).catch(() => undefined) : undefined;
|
|
@@ -200,11 +176,37 @@ async function servingNow(deps, workflow, digest, laid) {
|
|
|
200
176
|
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
177
|
return undefined;
|
|
202
178
|
}
|
|
203
|
-
const under = champion.source === "check" ? champion : await stillServing({ ...deps, commit: undefined }, text, champion.digest, champion);
|
|
204
|
-
if (!under)
|
|
205
|
-
return undefined;
|
|
206
179
|
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
|
|
180
|
+
return { workflow: text };
|
|
181
|
+
}
|
|
182
|
+
/** The words a hold of a serving revision this release's workflow DSL refuses starts with (holdRefused). */
|
|
183
|
+
export const DSL_REFUSES = "this release's workflow DSL refuses it";
|
|
184
|
+
/** `serving` as it serves this run, once a serving revision this release's workflow DSL refuses is held. The refusal is of
|
|
185
|
+
* the text alone (learn/skills.ts dslRefusalOf: the DSL's own validation, no tool list), never of a host setting (a tool
|
|
186
|
+
* gated, denied or missing, no adapter), which the run's own check still refuses as before. The hold is a promotion
|
|
187
|
+
* record of its digest, `hold` by its reason alone ("this release's workflow DSL refuses it: <code> at <path>: <its
|
|
188
|
+
* words>", cut of the host's secrets as a check's texts are), written only while the digest's newest record is still the
|
|
189
|
+
* promotion this claim read: of two claims at once one writes it, and a later claim finds it (nothing serves). The run
|
|
190
|
+
* still runs it, refused before any node runs, and hands back as before: the agent answers. The hold follows compile
|
|
191
|
+
* once as a check's does: the agent's next due run asks the one recompile with the reason as data (learn/compile.ts
|
|
192
|
+
* heldNamesOf), and that revision's check is the compile's second (attemptOf). */
|
|
193
|
+
async function holdRefused(deps, serving) {
|
|
194
|
+
if (!serving)
|
|
195
|
+
return serving;
|
|
196
|
+
const refused = dslRefusalOf(await import("@parcha/agentrun-dsl"), serving.workflow.workflow);
|
|
197
|
+
if (refused === undefined)
|
|
198
|
+
return serving;
|
|
199
|
+
const { name } = serving.workflow;
|
|
200
|
+
const digest = workflowDigest(serving.workflow);
|
|
201
|
+
const current = promotionOf(await promotionsOf(deps.store.settings, deps.agentId), name, digest);
|
|
202
|
+
if (current?.decided !== "promote")
|
|
203
|
+
return serving;
|
|
204
|
+
const reason = excerptShown(`${DSL_REFUSES}: ${refused}`, await deps.shown(), CHECK_TEXT_MAX);
|
|
205
|
+
const record = { workflow: name, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason, ...(current.commit ? { commit: current.commit } : {}) };
|
|
206
|
+
const kept = await recordPromotion(deps.store.settings, deps.agentId, record, (was) => was?.decided === "promote" && was.at === current.at);
|
|
207
|
+
if (kept.won)
|
|
208
|
+
deps.log(`workflow-first: ${name} at ${digest} is held: ${reason}; the agent's next run recompiles it once`);
|
|
209
|
+
return serving;
|
|
208
210
|
}
|
|
209
211
|
/** A run already executing keeps its revision: when an earlier claim of it served `workflow` first (its WORKFLOW_FIRST
|
|
210
212
|
* entry, answered or handed back: `deps.kept`), a re-claim serves the same digest, whoever the champion is now (the loop
|
|
@@ -216,7 +218,7 @@ async function keptFor(deps, workflow, digest) {
|
|
|
216
218
|
if (!kept || kept.workflow !== workflow.name || !kept.digest)
|
|
217
219
|
return undefined;
|
|
218
220
|
if (kept.digest !== digest) {
|
|
219
|
-
// Its newest record naming a commit
|
|
221
|
+
// Its newest record naming a commit.
|
|
220
222
|
const record = (await promotionsOf(deps.store.settings, deps.agentId)).findLast((one) => one.workflow === workflow.name && one.digest === kept.digest && one.commit);
|
|
221
223
|
const text = record?.commit && deps.champion ? await deps.champion(workflow.name, record.commit).catch(() => undefined) : undefined;
|
|
222
224
|
if (text && workflowDigest(text) === kept.digest) {
|
|
@@ -227,12 +229,10 @@ async function keptFor(deps, workflow, digest) {
|
|
|
227
229
|
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
230
|
return workflow;
|
|
229
231
|
}
|
|
230
|
-
/** Moves the laid revision's
|
|
231
|
-
*
|
|
232
|
-
* started. It decides nothing about who serves (servingNow does). */
|
|
232
|
+
/** Moves the laid revision's check on: a new digest is checked (startCheck), a replaying one settled once its runs ended
|
|
233
|
+
* (after finishing a launch that was interrupted). It decides nothing about who serves (servingNow does). */
|
|
233
234
|
async function decide(deps, workflow, digest) {
|
|
234
235
|
const { store, agentId, log } = deps;
|
|
235
|
-
const now = deps.now ?? Date.now;
|
|
236
236
|
const record = promotionOf(await promotionsOf(store.settings, agentId), workflow.name, digest);
|
|
237
237
|
if (record?.decided === "promote")
|
|
238
238
|
return;
|
|
@@ -240,78 +240,13 @@ async function decide(deps, workflow, digest) {
|
|
|
240
240
|
log(`workflow-first: ${workflow.name} at ${digest} is held (${record.reason}); it does not serve this run`);
|
|
241
241
|
return;
|
|
242
242
|
}
|
|
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
243
|
if (record?.decided === "replaying") {
|
|
248
244
|
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`);
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
// A new revision: its one check on the agent's own last runs (startCheck). Nothing else moves for it: no queue, no
|
|
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`);
|
|
245
|
+
if (!(await settleCheck(deps, workflow, digest, record)))
|
|
246
|
+
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`);
|
|
311
247
|
return;
|
|
312
248
|
}
|
|
313
|
-
|
|
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`);
|
|
249
|
+
return startCheck(deps, workflow, digest);
|
|
315
250
|
}
|
|
316
251
|
/** The loop's numbers (learning-setting.ts) of the revision the claim runs: its definition's `learning`, each one it
|
|
317
252
|
* leaves out at its default (a revision that cannot be read: every default). */
|
|
@@ -325,21 +260,50 @@ async function loopOfRevision(deps) {
|
|
|
325
260
|
}
|
|
326
261
|
}
|
|
327
262
|
/** 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
|
|
329
|
-
*
|
|
263
|
+
* check's hold, an audit's hold or a hold by its reason alone (holdRefused: the DSL refuses a serving revision), or a
|
|
264
|
+
* first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
|
|
265
|
+
* (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
|
|
266
|
+
* whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
|
|
330
267
|
function attemptOf(records, name, digest) {
|
|
331
268
|
const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
269
|
+
if (!before)
|
|
270
|
+
return newCompileAttempt(records.filter((one) => one.digest !== digest));
|
|
271
|
+
if (before.decided !== "hold")
|
|
272
|
+
return 1;
|
|
273
|
+
if (before.audit)
|
|
274
|
+
return before.audit.stopped ? 1 : 2;
|
|
275
|
+
return !before.check || (before.check.attempt === 1 && !before.check.stopped) ? 2 : 1;
|
|
276
|
+
}
|
|
277
|
+
/** The shadow runs a recompile's check runs on beside the agent's last runs: the disagreeing audit rows the workflow's
|
|
278
|
+
* newest audit hold names (a grade's row has no answer of the agent's to check against), when that hold is the
|
|
279
|
+
* workflow's newest record of another revision. */
|
|
280
|
+
function auditInputsOf(records, name, digest) {
|
|
281
|
+
const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
|
|
282
|
+
if (before?.decided !== "hold" || !before.audit || before.audit.stopped)
|
|
283
|
+
return [];
|
|
284
|
+
return before.audit.disagreements.filter((one) => !one.graded && one.agent !== null).map((one) => one.run);
|
|
285
|
+
}
|
|
286
|
+
/** An agent run a check may read its input from: a completed run of its own (agentRun: no learned workflow answered it
|
|
287
|
+
* alone, and it is no replay), neither archived nor imported, and never the claimed run (lastOwnRuns' own rule). */
|
|
288
|
+
const checkable = (deps, row) => row.id !== deps.runId && agentRun(row) && row.archivedAt === null && !row.importedFrom;
|
|
289
|
+
/** The inputs a check runs its draft on: the agent's runs `pick.of` names (a check's own, asked again; each still
|
|
290
|
+
* checkable), then the agent's last `pick.n` completed runs of its own (lastOwnRuns: never the claimed run, an archived
|
|
291
|
+
* or imported one), newest first, picked before anything else limits them: runs its workflow served since, however many,
|
|
292
|
+
* never push them out of the read. And `audited`: an audit hold's disagreeing shadow runs (auditInputsOf), each ended.
|
|
293
|
+
* Of those, the ones whose input `workflow` takes (fits), each with its launch read back; one with an uploaded file is
|
|
294
|
+
* never an input. With how many of the agent's runs it looked at (`looked`) and why each it looked at is no input
|
|
295
|
+
* (`unfit`, `files`). */
|
|
296
|
+
async function checkInputs(deps, workflow, pick, audited = []) {
|
|
341
297
|
const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
|
|
342
|
-
const
|
|
298
|
+
const named = (await Promise.all(pick.of.map((id) => deps.store.runs.get(id)))).filter((row) => row !== undefined && checkable(deps, row));
|
|
299
|
+
const last = pick.n ? await lastOwnRuns(deps.store, deps.agentId, pick.n + pick.of.length, deps.runId) : [];
|
|
300
|
+
const own = [...named, ...last.filter((row) => !pick.of.includes(row.id)).slice(0, pick.n)];
|
|
301
|
+
// And an audit hold's disagreeing shadow runs: the agent's answers the recompile must say too.
|
|
302
|
+
for (const id of audited) {
|
|
303
|
+
const row = await deps.store.runs.get(id);
|
|
304
|
+
if (row && row.state === "ended" && !own.some((one) => one.id === id))
|
|
305
|
+
own.push(row);
|
|
306
|
+
}
|
|
343
307
|
const out = [];
|
|
344
308
|
let files = 0;
|
|
345
309
|
for (const row of own) {
|
|
@@ -359,6 +323,11 @@ async function checkInputs(deps, workflow, n) {
|
|
|
359
323
|
* it fits), it is decided at once: never promoted, it stops with nothing checked (stopUnchecked). */
|
|
360
324
|
async function startCheck(deps, workflow, digest) {
|
|
361
325
|
const { store, agentId, log } = deps;
|
|
326
|
+
// Its replay runs are runs the runner starts, on no caller's key: skipped where the claimed run brought its own key or
|
|
327
|
+
// the server holds none (claimSpendOff).
|
|
328
|
+
const off = deps.spendOff?.("A learned workflow's replay check");
|
|
329
|
+
if (off)
|
|
330
|
+
return void log(`workflow-first: ${off} ${workflow.name} at ${digest} is not checked and does not serve this run`);
|
|
362
331
|
// Only the learning folder's newest revision is checked: a run pinned to an older commit lays an older text.
|
|
363
332
|
const newest = deps.newest ? await deps.newest(workflow.name) : undefined;
|
|
364
333
|
if (newest !== undefined && newest !== digest) {
|
|
@@ -367,17 +336,17 @@ async function startCheck(deps, workflow, digest) {
|
|
|
367
336
|
}
|
|
368
337
|
// One check at a time, and one at work finishes: decided here once its runs ended (its verdict stands), never
|
|
369
338
|
// cancelled. While it runs, this revision waits, recording nothing: the claim after it is decided starts this one.
|
|
370
|
-
for (const
|
|
371
|
-
await
|
|
339
|
+
for (const ahead of replayingOf(await promotionsOf(store.settings, agentId), workflow.name, digest))
|
|
340
|
+
await settleAhead(deps, workflow.name, ahead);
|
|
372
341
|
const records = await promotionsOf(store.settings, agentId);
|
|
373
342
|
const rival = replayingOf(records, workflow.name, digest)[0];
|
|
374
343
|
if (rival) {
|
|
375
|
-
log(`workflow-first: ${workflow.name} at ${digest} waits: ${rival.digest} is
|
|
344
|
+
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
345
|
return;
|
|
377
346
|
}
|
|
378
347
|
const loop = await loopOfRevision(deps);
|
|
379
348
|
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);
|
|
349
|
+
const { inputs, looked, unfit, files } = await checkInputs(deps, workflow, { of: [], n: loop.compile_after }, auditInputsOf(records, workflow.name, digest));
|
|
381
350
|
if (!inputs.length) {
|
|
382
351
|
// Nothing of the agent's to check it on (a workflow landed before any run it fits): never promoted unchecked. It
|
|
383
352
|
// stops, its record naming why (the compile's draft error), and asks no recompile: a revision would have nothing to be
|
|
@@ -389,7 +358,7 @@ async function startCheck(deps, workflow, digest) {
|
|
|
389
358
|
return;
|
|
390
359
|
}
|
|
391
360
|
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,
|
|
361
|
+
const reserved = await reserve(deps, workflow, digest, inputs, said, (was) => was === undefined, bar);
|
|
393
362
|
if (!reserved.won) {
|
|
394
363
|
log(`workflow-first: ${workflow.name} at ${digest}: another claim's decision on it came first; it does not serve this run`);
|
|
395
364
|
return;
|
|
@@ -405,20 +374,29 @@ export const NOTHING_TO_CHECK = "nothing to check it on";
|
|
|
405
374
|
* (attemptOf). Kept only while `still` holds of the digest's record (the one write). */
|
|
406
375
|
async function stopUnchecked(deps, name, digest, bar, why, still, check = {}, extra = {}) {
|
|
407
376
|
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",
|
|
377
|
+
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
378
|
if (decided.won)
|
|
410
379
|
deps.log(`workflow-first: ${name} at ${digest} stopped: ${reason}`);
|
|
411
380
|
return decided;
|
|
412
381
|
}
|
|
413
|
-
/**
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
|
|
382
|
+
/** Decides `ahead`, the check at work for a revision older than the laid (newest) one, as a claim laying it would
|
|
383
|
+
* (relaunch, then settleCheck) once its runs ended: its text read at its record's commit, its verdict standing (promote
|
|
384
|
+
* or hold) though a newer revision waits. Left replaying while a run of it is at work, or when its text cannot be read
|
|
385
|
+
* (its read, replayView, decides it then). */
|
|
386
|
+
async function settleAhead(deps, name, ahead) {
|
|
387
|
+
const text = ahead.commit && deps.champion ? await deps.champion(name, ahead.commit).catch(() => undefined) : undefined;
|
|
388
|
+
if (text === undefined || workflowDigest(text) !== ahead.digest) {
|
|
389
|
+
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`);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
await relaunch(deps, text, ahead.digest, ahead);
|
|
393
|
+
await settleCheck(deps, text, ahead.digest, ahead);
|
|
394
|
+
}
|
|
418
395
|
/** A check's rows, once every replay run ended (or REPLAY_DEADLINE_MS passed); undefined while one is at work or not
|
|
419
396
|
* created yet. One row per reserved input, so every one counts: a run not ended by the deadline failed, and so did one
|
|
420
397
|
* 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,
|
|
398
|
+
* the record names for it. With what its runs cost, the rows' outcomes (one per row, the never created failed), and how
|
|
399
|
+
* many were never created by the deadline.
|
|
422
400
|
* No grade is read: the label is the agent's own recorded answer. */
|
|
423
401
|
async function checkRows(deps, record) {
|
|
424
402
|
const { store, context } = deps;
|
|
@@ -435,20 +413,23 @@ async function checkRows(deps, record) {
|
|
|
435
413
|
// Never created (or its launch unreadable): a failed input, never left out of n.
|
|
436
414
|
const of = reservedOf;
|
|
437
415
|
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,
|
|
416
|
+
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
417
|
continue;
|
|
440
418
|
}
|
|
441
419
|
const outcome = outcomeOf(run);
|
|
442
420
|
const stoppedAt = outcome === "skipped_write" ? metricsOf(run).replay?.skipped : undefined;
|
|
443
|
-
const guards = metricsOf(run).guards;
|
|
444
421
|
rows.push({
|
|
445
|
-
of: replayed, input: inputText(launch.input), agent: await answerOf(store, replayed, context), outcome,
|
|
422
|
+
of: replayed, input: inputText(launch.input), agent: await answerOf(store, replayed, context), outcome,
|
|
446
423
|
answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
|
|
447
424
|
...(outcome === "handed_back" ? { escalated: (await handedBackOf(store, run.id, context)) ?? "" } : {}),
|
|
448
425
|
...(stoppedAt ? { skipped: stoppedAt } : {}),
|
|
449
426
|
});
|
|
450
427
|
}
|
|
451
|
-
|
|
428
|
+
// The outcomes are the rows', so they add up to its n: a reserved run never created is a failed input there too.
|
|
429
|
+
const outcomes = { ...NO_OUTCOMES };
|
|
430
|
+
for (const row of rows)
|
|
431
|
+
outcomes[row.outcome] += 1;
|
|
432
|
+
return { rows, cost: replayCost(runs, late), outcomes, unstarted: rows.filter((row) => row.unstarted).length };
|
|
452
433
|
}
|
|
453
434
|
/** A run's input as a check's disagreement shows it: its text, else its JSON. */
|
|
454
435
|
const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input) ?? "");
|
|
@@ -469,7 +450,7 @@ async function settleCheck(deps, workflow, digest, record) {
|
|
|
469
450
|
if (!read)
|
|
470
451
|
return undefined;
|
|
471
452
|
const bar = record.check ?? { ...(await loopOfRevision(deps)), attempt: 1 };
|
|
472
|
-
const decided = await decideCheck(deps, name, digest, bar, read,
|
|
453
|
+
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
454
|
if (decided.won) {
|
|
474
455
|
const cancelled = await cancelUnended(deps, record);
|
|
475
456
|
if (cancelled)
|
|
@@ -478,33 +459,24 @@ async function settleCheck(deps, workflow, digest, record) {
|
|
|
478
459
|
return decided.record?.decided === "replaying" ? undefined : decided.record;
|
|
479
460
|
}
|
|
480
461
|
/** 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,
|
|
462
|
+
* with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate and no
|
|
463
|
+
* failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
|
|
464
|
+
* agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
|
|
465
|
+
* nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
|
|
466
|
+
* (the one write: of two claims at once, one decides). */
|
|
467
|
+
export async function decideCheck(deps, name, digest, bar, read, still, extra) {
|
|
487
468
|
const now = deps.now ?? Date.now;
|
|
488
469
|
const ran = read.rows.filter((row) => row.outcome !== "skipped_write");
|
|
489
|
-
const alone = (row) => row.outcome === "answered"
|
|
470
|
+
const alone = (row) => row.outcome === "answered";
|
|
490
471
|
const agrees = (row) => alone(row) && sameAnswer(row.answer, row.agent);
|
|
491
472
|
const score = { n: ran.length, agreed: ran.filter(agrees).length, alone: ran.filter(alone).length };
|
|
492
473
|
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.
|
|
474
|
+
// Each text is cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown).
|
|
495
475
|
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
|
-
};
|
|
476
|
+
const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
|
|
505
477
|
const disagreements = ran.filter((row) => !agrees(row)).map((row) => ({
|
|
506
478
|
run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
|
|
507
|
-
...(row.outcome === "answered" ?
|
|
479
|
+
...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
|
|
508
480
|
}));
|
|
509
481
|
const stopped = !ok && bar.attempt === 2;
|
|
510
482
|
const pct = (value) => `${(value * 100).toFixed(1)}%`;
|
|
@@ -514,111 +486,43 @@ export async function decideCheck(deps, name, digest, bar, read, thresholds, sti
|
|
|
514
486
|
const tools = skippedToolsOf(read.rows);
|
|
515
487
|
const { skipped_write: skipped, failed } = read.outcomes;
|
|
516
488
|
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 } : {}) };
|
|
489
|
+
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
490
|
// Every input skipped at a write (each reserved input counts: one never created or never ended failed, so this is the
|
|
519
491
|
// only way to none): nothing to check it on, so it stops, never promoted unchecked, and asks no recompile.
|
|
520
492
|
if (!score.n) {
|
|
521
493
|
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
494
|
return stopUnchecked(deps, name, digest, bar, why, still, numbers, extra);
|
|
523
495
|
}
|
|
524
|
-
|
|
525
|
-
const
|
|
496
|
+
// A run never created is a failed outcome too, said once: as never started.
|
|
497
|
+
const ranFailed = failed - read.unstarted;
|
|
498
|
+
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("; ");
|
|
499
|
+
// Every input reserved and none started (a launch interrupted before its first run existed): each counts failed in n,
|
|
500
|
+
// and the words say none ran.
|
|
501
|
+
const said = read.unstarted === score.n
|
|
502
|
+
? `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`
|
|
503
|
+
: `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
504
|
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
505
|
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",
|
|
506
|
+
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
507
|
if (decided.won)
|
|
530
508
|
deps.log(`workflow-first: ${name} at ${digest} ${ok ? "promoted" : "held"}: ${reason}`);
|
|
531
509
|
return decided;
|
|
532
510
|
}
|
|
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
|
|
511
|
+
/** Reserves a check of `workflow` at `digest` on `inputs`, then starts its runs: its replaying record names the replay
|
|
606
512
|
* runs it will start (their ids, and the replay's own, minted here), kept only when `still` holds of the digest's record
|
|
607
513
|
* 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) {
|
|
514
|
+
* a claim of the same digest, or of another revision, or a person's ask, at once, starts none. A claim's (startCheck) and
|
|
515
|
+
* a person's (askReplay) are this one reservation. */
|
|
516
|
+
async function reserve(deps, workflow, digest, inputs, reason, still, check) {
|
|
612
517
|
const now = deps.now ?? Date.now;
|
|
613
518
|
const ids = inputs.map(() => uuidv7());
|
|
614
519
|
const launch = replayLaunchOf(deps);
|
|
615
|
-
const reserved = await recordPromotion(deps.store.settings, deps.agentId, { workflow: workflow.name, digest, at: iso(now()), decided: "replaying",
|
|
520
|
+
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
521
|
if (reserved.won)
|
|
617
522
|
for (const [i, one] of inputs.entries())
|
|
618
523
|
await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
|
|
619
524
|
return reserved;
|
|
620
525
|
}
|
|
621
|
-
const gradedRuns = (inputs) => inputs.map((one) => ({ run: one.grade.run, launch: one.launch }));
|
|
622
526
|
/** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
|
|
623
527
|
* `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
528
|
* 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 +552,7 @@ function replayLaunchOf(deps) {
|
|
|
648
552
|
* be replayed again), are not: an older replay's late decision never lands over a newer one. */
|
|
649
553
|
const sameReplay = (was, record) => was?.decided === "replaying" && was.replay_id === record.replay_id;
|
|
650
554
|
/** 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
|
|
555
|
+
* on its row): once its check is decided with runs still at work (past its deadline). How many were sent their cancel. The
|
|
652
556
|
* record is the durable half: a cancel that is lost (a crash after the record, a write that fails) leaves a run whose
|
|
653
557
|
* claim refuses it (replayClaimed: its revision no longer replays), so each cancel is tried and a failed one only logged. */
|
|
654
558
|
async function cancelUnended(deps, record) {
|
|
@@ -669,58 +573,6 @@ async function cancelUnended(deps, record) {
|
|
|
669
573
|
}
|
|
670
574
|
return cancelled;
|
|
671
575
|
}
|
|
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
576
|
/** The per_run MCP credentials run `launch.handed_from` was handed (its launch's sealed column, opened under the seal
|
|
725
577
|
* key), sealed for the replay run `id` alone, as the server's start seals a run's mcp_auth (store/seal.ts
|
|
726
578
|
* sealRunMcpAuth): the replay's claim reads them where any run's claim does (runner/mcp-claim.ts). None when the replay
|
|
@@ -734,7 +586,7 @@ async function handedTo(deps, launch, id) {
|
|
|
734
586
|
const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
|
|
735
587
|
return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
|
|
736
588
|
}
|
|
737
|
-
/** Starts the replay of `workflow` at `digest` on
|
|
589
|
+
/** Starts the replay of `workflow` at `digest` on agent run `of` (its launch `from`) as run `id` (the id its reserved
|
|
738
590
|
* record names), with the replay's chosen `launch` (replayLaunchOf: its run launch, revision and handed credentials,
|
|
739
591
|
* handedTo), whichever claim creates it. False when a run by that id exists already: another claim created it (a
|
|
740
592
|
* relaunch and the reserving claim at once), and it is left to that one. */
|
|
@@ -756,13 +608,15 @@ async function startReplay(deps, workflow, digest, of, from, id, launch) {
|
|
|
756
608
|
}
|
|
757
609
|
}
|
|
758
610
|
/** 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
|
|
611
|
+
* its reservation (and before its deadline) are created now, each under its reserved id on the agent run its record
|
|
760
612
|
* 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
|
-
*
|
|
613
|
+
* handed credentials, an owner's replay none), never this claim's: one check runs on one set of settings. One whose
|
|
614
|
+
* agent run's launch can no longer be read stays missing: past the deadline it is counted as never started. How many
|
|
763
615
|
* this claim created. */
|
|
764
616
|
async function relaunch(deps, workflow, digest, record) {
|
|
765
617
|
const { store } = deps;
|
|
618
|
+
if (deps.spendOff?.("A replay"))
|
|
619
|
+
return 0;
|
|
766
620
|
const since = (deps.now ?? Date.now)() - Date.parse(record.at);
|
|
767
621
|
const launch = record.launch;
|
|
768
622
|
if (!launch || since <= REPLAY_LAUNCH_GRACE_MS || since > REPLAY_DEADLINE_MS)
|
|
@@ -777,29 +631,33 @@ async function relaunch(deps, workflow, digest, record) {
|
|
|
777
631
|
made += 1;
|
|
778
632
|
}
|
|
779
633
|
if (made)
|
|
780
|
-
deps.log(`workflow-first: ${workflow.name} at ${digest}: its
|
|
634
|
+
deps.log(`workflow-first: ${workflow.name} at ${digest}: its check's launch was interrupted; ${plural(made, "replay run")} it reserved started now`);
|
|
781
635
|
return made;
|
|
782
636
|
}
|
|
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
|
-
|
|
637
|
+
/** 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,
|
|
638
|
+
* 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
|
|
639
|
+
* answer a follow-up gave since is never read for it. */
|
|
640
|
+
export async function answerRowOf(store, runId, context, turn) {
|
|
786
641
|
try {
|
|
787
642
|
const rows = await runTimeline(store, runId, context, { settled: true, caps: { text: Number.POSITIVE_INFINITY } });
|
|
788
|
-
|
|
643
|
+
const row = rows.findLast((one) => one.kind === "final_answer" && one.agent_label !== LEARNING_LABEL && (turn === undefined || one.id === turn));
|
|
644
|
+
return typeof row?.text === "string" ? { id: row.id, text: row.text } : null;
|
|
789
645
|
}
|
|
790
646
|
catch {
|
|
791
647
|
return null;
|
|
792
648
|
}
|
|
793
649
|
}
|
|
650
|
+
/** A run's final answer, whole (answerRowOf's text; `turn`: that row's), or null. */
|
|
651
|
+
export const answerOf = async (store, runId, context, turn) => (await answerRowOf(store, runId, context, turn))?.text ?? null;
|
|
794
652
|
const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
|
|
795
653
|
/** 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
|
|
654
|
+
* other end, or one not ended (past the check's deadline), failed: no evidence either way. */
|
|
797
655
|
const outcomeOf = (run) => {
|
|
798
656
|
const m = metricsOf(run);
|
|
799
657
|
return run.state === "ended" && (m.replay?.outcome === "answered" || m.replay?.outcome === "handed_back" || m.replay?.outcome === "skipped_write") ? m.replay.outcome : "failed";
|
|
800
658
|
};
|
|
801
659
|
const NO_OUTCOMES = { answered: 0, handed_back: 0, failed: 0, skipped_write: 0 };
|
|
802
|
-
/** How many of a
|
|
660
|
+
/** How many of a check's runs ended each way so far (ReplayOutcomes): one not ended counts only past the deadline
|
|
803
661
|
* (`late`), as failed; one never created, nothing. */
|
|
804
662
|
function outcomesOf(runs, late) {
|
|
805
663
|
const counts = { ...NO_OUTCOMES };
|
|
@@ -809,7 +667,7 @@ function outcomesOf(runs, late) {
|
|
|
809
667
|
return counts;
|
|
810
668
|
}
|
|
811
669
|
/** 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)
|
|
670
|
+
* deadline, one not ended, one ended with no cost); a run never created by the deadline spent nothing. */
|
|
813
671
|
function replayCost(runs, late) {
|
|
814
672
|
let cost = 0;
|
|
815
673
|
for (const run of runs) {
|
|
@@ -824,44 +682,6 @@ function replayCost(runs, late) {
|
|
|
824
682
|
}
|
|
825
683
|
return Math.round(cost * 1e6) / 1e6;
|
|
826
684
|
}
|
|
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
685
|
/** Why `skipped` inputs of a replay were skipped, in one phrase (`why`): the MCP tools among `tools` its server listed
|
|
866
686
|
* with no readOnlyHint, named (`hint`: the server may only lack the hint), with the rest in the recording's words;
|
|
867
687
|
* with none of those, the recording's words alone (SKIPPED_WRITE). */
|
|
@@ -871,159 +691,6 @@ function skipWordsOf(tools, skipped) {
|
|
|
871
691
|
const hint = unmarked.length ? unmarkedWords(unmarked.map((one) => toolWord(one.tool))) : undefined;
|
|
872
692
|
return { hint, why: !hint ? SKIPPED_WRITE : writes ? `${hint} (${writes} more ${writes === 1 ? "needs" : "need"} a write the recording doesn't have)` : hint };
|
|
873
693
|
}
|
|
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
694
|
/** Why a replay a person asked for (askReplay) or read (replayView) was refused: `missing`, no such workflow, revision or
|
|
1028
695
|
* replay of the agent (404); `conflict`, the revision cannot replay now (409), in words that say why. */
|
|
1029
696
|
export class ReplayRefused extends Error {
|
|
@@ -1056,15 +723,21 @@ async function revisionOf(ask, records, name, digest) {
|
|
|
1056
723
|
}
|
|
1057
724
|
return { named: onMain || records.some((one) => one.workflow === name) };
|
|
1058
725
|
}
|
|
1059
|
-
/**
|
|
1060
|
-
*
|
|
1061
|
-
*
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
726
|
+
/** The agent runs `name` at `digest` was last checked on: its newest record that names them, a decided
|
|
727
|
+
* check's `check.of` or a reservation's `inputs`. A check's reservation leaves the kept history (trimPromotions) while
|
|
728
|
+
* its decision stays, so the decision's own list is read first. Undefined when no record names any. */
|
|
729
|
+
function heldInputsOf(records, name, digest) {
|
|
730
|
+
const checked = (one) => (one.decided !== "replaying" && one.check?.of?.length ? one.check.of : undefined);
|
|
731
|
+
const last = records.findLast((one) => one.workflow === name && one.digest === digest && (checked(one) ?? one.inputs)?.length);
|
|
732
|
+
return last && (checked(last) ?? last.inputs);
|
|
733
|
+
}
|
|
734
|
+
/** A check of `name` at `digest` a person asked for: the claim path's check (reserve, startReplay), on `inputs`: `held`,
|
|
735
|
+
* the agent runs its last check ran on (else, with none, the agent's last compile_after completed runs), or a number,
|
|
736
|
+
* 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
|
|
737
|
+
* is decided by settleCheck: at a claim that lays the revision, or at its read (replayView). Refused (ReplayRefused): no
|
|
738
|
+
* such workflow or revision; one replaying already, or another revision of it replaying (one at a time); a promoted one
|
|
739
|
+
* (it serves already); no input it fits (nothing is reserved); an agent that does not learn here. The replay's id and
|
|
740
|
+
* its inputs. */
|
|
1068
741
|
export async function askReplay(ask, name, digest, inputs) {
|
|
1069
742
|
const records = await promotionsOf(ask.store.settings, ask.agentId);
|
|
1070
743
|
const found = await revisionOf(ask, records, name, digest);
|
|
@@ -1077,29 +750,31 @@ export async function askReplay(ask, name, digest, inputs) {
|
|
|
1077
750
|
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
751
|
const rival = replayingOf(records, name, digest)[0];
|
|
1079
752
|
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
|
-
|
|
753
|
+
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.`);
|
|
754
|
+
const last = inputs === "held" ? heldInputsOf(records, name, digest) : undefined;
|
|
755
|
+
// The agent's own numbers (its current revision's definition, the one its replay runs launch on): with no earlier
|
|
756
|
+
// check, its last compile_after completed runs, as the claim's check picks them (startCheck), never the default's.
|
|
757
|
+
const current = (await ask.store.agents.get(ask.agentId).catch(() => undefined))?.currentRevision;
|
|
758
|
+
const loop = current ? await loopOfRevision({ store: ask.store, revisionId: current }) : loopOf(undefined);
|
|
759
|
+
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 });
|
|
760
|
+
if (!picked.length)
|
|
761
|
+
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.`);
|
|
762
|
+
const { launch, revisionId } = await ask.launchOf(picked[0].launch.input);
|
|
1088
763
|
if (!launch.learning || launch.learning.notesOnly)
|
|
1089
764
|
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
765
|
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
|
|
766
|
+
const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, name, digest) };
|
|
767
|
+
const said = `checking it on ${plural(picked.length, "input")} of the agent's own runs, as its owner asked`;
|
|
1092
768
|
// 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,
|
|
769
|
+
const reserved = await reserve(deps, found.workflow, digest, picked, said, (was) => was?.at === own?.at && was?.decided === own?.decided, bar);
|
|
1094
770
|
if (!reserved.won || !reserved.record?.replay_id)
|
|
1095
771
|
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
772
|
ask.log(`workflow-first: ${name} at ${digest}: ${said}`);
|
|
1097
|
-
return { replay: reserved.record.replay_id, inputs:
|
|
773
|
+
return { replay: reserved.record.replay_id, inputs: picked.length };
|
|
1098
774
|
}
|
|
775
|
+
const NO_SCORE = { n: 0, agree: 0, agent_acc: 0, wf_acc: 0, delta: 0, handed_back: 0 };
|
|
1099
776
|
/** 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. */
|
|
777
|
+
* so far. */
|
|
1103
778
|
async function checkView(ask, record, id, name, digest) {
|
|
1104
779
|
const inputs = record.runs?.length ?? 0;
|
|
1105
780
|
const decided = record.decided === "promote" || record.decided === "hold" ? record.decided : undefined;
|
|
@@ -1108,64 +783,42 @@ async function checkView(ask, record, id, name, digest) {
|
|
|
1108
783
|
const n = check.n ?? 0;
|
|
1109
784
|
const handedBack = check.outcomes.handed_back;
|
|
1110
785
|
const wf = n ? Math.round(((check.agreed ?? 0) + handedBack) / n * 1e4) / 1e4 : 0;
|
|
1111
|
-
const neverStarted = inputs > 0 &&
|
|
786
|
+
const neverStarted = inputs > 0 && check.unstarted === inputs;
|
|
1112
787
|
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
788
|
}
|
|
1114
789
|
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:
|
|
790
|
+
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
791
|
}
|
|
1117
792
|
/** 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
|
-
*
|
|
793
|
+
* reserved (PromotionRecord.launch, the one every replay run of it runs with): its revision, and its learning commit.
|
|
794
|
+
* Undefined when that launch cannot be read. */
|
|
1120
795
|
function readPorts(ask, launch) {
|
|
1121
796
|
const body = readLaunchBody(launch.body);
|
|
1122
797
|
return body ? claimPromotion({ ...ask, revisionId: launch.revision, launch: body }) : undefined;
|
|
1123
798
|
}
|
|
1124
|
-
/** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (
|
|
1125
|
-
*
|
|
1126
|
-
*
|
|
1127
|
-
*
|
|
1128
|
-
*
|
|
799
|
+
/** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (settleCheck) once its runs
|
|
800
|
+
* ended or its deadline passed: it writes only the decision. A read never starts a run: a replay whose launch was
|
|
801
|
+
* interrupted (reserved runs never created) reads running until its deadline, then is decided held, read as failed, its
|
|
802
|
+
* reason saying none of its runs started and to start it again with POST. So a replay of a revision no claim lays (an
|
|
803
|
+
* older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
|
|
1129
804
|
* (missing) when the agent has no such replay. */
|
|
1130
805
|
export async function replayView(ask, name, digest, id) {
|
|
1131
806
|
const find = async () => (await promotionsOf(ask.store.settings, ask.agentId)).findLast((one) => one.workflow === name && one.digest === digest && one.replay_id === id);
|
|
1132
807
|
let record = await find();
|
|
1133
808
|
if (!record)
|
|
1134
809
|
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 };
|
|
810
|
+
if (record.decided === "replaying" && record.commit && record.launch) {
|
|
811
|
+
const text = (await workflowsAt(ask, record.commit).catch(() => [])).find((one) => one.name === name && workflowDigest(one) === digest);
|
|
812
|
+
const ports = text ? readPorts(ask, record.launch) : undefined;
|
|
813
|
+
if (ports && text) {
|
|
814
|
+
// Read back by its id: whatever settled it (this read, a claim, another read), never another replay's record.
|
|
815
|
+
await settleCheck(ports, text, digest, record);
|
|
816
|
+
record = (await find()) ?? record;
|
|
817
|
+
}
|
|
1159
818
|
}
|
|
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
|
-
};
|
|
819
|
+
return checkView(ask, record, id, name, digest);
|
|
1167
820
|
}
|
|
1168
|
-
/** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the
|
|
821
|
+
/** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
|
|
1169
822
|
* (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
823
|
* they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one:
|
|
1171
824
|
* every write is then skipped, never run. */
|
|
@@ -1175,12 +828,6 @@ export async function replayCallsFor(store, runId, launch, context) {
|
|
|
1175
828
|
const entries = await runEntries(store, launch.replay.of, context).catch(() => []);
|
|
1176
829
|
const recorded = recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
|
|
1177
830
|
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
|
-
};
|
|
831
|
+
const annotations = pinAnnotations(pin);
|
|
1185
832
|
return replayCalls(recorded, (tool) => toolClassOf(tool, annotations));
|
|
1186
833
|
}
|