@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.49

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.
Files changed (106) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +144 -16
  3. package/dist/agent-delete.d.ts +33 -10
  4. package/dist/agent-delete.js +184 -26
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/archil-routes.d.ts +1 -1
  12. package/dist/archil-routes.js +4 -3
  13. package/dist/browser-sessions.d.ts +56 -0
  14. package/dist/browser-sessions.js +117 -0
  15. package/dist/computer-routes.d.ts +4 -15
  16. package/dist/computer-routes.js +6 -10
  17. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  18. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  19. package/dist/console/index.html +2 -2
  20. package/dist/errors.d.ts +4 -1
  21. package/dist/errors.js +15 -5
  22. package/dist/import.js +4 -3
  23. package/dist/learn/check.d.ts +11 -2
  24. package/dist/learn/check.js +12 -9
  25. package/dist/learn/promote.d.ts +7 -1
  26. package/dist/learn/promote.js +47 -0
  27. package/dist/learn/repick.d.ts +34 -0
  28. package/dist/learn/repick.js +201 -0
  29. package/dist/learned-workflow.d.ts +2 -0
  30. package/dist/learned-workflow.js +18 -1
  31. package/dist/learning-setting.d.ts +13 -0
  32. package/dist/learning-setting.js +23 -1
  33. package/dist/llms.txt +1 -1
  34. package/dist/openapi.js +170 -12
  35. package/dist/paid-calls.d.ts +4 -1
  36. package/dist/paid-calls.js +1 -1
  37. package/dist/run-learning-served.d.ts +1 -1
  38. package/dist/run-usage.d.ts +110 -0
  39. package/dist/run-usage.js +312 -0
  40. package/dist/runner/adapter-loop.js +51 -20
  41. package/dist/runner/conformance/harness.d.ts +2 -0
  42. package/dist/runner/conformance/harness.js +18 -4
  43. package/dist/runner/feedback-round.d.ts +29 -1
  44. package/dist/runner/feedback-round.js +54 -3
  45. package/dist/runner/journal-kinds.d.ts +3 -1
  46. package/dist/runner/learning-end.js +49 -18
  47. package/dist/runner/loop-contract.d.ts +3 -0
  48. package/dist/runner/monid-run.js +2 -2
  49. package/dist/runner/promotion.js +8 -2
  50. package/dist/runner/reflect-hook.js +3 -2
  51. package/dist/runs-over-store.d.ts +3 -2
  52. package/dist/runs-over-store.js +9 -7
  53. package/dist/server.d.ts +3 -3
  54. package/dist/server.js +221 -98
  55. package/dist/store/index.d.ts +2 -2
  56. package/dist/store/index.js +1 -1
  57. package/dist/store/journal/storage.js +1 -1
  58. package/dist/store/open.d.ts +1 -1
  59. package/dist/store/open.js +1 -1
  60. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  61. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  62. package/dist/store/schema.d.ts +15 -1
  63. package/dist/store/schema.js +50 -5
  64. package/dist/store/sqlite/connection.d.ts +4 -1
  65. package/dist/store/sqlite/connection.js +5 -0
  66. package/dist/store/sqlite/run-patch.d.ts +8 -3
  67. package/dist/store/sqlite/run-patch.js +15 -7
  68. package/dist/store/sqlite/store.d.ts +5 -2
  69. package/dist/store/sqlite/store.js +249 -48
  70. package/dist/store/sqlite/worker.d.ts +9 -0
  71. package/dist/store/sqlite/worker.js +18 -1
  72. package/dist/store/store.d.ts +142 -9
  73. package/dist/store/store.js +63 -0
  74. package/dist/store-reads/analytics.js +2 -1
  75. package/dist/store-reads/cap.d.ts +8 -2
  76. package/dist/store-reads/cap.js +27 -3
  77. package/dist/store-reads/learning.d.ts +1 -1
  78. package/dist/store-reads/learning.js +5 -2
  79. package/dist/store-reads/runs.js +2 -0
  80. package/dist/store-reads/stats.js +4 -2
  81. package/dist/store-view.d.ts +7 -0
  82. package/dist/store-view.js +61 -20
  83. package/dist/tools.js +9 -0
  84. package/dist/trigger-targets.d.ts +7 -4
  85. package/dist/trigger-targets.js +6 -6
  86. package/dist/triggers.d.ts +2 -1
  87. package/dist/triggers.js +5 -2
  88. package/dist/validate.d.ts +4 -2
  89. package/dist/validate.js +13 -3
  90. package/dist/viewer-credential.d.ts +3 -4
  91. package/dist/viewer-credential.js +6 -4
  92. package/dist/workspace/computer-for-claim.d.ts +5 -1
  93. package/dist/workspace/computer-for-claim.js +47 -18
  94. package/dist/workspace/computer-intervals.d.ts +20 -0
  95. package/dist/workspace/computer-intervals.js +49 -0
  96. package/dist/workspace/computer-janitor.d.ts +7 -3
  97. package/dist/workspace/computer-janitor.js +14 -6
  98. package/dist/workspace/computer-kept.d.ts +7 -2
  99. package/dist/workspace/computer-kept.js +9 -2
  100. package/dist/workspace/resolve-computer.d.ts +7 -4
  101. package/dist/workspace/resolve-computer.js +21 -32
  102. package/dist/workspace/run-end-computers.d.ts +1 -0
  103. package/dist/workspace/run-end-computers.js +4 -1
  104. package/package.json +10 -10
  105. package/dist/console/assets/index-CTGegcKt.css +0 -1
  106. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -0,0 +1,312 @@
1
+ // A run's cost, line by line (GET /runs/{run_id}/usage): what one run used and what it cost, by the model its requests
2
+ // went to, by who charged for its paid tool calls, and by the browser provider whose session time it ran up. For the
3
+ // person who runs AgentRun and wants to know what a run cost and whose invoice each part lands on; anyone who accounts
4
+ // for runs reads the same lines. A quantity is as it was measured (tokens as reported, seconds unrounded), and its dollars
5
+ // are the figures the run's booking already holds, the ones `cost.usd` joins: nothing is priced here.
6
+ //
7
+ // Nothing is measured again. The lines are the run's booking (runner/metrics.ts bookedSpend) split by what each charge
8
+ // was: its model requests and its decisions by the model each was sent on (`tokens`), its paid tool calls by who charged
9
+ // for them (`tools`, with the calls that ran unpriced beside them), and its browser session time by its provider
10
+ // (`browser_time`, with the seconds its BROWSER_CHARGED records keep). Each part is read by bookedSpend itself, over the
11
+ // run's entries with only that part's requests left in, so a line's figure follows the one rule its sum does; and the
12
+ // lines join (costWordsOf) to `total`, which is the run's `cost.usd`: the same booking outside its end-of-run (learning)
13
+ // turn, as `cost.tools_usd` reads it (store-view.ts toolsUsdOverStore). That turn is the server's own work for the agent,
14
+ // not the run's task, and `cost.usd` leaves it out the same way. Unknown is never $0: a line whose charge is unknown says
15
+ // so (`usd` null, what is known beside it), and a run the server cannot split says why (`reason`) with no lines.
16
+ //
17
+ // Beside the lines, each computer the run made (`computer_intervals`, store computer_intervals): its provider's own id,
18
+ // what it was made with, when it was made and when its provider's delete answered ok (null while none did). Computer time
19
+ // has no price here yet: no line carries it, and `total` leaves it out.
20
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
21
+ import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
22
+ import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
23
+ import { browserSessionsOf } from "./browser-sessions.js";
24
+ import { BROWSER_CHARGED } from "./cap.js";
25
+ import { launchOf } from "./handed-values.js";
26
+ import { inReflect, reflectRanges } from "./runner/end-of-run.js";
27
+ import { journalRecords } from "./runner/journal-reader.js";
28
+ import { KINDS } from "./runner/journal-kinds.js";
29
+ import { bookedSpend, costBasisOf, costWordsOf } from "./runner/metrics.js";
30
+ import { unbookedCli } from "./store-reads/cap.js";
31
+ import { decisionsOverStore } from "./store-reads/decisions.js";
32
+ import { roundsOf } from "./store-reads/learning.js";
33
+ import { MODEL_PROVIDER } from "./model.js";
34
+ import { ApiError } from "./errors.js";
35
+ import { redacted } from "./key-refusal.js";
36
+ import { runCutValues } from "./run-cut.js";
37
+ import { WITHHELD_SIGN_IN } from "./run-view.js";
38
+ import { FINAL_STATES } from "./store/index.js";
39
+ import { TOOL_UNMETERED } from "./timeline/index.js";
40
+ /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
41
+ export function computerIntervalsOf(rows) {
42
+ return rows.map((row) => ({
43
+ provider: row.provider,
44
+ provider_id: row.providerId,
45
+ kind: row.kind,
46
+ gpu: row.gpuType === null && row.gpuCount === null ? null : { type: row.gpuType, count: row.gpuCount },
47
+ cpus: row.cpus,
48
+ memory_mb: row.memoryMb,
49
+ started_at: new Date(row.startedAt).toISOString(),
50
+ ended_at: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
51
+ kept: row.kept,
52
+ }));
53
+ }
54
+ /** `entries` with the run's booked requests (runner.request and runner.turn) left in only where `keep` says so of its
55
+ * turn; every other entry (each session's key among them) kept, so bookedSpend reads that part alone. */
56
+ function onlyRequests(entries, turnOf, keep) {
57
+ return entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || keep(turnOf(e)));
58
+ }
59
+ /** Two bookings as one: their requests, tokens and figures summed; their cost parts kept for the join. */
60
+ function joined(parts) {
61
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
62
+ const priced = { reported: 0, estimated: 0 };
63
+ let requests = 0;
64
+ let unmetered = 0;
65
+ for (const part of parts) {
66
+ requests += part.requests;
67
+ unmetered += part.unmetered;
68
+ priced.reported += part.priced.reported;
69
+ priced.estimated += part.priced.estimated;
70
+ for (const key of Object.keys(tokens))
71
+ tokens[key] += part.tokens[key];
72
+ }
73
+ return { parts: [...parts], requests, unmetered, tokens, priced };
74
+ }
75
+ const ORDER = { tokens: 0, tools: 1, browser_time: 2 };
76
+ const named = (value) => (typeof value === "string" && value !== "" ? value : null);
77
+ /** The provider a run's model requests on `model` went to, where this server sent them there itself: the run's own
78
+ * model's provider (its launch's), on a direct route. Null behind a gateway, whose upstream the server does not know,
79
+ * and for any other model (a workflow decision's), whose route the booking does not keep. */
80
+ function upstreamOf(model, launch) {
81
+ const pinned = launch?.model;
82
+ if (!pinned || !model || pinned.provider === MODEL_PROVIDER)
83
+ return null;
84
+ return model === pinned.modelId || model === `${pinned.provider}/${pinned.modelId}` ? pinned.provider : null;
85
+ }
86
+ /** A run's lines from its journal `entries` (every conversation, in log order), its end-of-run turns already left out:
87
+ * its model requests and decisions by model (`tokens`), its paid calls by who charged (`tools`), its browser time by
88
+ * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
89
+ * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
90
+ * (its booking names the decision alone), which this server called itself. */
91
+ export function usageLinesOf(entries, launch, receipts = new Map()) {
92
+ const conversation = (key) => entries.find((e) => e.kind === KINDS.sessionKey && e.data?.key === key)?.data;
93
+ const paidConv = Number(conversation(TOOL_SESSION)?.conversation ?? Number.NaN);
94
+ const conv = (e) => Number(e.conversationId);
95
+ const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
96
+ // A line is one meter, one name and, on `tokens`, one route: a model reached two ways (the run's own requests behind a
97
+ // gateway, a decision on its provider) is two lines, never one labelled with either's provider.
98
+ const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}`;
99
+ // Each booked request's group, by its turn: a model request's or a decision's, the model its runner.request was sent on;
100
+ // a paid charge's, who charged for it (`charged_by`), on browser_time when it is the browser's session time. A paid
101
+ // charge settled at its provider's own figure says so on its request (`reported`). A decision's request names the
102
+ // decision (`decision:<id>`): its receipt names the model and provider that answered it, and how its cost was reached.
103
+ const groups = new Map();
104
+ const reported = new Set();
105
+ const estimated = new Set();
106
+ // A decision's tokens are its receipt's: its booking keeps its cost, with no usage (the cap books it at none).
107
+ const decisionTokens = new Map();
108
+ for (const e of entries) {
109
+ if (e.kind !== RUNNER_RECORDS.request)
110
+ continue;
111
+ const d = (e.data ?? {});
112
+ if (conv(e) === paidConv)
113
+ groups.set(turnOf(e), { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by) });
114
+ else if (named(d.model)?.startsWith("decision:")) {
115
+ const receipt = receipts.get(String(d.model).slice("decision:".length));
116
+ // A receipt that names no model leaves `model` null: its provider is said as the provider, never as a model.
117
+ groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider) } : { meter: "tokens", name: null, provider: null });
118
+ if (receipt?.cost_basis === "reported")
119
+ reported.add(turnOf(e));
120
+ else if (receipt?.cost_basis === "estimate")
121
+ estimated.add(turnOf(e));
122
+ const usage = (receipt?.usage ?? undefined);
123
+ const tokenCount = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
124
+ const [input, output] = [tokenCount(usage?.input_tokens), tokenCount(usage?.output_tokens)];
125
+ if (input !== undefined && output !== undefined)
126
+ decisionTokens.set(turnOf(e), { input, output });
127
+ }
128
+ else
129
+ groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch) });
130
+ if (d.reported === true)
131
+ reported.add(turnOf(e));
132
+ }
133
+ // A turn booked with no request of its own (an older record) is its session's: a model's with no name, a paid charge
134
+ // with no charger. A turn given back or never sent used nothing, and says nothing of how a line was priced.
135
+ const found = new Map();
136
+ const turnKeys = new Map();
137
+ const unused = new Set();
138
+ // Answered turns whose booking kept no usage: bookedSpend counts each among `unmetered`.
139
+ const noUsage = new Set();
140
+ for (const e of entries) {
141
+ if (e.kind !== RUNNER_RECORDS.request && e.kind !== RUNNER_RECORDS.turn)
142
+ continue;
143
+ const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null } : { meter: "tokens", name: null, provider: null });
144
+ if (!found.has(keyOf(group)))
145
+ found.set(keyOf(group), group);
146
+ turnKeys.set(turnOf(e), keyOf(group));
147
+ const d = (e.data ?? {});
148
+ if (e.kind === RUNNER_RECORDS.turn && (d.givenBack === true || d.unsent === true))
149
+ unused.add(turnOf(e));
150
+ else if (e.kind === RUNNER_RECORDS.turn && d.usage === undefined)
151
+ noUsage.add(turnOf(e));
152
+ }
153
+ // Browser seconds by provider, from the charges' own records on the root (BROWSER_CHARGED): the seconds each charge was
154
+ // for, as the browser_time meter of GET /usage counts them.
155
+ const seconds = new Map();
156
+ // Tool calls with no price, run outside the run's cost (an MCP tool its owner set none for, TOOL_UNMETERED), by who
157
+ // would charge for them, as GET /usage's `not_metered_calls` counts them.
158
+ const unpricedCalls = new Map();
159
+ for (const e of entries) {
160
+ const d = (e.data ?? {});
161
+ if (e.kind === TOOL_UNMETERED) {
162
+ const group = { meter: "tools", name: named(d.charged_by) };
163
+ unpricedCalls.set(keyOf(group), (unpricedCalls.get(keyOf(group)) ?? 0) + 1);
164
+ if (!found.has(keyOf(group)))
165
+ found.set(keyOf(group), group);
166
+ continue;
167
+ }
168
+ if (e.kind !== BROWSER_CHARGED || d.tool !== "browser" || typeof d.seconds !== "number" || !Number.isFinite(d.seconds))
169
+ continue;
170
+ const group = { meter: "browser_time", name: named(d.charged_by) };
171
+ seconds.set(keyOf(group), (seconds.get(keyOf(group)) ?? 0) + d.seconds);
172
+ if (!found.has(keyOf(group)))
173
+ found.set(keyOf(group), group);
174
+ }
175
+ const lines = [];
176
+ for (const group of found.values()) {
177
+ const key = keyOf(group);
178
+ const part = onlyRequests(entries, turnOf, (turn) => turnKeys.get(turn) === key);
179
+ const booked = group.meter === "tokens" ? joined([bookedSpend(part, "model"), bookedSpend(part, "decisions")]) : joined([bookedSpend(part, "paid")]);
180
+ const notMetered = unpricedCalls.get(key);
181
+ // A part whose every request was given back (never sent) used nothing: no line, unless calls ran on it unpriced.
182
+ if (booked.requests === 0 && group.meter !== "browser_time" && !notMetered)
183
+ continue;
184
+ const priced = booked.requests - booked.parts.reduce((sum, p) => sum + p.unpriced, 0);
185
+ const turns = [...turnKeys].filter(([turn, k]) => k === key && !unused.has(turn)).map(([turn]) => turn);
186
+ if (group.meter === "tokens") {
187
+ // A decision's tokens from its receipt, where it says them; the request then reported usage, so it is not unmetered.
188
+ const told = turns.filter((turn) => decisionTokens.has(turn));
189
+ const input = booked.tokens.input + told.reduce((sum, turn) => sum + decisionTokens.get(turn).input, 0);
190
+ const output = booked.tokens.output + told.reduce((sum, turn) => sum + decisionTokens.get(turn).output, 0);
191
+ const { cacheRead, cacheWrite } = booked.tokens;
192
+ const unmetered = Math.max(0, booked.unmetered - told.filter((turn) => noUsage.has(turn)).length);
193
+ // A decision's booking keeps no price table's mark: its receipt says how its cost was reached.
194
+ const priced = { reported: booked.priced.reported + turns.filter((turn) => reported.has(turn)).length, estimated: booked.priced.estimated + turns.filter((turn) => estimated.has(turn)).length };
195
+ lines.push({ meter: "tokens", model: group.name, provider: group.provider ?? null, charged_by: null, quantity: input + output + cacheRead + cacheWrite, unit: "token", basis: costBasisOf({ priced }), ...costWordsOf(booked.parts), requests: booked.requests, tokens: { input, output, cache_read: cacheRead, cache_write: cacheWrite }, unmetered_requests: unmetered });
196
+ }
197
+ else if (group.meter === "tools") {
198
+ // `reported` when every charge with a figure was settled at its provider's own (monid's answer says what it
199
+ // charged); `estimate` when any was settled at a price this server holds (an MCP tool's owner's, Parallel's).
200
+ const basis = priced <= 0 ? "unpriced" : turns.every((turn) => reported.has(turn)) ? "reported" : "estimate";
201
+ // Calls that ran unpriced only: none booked, so nothing is charged on the line, by its owner's choice of no price.
202
+ const words = booked.requests === 0 ? { usd: 0 } : costWordsOf(booked.parts);
203
+ lines.push({ meter: "tools", model: null, provider: group.name, charged_by: group.name, quantity: booked.requests, unit: "call", basis, ...words, ...(notMetered ? { not_metered_calls: notMetered } : {}) });
204
+ }
205
+ else {
206
+ const s = seconds.get(key);
207
+ // A browser's holds given back with no time charged (a call that held and used nothing, a provider priced at $0 with
208
+ // no charge record) used nothing: no line.
209
+ if (booked.requests === 0 && s === undefined)
210
+ continue;
211
+ // A browser provider whose time no charge booked (none, or each given back) still ran: its seconds with no figure.
212
+ const words = booked.requests === 0 ? { usd: null } : costWordsOf(booked.parts);
213
+ lines.push({ meter: "browser_time", model: null, provider: group.name, charged_by: null, quantity: s === undefined ? null : Math.round(s * 1e6) / 1e6, unit: "second", basis: priced > 0 ? "estimate" : "unpriced", ...words });
214
+ }
215
+ }
216
+ // Each meter by its name (a model, a charger, a browser provider; none first), `tokens` then by its route's provider.
217
+ const sortKey = (line) => (line.meter === "tokens" ? `${line.model ?? ""}\u0000${line.provider ?? ""}` : line.meter === "tools" ? line.charged_by ?? "" : line.provider ?? "");
218
+ lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0));
219
+ // The join over the whole booking, never the lines' rounded figures: the same figure cost.usd is. A browser line whose
220
+ // time no charge booked is unknown beside it: the total is too, with the booking's figure as what is known.
221
+ const total = costWordsOf([bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")]);
222
+ const unbooked = lines.filter((line) => line.usd === null && line.meter === "browser_time" && line.so_far_usd === undefined).length;
223
+ if (!unbooked)
224
+ return { lines, total };
225
+ const known = total.usd ?? total.so_far_usd ?? 0;
226
+ return { lines, total: { usd: null, so_far_usd: known, unpriced: (total.usd === null ? (total.unpriced ?? 0) : 0) + unbooked } };
227
+ }
228
+ /** The run's own browser sessions: those its job opened or charged (`job`, the journal less the end-of-run learning
229
+ * turn), each with its end read from the whole journal (`all`). The run's end lets its browsers go inside the learning
230
+ * turn's range (reflectRanges runs to the run's end), so an end read from `job` alone would be missing for a session
231
+ * released there. A session the learning turn opened is not the job's, as its cost is not. */
232
+ function jobSessions(job, all) {
233
+ const ends = new Map(browserSessionsOf(all).map((one) => [one.tag, one]));
234
+ return browserSessionsOf(job).map((one) => {
235
+ const whole = ends.get(one.tag);
236
+ if (one.ended_at !== null || !whole || whole.ended_at === null)
237
+ return one;
238
+ const { provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status } = whole;
239
+ return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status };
240
+ });
241
+ }
242
+ /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
243
+ * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
244
+ * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
245
+ * of the store (one moment): a follow-up that reopens the run between two reads can't put its requests under its end. */
246
+ export async function runUsageOverStore(store, runId) {
247
+ return store.snapshot(async (snapshot) => {
248
+ const run = await snapshot.runs.get(runId);
249
+ if (!run)
250
+ return undefined;
251
+ const ended = FINAL_STATES.includes(run.state) && run.endedAt !== null ? new Date(run.endedAt).toISOString() : null;
252
+ const none = (reason) => ({ run_id: runId, ended_at: reason === "running" ? null : ended, currency: "USD", total: null, lines: null, browser_sessions: null, computer_intervals: null, reason });
253
+ if (!FINAL_STATES.includes(run.state))
254
+ return none("running");
255
+ const launch = await launchOf(snapshot, runId);
256
+ if (run.importedFrom || launch?.native || launch?.sdk)
257
+ return none("not_booked");
258
+ if ((await roundsOf(snapshot, runId)).length > 1)
259
+ return none("reopened");
260
+ const records = await journalRecords(snapshot.readJournal(runId), BACKGROUND_CONTEXT);
261
+ if (unbookedCli(records.entries))
262
+ return none("not_booked");
263
+ const turns = reflectRanges(records.submissions ?? [], records.entries);
264
+ const entries = records.entries.filter((entry) => !inReflect(turns, Number(entry.id)));
265
+ // A workflow's decision receipts, read only when it made a decision: the model and provider each was answered on.
266
+ const decided = entries.some((e) => e.kind === RUNNER_RECORDS.request && String(e.data?.model ?? "").startsWith("decision:"));
267
+ const receipts = decided ? new Map((await decisionsOverStore(snapshot, runId, BACKGROUND_CONTEXT)).map((receipt) => [String(receipt.decision_id ?? receipt.id), receipt])) : undefined;
268
+ const { lines, total } = usageLinesOf(entries, launch, receipts);
269
+ // Its computers in the same snapshot; a store that keeps none (a test's) reads as none made.
270
+ const computers = snapshot.computerIntervals ? computerIntervalsOf(await snapshot.computerIntervals.forRun(runId)) : [];
271
+ return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries), computer_intervals: computers, reason: null };
272
+ });
273
+ }
274
+ /** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
275
+ * the run's cut, as its trace serves a model's name, since a decision provider or a tool names itself in what it
276
+ * returns. A run withheld (its sign-in can't be read back here) is refused (403), as its trace is. */
277
+ export async function servedRunUsage(deps, store, runId) {
278
+ if ((await runCutValues(deps, store, runId)) === "unreadable")
279
+ throw new ApiError("forbidden", WITHHELD_SIGN_IN);
280
+ const usage = await runUsageOverStore(store, runId);
281
+ // The cut after the read: it only grows, so it holds every value the read could have seen.
282
+ const cut = await runCutValues(deps, store, runId);
283
+ if (cut === "unreadable")
284
+ throw new ApiError("forbidden", WITHHELD_SIGN_IN);
285
+ if (!usage?.lines)
286
+ return usage;
287
+ const said = (text) => (text === null ? null : redacted(text, cut.values));
288
+ // A browser session's words too, every one its records keep: its provider names it, and the provider's record says the rest.
289
+ const session = (one) => ({
290
+ ...one,
291
+ provider: redacted(one.provider, cut.values),
292
+ tag: redacted(one.tag, cut.values),
293
+ provider_session_id: said(one.provider_session_id),
294
+ started_at: said(one.started_at),
295
+ ended_at: said(one.ended_at),
296
+ release_reason: said(one.release_reason),
297
+ provider_record: one.provider_record && { ...one.provider_record, started_at: said(one.provider_record.started_at), ended_at: said(one.provider_record.ended_at) },
298
+ });
299
+ return {
300
+ ...usage,
301
+ lines: usage.lines.map((line) => ({ ...line, model: said(line.model), provider: said(line.provider), charged_by: said(line.charged_by) })),
302
+ browser_sessions: usage.browser_sessions && usage.browser_sessions.map(session),
303
+ // A computer's words too: its provider's id for it is the provider's, which a run's own tools can name.
304
+ computer_intervals: usage.computer_intervals && usage.computer_intervals.map((one) => ({
305
+ ...one,
306
+ provider: redacted(one.provider, cut.values),
307
+ provider_id: redacted(one.provider_id, cut.values),
308
+ kind: said(one.kind),
309
+ gpu: one.gpu && { ...one.gpu, type: said(one.gpu.type) },
310
+ })),
311
+ };
312
+ }
@@ -53,7 +53,7 @@ import { answerAsServed } from "../answer-json.js";
53
53
  import { reserveFor, stepAndAnswerFor, wrappingUp, wrapUpText } from "../wrap-up.js";
54
54
  import { LEARNED_CARD_FIELDS, LEARNED_CLIP, LEARNED_WORKFLOW_TOOL, learnedApprovedTools } from "../learned-workflow.js";
55
55
  import { warnHoldShort } from "../print.js";
56
- import { feedbackAsk, feedbackOf, pendingFeedbackOf } from "./feedback-round.js";
56
+ import { feedbackAsk, feedbackOf, jobEndOpen, pendingFeedbackOf } from "./feedback-round.js";
57
57
  import { handbackText, servedAnswerOf, servedAnswerText, WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
58
58
  /** The end of a harness's own call (Claude Code's WebSearch) the gate held and then let run: the host ran nothing of it,
59
59
  * and the harness's next call runs it. */
@@ -2302,7 +2302,14 @@ function adapterLoop(specOf, options, deps) {
2302
2302
  // CLI's look-back has no submission until it ends: its record's lookingBack, below). Read before the session
2303
2303
  // opens, so its first request is already learning's.
2304
2304
  const lookingBackOpen = (await harness.inspect(context)).submissions.filter((one) => one.type === "input" && Number(one.conversationId) === Number(ROOT_CONVERSATION_ID)).at(-1)?.requestId?.startsWith(REFLECT_PREFIX) === true;
2305
- reflecting = lookingBackOpen;
2305
+ // The job's end an earlier claim kept for its look-back, with no run end after it (feedback-round.ts jobEndOpen):
2306
+ // its runner was lost after keeping it, maybe before the look-back's first ask (no input in flight then). The job
2307
+ // ended there too: this pass runs no job turn, and the run ends on that end at its time (jobEndKept), never on one
2308
+ // worked out again now, which would move the end every reader served. A follow-up's turn after the run's last end
2309
+ // has kept none, so it is never taken for one.
2310
+ const rootFound = await harness.conversation(ROOT_CONVERSATION_ID, context);
2311
+ const jobKept = rootFound ? jobEndOpen(await entriesOf(gate.journal, rootFound.id, context)) : false;
2312
+ reflecting = lookingBackOpen || jobKept;
2306
2313
  // The MCP tools are host tools like any other (mcp.tools, wrapped above): every harness gets them on its own channel
2307
2314
  // for host tools, each call through the gate before its intent.
2308
2315
  session = await spec.adapter.open({ ...spec.session, tools, deferCatalog: deferred }, io);
@@ -2662,7 +2669,8 @@ function adapterLoop(specOf, options, deps) {
2662
2669
  }, context);
2663
2670
  }
2664
2671
  }
2665
- if (firstToServe && !followedUp && !firstUnplaced && session.state === "new") {
2672
+ // Never again for a job whose end is kept (jobKept): what the workflow did is in that end.
2673
+ if (firstToServe && !followedUp && !firstUnplaced && !jobKept && session.state === "new") {
2666
2674
  let release;
2667
2675
  servingFirst = new Promise((resolve) => (release = resolve));
2668
2676
  try {
@@ -2700,9 +2708,10 @@ function adapterLoop(specOf, options, deps) {
2700
2708
  }
2701
2709
  }
2702
2710
  const placed = served !== undefined || followedUp || (session.state !== "idle" && !firstUnplaced);
2703
- // The end-of-run turn found open (lookingBackOpen), with no turn of this claim's sent before it: never recovered as
2704
- // the job's; the run goes to its end-of-run step, on the job's end the claim that asked it kept (jobEndKept).
2705
- const lookingBack = lookingBackOpen && !followedUp && served === undefined;
2711
+ // The end-of-run turn found open (lookingBackOpen), or the job's end found kept before that turn's first ask
2712
+ // (jobKept), with no turn of this claim's sent before it: never recovered as the job's; the run goes to its
2713
+ // end-of-run step, on the job's end the claim that kept it kept (jobEndKept).
2714
+ const lookingBack = (lookingBackOpen || jobKept) && !followedUp && served === undefined;
2706
2715
  if (served || followedUp || firstUnplaced || lookingBack) {
2707
2716
  // The workflow answered, or handed back and its handback is the turn; the follow-up is the turn this claim runs,
2708
2717
  // or there is none.
@@ -2733,8 +2742,16 @@ function adapterLoop(specOf, options, deps) {
2733
2742
  let parkOn;
2734
2743
  /** The ask_person call the run waits on in its claim, while it does. */
2735
2744
  let waitingOn;
2745
+ /** When the job's end was, once it is kept (keepJobEnd): the look-back after it never moves it, and its end is
2746
+ * written at that time. A grade's round keeps the end the run had when the grade opened it (feedbackNow.kept). */
2747
+ let keptAt;
2736
2748
  if (alone && lookingBack)
2737
- ({ end: data, failedWith } = await jobEndKept(root));
2749
+ ({ end: data, failedWith, endedAt: keptAt } = await jobEndKept(root));
2750
+ else if (alone && feedbackNow?.kept) {
2751
+ const { endedAt, ...end } = feedbackNow.kept;
2752
+ data = end;
2753
+ keptAt = endedAt;
2754
+ }
2738
2755
  else if (alone)
2739
2756
  data = { state: "ended" };
2740
2757
  else
@@ -2969,14 +2986,19 @@ function adapterLoop(specOf, options, deps) {
2969
2986
  // The run's status is how its job's own turn ended (`data`), whatever the step spends after it: learning spend that
2970
2987
  // takes the run past its cap is the learning's (askEndOfRun reads overCap after each of its turns), never the run's.
2971
2988
  // That end is kept before the step's first ask, so a claim that finds its turn open ends the run on it (jobEndKept).
2989
+ // Kept with its time: from then on every reader serves it, and the run's end is written at it (writeEnd `keptAt`).
2972
2990
  if (!lookingBack)
2973
- await keepJobEnd(harness, root, spec, data, failedWith);
2974
- const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap);
2991
+ keptAt = await keepJobEnd(harness, root, spec, data, failedWith, keptAt);
2992
+ const step = await endOfRunStep(claim, spec, data.state === "failed" ? "failed" : "completed", overCap, keptAt);
2993
+ // A stop or cancel the runner took during the step (one that raced the read refusing it, its row written while the
2994
+ // run still read as going on) cuts the look-back alone: the run ends on its job's end, the row taken by that end.
2995
+ if (step.kind === "stopped" && keptAt !== undefined)
2996
+ return await writeEnd(harness, root, gate, data, [step.commandId], await cutRows(claim, spec, "stopped-looking"), failedWith, keptAt);
2975
2997
  if (step.kind === "stopped")
2976
2998
  return await writeEnd(harness, root, gate, stopEnd(stopReason?.kind === "command" ? stopReason.cancel : undefined), [step.commandId], await cutRows(claim, spec, "stopped-looking"));
2977
2999
  if (step.kind === "interrupted")
2978
3000
  return await interrupted(stopReason?.kind ?? "its claim's signal aborted");
2979
- return await writeEnd(harness, root, gate, data, [], step.also, failedWith);
3001
+ return await writeEnd(harness, root, gate, data, [], step.also, failedWith, keptAt);
2980
3002
  }
2981
3003
  }
2982
3004
  catch (error) {
@@ -3361,13 +3383,16 @@ function adapterLoop(specOf, options, deps) {
3361
3383
  }
3362
3384
  /** How the job's own turn ended (`data`, and a CLI's error answer `failedWith`), as this claim decided it, kept on the
3363
3385
  * root before the end-of-run step asks its first turn (KINDS.jobEnd), for a run with a step to ask (stepOf). Its
3364
- * summary is cut of every secret the runner holds, as every summary is when served. */
3365
- async function keepJobEnd(on, conversation, spec, data, failedWith) {
3386
+ * summary is cut of every secret the runner holds, as every summary is when served. Kept with its time, `at` (a grade's
3387
+ * round keeps the end it found) or now, which it answers; with no step to ask, nothing is kept and `at` comes back. */
3388
+ async function keepJobEnd(on, conversation, spec, data, failedWith, at) {
3366
3389
  if (!stepOf(spec))
3367
- return;
3390
+ return at;
3368
3391
  const end = data.summary !== undefined && deps.redact ? { ...data, summary: deps.redact(data.summary) } : data;
3369
- const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}) };
3392
+ const endedAt = at ?? now();
3393
+ const kept = { end, ...(failedWith !== undefined ? { failedWith } : {}), endedAt };
3370
3394
  await on.commit((tx) => tx.appendEntry(conversation.id, { kind: KINDS.jobEnd, data: kept }), context);
3395
+ return endedAt;
3371
3396
  }
3372
3397
  /** The job's end for a claim that found the end-of-run turn open (lookingBackOpen): the newest keepJobEnd kept (a
3373
3398
  * follow-up's round keeps its own), never worked out again. */
@@ -3537,7 +3562,7 @@ function adapterLoop(specOf, options, deps) {
3537
3562
  * came during it; `interrupted` when the claim was lost or the runner is closing (no end is written, and the next claim
3538
3563
  * asks it again). A step that throws on its own writes the end without rows: the run's end never waits on it. `over`:
3539
3564
  * the claim's overCap, read after each turn the step asks (askEndOfRun). */
3540
- async function endOfRunStep(claim, spec, outcome, over) {
3565
+ async function endOfRunStep(claim, spec, outcome, over, endedAt) {
3541
3566
  const cut = () => {
3542
3567
  if (stopReason?.kind === "command")
3543
3568
  return { kind: "stopped", commandId: stopReason.commandId };
@@ -3559,7 +3584,7 @@ function adapterLoop(specOf, options, deps) {
3559
3584
  void harness?.closed.then(() => closed.abort(new Error("the Session closed")), () => closed.abort(new Error("the Session closed")));
3560
3585
  const signal = AbortSignal.any([deps.signal, stopAbort.signal, closed.signal]);
3561
3586
  try {
3562
- const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3587
+ const rows = await step({ runId: claim.runId, agentId: spec.agentId, claim, outcome, ...(endedAt !== undefined ? { endedAt } : {}), signal, ask: (prompt, opts) => askEndOfRun(claim, over, prompt, opts.deadlineMs, opts.again === true, opts.round ?? 1, opts.keep, opts.step), keptOf: await keptOf(claim) });
3563
3588
  // A replay's or a shadow's grader verdict (runner/compare-end.ts), on its root before its end: its metrics carry it
3564
3589
  // (workflow-first.ts pathMetrics), where the check and the audit read it.
3565
3590
  const on = harness;
@@ -3884,8 +3909,11 @@ function adapterLoop(specOf, options, deps) {
3884
3909
  /** The end commit: an `agentrun.end` entry carrying the run row's final patch (the spec's end patch in it), the rows
3885
3910
  * staged with it (the end-of-run step's), and the rows it takes. */
3886
3911
  /** `failedWith`: a CLI turn's own error (record "loop"), cut of every secret the runner holds: written in the end's
3887
- * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn. */
3888
- async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith) {
3912
+ * commit, right before the end, as pi's own error answer (cliErrorAnswer), main's error row for a CLI's turn.
3913
+ * `keptAt`: the end is the job's, kept before its look-back (keepJobEnd), and every reader served it while the run
3914
+ * looked back: it is written at that time, and a stop or cancel taken here cut the look-back alone, never the end
3915
+ * (the store refuses one still waiting: RunPatch.keepsEnd). */
3916
+ async function writeEnd(on, conversation, theGate, base, take, also = [], failedWith, keptAt) {
3889
3917
  // A person's stop of a run that holds its computer ends its agent, not the hold (computer-held.ts): the end, and the
3890
3918
  // computer's release after it, wait for the owner's release or the hold's lapse, the owner's calls still answered.
3891
3919
  // A cancel, a lost claim or a shutdown meanwhile ends the wait; a cancel's end is then the run's, taking both rows.
@@ -3896,7 +3924,8 @@ function adapterLoop(specOf, options, deps) {
3896
3924
  await heldNow.heldAtEnd(Promise.race([heldCut, aborted, on.closed]), heldWords.stopped(heldNow.minutes));
3897
3925
  const later = laterStop;
3898
3926
  if (later?.kind === "command" && later.cancel) {
3899
- base = { ...base, ...stopEnd(true) };
3927
+ if (keptAt === undefined)
3928
+ base = { ...base, ...stopEnd(true) };
3900
3929
  take = [...take, later.commandId];
3901
3930
  }
3902
3931
  }
@@ -3915,9 +3944,11 @@ function adapterLoop(specOf, options, deps) {
3915
3944
  const lateStop = late?.kind === "command" && !take.includes(late.commandId) ? late : undefined;
3916
3945
  if (lateStop)
3917
3946
  take = [...take, lateStop.commandId];
3918
- const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop ? stopEnd(lateStop.cancel) : {}) };
3947
+ // An end that keeps the job's takes it too, and stays the job's.
3948
+ const data = { ...base, ...(patch.outcome !== undefined ? { outcome: patch.outcome } : {}), ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd, ...(patch.costUpperBound ? { costUpperBound: true } : {}) } : {}), ...(patch.metrics !== undefined ? { metrics: patch.metrics } : {}), ...(lateStop && keptAt === undefined ? stopEnd(lateStop.cancel) : {}) };
3919
3949
  const run = {
3920
3950
  state: data.state,
3951
+ ...(keptAt !== undefined ? { endedAt: keptAt, keepsEnd: true } : {}),
3921
3952
  // An end's summary is its own: with none, a wait's summary the row still says (a question's, a hand-over's: HELD_WAITS
3922
3953
  // and the park's) goes, so an ended run never reads as waiting on its person.
3923
3954
  ...(data.summary ? { summary: data.summary } : {}),
@@ -25,6 +25,8 @@ export declare function suiteTools(countFile?: string): {
25
25
  ran: Record<ToolName, number>;
26
26
  letSlowGo: () => void;
27
27
  slowStarted: Promise<void>;
28
+ holdAsked: () => undefined;
29
+ letAskedGo: () => void;
28
30
  };
29
31
  /** Catalog tools (an MCP server's, by wire name) that do nothing, enough of them to pass DEFER_CATALOG_OVER: a run with that
30
32
  * many has its catalog deferred (not listed) and is offered tools_search and tools_call, which the meta cases need. */
@@ -87,6 +87,10 @@ export function suiteTools(countFile) {
87
87
  const slowGate = new Promise((resolve) => (letGo = resolve));
88
88
  let slowStarted = () => { };
89
89
  const started = new Promise((resolve) => (slowStarted = resolve));
90
+ // Held (holdAsked), an approved `asked` call runs until the suite lets it go (letAskedGo), so its run cannot end first.
91
+ let askedGate;
92
+ let letAskedGoNow = () => { };
93
+ const holdAsked = () => void (askedGate = new Promise((resolve) => (letAskedGoNow = resolve)));
90
94
  const tool = (name, replaySafe, ask, run) => ({ name, replaySafe, ask, run });
91
95
  const tools = {
92
96
  effect: tool("effect", false, false, async () => {
@@ -103,12 +107,14 @@ export function suiteTools(countFile) {
103
107
  await Promise.race([slowGate, new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
104
108
  return signal.aborted ? "cut" : "slow done";
105
109
  }),
106
- asked: tool("asked", false, true, async () => {
110
+ asked: tool("asked", false, true, async (_args, signal) => {
107
111
  ran.asked += 1;
112
+ if (askedGate)
113
+ await Promise.race([askedGate, new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
108
114
  return "asked done";
109
115
  }),
110
116
  };
111
- return { tools, ran, letSlowGo: () => letGo(), slowStarted: started };
117
+ return { tools, ran, letSlowGo: () => letGo(), slowStarted: started, holdAsked, letAskedGo: () => letAskedGoNow() };
112
118
  }
113
119
  /** Catalog tools (an MCP server's, by wire name) that do nothing, enough of them to pass DEFER_CATALOG_OVER: a run with that
114
120
  * many has its catalog deferred (not listed) and is offered tools_search and tools_call, which the meta cases need. */
@@ -1022,12 +1028,20 @@ const CASES = [
1022
1028
  title: "a double-clicked approval runs the call once: the first answers it, and the store refuses the second (one answer per approval)",
1023
1029
  async body(subject, t) {
1024
1030
  const w = await world(subject, t);
1025
- const { tools, ran } = suiteTools();
1031
+ const { tools, ran, holdAsked, letAskedGo } = suiteTools();
1032
+ // The approved call is held until the second click is answered, so the run cannot end first: a run that ended
1033
+ // refuses any command as final (RunFinal) before the one-answer index is reached, which is not this case.
1034
+ holdAsked();
1026
1035
  await w.start("runner-a", { script: [{ call: "asked" }, { say: "done" }], tools, hooks: quiet });
1027
1036
  await w.ended("parked");
1028
1037
  const callId = await w.askedCall();
1029
1038
  const first = await sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } });
1030
- await assert.rejects(sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }), AnswerTaken, "a second answer to one approval is never written: the store says it is answered already");
1039
+ try {
1040
+ await assert.rejects(sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }), AnswerTaken, "a second answer to one approval is never written: the store says it is answered already");
1041
+ }
1042
+ finally {
1043
+ letAskedGo();
1044
+ }
1031
1045
  await w.ended("ended");
1032
1046
  assert.equal(ran.asked, 1, "the call ran once");
1033
1047
  assert.equal((await w.commandRow(first.id)).refused, null, "the first approve answered it");
@@ -2,15 +2,43 @@ import { type Grade } from "../learn/promote.js";
2
2
  import type { RunPath } from "../learning-cost.js";
3
3
  import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Command, type Store } from "../store/store.js";
5
+ import { type EndData } from "./journal-kinds.js";
5
6
  export declare const FEEDBACK_ROUNDS: readonly ["correction"];
6
7
  export type FeedbackRound = (typeof FEEDBACK_ROUNDS)[number];
8
+ /** The end a run's look-back keeps: how its job ended (its state, summary and outcome) and when. While the run looks
9
+ * back (its end-of-run step, a fresh run's or a grade's feedback round) every reader serves this end, and the look-back's
10
+ * own end writes it again at the same time (adapter-loop.ts writeEnd `keptAt`): a look-back never undoes or moves its
11
+ * run's end. */
12
+ export interface KeptEnd {
13
+ readonly state: EndData["state"];
14
+ readonly summary?: string;
15
+ readonly outcome?: EndData["outcome"];
16
+ readonly endedAt: number;
17
+ }
7
18
  /** A feedback round, as its steer's body carries it (`feedback`) and its FEEDBACK entry keeps it: the round, whether the
8
- * grade said right, and the grade's words (`text`). */
19
+ * grade said right, the grade's words (`text`), and the end the run had when the grade opened it again (`kept`). */
9
20
  export interface FeedbackData {
10
21
  readonly round: FeedbackRound;
11
22
  readonly correct: boolean;
12
23
  readonly text: string;
24
+ readonly kept?: KeptEnd;
13
25
  }
26
+ /** Whether the run's root `entries` hold a job's end kept for its look-back (KINDS.jobEnd) with no run end after it: the
27
+ * job ended and its look-back is under way, whether or not that look-back has asked anything yet. A follow-up's turn
28
+ * keeps none until its own job's end is kept, so a turn after the run's last end reads false. */
29
+ export declare function jobEndOpen(entries: readonly {
30
+ readonly kind: string;
31
+ }[]): boolean;
32
+ /** The end run's look-back keeps while it runs, from the run's root `entries` and its command rows, else undefined (no
33
+ * look-back under way, or one whose job's end was never kept):
34
+ * - the job's end its claim kept before the end-of-run step (KINDS.jobEnd, with its time), newer than the run's last end;
35
+ * - else the end a grade's round kept, from its FEEDBACK entry newer than the run's last end;
36
+ * - else from the round's steer the grade wrote, not taken yet (the run opened again, no runner on it yet).
37
+ * A follow-up's own turn keeps none until its job's end is kept: its run reads as going on, as main's does. */
38
+ export declare function keptEndOf(entries: readonly {
39
+ readonly kind: string;
40
+ readonly data?: unknown;
41
+ }[], commands: readonly Pick<Command, "kind" | "body" | "takenAt" | "refused">[]): KeptEnd | undefined;
14
42
  /** What a grade asks for: `correction` for a graded run the agent finished when the grade has words, else none
15
43
  * (undefined): a run its learned workflow answered alone opens none, right or wrong (its grade is kept). A replay run
16
44
  * is never graded. */