@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.52

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 (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
package/dist/run-usage.js CHANGED
@@ -22,6 +22,13 @@
22
22
  // run's ledger booked for it while a claim held it, so `total` stays the run's `cost.usd`. Time no claim held (a computer
23
23
  // kept for a follow-up, one deleted after its run, one whose delete failed) is said apart (`unheld_quantity`) and costs
24
24
  // nothing on the line or in `total`. A resource with no price is `unpriced`, its `usd` null.
25
+ //
26
+ // Each line is one attempt's (store run_attempts): a claim that was cut (its runner drained, crashed or lost its lease, or
27
+ // its turn was tried again) and whose turn another claim worked again made every request and paid call of it again. Its
28
+ // lines say so (`billable: false`, its `attempt` beside it), apart from the attempt that finished the turn, and the run's
29
+ // `infra_usd` is their sum: the cost of the infrastructure's own redo, not of the run's task. Data only: `total` and
30
+ // `cost.usd` still hold every line, billable or not, as the run was charged before. A run whose claims kept no attempt
31
+ // (one made before them) reads each line's `attempt` as null and every line billable.
25
32
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
26
33
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
27
34
  import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
@@ -44,7 +51,8 @@ import { FINAL_STATES } from "./store/index.js";
44
51
  import { COMPUTE_TOOL, COMPUTE_UNITS, computeTag, resourcesOf, unmetered } from "./compute-cost.js";
45
52
  import { TOOL_UNMETERED } from "./timeline/index.js";
46
53
  /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
47
- export function computerIntervalsOf(rows) {
54
+ export function computerIntervalsOf(rows, attempts = []) {
55
+ const tags = attemptTags(attempts);
48
56
  return rows.map((row) => ({
49
57
  provider: row.provider,
50
58
  provider_id: row.providerId,
@@ -57,8 +65,55 @@ export function computerIntervalsOf(rows) {
57
65
  ended_at: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
58
66
  kept: row.kept,
59
67
  booked_seconds: row.bookedMs / 1000,
68
+ ...tags.atTime(row.startedAt),
60
69
  }));
61
70
  }
71
+ const NO_ATTEMPT = { attempt: null, billable: true };
72
+ /** A run's attempts (`rows`, by epoch) as tags: the attempt a journal entry was written in (the last claim whose first
73
+ * entry id is at or below the entry's), and the one a time falls in (the last claim made at or before it, on the
74
+ * store's clock: a computer is made a moment after its claim). `spans` splits a stretch of time across the claims whose
75
+ * windows it falls in (each claim's window runs from its claim to the next claim's). Every part is billable: a claim
76
+ * that takes over a cut turn resumes from what the cut one saved (its answered requests, its finished calls), so that
77
+ * work is the task's, done once. `redoneAt` is the one exception: the attempt an entry was written in, billable unless
78
+ * another claim worked its turn again after it (the same turn, one attempt more), for a model request that attempt sent
79
+ * and never finished (usageLinesOf), which the claim after it sends again. With no rows (a run from before
80
+ * them), every part is NO_ATTEMPT: attempt null, billable. A part before the first row is NO_ATTEMPT too, unless that
81
+ * row is the run's first claim (taken from queued): then nothing came before it, and a part read a moment early (a
82
+ * runner's clock behind the store's) is that claim's. A run that took its first row after the change that writes them
83
+ * (an older run's follow-up) never counts what it did before as any attempt's. */
84
+ export function attemptTags(rows) {
85
+ const sorted = [...rows].sort((a, b) => a.epoch - b.epoch);
86
+ const tagOf = (row) => (row === undefined ? NO_ATTEMPT : { attempt: row.attempt, billable: true });
87
+ const redoneOf = (row) => row === undefined ? NO_ATTEMPT : { attempt: row.attempt, billable: !sorted.some((later) => later.epoch > row.epoch && later.turn === row.turn && later.attempt === row.attempt + 1) };
88
+ const last = (fits) => sorted.filter(fits).at(-1);
89
+ const before = sorted[0]?.from === "queued" ? sorted[0] : undefined;
90
+ const entryRow = (id) => {
91
+ const n = Number(id);
92
+ return Number.isFinite(n) ? last((row) => row.journalFrom <= n) ?? before : sorted.at(-1);
93
+ };
94
+ return {
95
+ atEntry: (id) => tagOf(entryRow(id)),
96
+ redoneAt: (id) => redoneOf(entryRow(id)),
97
+ atTime: (ms) => tagOf(last((row) => row.claimedAt <= ms) ?? before),
98
+ spans: (from, to) => {
99
+ if (!(to > from))
100
+ return [{ at: tagOf(last((row) => row.claimedAt <= from) ?? before), ms: 0 }];
101
+ const out = [];
102
+ // The edges of each claim's window, the first one's reaching back to `from` when it is the run's first claim.
103
+ const edges = sorted.map((row, i) => ({ row, start: i === 0 && before ? Number.NEGATIVE_INFINITY : row.claimedAt, end: sorted[i + 1]?.claimedAt ?? Number.POSITIVE_INFINITY }));
104
+ const firstStart = edges[0]?.start ?? Number.POSITIVE_INFINITY;
105
+ if (from < firstStart)
106
+ out.push({ at: NO_ATTEMPT, ms: Math.min(to, firstStart) - from });
107
+ for (const edge of edges) {
108
+ const ms = Math.min(to, edge.end) - Math.max(from, edge.start);
109
+ if (ms > 0)
110
+ out.push({ at: tagOf(edge.row), ms });
111
+ }
112
+ return out;
113
+ },
114
+ };
115
+ }
116
+ const attemptKey = (at) => `${at.attempt ?? ""}:${at.billable ? 1 : 0}`;
62
117
  /** `entries` with the run's booked requests (runner.request and runner.turn) left in only where `keep` says so of its
63
118
  * turn; every other entry (each session's key among them) kept, so bookedSpend reads that part alone. */
64
119
  function onlyRequests(entries, turnOf, keep) {
@@ -96,14 +151,42 @@ function upstreamOf(model, launch) {
96
151
  * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
97
152
  * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
98
153
  * (its booking names the decision alone), which this server called itself. */
99
- export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }) {
154
+ export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }, attempts = []) {
100
155
  const conversation = (key) => entries.find((e) => e.kind === KINDS.sessionKey && e.data?.key === key)?.data;
101
156
  const paidConv = Number(conversation(TOOL_SESSION)?.conversation ?? Number.NaN);
102
157
  const conv = (e) => Number(e.conversationId);
103
158
  const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
104
159
  // A line is one meter, one name and, on `tokens`, one route: a model reached two ways (the run's own requests behind a
105
160
  // gateway, a decision on its provider) is two lines, never one labelled with either's provider.
106
- const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}`;
161
+ const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}\u0000${attemptKey(group.at)}`;
162
+ // Each booked request's attempt: the claim that wrote its first record (its hold, or its booking), never a later
163
+ // claim's settling of it.
164
+ const tags = attemptTags(attempts);
165
+ // A browser charge is the attempt's whose claim wrote it on the root (BROWSER_CHARGED), even when its booking landed
166
+ // under a later claim (browser-cost.ts bookRootCharges books one its process lost): the booking names it by its ref.
167
+ const chargeAt = new Map();
168
+ for (const e of entries) {
169
+ const d = (e.data ?? {});
170
+ if (e.kind === BROWSER_CHARGED && typeof d.tag === "string")
171
+ chargeAt.set(`browser:${d.tag}@${String(d.at)}${d.final ? "/final" : ""}`, tags.atEntry(e.id));
172
+ }
173
+ // A model request its attempt sent and never finished: no answer booked (a crash cut it off), or booked as cut (a stop
174
+ // cut it, at its hold). The claim that takes the turn over sends it again, so when a later claim redid that turn it is
175
+ // the infrastructure's (redoneAt). An answered request, and every paid call, is the task's: the next claim reuses it.
176
+ const answered = new Set();
177
+ for (const e of entries) {
178
+ if (e.kind === RUNNER_RECORDS.turn && e.data?.cut !== true)
179
+ answered.add(turnOf(e));
180
+ }
181
+ const unfinished = (e) => conv(e) !== paidConv && !answered.has(turnOf(e));
182
+ const atOf = new Map();
183
+ for (const e of entries) {
184
+ if (!(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || atOf.has(turnOf(e)))
185
+ continue;
186
+ const ref = e.data?.ref;
187
+ atOf.set(turnOf(e), (typeof ref === "string" ? chargeAt.get(ref) : undefined) ?? (unfinished(e) ? tags.redoneAt(e.id) : tags.atEntry(e.id)));
188
+ }
189
+ const at = (e) => atOf.get(turnOf(e)) ?? tags.atEntry(e.id);
107
190
  // Each booked request's group, by its turn: a model request's or a decision's, the model its runner.request was sent on;
108
191
  // a paid charge's, who charged for it (`charged_by`), on browser_time when it is the browser's session time. A paid
109
192
  // charge settled at its provider's own figure says so on its request (`reported`). A decision's request names the
@@ -121,15 +204,15 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
121
204
  const d = (e.data ?? {});
122
205
  // A computer's time (compute-cost.ts) by its provider and resource (its tag); a browser's by its provider.
123
206
  if (conv(e) === paidConv)
124
- groups.set(turnOf(e), d.tool === COMPUTE_TOOL ? { meter: "compute_time", name: named(d.charged_by), tag: named(d.tag) } : { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by) });
207
+ groups.set(turnOf(e), d.tool === COMPUTE_TOOL ? { meter: "compute_time", name: named(d.charged_by), tag: named(d.tag), at: at(e) } : { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by), at: at(e) });
125
208
  else if (named(d.model)?.startsWith("decision:")) {
126
209
  const receipt = receipts.get(String(d.model).slice("decision:".length));
127
210
  if (receipt && chargedByParallel(receipt)) {
128
- groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER });
211
+ groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER, at: at(e) });
129
212
  continue;
130
213
  }
131
214
  // A receipt that names no model leaves `model` null: its provider is said as the provider, never as a model.
132
- groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider) } : { meter: "tokens", name: null, provider: null });
215
+ groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider), at: at(e) } : { meter: "tokens", name: null, provider: null, at: at(e) });
133
216
  if (receipt?.cost_basis === "reported")
134
217
  reported.add(turnOf(e));
135
218
  else if (receipt?.cost_basis === "estimate")
@@ -141,7 +224,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
141
224
  decisionTokens.set(turnOf(e), { input, output });
142
225
  }
143
226
  else
144
- groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch) });
227
+ groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch), at: at(e) });
145
228
  if (d.reported === true)
146
229
  reported.add(turnOf(e));
147
230
  }
@@ -155,7 +238,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
155
238
  for (const e of entries) {
156
239
  if (e.kind !== RUNNER_RECORDS.request && e.kind !== RUNNER_RECORDS.turn)
157
240
  continue;
158
- const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null } : { meter: "tokens", name: null, provider: null });
241
+ const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null, at: at(e) } : { meter: "tokens", name: null, provider: null, at: at(e) });
159
242
  if (!found.has(keyOf(group)))
160
243
  found.set(keyOf(group), group);
161
244
  turnKeys.set(turnOf(e), keyOf(group));
@@ -174,7 +257,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
174
257
  for (const e of entries) {
175
258
  const d = (e.data ?? {});
176
259
  if (e.kind === TOOL_UNMETERED) {
177
- const group = { meter: "tools", name: named(d.charged_by) };
260
+ const group = { meter: "tools", name: named(d.charged_by), at: tags.atEntry(e.id) };
178
261
  unpricedCalls.set(keyOf(group), (unpricedCalls.get(keyOf(group)) ?? 0) + 1);
179
262
  if (!found.has(keyOf(group)))
180
263
  found.set(keyOf(group), group);
@@ -182,7 +265,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
182
265
  }
183
266
  if (e.kind !== BROWSER_CHARGED || d.tool !== "browser" || typeof d.seconds !== "number" || !Number.isFinite(d.seconds))
184
267
  continue;
185
- const group = { meter: "browser_time", name: named(d.charged_by) };
268
+ const group = { meter: "browser_time", name: named(d.charged_by), at: tags.atEntry(e.id) };
186
269
  seconds.set(keyOf(group), (seconds.get(keyOf(group)) ?? 0) + d.seconds);
187
270
  if (!found.has(keyOf(group)))
188
271
  found.set(keyOf(group), group);
@@ -198,7 +281,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
198
281
  if (group.meter === "compute_time") {
199
282
  // A hold for a stretch names no resource (no tag) and books nothing: it is given back.
200
283
  if (group.tag !== null && group.tag !== undefined)
201
- computeBooked.set(computeKey(group.name ?? "", group.tag), booked);
284
+ computeBooked.set(computeKey(group.name ?? "", group.tag, group.at), { booked, at: group.at });
202
285
  continue;
203
286
  }
204
287
  const notMetered = unpricedCalls.get(key);
@@ -216,7 +299,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
216
299
  const unmetered = Math.max(0, booked.unmetered - told.filter((turn) => noUsage.has(turn)).length);
217
300
  // A decision's booking keeps no price table's mark: its receipt says how its cost was reached.
218
301
  const priced = { reported: booked.priced.reported + turns.filter((turn) => reported.has(turn)).length, estimated: booked.priced.estimated + turns.filter((turn) => estimated.has(turn)).length };
219
- 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 });
302
+ lines.push({ meter: "tokens", model: group.name, provider: group.provider ?? null, charged_by: null, quantity: input + output + cacheRead + cacheWrite, unit: "token", basis: costBasisOf({ priced }), ...group.at, ...costWordsOf(booked.parts), requests: booked.requests, tokens: { input, output, cache_read: cacheRead, cache_write: cacheWrite }, unmetered_requests: unmetered });
220
303
  }
221
304
  else if (group.meter === "tools") {
222
305
  // `reported` when every charge with a figure was settled at its provider's own (monid's answer says what it
@@ -225,7 +308,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
225
308
  const basis = priced <= 0 ? "unpriced" : turns.every((turn) => reported.has(turn)) ? "reported" : "estimate";
226
309
  // Calls that ran unpriced only: none booked, so nothing is charged on the line, by its owner's choice of no price.
227
310
  const words = booked.requests === 0 ? { usd: 0 } : costWordsOf(booked.parts);
228
- 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 } : {}) });
311
+ lines.push({ meter: "tools", model: null, provider: group.name, charged_by: group.name, quantity: booked.requests, unit: "call", basis, ...group.at, ...words, ...(notMetered ? { not_metered_calls: notMetered } : {}) });
229
312
  }
230
313
  else {
231
314
  const s = seconds.get(key);
@@ -235,10 +318,10 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
235
318
  continue;
236
319
  // A browser provider whose time no charge booked (none, or each given back) still ran: its seconds with no figure.
237
320
  const words = booked.requests === 0 ? { usd: null } : costWordsOf(booked.parts);
238
- 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 });
321
+ 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", ...group.at, ...words });
239
322
  }
240
323
  }
241
- lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked));
324
+ lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked, tags.spans));
242
325
  // Each meter by its name (a model, a charger, a browser provider; none first), `tokens` then by its route's provider,
243
326
  // `compute_time` then by its resource in compute-cost.ts's order and a GPU's type.
244
327
  const sortKey = (line) => line.meter === "tokens"
@@ -248,7 +331,9 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
248
331
  : line.meter === "compute_time"
249
332
  ? `${line.provider ?? ""}\u0000${RESOURCE_ORDER[line.resource ?? "vcpu"]}\u0000${line.gpu_type ?? ""}`
250
333
  : line.provider ?? "";
251
- lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0));
334
+ // Then by attempt, a line of no attempt first, and a cut attempt's before the billable one of the same number.
335
+ const attemptOrder = (line) => (line.attempt ?? 0) * 2 + (line.billable ? 1 : 0);
336
+ lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0) || attemptOrder(a) - attemptOrder(b));
252
337
  // The join over the whole booking, never the lines' rounded figures: the same figure cost.usd is. A browser line whose
253
338
  // time no charge booked is unknown beside it: the total is too, with the booking's figure as what is known.
254
339
  const total = costWordsOf([bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")]);
@@ -258,8 +343,8 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
258
343
  const known = total.usd ?? total.so_far_usd ?? 0;
259
344
  return { lines, total: { usd: null, so_far_usd: known, unpriced: (total.usd === null ? (total.unpriced ?? 0) : 0) + unbooked } };
260
345
  }
261
- /** A compute line's key: its provider and its resource's tag (computeTag). */
262
- const computeKey = (provider, tag) => `${provider}\u0000${tag}`;
346
+ /** A compute line's key: its provider, its resource's tag (computeTag) and its attempt. */
347
+ const computeKey = (provider, tag, at) => `${provider}\u0000${tag}\u0000${attemptKey(at)}`;
263
348
  const RESOURCE_ORDER = { vcpu: 0, memory: 1, gpu: 2, disk: 3 };
264
349
  /** Up to the millionth, as the browser's seconds are. */
265
350
  const micro = (value) => Math.round(value * 1e6) / 1e6;
@@ -267,23 +352,32 @@ const micro = (value) => Math.round(value * 1e6) / 1e6;
267
352
  * its figure, an open one's up to `at` (the read), and the part no claim held (its life less its booked time) apart in
268
353
  * `unheld_quantity`. Its money is what the run's ledger booked for it (`booked`, by computeKey): `estimate` when any was;
269
354
  * $0 for a provider that bills nothing; else `unpriced`, its usd null. A figure no one said makes its quantity null. */
270
- function computeLinesOf(rows, at, booked) {
355
+ function computeLinesOf(rows, at, booked, spans) {
271
356
  const sums = new Map();
272
357
  for (const row of rows) {
273
- const livedS = Math.max(0, (row.endedAt ?? at) - row.startedAt) / 1000;
358
+ const end = row.endedAt ?? at;
359
+ const livedS = Math.max(0, end - row.startedAt) / 1000;
274
360
  const unheldS = Math.max(0, livedS - row.bookedMs / 1000);
275
- for (const one of resourcesOf(row)) {
276
- const key = computeKey(row.provider, computeTag(one));
277
- const sum = sums.get(key) ?? { provider: row.provider, resource: one.resource, gpuType: one.gpuType, quantity: 0, unheld: 0, open: 0 };
278
- sum.quantity = sum.quantity === null || one.perSecond === null ? null : sum.quantity + one.perSecond * livedS;
279
- sum.unheld = sum.unheld === null || one.perSecond === null ? null : sum.unheld + one.perSecond * unheldS;
280
- if (row.endedAt === null)
281
- sum.open += 1;
282
- sums.set(key, sum);
361
+ // Its time is the claims' that held it, by each claim's window (a computer kept across a park is billed by the claim
362
+ // that resumed it), so each stretch sits with the attempt whose bookings paid for it. The part no claim held is kept
363
+ // per computer alone: it is spread over the windows by their share of its life.
364
+ const pieces = spans(row.startedAt, end);
365
+ for (const span of pieces) {
366
+ const share = livedS > 0 ? span.ms / 1000 / livedS : 1;
367
+ for (const one of resourcesOf(row)) {
368
+ const key = computeKey(row.provider, computeTag(one), span.at);
369
+ const sum = sums.get(key) ?? { provider: row.provider, resource: one.resource, gpuType: one.gpuType, quantity: 0, unheld: 0, open: 0, at: span.at };
370
+ sum.quantity = sum.quantity === null || one.perSecond === null ? null : sum.quantity + one.perSecond * (span.ms / 1000);
371
+ sum.unheld = sum.unheld === null || one.perSecond === null ? null : sum.unheld + one.perSecond * unheldS * share;
372
+ // An open computer counts once, on the line of the window it is in now.
373
+ if (row.endedAt === null && span === pieces.at(-1))
374
+ sum.open += 1;
375
+ sums.set(key, sum);
376
+ }
283
377
  }
284
378
  }
285
379
  // A booking whose computer has no row here (one made before this server kept them): its money, with no quantity.
286
- for (const key of booked.keys()) {
380
+ for (const [key, one] of booked) {
287
381
  if (sums.has(key))
288
382
  continue;
289
383
  const [provider = "", tag = ""] = key.split("\u0000");
@@ -291,16 +385,16 @@ function computeLinesOf(rows, at, booked) {
291
385
  const resource = (gpu ? "gpu" : tag);
292
386
  if (!Object.hasOwn(COMPUTE_UNITS, resource))
293
387
  continue;
294
- sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0 });
388
+ sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0, at: one.at });
295
389
  }
296
390
  return [...sums.entries()].map(([key, sum]) => {
297
- const spend = booked.get(key);
391
+ const spend = booked.get(key)?.booked;
298
392
  const charged = spend !== undefined && spend.requests > 0;
299
393
  const free = !charged && unmetered(sum.provider);
300
394
  const words = charged ? costWordsOf(spend.parts) : free ? { usd: 0 } : { usd: null };
301
395
  return {
302
396
  meter: "compute_time", model: null, provider: sum.provider, charged_by: sum.provider,
303
- quantity: sum.quantity === null ? null : micro(sum.quantity), unit: COMPUTE_UNITS[sum.resource], basis: charged || free ? "estimate" : "unpriced", ...words,
397
+ quantity: sum.quantity === null ? null : micro(sum.quantity), unit: COMPUTE_UNITS[sum.resource], basis: charged || free ? "estimate" : "unpriced", ...sum.at, ...words,
304
398
  resource: sum.resource, gpu_type: sum.gpuType, unheld_quantity: sum.unheld === null ? null : micro(sum.unheld), open_computers: sum.open,
305
399
  ...(sum.open > 0 ? { measured_to: new Date(at).toISOString() } : {}),
306
400
  };
@@ -310,16 +404,37 @@ function computeLinesOf(rows, at, booked) {
310
404
  * turn), each with its end read from the whole journal (`all`). The run's end lets its browsers go inside the learning
311
405
  * turn's range (reflectRanges runs to the run's end), so an end read from `job` alone would be missing for a session
312
406
  * released there. A session the learning turn opened is not the job's, as its cost is not. */
313
- function jobSessions(job, all) {
407
+ function jobSessions(job, all, attempts = []) {
314
408
  const ends = new Map(browserSessionsOf(all).map((one) => [one.tag, one]));
409
+ // A session is the attempt's whose claim first wrote of it (its open, else its first charge).
410
+ const tags = attemptTags(attempts);
411
+ const first = new Map();
412
+ for (const e of job) {
413
+ const tag = e.data?.tag;
414
+ if (typeof tag === "string" && !first.has(tag))
415
+ first.set(tag, tags.atEntry(e.id));
416
+ }
315
417
  return browserSessionsOf(job).map((one) => {
418
+ const at = first.get(one.tag) ?? NO_ATTEMPT;
316
419
  const whole = ends.get(one.tag);
317
420
  if (one.ended_at !== null || !whole || whole.ended_at === null)
318
- return one;
421
+ return { ...one, ...at };
319
422
  const { provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status } = whole;
320
- return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status };
423
+ return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status, ...at };
321
424
  });
322
425
  }
426
+ /** The sum of the lines no customer is charged for (`billable: false`): null when one of them has no known figure. */
427
+ export function infraUsdOf(lines) {
428
+ let sum = 0;
429
+ for (const line of lines) {
430
+ if (line.billable)
431
+ continue;
432
+ if (line.usd === null)
433
+ return null;
434
+ sum += line.usd;
435
+ }
436
+ return Math.round(sum * 1e12) / 1e12;
437
+ }
323
438
  /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
324
439
  * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
325
440
  * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
@@ -330,7 +445,7 @@ export async function runUsageOverStore(store, runId) {
330
445
  if (!run)
331
446
  return undefined;
332
447
  const ended = FINAL_STATES.includes(run.state) && run.endedAt !== null ? new Date(run.endedAt).toISOString() : null;
333
- 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 });
448
+ const none = (reason) => ({ run_id: runId, ended_at: reason === "running" ? null : ended, currency: "USD", total: null, lines: null, browser_sessions: null, computer_intervals: null, infra_usd: null, reason });
334
449
  if (!FINAL_STATES.includes(run.state))
335
450
  return none("running");
336
451
  const launch = await launchOf(snapshot, runId);
@@ -348,9 +463,11 @@ export async function runUsageOverStore(store, runId) {
348
463
  // Its computers in the same snapshot, an open one's time counted up to now; a store that keeps none (a test's) reads
349
464
  // as none made.
350
465
  const rows = snapshot.computerIntervals ? await snapshot.computerIntervals.forRun(runId) : [];
351
- const { lines, total } = usageLinesOf(entries, launch, receipts, { rows, at: Date.now() });
352
- const computers = computerIntervalsOf(rows);
353
- return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries), computer_intervals: computers, reason: null };
466
+ // Its claims' attempts in the same snapshot; a store that keeps none (a test's) reads as a run of no attempts.
467
+ const attempts = snapshot.runAttempts ? await snapshot.runAttempts.forRun(runId) : [];
468
+ const { lines, total } = usageLinesOf(entries, launch, receipts, { rows, at: Date.now() }, attempts);
469
+ const computers = computerIntervalsOf(rows, attempts);
470
+ return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries, attempts), computer_intervals: computers, infra_usd: infraUsdOf(lines), reason: null };
354
471
  });
355
472
  }
356
473
  /** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
@@ -55,7 +55,7 @@ export type Status = "queued" | "working" | "paused" | "input_required" | "compl
55
55
  export type State = "working" | "waiting" | "idle";
56
56
  /** A tool call that waited for a person's approval, as the run's store has it (tool-gate.ts): `resolved` once the run's
57
57
  * process acted on the answer. */
58
- /** `asks_because`: why the gate asked a call its setting allows (its card's ASKED_BECAUSE), kept out of `args_json`. */
58
+ /** `asks_because`: why the gate asked a call its setting allows (its ask's own `because`, never one of the call's arguments). */
59
59
  export type Approval = {
60
60
  id: string;
61
61
  tool: string;
package/dist/run-view.js CHANGED
@@ -17,8 +17,7 @@ import { pointerHash } from "./sign-ins-store.js";
17
17
  import { MIN_SECRET } from "./learn/secrets.js";
18
18
  import { costWordsOf, usageParts } from "./runner/metrics.js";
19
19
  import { KINDS } from "./runner/journal-kinds.js";
20
- import { ASKED_BECAUSE, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
21
- import { isObject } from "./validate.js";
20
+ import { ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
22
21
  /** The run's newest usage row, which carries its cost. */
23
22
  const usageOf = (rows) => rows.findLast((r) => r.kind === "usage");
24
23
  /** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
@@ -136,15 +135,12 @@ export function asksOf(entries) {
136
135
  if (typeof d?.callId !== "string" || map.has(d.callId))
137
136
  continue;
138
137
  const price = priceOfAsk(d.price);
139
- // The card's reason for asking a call its setting allows is the gate's, never one of the call's arguments.
140
- const raw = d.args ?? {};
141
- const { [ASKED_BECAUSE]: because, ...args } = isObject(raw) ? raw : {};
142
138
  map.set(d.callId, {
143
139
  id: d.callId,
144
140
  tool: d.tool,
145
141
  call_id: d.callId,
146
- args_json: JSON.stringify(isObject(raw) ? args : raw) ?? "{}",
147
- ...(typeof because === "string" ? { asks_because: because } : {}),
142
+ args_json: JSON.stringify(d.args ?? {}) ?? "{}",
143
+ ...(typeof d.because === "string" ? { asks_because: d.because } : {}),
148
144
  requested_at: d.requestedAt,
149
145
  ...(price !== undefined ? { price } : {}),
150
146
  ...(d.destructive === true ? { destructive: true } : {}),
@@ -56,11 +56,13 @@ export type RaiseCheck = {
56
56
  retry?: undefined;
57
57
  };
58
58
  /** The gate's answer for a call: run it, ask a person (`ask` with fields its card shows before the call's input: a
59
- * learned workflow's MCP actions), or refuse it (with the words the model reads, or generic ones). */
59
+ * learned workflow's MCP actions; `because`, why a call its setting allows asks anyway, its ask's own field and never
60
+ * one of the call's arguments), or refuse it (with the words the model reads, or generic ones). */
60
61
  export type GateAnswer = "allow" | "ask" | "deny" | {
61
62
  readonly deny: string;
62
63
  } | {
63
64
  readonly ask: Readonly<Record<string, unknown>>;
65
+ readonly because?: string;
64
66
  };
65
67
  /** The gate before a call's intent; `askedAs`, when it has one, names a call as a person is asked about it (its settings
66
68
  * key, as main's pending approval names it), else the call is asked about by its own name. `replayed`: asked again for a
@@ -27,7 +27,7 @@ const outputRetried = (entries) => {
27
27
  return at >= 0 && entries.slice(at + 1).some((entry) => entry.kind === "pi.assistant" || (entry.kind === KINDS.message && entry.data?.role === "model"));
28
28
  };
29
29
  import { ClaimRefused, deniedText, noteOf, stopEnd } from "./loop-contract.js";
30
- import { ASKED_BECAUSE, deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
30
+ import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
31
31
  import { ADAPTER_API } from "../turn-end.js";
32
32
  import { answerText, REFLECT_PREFIX, reflectRequestId } from "./end-of-run.js";
33
33
  import { agentEntriesOf, approvalOf, BOOKING_WRITE_MS, CLOSE_MS, CUT_STEP_MS, END_PATCH_MS, END_PATCH_UNKNOWN, PARK_SIBLINGS_MS, readAgain, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, INPUT_REQUEST, Interrupted, KernelFault, lastAnswerText, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
@@ -62,12 +62,11 @@ export const OWN_TOOL_RELEASED = "Allowed after it waited; the agent's own tool
62
62
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
63
63
  /** An asked call's card: the gate's own fields (`shown`) first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES)
64
64
  * still names them whatever the input's size, then the call's input, which the model wrote, without any field of
65
- * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's, and so is the reason a
66
- * call its setting allows asks anyway (ASKED_BECAUSE). */
65
+ * theirs; a learned_workflow call's card fields (LEARNED_CARD_FIELDS) are only ever the gate's. */
67
66
  function cardOf(tool, shown, args) {
68
- if (!shown && tool !== LEARNED_WORKFLOW_TOOL && !(args && Object.hasOwn(args, ASKED_BECAUSE)))
67
+ if (!shown && tool !== LEARNED_WORKFLOW_TOOL)
69
68
  return args;
70
- return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && key !== ASKED_BECAUSE && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
69
+ return { ...shown, ...Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => !(shown && Object.hasOwn(shown, key)) && !(tool === LEARNED_WORKFLOW_TOOL && LEARNED_CARD_FIELDS.has(key)))) };
71
70
  }
72
71
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
73
72
  const COMMAND_REQUEST_PREFIX = commandRequest(0).replace(/0$/, "");
@@ -2003,6 +2002,7 @@ function adapterLoop(specOf, options, deps) {
2003
2002
  return { text: given.deny, isError: true };
2004
2003
  // An ask with its card's own fields is an ask, its card as the gate shows it.
2005
2004
  const shown = typeof given === "object" ? given.ask : undefined;
2005
+ const because = typeof given === "object" ? given.because : undefined;
2006
2006
  const now = shown ? "ask" : given;
2007
2007
  // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
2008
2008
  // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
@@ -2010,7 +2010,7 @@ function adapterLoop(specOf, options, deps) {
2010
2010
  // the setting at allow now: the setting answers the ask (allowedBySetting).
2011
2011
  const bySetting = now === "allow" && (await askStands(toolContext.callId));
2012
2012
  if (now === "ask" || bySetting) {
2013
- const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})) };
2013
+ const call = { callId: toolContext.callId, tool: name, args: cardOf(name, shown, (args ?? {})), ...(because !== undefined ? { because } : {}) };
2014
2014
  const price = mcp?.priceOf(name) ?? null;
2015
2015
  const answer = bySetting ? await allowedBySetting(call, price, asked) : await answerOf(call, price, asked);
2016
2016
  if (answer === "park")
@@ -3066,8 +3066,10 @@ function adapterLoop(specOf, options, deps) {
3066
3066
  // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
3067
3067
  const replayed = call.replayed === true;
3068
3068
  const given = (await spec.gate?.(kernelCall, { ...(replayed ? { replayed } : {}), ran: ranOf })) ?? "allow";
3069
- // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape).
3069
+ // An ask with its card's own fields (a learned workflow's MCP actions set to ask, each with its arguments' shape), or
3070
+ // with the reason a call its setting allows asks anyway (`because`).
3070
3071
  const shown = typeof given === "object" && "ask" in given ? given.ask : undefined;
3072
+ const because = typeof given === "object" && "ask" in given ? given.because : undefined;
3071
3073
  let decision = shown ? "ask" : given;
3072
3074
  // A call nested in a learned_workflow call a person approved, of an MCP tool that call's card named: its ask is
3073
3075
  // answered by that approval, as the card they saw named it (never one built again now). Any other asks for itself.
@@ -3113,7 +3115,8 @@ function adapterLoop(specOf, options, deps) {
3113
3115
  // Marked destructive when the tool is, or when any MCP tool the one allow lets run is (the card's `mcp_calls`, a
3114
3116
  // learned workflow's MCP actions set to ask): that allow takes the second confirm too.
3115
3117
  const destructive = [asked, ...learnedApprovedTools(shown)].some((name) => mcp?.effectOf(name) === "destructive");
3116
- const answer = bySetting ? await allowedBySetting({ ...call, tool, args }, price, asked) : await answerOf({ ...call, tool, args }, price, asked, destructive);
3118
+ const card = { ...call, tool, args, ...(because !== undefined ? { because } : {}) };
3119
+ const answer = bySetting ? await allowedBySetting(card, price, asked) : await answerOf(card, price, asked, destructive);
3117
3120
  if (answer === "park")
3118
3121
  return { park: true };
3119
3122
  if (answer.approved)
@@ -3152,7 +3155,7 @@ function adapterLoop(specOf, options, deps) {
3152
3155
  // run's pending approval, its approval row, an "always" answer pinned by it) has the one name main gives it.
3153
3156
  // An MCP tool its run's pin marks destructive (ClaimMcp.effectOf), or a call whose allow covers one (`destructive`):
3154
3157
  // its card asks a second confirm of an allow.
3155
- const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
3158
+ const ask = first ?? { callId: call.callId, tool: asked, args: call.args ?? null, ...(call.because !== undefined ? { because: call.because } : {}), requestedAt: isoNow(), price, ...(destructive ? { destructive: true } : {}) };
3156
3159
  const entryLands = (kind, data, staged) => landEntry(conversation, kind, data, staged);
3157
3160
  if (first === undefined) {
3158
3161
  // Asked and parked; or held as the parked call is, when another call of the round parked the run first.
@@ -186,7 +186,7 @@ export declare function modelRetryOf(routes: Iterable<Pick<ModelRoute, "like">>)
186
186
  export declare function graderRouteOf(body: {
187
187
  readonly modelTiers?: Readonly<Partial<Record<SubagentTier, string>>>;
188
188
  readonly learning?: unknown;
189
- }, keyed: boolean, runKey: ClaimModelKey | undefined, claimed: NodeJS.ProcessEnv, cut: HeldRedact, log: (line: string) => void, deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "env" | "routeOf">, holds?: readonly HeldRedact[]): Promise<ModelRoute | undefined>;
189
+ }, keyed: boolean, runKey: ClaimModelKey | undefined, claimed: NodeJS.ProcessEnv, cut: HeldRedact, log: (line: string) => void, deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "env" | "routeOf">, holds?: readonly HeldRedact[], claim?: Pick<Claim, "runId" | "turn" | "attempt">): Promise<ModelRoute | undefined>;
190
190
  /** What the runner routes a claimed run on: the launch's model as its start pinned it, sent as pinned, with the
191
191
  * revision's own ref beside it (main prices a gateway's id by the provider that ref names); the revision's ref alone
192
192
  * when the start pinned none. Never the pin's provider and id joined into a ref: a gateway refuses the joined id, and