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

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 +26 -9
  2. package/README.md +104 -22
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/api-only.d.ts +7 -10
  6. package/dist/api-only.js +9 -11
  7. package/dist/compute-cost.d.ts +101 -0
  8. package/dist/compute-cost.js +250 -0
  9. package/dist/console/assets/{index-CR2ZGei1.css → index-D0mr9wfZ.css} +1 -1
  10. package/dist/console/assets/index-D7G6o-1E.js +720 -0
  11. package/dist/console/index.html +2 -2
  12. package/dist/eval-previous.d.ts +52 -0
  13. package/dist/eval-previous.js +164 -0
  14. package/dist/file-types.d.ts +2 -0
  15. package/dist/file-types.js +3 -1
  16. package/dist/harness.js +2 -1
  17. package/dist/learn/check.d.ts +8 -5
  18. package/dist/learn/check.js +25 -24
  19. package/dist/learn/repick.d.ts +22 -13
  20. package/dist/learn/repick.js +57 -56
  21. package/dist/learn/workflow-draft.d.ts +4 -0
  22. package/dist/learn/workflow-draft.js +10 -7
  23. package/dist/learned-workflow.js +8 -8
  24. package/dist/learning-setting.js +2 -2
  25. package/dist/openapi.js +25 -17
  26. package/dist/paid-calls.d.ts +13 -6
  27. package/dist/paid-calls.js +14 -8
  28. package/dist/run-launch.d.ts +2 -2
  29. package/dist/run-launch.js +2 -1
  30. package/dist/run-timeline-served.js +5 -3
  31. package/dist/run-usage.d.ts +23 -8
  32. package/dist/run-usage.js +100 -18
  33. package/dist/runner/adapter-loop.d.ts +4 -0
  34. package/dist/runner/adapter-loop.js +15 -1
  35. package/dist/runner/adapter-run-spec.d.ts +8 -3
  36. package/dist/runner/adapter-run-spec.js +13 -6
  37. package/dist/runner/big-writes.d.ts +33 -0
  38. package/dist/runner/big-writes.js +105 -0
  39. package/dist/runner/cli-run-spec.js +14 -6
  40. package/dist/runner/held.d.ts +4 -1
  41. package/dist/runner/learning-end.js +9 -4
  42. package/dist/runner/metrics.d.ts +4 -0
  43. package/dist/runner/metrics.js +9 -0
  44. package/dist/runner/run-child-host.d.ts +15 -2
  45. package/dist/runner/run-child-host.js +24 -8
  46. package/dist/runner/run-child.js +3 -0
  47. package/dist/runner/save-slots.d.ts +9 -0
  48. package/dist/runner/save-slots.js +91 -0
  49. package/dist/sdk/runs.d.ts +3 -4
  50. package/dist/sdk/runs.js +10 -7
  51. package/dist/sdk/runtimes.d.ts +19 -0
  52. package/dist/sdk/runtimes.js +23 -0
  53. package/dist/sdk/schema.d.ts +14 -8
  54. package/dist/sdk/schema.js +18 -6
  55. package/dist/server.d.ts +4 -0
  56. package/dist/server.js +3 -3
  57. package/dist/store/agent-body.d.ts +2 -3
  58. package/dist/store/agent-body.js +3 -2
  59. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  60. package/dist/store/schema.d.ts +8 -3
  61. package/dist/store/schema.js +12 -2
  62. package/dist/store/sqlite/connection.d.ts +3 -3
  63. package/dist/store/sqlite/connection.js +3 -3
  64. package/dist/store/sqlite/store.d.ts +2 -4
  65. package/dist/store/sqlite/store.js +95 -85
  66. package/dist/store/store.d.ts +8 -1
  67. package/dist/store-reads/cap.d.ts +9 -5
  68. package/dist/store-reads/cap.js +28 -2
  69. package/dist/store-reads/decisions.d.ts +21 -0
  70. package/dist/store-reads/decisions.js +22 -0
  71. package/dist/store-reads/journal.d.ts +8 -2
  72. package/dist/store-reads/journal.js +27 -8
  73. package/dist/store-view.d.ts +5 -1
  74. package/dist/store-view.js +37 -18
  75. package/dist/template-eval.d.ts +15 -1
  76. package/dist/template-eval.js +92 -13
  77. package/dist/templates.d.ts +1 -1
  78. package/dist/templates.js +4 -3
  79. package/dist/timeline/labels.js +17 -0
  80. package/dist/tool-list.js +1 -0
  81. package/dist/tools.d.ts +6 -2
  82. package/dist/tools.js +13 -1
  83. package/dist/trigger-targets.d.ts +21 -5
  84. package/dist/trigger-targets.js +13 -10
  85. package/dist/web-fake.d.ts +25 -0
  86. package/dist/web-fake.js +38 -1
  87. package/dist/web-save.d.ts +75 -0
  88. package/dist/web-save.js +235 -0
  89. package/dist/workspace/archil-claim.d.ts +5 -2
  90. package/dist/workspace/archil-claim.js +5 -2
  91. package/dist/workspace/archil-disk.d.ts +10 -1
  92. package/dist/workspace/archil-disk.js +19 -1
  93. package/dist/workspace/archil.d.ts +3 -0
  94. package/dist/workspace/archil.js +101 -16
  95. package/dist/workspace/computer-for-claim.d.ts +14 -0
  96. package/dist/workspace/computer-for-claim.js +46 -7
  97. package/dist/workspace/computer-intervals.d.ts +9 -3
  98. package/dist/workspace/computer-intervals.js +17 -8
  99. package/dist/workspace/pieced.d.ts +14 -0
  100. package/dist/workspace/pieced.js +23 -0
  101. package/dist/workspace/run-disk.js +32 -12
  102. package/dist/workspace/run-workspace.d.ts +1 -1
  103. package/dist/workspace/run-workspace.js +11 -6
  104. package/package.json +10 -10
  105. package/templates/README.md +36 -7
  106. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
@@ -3,9 +3,11 @@ import { type CostBasis, type CostWords } from "./runner/metrics.js";
3
3
  import type { RunLaunch } from "./run-launch.js";
4
4
  import { type SignInReader } from "./run-view.js";
5
5
  import { type ComputerIntervalRow, type Store } from "./store/index.js";
6
+ import { type ComputeResource, type ComputeUnit } from "./compute-cost.js";
6
7
  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";
8
+ /** The meters a run's lines are on: the contract's `tokens` and `browser_time`, and this server's `tools` and
9
+ * `compute_time`. */
10
+ export type UsageMeter = "tokens" | "tools" | "browser_time" | "compute_time";
9
11
  /** One line of a run's cost: one model, one charger or one browser provider on a meter. Which it is: `model` and
10
12
  * `provider` on `tokens` (the model the requests were sent on; the provider they went to, named only when the server
11
13
  * sent them there itself, null behind a gateway, whose upstream the server does not know), `charged_by` on `tools` (who
@@ -22,8 +24,15 @@ export type RunUsageLine = {
22
24
  provider: string | null;
23
25
  charged_by: string | null;
24
26
  quantity: number | null;
25
- unit: "token" | "call" | "second";
27
+ unit: "token" | "call" | "second" | ComputeUnit;
26
28
  basis: CostBasis;
29
+ /** On `compute_time`: the resource (vcpu, memory, gpu, disk), a GPU's type, the part of `quantity` no claim held (in
30
+ * no cost), and how many of its computers are still open, their time counted up to `measured_to`. */
31
+ resource?: ComputeResource;
32
+ gpu_type?: string | null;
33
+ unheld_quantity?: number | null;
34
+ open_computers?: number;
35
+ measured_to?: string;
27
36
  requests?: number;
28
37
  tokens?: {
29
38
  input: number;
@@ -59,10 +68,11 @@ export type RunUsage = {
59
68
  reason: UsageReason | null;
60
69
  };
61
70
  /** 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. */
71
+ * it: the provider (this server's id for it) and the provider's own id for the computer, its kind, what it was made with
72
+ * (its provider's own figures where it gave them, else what its create asked; null where neither says), when it was made,
73
+ * when its provider's delete answered ok (`ended_at`, null while none did: still running, or its delete failed or was
74
+ * never asked), whether the run's park kept it past its claim, and how much of its time a claim of the run booked
75
+ * (`booked_seconds`; the rest is time no claim held). */
66
76
  export type ComputerIntervalLine = {
67
77
  provider: string;
68
78
  provider_id: string;
@@ -73,9 +83,11 @@ export type ComputerIntervalLine = {
73
83
  } | null;
74
84
  cpus: number | null;
75
85
  memory_mb: number | null;
86
+ disk_gb: number | null;
76
87
  started_at: string;
77
88
  ended_at: string | null;
78
89
  kept: boolean;
90
+ booked_seconds: number;
79
91
  };
80
92
  /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
81
93
  export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[]): ComputerIntervalLine[];
@@ -92,7 +104,10 @@ export type DecisionReceiptLike = {
92
104
  * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
93
105
  * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
94
106
  * (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>): {
107
+ export declare function usageLinesOf(entries: readonly EntryLike[], launch?: Pick<RunLaunch, "model">, receipts?: ReadonlyMap<string, DecisionReceiptLike>, computers?: {
108
+ readonly rows: readonly ComputerIntervalRow[];
109
+ readonly at: number;
110
+ }): {
96
111
  lines: RunUsageLine[];
97
112
  total: CostWords;
98
113
  };
package/dist/run-usage.js CHANGED
@@ -6,7 +6,8 @@
6
6
  //
7
7
  // Nothing is measured again. The lines are the run's booking (runner/metrics.ts bookedSpend) split by what each charge
8
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
9
+ // for them (`tools`, with the calls that ran unpriced beside them; a decision Parallel answered on its own API is one,
10
+ // Parallel's, beside its web tools' calls), and its browser session time by its provider
10
11
  // (`browser_time`, with the seconds its BROWSER_CHARGED records keep). Each part is read by bookedSpend itself, over the
11
12
  // 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
13
  // lines join (costWordsOf) to `total`, which is the run's `cost.usd`: the same booking outside its end-of-run (learning)
@@ -15,8 +16,12 @@
15
16
  // so (`usd` null, what is known beside it), and a run the server cannot split says why (`reason`) with no lines.
16
17
  //
17
18
  // 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.
19
+ // what it was made with, when it was made and when its provider's delete answered ok (null while none did). Its time is on
20
+ // `compute_time` lines (compute-cost.ts), one per provider and resource (vCPU, memory, a GPU type, disk): the quantity is
21
+ // every second of each such computer of the run's at its figure (an open one's up to the read), and `usd` is what the
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
+ // kept for a follow-up, one deleted after its run, one whose delete failed) is said apart (`unheld_quantity`) and costs
24
+ // nothing on the line or in `total`. A resource with no price is `unpriced`, its `usd` null.
20
25
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
21
26
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
22
27
  import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
@@ -28,7 +33,7 @@ import { journalRecords } from "./runner/journal-reader.js";
28
33
  import { KINDS } from "./runner/journal-kinds.js";
29
34
  import { bookedSpend, costBasisOf, costWordsOf } from "./runner/metrics.js";
30
35
  import { unbookedCli } from "./store-reads/cap.js";
31
- import { decisionsOverStore } from "./store-reads/decisions.js";
36
+ import { booksDecisions, chargedByParallel, decisionsOverStore, PARALLEL_CHARGER, receiptIdOf } from "./store-reads/decisions.js";
32
37
  import { roundsOf } from "./store-reads/learning.js";
33
38
  import { MODEL_PROVIDER } from "./model.js";
34
39
  import { ApiError } from "./errors.js";
@@ -36,6 +41,7 @@ import { redacted } from "./key-refusal.js";
36
41
  import { runCutValues } from "./run-cut.js";
37
42
  import { WITHHELD_SIGN_IN } from "./run-view.js";
38
43
  import { FINAL_STATES } from "./store/index.js";
44
+ import { COMPUTE_TOOL, COMPUTE_UNITS, computeTag, resourcesOf, unmetered } from "./compute-cost.js";
39
45
  import { TOOL_UNMETERED } from "./timeline/index.js";
40
46
  /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
41
47
  export function computerIntervalsOf(rows) {
@@ -46,9 +52,11 @@ export function computerIntervalsOf(rows) {
46
52
  gpu: row.gpuType === null && row.gpuCount === null ? null : { type: row.gpuType, count: row.gpuCount },
47
53
  cpus: row.cpus,
48
54
  memory_mb: row.memoryMb,
55
+ disk_gb: row.diskGb,
49
56
  started_at: new Date(row.startedAt).toISOString(),
50
57
  ended_at: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
51
58
  kept: row.kept,
59
+ booked_seconds: row.bookedMs / 1000,
52
60
  }));
53
61
  }
54
62
  /** `entries` with the run's booked requests (runner.request and runner.turn) left in only where `keep` says so of its
@@ -72,7 +80,7 @@ function joined(parts) {
72
80
  }
73
81
  return { parts: [...parts], requests, unmetered, tokens, priced };
74
82
  }
75
- const ORDER = { tokens: 0, tools: 1, browser_time: 2 };
83
+ const ORDER = { tokens: 0, tools: 1, browser_time: 2, compute_time: 3 };
76
84
  const named = (value) => (typeof value === "string" && value !== "" ? value : null);
77
85
  /** The provider a run's model requests on `model` went to, where this server sent them there itself: the run's own
78
86
  * model's provider (its launch's), on a direct route. Null behind a gateway, whose upstream the server does not know,
@@ -88,18 +96,20 @@ function upstreamOf(model, launch) {
88
96
  * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
89
97
  * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
90
98
  * (its booking names the decision alone), which this server called itself. */
91
- export function usageLinesOf(entries, launch, receipts = new Map()) {
99
+ export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }) {
92
100
  const conversation = (key) => entries.find((e) => e.kind === KINDS.sessionKey && e.data?.key === key)?.data;
93
101
  const paidConv = Number(conversation(TOOL_SESSION)?.conversation ?? Number.NaN);
94
102
  const conv = (e) => Number(e.conversationId);
95
103
  const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
96
104
  // 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
105
  // 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 ?? ""}`;
106
+ const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}`;
99
107
  // 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
108
  // a paid charge's, who charged for it (`charged_by`), on browser_time when it is the browser's session time. A paid
101
109
  // charge settled at its provider's own figure says so on its request (`reported`). A decision's request names the
102
110
  // decision (`decision:<id>`): its receipt names the model and provider that answered it, and how its cost was reached.
111
+ // A decision Parallel answered on its own API (chargedByParallel) is a paid call Parallel charged at its list price, on
112
+ // Parallel's `tools` line beside its web tools' calls, not a model's tokens: it is on one line, never on both.
103
113
  const groups = new Map();
104
114
  const reported = new Set();
105
115
  const estimated = new Set();
@@ -109,10 +119,15 @@ export function usageLinesOf(entries, launch, receipts = new Map()) {
109
119
  if (e.kind !== RUNNER_RECORDS.request)
110
120
  continue;
111
121
  const d = (e.data ?? {});
122
+ // A computer's time (compute-cost.ts) by its provider and resource (its tag); a browser's by its provider.
112
123
  if (conv(e) === paidConv)
113
- groups.set(turnOf(e), { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by) });
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) });
114
125
  else if (named(d.model)?.startsWith("decision:")) {
115
126
  const receipt = receipts.get(String(d.model).slice("decision:".length));
127
+ if (receipt && chargedByParallel(receipt)) {
128
+ groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER });
129
+ continue;
130
+ }
116
131
  // A receipt that names no model leaves `model` null: its provider is said as the provider, never as a model.
117
132
  groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider) } : { meter: "tokens", name: null, provider: null });
118
133
  if (receipt?.cost_basis === "reported")
@@ -173,10 +188,19 @@ export function usageLinesOf(entries, launch, receipts = new Map()) {
173
188
  found.set(keyOf(group), group);
174
189
  }
175
190
  const lines = [];
191
+ /** What the ledger booked for each computer provider and resource (computeLinesOf), by its line's key. */
192
+ const computeBooked = new Map();
176
193
  for (const group of found.values()) {
177
194
  const key = keyOf(group);
178
195
  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")]);
196
+ // A `tools` line's part holds its charger's paid calls and, on Parallel's, the decisions Parallel charged.
197
+ const booked = joined(group.meter === "tokens" ? [bookedSpend(part, "model"), bookedSpend(part, "decisions")] : group.meter === "tools" ? [bookedSpend(part, "paid"), bookedSpend(part, "decisions")] : [bookedSpend(part, "paid")]);
198
+ if (group.meter === "compute_time") {
199
+ // A hold for a stretch names no resource (no tag) and books nothing: it is given back.
200
+ if (group.tag !== null && group.tag !== undefined)
201
+ computeBooked.set(computeKey(group.name ?? "", group.tag), booked);
202
+ continue;
203
+ }
180
204
  const notMetered = unpricedCalls.get(key);
181
205
  // A part whose every request was given back (never sent) used nothing: no line, unless calls ran on it unpriced.
182
206
  if (booked.requests === 0 && group.meter !== "browser_time" && !notMetered)
@@ -196,7 +220,8 @@ export function usageLinesOf(entries, launch, receipts = new Map()) {
196
220
  }
197
221
  else if (group.meter === "tools") {
198
222
  // `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).
223
+ // charged); `estimate` when any was settled at a price this server holds (an MCP tool's owner's, Parallel's, a
224
+ // Parallel decision's list price).
200
225
  const basis = priced <= 0 ? "unpriced" : turns.every((turn) => reported.has(turn)) ? "reported" : "estimate";
201
226
  // Calls that ran unpriced only: none booked, so nothing is charged on the line, by its owner's choice of no price.
202
227
  const words = booked.requests === 0 ? { usd: 0 } : costWordsOf(booked.parts);
@@ -213,8 +238,16 @@ export function usageLinesOf(entries, launch, receipts = new Map()) {
213
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 });
214
239
  }
215
240
  }
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 ?? "");
241
+ lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked));
242
+ // Each meter by its name (a model, a charger, a browser provider; none first), `tokens` then by its route's provider,
243
+ // `compute_time` then by its resource in compute-cost.ts's order and a GPU's type.
244
+ const sortKey = (line) => line.meter === "tokens"
245
+ ? `${line.model ?? ""}\u0000${line.provider ?? ""}`
246
+ : line.meter === "tools"
247
+ ? line.charged_by ?? ""
248
+ : line.meter === "compute_time"
249
+ ? `${line.provider ?? ""}\u0000${RESOURCE_ORDER[line.resource ?? "vcpu"]}\u0000${line.gpu_type ?? ""}`
250
+ : line.provider ?? "";
218
251
  lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0));
219
252
  // The join over the whole booking, never the lines' rounded figures: the same figure cost.usd is. A browser line whose
220
253
  // time no charge booked is unknown beside it: the total is too, with the booking's figure as what is known.
@@ -225,6 +258,54 @@ export function usageLinesOf(entries, launch, receipts = new Map()) {
225
258
  const known = total.usd ?? total.so_far_usd ?? 0;
226
259
  return { lines, total: { usd: null, so_far_usd: known, unpriced: (total.usd === null ? (total.unpriced ?? 0) : 0) + unbooked } };
227
260
  }
261
+ /** A compute line's key: its provider and its resource's tag (computeTag). */
262
+ const computeKey = (provider, tag) => `${provider}\u0000${tag}`;
263
+ const RESOURCE_ORDER = { vcpu: 0, memory: 1, gpu: 2, disk: 3 };
264
+ /** Up to the millionth, as the browser's seconds are. */
265
+ const micro = (value) => Math.round(value * 1e6) / 1e6;
266
+ /** The run's `compute_time` lines: one per provider and resource of the computers it made (`rows`), each second of each at
267
+ * 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
+ * `unheld_quantity`. Its money is what the run's ledger booked for it (`booked`, by computeKey): `estimate` when any was;
269
+ * $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) {
271
+ const sums = new Map();
272
+ for (const row of rows) {
273
+ const livedS = Math.max(0, (row.endedAt ?? at) - row.startedAt) / 1000;
274
+ 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);
283
+ }
284
+ }
285
+ // 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()) {
287
+ if (sums.has(key))
288
+ continue;
289
+ const [provider = "", tag = ""] = key.split("\u0000");
290
+ const gpu = tag.startsWith("gpu:");
291
+ const resource = (gpu ? "gpu" : tag);
292
+ if (!Object.hasOwn(COMPUTE_UNITS, resource))
293
+ continue;
294
+ sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0 });
295
+ }
296
+ return [...sums.entries()].map(([key, sum]) => {
297
+ const spend = booked.get(key);
298
+ const charged = spend !== undefined && spend.requests > 0;
299
+ const free = !charged && unmetered(sum.provider);
300
+ const words = charged ? costWordsOf(spend.parts) : free ? { usd: 0 } : { usd: null };
301
+ return {
302
+ 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,
304
+ resource: sum.resource, gpu_type: sum.gpuType, unheld_quantity: sum.unheld === null ? null : micro(sum.unheld), open_computers: sum.open,
305
+ ...(sum.open > 0 ? { measured_to: new Date(at).toISOString() } : {}),
306
+ };
307
+ });
308
+ }
228
309
  /** The run's own browser sessions: those its job opened or charged (`job`, the journal less the end-of-run learning
229
310
  * turn), each with its end read from the whole journal (`all`). The run's end lets its browsers go inside the learning
230
311
  * turn's range (reflectRanges runs to the run's end), so an end read from `job` alone would be missing for a session
@@ -263,11 +344,12 @@ export async function runUsageOverStore(store, runId) {
263
344
  const turns = reflectRanges(records.submissions ?? [], records.entries);
264
345
  const entries = records.entries.filter((entry) => !inReflect(turns, Number(entry.id)));
265
346
  // 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)) : [];
347
+ const receipts = booksDecisions(entries) ? new Map((await decisionsOverStore(snapshot, runId, BACKGROUND_CONTEXT)).map((receipt) => [receiptIdOf(receipt), receipt])) : undefined;
348
+ // 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
+ // as none made.
350
+ 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);
271
353
  return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries), computer_intervals: computers, reason: null };
272
354
  });
273
355
  }
@@ -298,7 +380,7 @@ export async function servedRunUsage(deps, store, runId) {
298
380
  });
299
381
  return {
300
382
  ...usage,
301
- lines: usage.lines.map((line) => ({ ...line, model: said(line.model), provider: said(line.provider), charged_by: said(line.charged_by) })),
383
+ lines: usage.lines.map((line) => ({ ...line, model: said(line.model), provider: said(line.provider), charged_by: said(line.charged_by), ...(line.gpu_type === undefined ? {} : { gpu_type: said(line.gpu_type) }) })),
302
384
  browser_sessions: usage.browser_sessions && usage.browser_sessions.map(session),
303
385
  // A computer's words too: its provider's id for it is the provider's, which a run's own tools can name.
304
386
  computer_intervals: usage.computer_intervals && usage.computer_intervals.map((one) => ({
@@ -319,6 +319,10 @@ export interface RunLedger {
319
319
  /** The store's flush (what the runner's flush before a side effect runs): a record a tool writes during its call that
320
320
  * must be on disk before the call's next step leaves the box (a browser session's open, before its vendor is asked). */
321
321
  flush(): Promise<void>;
322
+ /** Whether the run's cap can judge a paid step now. False while the run's spec is built (its cap is the spec's): a paid
323
+ * step asked then waits for the spec, so a step the build itself waits on (a computer's hold before its create,
324
+ * compute-cost.ts) is not asked until this is true. Absent: it always can. */
325
+ judges?(): boolean;
322
326
  }
323
327
  /** pi's retry of a model request that failed in a way it retries (a provider's 429, overload or 5xx, a dropped connection,
324
328
  * a stream cut mid-answer): up to 8 more attempts, 2s doubling to at most 30s apart (about two and a half minutes in all),
@@ -1391,7 +1391,15 @@ function adapterLoop(specOf, options, deps) {
1391
1391
  const decisionsOf = () => (decisionsOpen ??= sessions.open(DECISION_SESSION).then((w) => theCap().decisions(w, flushed)).then((d) => (decisionsReady = d)));
1392
1392
  let paidReady;
1393
1393
  let paidOpen;
1394
- const paidOf = () => (paidOpen ??= sessions.open(TOOL_SESSION).then((w) => theCap().tools(w, flushed)).then((p) => (paidReady = p)));
1394
+ // The run's cap is its spec's (theCap): a paid step asked while the spec is still built (a computer's time, metered
1395
+ // from its create, compute-cost.ts) waits for it, and fails as the spec's build does. `capJudges` says whether it
1396
+ // can judge now, so a caller inside the build never waits on itself.
1397
+ let capJudges = false;
1398
+ let specBuilt;
1399
+ let specFailed;
1400
+ const specSet = new Promise((resolve, reject) => ((specBuilt = resolve), (specFailed = reject)));
1401
+ specSet.catch(() => undefined);
1402
+ const paidOf = () => (paidOpen ??= specSet.then(() => sessions.open(TOOL_SESSION)).then((w) => theCap().tools(w, flushed)).then((p) => (paidReady = p)));
1395
1403
  /** The pause of a paid call the cap refused (ledger.pause), set once the claim's booking is: below. */
1396
1404
  let pauseFor;
1397
1405
  const ledger = {
@@ -1414,6 +1422,7 @@ function adapterLoop(specOf, options, deps) {
1414
1422
  await pauseFor?.(refusal);
1415
1423
  },
1416
1424
  flush: () => deps.flush(),
1425
+ judges: () => capJudges,
1417
1426
  };
1418
1427
  // A phase of the host's, on the run's timeline while its step runs. Said before the root exists (the claim's computer
1419
1428
  // waiting on its image build, inside specOf), it makes the root then, the row in its creating commit (above), so a
@@ -1455,6 +1464,8 @@ function adapterLoop(specOf, options, deps) {
1455
1464
  spec = await specOf(claim, runOf);
1456
1465
  }
1457
1466
  catch (error) {
1467
+ // A paid step that waited on the spec (paidOf) fails with it: nothing was booked.
1468
+ specFailed(error);
1458
1469
  if (error instanceof Fenced)
1459
1470
  return await interrupted("its claim was lost while its MCP credentials were made fresh");
1460
1471
  if (error instanceof McpClaimRefused)
@@ -1479,6 +1490,9 @@ function adapterLoop(specOf, options, deps) {
1479
1490
  mcp = spec.mcp;
1480
1491
  specNow = spec;
1481
1492
  specKnown = true;
1493
+ // The run's cap can judge from here: a paid step that waited on the spec goes on.
1494
+ capJudges = true;
1495
+ specBuilt();
1482
1496
  // The spec's resources are the pass's from here: a claim lost in any write below still lets them go (closeSession).
1483
1497
  releaseNow = spec.release;
1484
1498
  // A root a phase made while the spec was built (on this claim or an earlier one lost before this point) took none
@@ -11,6 +11,7 @@ import type { Store } from "../store/store.js";
11
11
  import { type ArgumentsOf, type Permission, type RunFiles, type SettingFrom, type ToolEffect } from "../tool-gate.js";
12
12
  import { loadToolSettings } from "../tool-plane.js";
13
13
  import { type EmailFake, type ToolHost } from "../tools.js";
14
+ import type { SaveSlots } from "../web-save.js";
14
15
  import type { WebFake } from "../web-fake.js";
15
16
  import { type HostToolCtx } from "../host-tools.js";
16
17
  import { type LearnedWorkflow } from "../learning.js";
@@ -108,8 +109,8 @@ export interface AdapterSpecDeps {
108
109
  readonly computerDeps: ComputerDeps;
109
110
  /** A Mode 2 claim's Archil disk (a test's fake); absent, the real disk the Archil settings name. */
110
111
  readonly makeArchilDisk?: ArchilClaimOptions["makeDisk"];
111
- /** The Archil mount credential's control plane, for a test's loopback fake (archilControlFake): its base URL and the
112
- * fetch to call it with, spread into the claim's mount. Absent, the real control plane the mount credential names. No
112
+ /** Archil's control plane, for a test's loopback fake (archilControlFake): its base URL and the fetch to call it with,
113
+ * the claim's control (where the run's disk is read and its mount credential minted). Absent, the region's own. No
113
114
  * test ever reaches the real Archil control plane. */
114
115
  readonly mountControl?: {
115
116
  readonly baseUrl?: string;
@@ -155,8 +156,10 @@ export interface AdapterSpecDeps {
155
156
  * on purpose does not wait out MODEL_RETRY's two and a half minutes. No environment variable, flag or setting maps onto
156
157
  * it; absent, MODEL_RETRY and MODEL_STREAM. */
157
158
  readonly modelRetry?: Pick<AdapterLoopOptions, "retry" | "stream">;
159
+ /** web_save's download slots (ToolHost.saveSlots): in a run's own process, its runner's (run-child.ts). */
160
+ readonly saveSlots?: SaveSlots;
158
161
  }
159
- /** One run's template eval fakes (template-eval.ts, from its case). `web`: its web_search and web_fetch answer from the
162
+ /** One run's template eval fakes (template-eval.ts, from its case). `web`: its web_search, web_fetch and web_save answer from the
160
163
  * case, and its harness's own search is never offered (web-fake.ts, fakedPlane). `now`: its clock, the date and time it
161
164
  * is told wherever it reads "now" (environment.ts environmentLine, claude-agent's turn date); absent, the real clock.
162
165
  * `monid`: its monid endpoints answer as monid unreachable does, never sent (monid-run.ts monidForClaim). `email`: the
@@ -347,6 +350,8 @@ export declare function buildToolHost(opts: {
347
350
  readonly own?: readonly string[];
348
351
  /** A runner on another host than its server: where the run's viewers answer, under its run's key (claimLiveAt). */
349
352
  readonly liveAt?: RunnerLive;
353
+ /** web_save's download slots (AdapterSpecDeps.saveSlots). */
354
+ readonly saveSlots?: SaveSlots;
350
355
  }): ToolHost;
351
356
  /** Where the claim's viewers answer on a runner on another host than its server (live-reach.ts runnerLiveOf), under the
352
357
  * claim's run's own proof key (liveForRun); none on the server's machine. In a run's own process its runner's
@@ -293,10 +293,11 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
293
293
  // a 24 h ttl as the safety net if revoke never comes (revoke normally runs at the run's end, below). A run with no
294
294
  // mounting computer never mints one.
295
295
  // The mint is lazy (archil-claim.ts token(), k2's run-tools.ts): only a mounting computer asks for it, so a Mode 2 run
296
- // with no computer makes no control-plane call. mountControl (a test's loopback control-plane fake) is spread into the
297
- // mount, so no test reaches the real control plane. MOUNT_TTL_MS is the credential's safety net (its computer's 24 h bound), not its lifetime.
298
- // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one.
299
- : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
296
+ // with no computer mints nothing. mountControl (a test's loopback control-plane fake) is the claim's control, so no
297
+ // test reaches the real control plane. MOUNT_TTL_MS is the credential's safety net (its computer's 24 h bound), not its lifetime.
298
+ // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one,
299
+ // and read at Archil at every claim.
300
+ : await archilWhereHeld({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS }, ...(deps.mountControl ? { control: deps.mountControl } : {}), run: { agentId: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
300
301
  // Each resource is held the moment it exists (spec-holds.ts): a throw after it lets it go.
301
302
  holds.hold({ archil });
302
303
  // The run's Workspace at the claim: Mode 1 the run's local folder (made here, the server's start made it before); Mode 2
@@ -359,7 +360,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
359
360
  // claim's is a new one whatever ended the earlier claim (a lost runner, a server's stop, a park past its keep). The
360
361
  // computer a park kept, attached again, brings its mount credential with it (inheritMount): none is minted. A
361
362
  // recording of its screen (computer.record) goes in the run's recordings folder, beside its folder, said on its timeline.
362
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
363
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(run.ledger ? { compute: { ledger: { paid: run.ledger.paid, pause: (refusal) => run.ledger.pause(refusal), judges: () => run.ledger.judges?.() ?? true }, env: deps.env } } : {}), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
363
364
  // The run's shell is its computer's (600 s) where one mounts its folder; with none, Archil's serverless exec in Mode 2
364
365
  // (295 s), and in Mode 1 none at all: no bash family, its folder being one of this server's own (run-tools.ts).
365
366
  // A desktop's or a phone's hold (the person's take-over) wraps its ports: a call made while the person holds it waits,
@@ -573,13 +574,18 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
573
574
  // Harness is open before the session, and at the run's end (the browser tool's reconcile and release hang off these). The
574
575
  // adapter loop runs them from the spec's `lifecycle` (adapter-loop.ts hostLifecycle).
575
576
  const life = hostLifecycle();
577
+ // The claim's computers' time booked up to now before the run's end or park is written (compute-cost.ts), so the end's
578
+ // cost holds it: the release that deletes them comes after the end.
579
+ const settleComputers = computer.settle;
580
+ if (settleComputers)
581
+ life.register.beforeRelease(() => settleComputers());
576
582
  // The ToolHost the non-hand tools (browser, web, MCP, decisions, monid) bind through (buildToolHost, the one the CLI
577
583
  // spec builds too), on the claim's keys and the run's one ledger and redactor.
578
584
  // An agent whose computer is a browser the claim started gets the browser tool on that one session (tools.ts).
579
585
  const claimBrowser = computer.computer?.kind === "browser" ? computer.computer.browser : undefined;
580
586
  const fakes = deps.evalFakes?.(runRow.agentId);
581
587
  const liveAt = await claimLiveAt(deps, claim.runId);
582
- const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
588
+ const host = { ...buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: cut, launch, toolSettings: body.toolSettings, ...(fakes ? { fakes } : {}), ...reach, ...(liveAt ? { liveAt } : {}), ...(deps.saveSlots ? { saveSlots: deps.saveSlots } : {}) }), ...(claimBrowser ? { browserComputer: claimBrowser } : {}) };
583
589
  gate.askedOn(host);
584
590
  // The run's tools. The hands (read/write/edit/bash and the background tools) are the kernel registry's over the run's
585
591
  // Workspace and computer (runTools.hostTools); the gate is the adapter loop's own (spec.gate), so they run as asked.
@@ -938,6 +944,7 @@ export function buildToolHost(opts) {
938
944
  ...(email ? { emailFake: email } : {}),
939
945
  ...(opts.loopback ? { calendarLoopback: true } : {}),
940
946
  ...(opts.own ? { serverOwn: opts.own } : {}),
947
+ ...(opts.saveSlots ? { saveSlots: opts.saveSlots } : {}),
941
948
  // The run's directory and its per-claim environment: the hands come from runTools, so the non-hand tools get the run's
942
949
  // environment only.
943
950
  where: { root, work: root, ref: { id: claim.runId } },
@@ -0,0 +1,33 @@
1
+ import { type SaveSlots } from "../web-save.js";
2
+ import type { Pieces } from "../workspace/pieced.js";
3
+ import { type Workspace } from "../workspace/workspace.js";
4
+ export type { Pieces, PullPiece, WritePieces } from "../workspace/pieced.js";
5
+ export { piecedWorkspace } from "../workspace/pieced.js";
6
+ /** The most bytes one piece carries over the channel: well under its MAX_FRAME (32 MiB). A write of at most this many
7
+ * bytes crosses as one call, as before. */
8
+ export declare const PIECE_BYTES: number;
9
+ /** The most bytes one pieced write may have: web_save's cap. */
10
+ export declare const BIG_WRITE_MAX: number;
11
+ /** How long the runner waits for one piece before the write fails. */
12
+ export declare const PIECE_MS = 60000;
13
+ /** The most pieced writes a runner assembles at once, across its runs: with BIG_WRITE_MAX, what they hold in memory. */
14
+ export declare const BIG_WRITES = 4;
15
+ /** The most pieced writes one run may have held or waiting at once: its waiters live in the runner. */
16
+ export declare const BIG_WRITES_PER_RUN = 8;
17
+ /** The runner's one gate for pieced writes. */
18
+ export declare const BIG_WRITE_SLOTS: SaveSlots;
19
+ export type BigWritesOptions = {
20
+ /** Default BIG_WRITE_SLOTS. */
21
+ readonly gate?: SaveSlots;
22
+ /** Default PIECE_BYTES. */
23
+ readonly piece?: number;
24
+ /** Default PIECE_MS. */
25
+ readonly pieceMs?: number;
26
+ };
27
+ /** One run's pieced writes on its runner: `pieces(ws)` is what is handed beside `ws`; `close()`, called when the run's
28
+ * channel ends (or its claim is released), lets every wait and hold of the run go. */
29
+ export interface RunBigWrites {
30
+ pieces(ws: Workspace): Pieces;
31
+ close(): void;
32
+ }
33
+ export declare function runBigWrites(options?: BigWritesOptions): RunBigWrites;
@@ -0,0 +1,105 @@
1
+ // A Workspace write bigger than a channel frame, from a run's own process. In Mode 2 the run's process holds its runner's
2
+ // Workspace of the run's folder by handle (held.ts archil, archil-claim.ts archilWhereHeld), and a call carries all its
3
+ // arguments in one frame of the run's channel (run-channel.ts MAX_FRAME): a write of a file past that would fail after
4
+ // the bytes were made (web_save's download, up to SAVE_MAX_BYTES). So a write of more than one piece does not cross as one
5
+ // call: the runner, handed the length, pulls the bytes from the run's process a piece at a time, each piece of exactly
6
+ // the length it asked for, into one buffer allocated at that length, and makes the one atomic write itself, on the same
7
+ // Workspace the run's process would have written through. A piece that is not the length asked, a length past
8
+ // BIG_WRITE_MAX, the run's signal, a piece not answered in PIECE_MS, or the run's channel ending writes nothing.
9
+ //
10
+ // The runner holds each assembled file in memory until its write returns, so it bounds them: at most BIG_WRITES at once
11
+ // across its runs (BIG_WRITE_SLOTS, a gate of its own, never web_save's download slots, so a run that holds a download
12
+ // slot never waits on itself), the rest waiting under their call's signal, and at most BIG_WRITES_PER_RUN held or waiting
13
+ // per run. Every wait and hold of a run is let go when its channel ends (save-slots.ts does the same for its slots). The
14
+ // runner only copies bytes and calls the Workspace: it reads nothing of them and dials nothing.
15
+ import { ClaimRefused } from "./loop-contract.js";
16
+ import { ChannelClosed } from "./run-channel.js";
17
+ import { saveSlots, SAVE_MAX_BYTES } from "../web-save.js";
18
+ import { WorkspaceError } from "../workspace/workspace.js";
19
+ export { piecedWorkspace } from "../workspace/pieced.js";
20
+ const MIB = 1024 * 1024;
21
+ /** The most bytes one piece carries over the channel: well under its MAX_FRAME (32 MiB). A write of at most this many
22
+ * bytes crosses as one call, as before. */
23
+ export const PIECE_BYTES = 8 * MIB;
24
+ /** The most bytes one pieced write may have: web_save's cap. */
25
+ export const BIG_WRITE_MAX = SAVE_MAX_BYTES;
26
+ /** How long the runner waits for one piece before the write fails. */
27
+ export const PIECE_MS = 60_000;
28
+ /** The most pieced writes a runner assembles at once, across its runs: with BIG_WRITE_MAX, what they hold in memory. */
29
+ export const BIG_WRITES = 4;
30
+ /** The most pieced writes one run may have held or waiting at once: its waiters live in the runner. */
31
+ export const BIG_WRITES_PER_RUN = 8;
32
+ /** The runner's one gate for pieced writes. */
33
+ export const BIG_WRITE_SLOTS = saveSlots(BIG_WRITES);
34
+ /** `work`'s answer, or `signal`'s reason as soon as it aborts. */
35
+ function until(work, signal) {
36
+ if (signal.aborted)
37
+ return Promise.reject(signal.reason);
38
+ return new Promise((resolve, reject) => {
39
+ const abort = () => reject(signal.reason);
40
+ signal.addEventListener("abort", abort, { once: true });
41
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
42
+ });
43
+ }
44
+ export function runBigWrites(options = {}) {
45
+ const gate = options.gate ?? BIG_WRITE_SLOTS;
46
+ const piece = options.piece ?? PIECE_BYTES;
47
+ const pieceMs = options.pieceMs ?? PIECE_MS;
48
+ /** Each write of the run, waiting or held: aborted when the run's channel ends. */
49
+ const live = new Set();
50
+ let closed = false;
51
+ const writeOn = (ws) => async (path, size, pull, signal) => {
52
+ if (closed)
53
+ throw new ChannelClosed("the run's channel ended");
54
+ if (typeof path !== "string")
55
+ throw new TypeError("a pieced write names its path");
56
+ if (!Number.isSafeInteger(size) || size < 0)
57
+ throw new TypeError("a pieced write's size is a whole number of bytes");
58
+ // Before anything is taken or allocated.
59
+ if (size > BIG_WRITE_MAX)
60
+ throw new WorkspaceError("TOO_LARGE", `a write from a run's process is at most ${BIG_WRITE_MAX} bytes, not ${size}`, { path });
61
+ if (typeof pull !== "function")
62
+ throw new TypeError("a pieced write is pulled through a function");
63
+ if (signal !== undefined && !(signal instanceof AbortSignal))
64
+ throw new TypeError("a pieced write runs under the call's signal");
65
+ if (live.size >= BIG_WRITES_PER_RUN)
66
+ throw new ClaimRefused(`this run already has ${BIG_WRITES_PER_RUN} big writes held or waiting`);
67
+ const left = new AbortController();
68
+ live.add(left);
69
+ const under = signal ? AbortSignal.any([signal, left.signal]) : left.signal;
70
+ try {
71
+ const release = await gate.take(under);
72
+ try {
73
+ const bytes = new Uint8Array(size);
74
+ for (let at = 0; at < size;) {
75
+ const want = Math.min(piece, size - at);
76
+ const got = await until(Promise.resolve().then(() => pull(at, want)), AbortSignal.any([under, AbortSignal.timeout(pieceMs)]));
77
+ if (!(got instanceof Uint8Array) || got.length !== want) {
78
+ throw new WorkspaceError("REFUSED", `the piece at ${at} of a write is ${got instanceof Uint8Array ? `${got.length} bytes` : "not bytes"}, not the ${want} asked for: nothing was written`, { path });
79
+ }
80
+ bytes.set(got, at);
81
+ at += want;
82
+ }
83
+ // The run's end while the last piece came: nothing is written for it.
84
+ under.throwIfAborted();
85
+ await ws.write(path, bytes);
86
+ }
87
+ finally {
88
+ release();
89
+ }
90
+ }
91
+ finally {
92
+ live.delete(left);
93
+ }
94
+ };
95
+ return {
96
+ pieces: (ws) => ({ write: writeOn(ws), piece }),
97
+ close() {
98
+ if (closed)
99
+ return;
100
+ closed = true;
101
+ for (const write of live)
102
+ write.abort(new ChannelClosed("the run's channel ended"));
103
+ },
104
+ };
105
+ }