@parcha/agentrun-serve 0.1.0-beta.47 → 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 (185) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/README.md +218 -20
  3. package/dist/acp-package.d.ts +24 -6
  4. package/dist/adapter-facts.d.ts +0 -4
  5. package/dist/adapter-facts.js +1 -4
  6. package/dist/adapters.d.ts +3 -12
  7. package/dist/adapters.js +1 -70
  8. package/dist/agent-delete.d.ts +33 -10
  9. package/dist/agent-delete.js +184 -26
  10. package/dist/agents-store.d.ts +6 -2
  11. package/dist/agents-store.js +18 -5
  12. package/dist/agents.d.ts +8 -1
  13. package/dist/agents.js +14 -4
  14. package/dist/answer-json.d.ts +10 -0
  15. package/dist/answer-json.js +23 -0
  16. package/dist/api-only.d.ts +5 -2
  17. package/dist/api-only.js +10 -2
  18. package/dist/archil-routes.d.ts +1 -1
  19. package/dist/archil-routes.js +4 -3
  20. package/dist/browser-live.d.ts +9 -4
  21. package/dist/browser-live.js +18 -5
  22. package/dist/browser-sessions.d.ts +56 -0
  23. package/dist/browser-sessions.js +117 -0
  24. package/dist/cap.js +7 -9
  25. package/dist/cli.js +6 -6
  26. package/dist/computer-routes.d.ts +6 -14
  27. package/dist/computer-routes.js +8 -10
  28. package/dist/computers.d.ts +6 -2
  29. package/dist/computers.js +4 -2
  30. package/dist/conformance.d.ts +4 -0
  31. package/dist/conformance.js +6 -0
  32. package/dist/console/assets/index-Bzn4eUYF.js +715 -0
  33. package/dist/console/assets/index-CR2ZGei1.css +1 -0
  34. package/dist/console/index.html +2 -2
  35. package/dist/errors.d.ts +4 -1
  36. package/dist/errors.js +15 -5
  37. package/dist/harness-check.d.ts +3 -1
  38. package/dist/harness-check.js +99 -70
  39. package/dist/harness-cursor.d.ts +10 -27
  40. package/dist/harness-cursor.js +5 -84
  41. package/dist/harness-goose.d.ts +4 -29
  42. package/dist/harness-goose.js +6 -86
  43. package/dist/harness-module.d.ts +4 -0
  44. package/dist/harness-module.js +1 -0
  45. package/dist/harness-owned.d.ts +52 -0
  46. package/dist/harness-owned.js +92 -0
  47. package/dist/harness-recipe.js +2 -24
  48. package/dist/harness-table.d.ts +109 -6
  49. package/dist/harness-table.js +242 -28
  50. package/dist/harness.js +2 -2
  51. package/dist/import.js +4 -3
  52. package/dist/key-refusal.d.ts +2 -1
  53. package/dist/key-refusal.js +18 -2
  54. package/dist/learn/check.d.ts +11 -2
  55. package/dist/learn/check.js +12 -9
  56. package/dist/learn/promote.d.ts +18 -1
  57. package/dist/learn/promote.js +47 -0
  58. package/dist/learn/repick.d.ts +34 -0
  59. package/dist/learn/repick.js +201 -0
  60. package/dist/learn/secrets.d.ts +4 -0
  61. package/dist/learn/secrets.js +23 -0
  62. package/dist/learned-workflow.d.ts +2 -0
  63. package/dist/learned-workflow.js +18 -1
  64. package/dist/learning-model.d.ts +18 -0
  65. package/dist/learning-model.js +77 -0
  66. package/dist/learning-setting.d.ts +13 -0
  67. package/dist/learning-setting.js +23 -1
  68. package/dist/llms.txt +1 -0
  69. package/dist/model-form.js +12 -12
  70. package/dist/model.d.ts +5 -4
  71. package/dist/model.js +19 -13
  72. package/dist/openapi.js +203 -15
  73. package/dist/page.d.ts +1 -0
  74. package/dist/page.js +1 -1
  75. package/dist/paid-calls.d.ts +4 -1
  76. package/dist/paid-calls.js +1 -1
  77. package/dist/run-learning-served.d.ts +1 -1
  78. package/dist/run-secrets.d.ts +2 -2
  79. package/dist/run-secrets.js +6 -5
  80. package/dist/run-trace.js +6 -3
  81. package/dist/run-usage.d.ts +110 -0
  82. package/dist/run-usage.js +312 -0
  83. package/dist/runner/adapter-loop.d.ts +4 -1
  84. package/dist/runner/adapter-loop.js +52 -22
  85. package/dist/runner/adapter-run-spec.d.ts +3 -2
  86. package/dist/runner/adapter-run-spec.js +8 -4
  87. package/dist/runner/adapters/index.d.ts +4 -2
  88. package/dist/runner/adapters/index.js +6 -42
  89. package/dist/runner/cli-run-spec.js +10 -6
  90. package/dist/runner/conformance/harness.d.ts +2 -0
  91. package/dist/runner/conformance/harness.js +18 -4
  92. package/dist/runner/conformance/host-tools.d.ts +4 -0
  93. package/dist/runner/conformance/host-tools.js +14 -0
  94. package/dist/runner/feedback-round.d.ts +29 -1
  95. package/dist/runner/feedback-round.js +54 -3
  96. package/dist/runner/journal-kinds.d.ts +3 -1
  97. package/dist/runner/learning-end.js +49 -18
  98. package/dist/runner/loop-contract.d.ts +3 -0
  99. package/dist/runner/meta-tools.js +4 -2
  100. package/dist/runner/monid-run.js +2 -2
  101. package/dist/runner/presence.d.ts +3 -0
  102. package/dist/runner/presence.js +19 -12
  103. package/dist/runner/promotion.d.ts +62 -4
  104. package/dist/runner/promotion.js +154 -17
  105. package/dist/runner/reflect-hook.js +3 -2
  106. package/dist/runner/sdk-loop.js +25 -1
  107. package/dist/runner/workflow-spec.js +3 -2
  108. package/dist/runs-over-store.d.ts +5 -3
  109. package/dist/runs-over-store.js +11 -11
  110. package/dist/sdk/check.d.ts +31 -0
  111. package/dist/sdk/check.js +58 -0
  112. package/dist/sdk/runs.d.ts +10 -2
  113. package/dist/sdk/runs.js +87 -17
  114. package/dist/sdk/schema.js +11 -3
  115. package/dist/server.d.ts +6 -3
  116. package/dist/server.js +297 -98
  117. package/dist/store/index.d.ts +2 -2
  118. package/dist/store/index.js +1 -1
  119. package/dist/store/journal/storage.js +1 -1
  120. package/dist/store/open.d.ts +1 -1
  121. package/dist/store/open.js +1 -1
  122. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  123. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  124. package/dist/store/schema.d.ts +15 -1
  125. package/dist/store/schema.js +50 -5
  126. package/dist/store/sqlite/connection.d.ts +4 -1
  127. package/dist/store/sqlite/connection.js +5 -0
  128. package/dist/store/sqlite/run-patch.d.ts +8 -3
  129. package/dist/store/sqlite/run-patch.js +15 -7
  130. package/dist/store/sqlite/store.d.ts +5 -2
  131. package/dist/store/sqlite/store.js +283 -77
  132. package/dist/store/sqlite/worker.d.ts +9 -0
  133. package/dist/store/sqlite/worker.js +18 -1
  134. package/dist/store/store.d.ts +162 -27
  135. package/dist/store/store.js +63 -0
  136. package/dist/store-reads/analytics.js +2 -1
  137. package/dist/store-reads/cap.d.ts +8 -2
  138. package/dist/store-reads/cap.js +27 -3
  139. package/dist/store-reads/learning.d.ts +1 -1
  140. package/dist/store-reads/learning.js +5 -2
  141. package/dist/store-reads/runs.js +2 -0
  142. package/dist/store-reads/stats.js +4 -2
  143. package/dist/store-view.d.ts +12 -3
  144. package/dist/store-view.js +70 -27
  145. package/dist/template-eval.js +5 -2
  146. package/dist/template-github-permissions.d.ts +5 -1
  147. package/dist/template-github-permissions.js +7 -3
  148. package/dist/timeline/index.d.ts +1 -1
  149. package/dist/timeline/index.js +1 -1
  150. package/dist/timeline/timeline.d.ts +8 -0
  151. package/dist/timeline/timeline.js +18 -6
  152. package/dist/tool-gate.d.ts +8 -4
  153. package/dist/tool-gate.js +6 -7
  154. package/dist/tool-plane.d.ts +4 -0
  155. package/dist/tool-plane.js +10 -10
  156. package/dist/tools.js +9 -0
  157. package/dist/trigger-targets.d.ts +14 -2
  158. package/dist/trigger-targets.js +73 -4
  159. package/dist/triggers.d.ts +2 -1
  160. package/dist/triggers.js +5 -2
  161. package/dist/validate.d.ts +4 -2
  162. package/dist/validate.js +18 -4
  163. package/dist/viewer-credential.d.ts +24 -0
  164. package/dist/viewer-credential.js +53 -0
  165. package/dist/workspace/computer-for-claim.d.ts +5 -1
  166. package/dist/workspace/computer-for-claim.js +47 -18
  167. package/dist/workspace/computer-intervals.d.ts +20 -0
  168. package/dist/workspace/computer-intervals.js +49 -0
  169. package/dist/workspace/computer-janitor.d.ts +7 -3
  170. package/dist/workspace/computer-janitor.js +14 -6
  171. package/dist/workspace/computer-kept.d.ts +7 -2
  172. package/dist/workspace/computer-kept.js +9 -2
  173. package/dist/workspace/resolve-computer.d.ts +9 -1
  174. package/dist/workspace/resolve-computer.js +29 -22
  175. package/dist/workspace/run-end-computers.d.ts +1 -0
  176. package/dist/workspace/run-end-computers.js +4 -1
  177. package/package.json +18 -10
  178. package/templates/code-review/agent.md +2 -3
  179. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  180. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  181. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  182. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  183. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  184. package/dist/console/assets/index-BBFzAxLB.js +0 -715
  185. package/dist/console/assets/index-BRi-Rgq6.css +0 -1
package/dist/run-trace.js CHANGED
@@ -14,6 +14,9 @@ const finite = (value) => (typeof value === "number" && Number.isFinite(value) ?
14
14
  const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
15
15
  /** A time as the rows write theirs; undefined for one no Date holds. */
16
16
  const iso = (ms) => (Math.abs(ms) <= 8.64e15 ? new Date(ms).toISOString() : undefined);
17
+ /** An amount with a sum's floating-point noise off (0.1 + 0.2 is 0.3, not 0.30000000000000004), to a millionth of a
18
+ * millionth of a dollar: far below any price, so no cost is rounded away. Every span's cost is written through it. */
19
+ const noiseOff = (usd) => Math.round(usd * 1e12) / 1e12;
17
20
  const STOP_REASONS = new Set(["stop", "length", "toolUse", "error", "aborted", "deferred", "pending"]);
18
21
  /** An answer's tokens, by the usage row's rule (timeline tokensOf): all four known, and some input unless it failed. */
19
22
  function tokensOf(usage, failed) {
@@ -104,7 +107,7 @@ export function traceSpans(rows, entries, options = {}) {
104
107
  stop_reason: typeof message.stopReason === "string" && STOP_REASONS.has(message.stopReason) ? message.stopReason : null,
105
108
  // A request cut before its end reported no final usage and no cost (the usage row counts it unknown).
106
109
  tokens: aborted ? null : tokensOf(message.usage, failed),
107
- usd: booked || aborted || total === undefined || total < 0 ? null : total, decision: false,
110
+ usd: booked || aborted || total === undefined || total < 0 ? null : noiseOff(total), decision: false,
108
111
  charged: false, not_metered: false, tool_use_id: null, input_preview: null, result_preview: null, result_size_bytes: null,
109
112
  });
110
113
  }
@@ -128,7 +131,7 @@ export function traceSpans(rows, entries, options = {}) {
128
131
  stop_reason: null,
129
132
  // A receipt keeps its input whole, with no split by cache.
130
133
  tokens: input !== undefined && output !== undefined ? { input, cache_read: 0, cache_write: 0, output } : null,
131
- usd: cost !== undefined && cost >= 0 ? cost : null, decision: true,
134
+ usd: cost !== undefined && cost >= 0 ? noiseOff(cost) : null, decision: true,
132
135
  charged: false, not_metered: false, tool_use_id: null, input_preview: null, result_preview: null, result_size_bytes: null,
133
136
  });
134
137
  });
@@ -219,7 +222,7 @@ export function traceSpans(rows, entries, options = {}) {
219
222
  at, id: nth === 0 ? `t:${key}` : `t:${key}#${nth + 1}`, kind: "tool", parent_id: parent, name: use.tool_name ?? "tool", agent_label: use.agent_label ?? null,
220
223
  started_at: iso(at) ?? use.timestamp, ended_at: over ? iso(done) ?? null : null, status,
221
224
  stop_reason: null, tokens: null,
222
- usd: charge?.charged ? (charge.unknown ? null : Math.round(charge.known * 1e12) / 1e12) : null,
225
+ usd: charge?.charged ? (charge.unknown ? null : noiseOff(charge.known)) : null,
223
226
  decision: false, charged: charge?.charged ?? false, not_metered: charge?.notMetered ?? false,
224
227
  tool_use_id: use.tool_use_id, input_preview: use.tool_input_preview ?? null,
225
228
  // A call that never ran has no result of its own: what its rows say of it is the Timeline's words, not its output.
@@ -0,0 +1,110 @@
1
+ import { type BrowserSessionLine } from "./browser-sessions.js";
2
+ import { type CostBasis, type CostWords } from "./runner/metrics.js";
3
+ import type { RunLaunch } from "./run-launch.js";
4
+ import { type SignInReader } from "./run-view.js";
5
+ import { type ComputerIntervalRow, type Store } from "./store/index.js";
6
+ import { type EntryLike } from "./timeline/index.js";
7
+ /** The meters a run's lines are on: the contract's `tokens` and `browser_time`, and this server's `tools`. */
8
+ export type UsageMeter = "tokens" | "tools" | "browser_time";
9
+ /** One line of a run's cost: one model, one charger or one browser provider on a meter. Which it is: `model` and
10
+ * `provider` on `tokens` (the model the requests were sent on; the provider they went to, named only when the server
11
+ * sent them there itself, null behind a gateway, whose upstream the server does not know), `charged_by` on `tools` (who
12
+ * charged for the calls) and `provider` beside it (the same name: the vendor that charges for a call is its provider),
13
+ * `provider` on `browser_time`; every other one null, and null where the record names none, never "". `quantity` in `unit`: tokens
14
+ * (input, cache read, cache write and output, as each request reported them), charges booked (one per paid call), or
15
+ * seconds of browser session time on this server's clock, unrounded; null when none was measured. `usd` and its words
16
+ * are the cost block's (CostWords): null when a charge is unknown, with `so_far_usd` and `unpriced` beside it;
17
+ * `upper_bound` when a cut request counts at its hold. Not the contract's UsageLine (GET /usage's, a sum over many
18
+ * runs by group): a line of one run. */
19
+ export type RunUsageLine = {
20
+ meter: UsageMeter;
21
+ model: string | null;
22
+ provider: string | null;
23
+ charged_by: string | null;
24
+ quantity: number | null;
25
+ unit: "token" | "call" | "second";
26
+ basis: CostBasis;
27
+ requests?: number;
28
+ tokens?: {
29
+ input: number;
30
+ output: number;
31
+ cache_read: number;
32
+ cache_write: number;
33
+ };
34
+ unmetered_requests?: number;
35
+ not_metered_calls?: number;
36
+ } & CostWords;
37
+ /** Why a run has no lines: `running`, it is at work and its booking still moves; `not_booked`, its figure is not its
38
+ * booking's (an imported run's, a native or SDK run's harness's own, a CLI run whose model requests went past its proxy);
39
+ * `reopened`, a learning run a follow-up opened again, whose `cost.usd` is its first round's and whose booking can't be
40
+ * split by round. */
41
+ export type UsageReason = "running" | "not_booked" | "reopened";
42
+ export type RunUsage = {
43
+ run_id: string;
44
+ /** When the run ended: the moment its lines cover. Null while it is at work. A follow-up opens an ended run again
45
+ * (store/sqlite/run-patch.ts REOPEN_SET clears it), and its next end is a later one: a reader that keeps it beside the
46
+ * lines knows from a later read whether the run moved since. */
47
+ ended_at: string | null;
48
+ currency: "USD";
49
+ /** The lines joined by the one rule (costWordsOf): the run's `cost.usd`, with what is known of it when it is unknown
50
+ * (`so_far_usd`, `unpriced`) and `upper_bound` when it is a bound. Null with no lines. */
51
+ total: CostWords | null;
52
+ lines: RunUsageLine[] | null;
53
+ /** One record per browser session the run opened (browser-sessions.ts), for matching `browser_time` to the provider's
54
+ * own records by its session id; null exactly when `lines` is. */
55
+ browser_sessions: BrowserSessionLine[] | null;
56
+ /** One record per computer the run made (computerIntervalsOf), by when each was made; null exactly when `lines` is.
57
+ * Computer time is not priced: its cost is in no line and not in `total`. */
58
+ computer_intervals: ComputerIntervalLine[] | null;
59
+ reason: UsageReason | null;
60
+ };
61
+ /** One computer the run made through its provider (a sandbox, a desktop, a phone), as GET /runs/{run_id}/usage serves
62
+ * it: the provider (this server's id for it) and the provider's own id for the computer, its kind, what its create asked
63
+ * for (null where it asked none: a hosted vendor sizes its own), when it was made, when its provider's delete answered ok
64
+ * (`ended_at`, null while none did: still running, or its delete failed or was never asked), and whether the run's park
65
+ * kept it past its claim. */
66
+ export type ComputerIntervalLine = {
67
+ provider: string;
68
+ provider_id: string;
69
+ kind: string | null;
70
+ gpu: {
71
+ type: string | null;
72
+ count: number | null;
73
+ } | null;
74
+ cpus: number | null;
75
+ memory_mb: number | null;
76
+ started_at: string;
77
+ ended_at: string | null;
78
+ kept: boolean;
79
+ };
80
+ /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
81
+ export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[]): ComputerIntervalLine[];
82
+ /** A workflow decision's receipt as the lines read it (store-reads/decisions.ts): by its `decision_id`, which its
83
+ * request's booking names (`decision:<id>`), the model and provider that answered it, and how its cost was reached. */
84
+ export type DecisionReceiptLike = {
85
+ model?: unknown;
86
+ provider?: unknown;
87
+ cost_basis?: unknown;
88
+ usage?: unknown;
89
+ };
90
+ /** A run's lines from its journal `entries` (every conversation, in log order), its end-of-run turns already left out:
91
+ * its model requests and decisions by model (`tokens`), its paid calls by who charged (`tools`), its browser time by
92
+ * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
93
+ * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
94
+ * (its booking names the decision alone), which this server called itself. */
95
+ export declare function usageLinesOf(entries: readonly EntryLike[], launch?: Pick<RunLaunch, "model">, receipts?: ReadonlyMap<string, DecisionReceiptLike>): {
96
+ lines: RunUsageLine[];
97
+ total: CostWords;
98
+ };
99
+ /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
100
+ * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
101
+ * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
102
+ * of the store (one moment): a follow-up that reopens the run between two reads can't put its requests under its end. */
103
+ export declare function runUsageOverStore(store: Store, runId: string): Promise<RunUsage | undefined>;
104
+ /** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
105
+ * the run's cut, as its trace serves a model's name, since a decision provider or a tool names itself in what it
106
+ * returns. A run withheld (its sign-in can't be read back here) is refused (403), as its trace is. */
107
+ export declare function servedRunUsage(deps: {
108
+ serverSecrets: () => string[];
109
+ signIns?: SignInReader;
110
+ }, store: Store, runId: string): Promise<RunUsage | undefined>;
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { type ConversationId, type ConversationRetryPolicy, type ConversationStreamOptions, Harness, type Tx } from "@earendil-works/pi-durable";
2
- import { type AgentAdapter, type Refusal, type SessionRecord, type SessionSpec } from "@parcha/agentrun-kernel";
2
+ import { type AdapterFacts, type AgentAdapter, type Refusal, type SessionRecord, type SessionSpec } from "@parcha/agentrun-kernel";
3
3
  import type { KernelHooks, ToolCall } from "./conformance/subject.js";
4
4
  import { type BudgetData, type EndData, type ToolCalls } from "./journal-kinds.js";
5
5
  import { type MessageOrigin } from "../timeline/index.js";
@@ -79,6 +79,9 @@ export type SpecGate = ((call: ToolCall, options?: {
79
79
  /** What one claimed run's adapter loop runs. */
80
80
  export interface AdapterRunSpec {
81
81
  readonly adapter: AgentAdapter;
82
+ /** The adapter's facts on the owner's table (harness-table.ts factsOf: a module's harness's too); undefined for one with
83
+ * none. Always given: what codemode and tool search read, so a caller names them. */
84
+ readonly facts: AdapterFacts | undefined;
82
85
  readonly session: SessionSpec;
83
86
  /** The person's first message, sent once, on the run's first claim. */
84
87
  readonly input: string;