@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
package/dist/server.js CHANGED
@@ -329,7 +329,7 @@ export const ROUTES = [
329
329
  { method: "POST", pattern: /^\/runs$/, name: "createInlineRun" },
330
330
  { method: "GET", pattern: /^\/runs\/([^/]+)$/, name: "getRun" },
331
331
  { method: "PATCH", pattern: /^\/runs\/([^/]+)$/, name: "raiseRunCap" },
332
- // A final run deleted whole, with the runs made from it (agent-delete.ts deleteRun).
332
+ // A run purged, its cost kept, with the runs made from it (agent-delete.ts purgeRun).
333
333
  { method: "DELETE", pattern: /^\/runs\/([^/]+)$/, name: "deleteRun" },
334
334
  { method: "GET", pattern: /^\/runs\/([^/]+)\/timeline$/, name: "getTimeline" },
335
335
  { method: "POST", pattern: /^\/runs\/([^/]+)\/messages$/, name: "sendMessage" },
@@ -2226,7 +2226,7 @@ async function startHolding(options, data, checked, stops) {
2226
2226
  idempotency.delete(slot);
2227
2227
  await keep();
2228
2228
  };
2229
- const deleteInTurn = oneAtATime();
2229
+ const deleteInTurn = oneAtATime(options.deleteTurnQueued);
2230
2230
  /** `work`, a write to agent `id`'s home or learning (files a delete removes with the agent's folders, settings it leaves
2231
2231
  * to deleteLearning, answers kept under its path), done in the agent's delete turn, the agent read there: a write sent
2232
2232
  * while a DELETE runs waits for it, then finds the agent gone (404) or still being deleted (409 agent_not_runnable),
@@ -3095,7 +3095,7 @@ async function startHolding(options, data, checked, stops) {
3095
3095
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
3096
3096
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
3097
3097
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
3098
- const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
3098
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
3099
3099
  return { applied, minted, updated: onto !== undefined };
3100
3100
  }
3101
3101
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -1,3 +1,4 @@
1
+ import { type SdkBinding } from "../sdk/runtimes.js";
1
2
  import type { NativeBinding } from "../native/types.js";
2
3
  import { type LearningSetting } from "../learning-setting.js";
3
4
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
@@ -59,9 +60,7 @@ export type MonidPinBody = Readonly<Record<string, {
59
60
  readonly input: Record<string, unknown>;
60
61
  readonly usd: number | null;
61
62
  }>>;
62
- export type SdkBinding = {
63
- runtime: "claude-agent-sdk" | "codex-sdk" | "eve";
64
- };
63
+ export type { SdkBinding } from "../sdk/runtimes.js";
65
64
  export type AgenticBody = {
66
65
  sdk?: SdkBinding;
67
66
  native?: NativeBinding;
@@ -5,6 +5,7 @@
5
5
  // revision's own row (store schema `revisions`). Everything the old validator accepted it accepts, plus the agent-level
6
6
  // argument `pin` form in tool settings (the lead's ruling): at most 8 arguments mapped to JSON scalars, keys sorted, so
7
7
  // two equal pins are one revision.
8
+ import { sdkBindingOf } from "../sdk/runtimes.js";
8
9
  import { createHash } from "node:crypto";
9
10
  import { nativeBindingOf } from "../native/binding.js";
10
11
  import { learningSettingIssue, learningSettingOf } from "../learning-setting.js";
@@ -127,8 +128,8 @@ export function bodyOf(input) {
127
128
  invalid("the checkout is not pull_request");
128
129
  if (input.modelTiers !== undefined && !(isObject(input.modelTiers) && Object.keys(input.modelTiers).length && Object.entries(input.modelTiers).every(([tier, ref]) => (tier === "fast" || tier === "strong") && typeof ref === "string" && ref !== "")))
129
130
  invalid("the modelTiers are not fast and strong to a non-empty model");
130
- if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime") || !["claude-agent-sdk", "codex-sdk", "eve"].includes(input.sdk.runtime)))
131
- invalid("sdk is {runtime: claude-agent-sdk, codex-sdk or eve}");
131
+ if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime" && key !== "platform") || !sdkBindingOf(input.sdk)))
132
+ invalid("sdk is {runtime: claude-agent-sdk, codex-sdk or eve}, or {runtime: external, platform: a label of 1–80 characters without surrounding whitespace, controls or lone surrogates}");
132
133
  if (input.sdk && input.native)
133
134
  invalid("sdk and native connections are mutually exclusive");
134
135
  const body = {
@@ -0,0 +1,14 @@
1
+ -- The store's schema on Postgres, version 23: a computer's disk and the time its run's claims booked, as store/schema.ts
2
+ -- keeps them on SQLite (COMPUTER_INTERVALS). Applied once, after 0022, inside the transaction migrate.ts opens. Never edit
3
+ -- this file once applied: a change is a new file.
4
+ --
5
+ -- computer_intervals.disk_gb: the computer's disk in GB, where its provider said it; null else (never a guess).
6
+ -- computer_intervals.booked_ms: how much of the computer's time a claim of its run booked on the run's ledger; the rest
7
+ -- of its life is time no claim held (kept for a follow-up, deleted after its run, still running). A row from before this
8
+ -- file has none booked. Each column is added only where missing, so a store whose record of this file was lost applies
9
+ -- it again unharmed.
10
+
11
+ ALTER TABLE computer_intervals ADD COLUMN IF NOT EXISTS disk_gb DOUBLE PRECISION;
12
+ ALTER TABLE computer_intervals ADD COLUMN IF NOT EXISTS booked_ms BIGINT NOT NULL DEFAULT 0 CHECK (booked_ms >= 0);
13
+
14
+ UPDATE store_meta SET schema_version = 23 WHERE singleton = 1;
@@ -42,13 +42,18 @@ export declare const IMPORTED_TEMPLATES: string;
42
42
  export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (\n machine TEXT PRIMARY KEY,\n token_sha256 TEXT NOT NULL UNIQUE,\n kind TEXT NOT NULL,\n os TEXT NOT NULL,\n arch TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL,\n runner TEXT,\n incarnation TEXT,\n run TEXT,\n refused TEXT\n ) STRICT";
43
43
  /** Each computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the provider's own id for it:
44
44
  * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
45
- * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`), as its create
46
- * asked, null where the create asked none (a hosted vendor that sizes its own machines): never a guess. `kept`: 1 once
45
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
46
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
47
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
48
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
47
49
  * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
48
50
  * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
49
51
  * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
50
52
  * a store an earlier build of this version made, as MINTED_TOKENS is. */
51
- export declare const COMPUTER_INTERVALS = "CREATE TABLE IF NOT EXISTS computer_intervals (\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n kind TEXT,\n gpu_type TEXT,\n gpu_count INTEGER,\n cpus REAL,\n memory_mb INTEGER,\n started_at INTEGER NOT NULL,\n kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),\n ended_at INTEGER,\n PRIMARY KEY (provider, provider_id)\n ) STRICT";
53
+ export declare const COMPUTER_INTERVALS = "CREATE TABLE IF NOT EXISTS computer_intervals (\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n kind TEXT,\n gpu_type TEXT,\n gpu_count INTEGER,\n cpus REAL,\n memory_mb INTEGER,\n disk_gb REAL,\n started_at INTEGER NOT NULL,\n kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),\n ended_at INTEGER,\n booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),\n PRIMARY KEY (provider, provider_id)\n ) STRICT";
54
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
55
+ * added at a server open where missing (sqlite/store.ts). */
56
+ export declare const COMPUTER_INTERVALS_ADDED: Readonly<Record<string, string>>;
52
57
  /** A run's computers, read by its run (store.computerIntervals.forRun). */
53
58
  export declare const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
54
59
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
@@ -106,8 +106,10 @@ export const MINTED_TOKENS = `CREATE TABLE IF NOT EXISTS minted_tokens (
106
106
  ) STRICT`;
107
107
  /** Each computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the provider's own id for it:
108
108
  * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
109
- * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`), as its create
110
- * asked, null where the create asked none (a hosted vendor that sizes its own machines): never a guess. `kept`: 1 once
109
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
110
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
111
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
112
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
111
113
  * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
112
114
  * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
113
115
  * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
@@ -121,11 +123,19 @@ export const COMPUTER_INTERVALS = `CREATE TABLE IF NOT EXISTS computer_intervals
121
123
  gpu_count INTEGER,
122
124
  cpus REAL,
123
125
  memory_mb INTEGER,
126
+ disk_gb REAL,
124
127
  started_at INTEGER NOT NULL,
125
128
  kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),
126
129
  ended_at INTEGER,
130
+ booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),
127
131
  PRIMARY KEY (provider, provider_id)
128
132
  ) STRICT`;
133
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
134
+ * added at a server open where missing (sqlite/store.ts). */
135
+ export const COMPUTER_INTERVALS_ADDED = {
136
+ disk_gb: "ALTER TABLE computer_intervals ADD COLUMN disk_gb REAL",
137
+ booked_ms: "ALTER TABLE computer_intervals ADD COLUMN booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0)",
138
+ };
129
139
  /** A run's computers, read by its run (store.computerIntervals.forRun). */
130
140
  export const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
131
141
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
@@ -95,9 +95,9 @@ export declare class Connection implements SqliteDatabase, StoreConnection {
95
95
  runCounted(sql: string, ...params: SqliteValue[]): Promise<number>;
96
96
  get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
97
97
  all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
98
- /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer, never the
99
- * connection's own busy wait: every call queued behind it waits that long at most for it. Busy (1) when one held it. */
100
- checkpoint(busyMs: number): Promise<CheckpointResult | undefined>;
98
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
99
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
100
+ checkpoint(busyMs?: number): Promise<CheckpointResult | undefined>;
101
101
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
102
102
  * FULL commit, durable against a lost box together with every commit before it. */
103
103
  write(statements: readonly Statement[], { full }?: {
@@ -291,9 +291,9 @@ export class Connection {
291
291
  all(sql, ...params) {
292
292
  return this.#queued(async () => (await this.#stmt(sql, params, "all")));
293
293
  }
294
- /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer, never the
295
- * connection's own busy wait: every call queued behind it waits that long at most for it. Busy (1) when one held it. */
296
- checkpoint(busyMs) {
294
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
295
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
296
+ checkpoint(busyMs = this.#busyTimeoutMs) {
297
297
  return this.#queued(async () => ((await this.#send({ op: "checkpoint", busyMs })) ?? undefined));
298
298
  }
299
299
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
@@ -21,8 +21,6 @@ export type SqliteStoreOptions = (
21
21
  now?: () => number;
22
22
  /** How long a write waits for another process's lock before StoreBusy. */
23
23
  busyTimeoutMs?: number;
24
- /** Told what a person should know that no caller is answered (a purge's checkpoint that left the WAL): stderr by default. */
25
- warn?: (message: string) => void;
26
24
  };
27
25
  /** Opens the store in `dataDir` (its file is STORE_FILE there), or at `file` (the store's own tests). As the server (the
28
26
  * default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
@@ -33,5 +31,5 @@ export declare function openSqliteStore(options: SqliteStoreOptions): Promise<St
33
31
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
34
32
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
35
33
  * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
36
- * purge checkpoints. `warn`: told when that checkpoint could not empty the WAL (stderr by default). */
37
- export declare function storeOver(connection: StoreConnection, now: () => number, file?: string, warn?: (message: string) => void): Store;
34
+ * purge checkpoints. */
35
+ export declare function storeOver(connection: StoreConnection, now: () => number, file?: string): Store;
@@ -12,7 +12,7 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
- import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_RUN, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
16
  import { AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
17
17
  /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
18
  const madeOf = (body) => {
@@ -171,7 +171,7 @@ const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), u
171
171
  const orNull = (value) => (value === null ? null : Number(value));
172
172
  const intervalOf = (r) => ({
173
173
  runId: r.run_id, provider: r.provider, providerId: r.provider_id, kind: r.kind, gpuType: r.gpu_type, gpuCount: orNull(r.gpu_count), cpus: orNull(r.cpus),
174
- memoryMb: orNull(r.memory_mb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at),
174
+ memoryMb: orNull(r.memory_mb), diskGb: orNull(r.disk_gb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at), bookedMs: Number(r.booked_ms),
175
175
  });
176
176
  const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
177
177
  const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
@@ -398,6 +398,12 @@ export async function openSqliteStore(options) {
398
398
  { sql: COMPUTER_INTERVALS_RUN },
399
399
  { sql: NATIVE_COMMANDS_INDEX },
400
400
  ], { full: true });
401
+ // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
402
+ // COMPUTER_INTERVALS_ADDED): each column added where missing, its rows' disk unknown (null) and booked time none.
403
+ const intervalColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('computer_intervals')")).map((column) => column.name));
404
+ const missing = Object.entries(COMPUTER_INTERVALS_ADDED).filter(([column]) => !intervalColumns.has(column)).map(([, sql]) => ({ sql }));
405
+ if (missing.length > 0)
406
+ await connection.write(missing, { full: true });
401
407
  await backfillNativeCommandOwners(connection);
402
408
  if (found === 11) {
403
409
  const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
@@ -417,7 +423,7 @@ export async function openSqliteStore(options) {
417
423
  await connection.close().catch(() => undefined);
418
424
  throw error;
419
425
  }
420
- return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file, options.warn);
426
+ return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
421
427
  }
422
428
  /** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
423
429
  const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
@@ -478,27 +484,48 @@ function readOnly(tx) {
478
484
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
479
485
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
480
486
  * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
481
- * purge checkpoints. `warn`: told when that checkpoint could not empty the WAL (stderr by default). */
482
- export function storeOver(connection, now, file, warn = stderrWarn) {
483
- return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`, warn);
487
+ * purge checkpoints. */
488
+ export function storeOver(connection, now, file) {
489
+ return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`);
484
490
  }
485
- const stderrWarn = (message) => void process.stderr.write(`agentrun-serve: ${message}\n`);
486
- /** How long a purge's checkpoint waits, once SQLite's busy wait ran out on another connection's reader or writer, before
487
- * its one retry. */
488
- const PURGE_CHECKPOINT_RETRY_MS = 200;
489
- /** How long a purge's checkpoint waits for another connection's reader or writer before it gives up (and is retried):
490
- * short, since every other request of the store's connection queues behind it. */
491
+ /** How long a purge's checkpoint waits for another connection's reader or writer before it leaves the log to the next
492
+ * start's scrub: short, since every other request of the store's connection queues behind it. */
491
493
  const PURGE_CHECKPOINT_BUSY_MS = 20;
492
- /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
493
- * file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
494
+ /** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
495
+ * (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
496
+ async function dropRunContent(tx, runId) {
497
+ for (const table of PI_TABLES)
498
+ await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
499
+ await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
500
+ await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
501
+ await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
502
+ await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
503
+ await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
504
+ await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
505
+ await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
506
+ await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
507
+ await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
508
+ await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
509
+ }
510
+ /** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
511
+ * purge (Agents.purge) and its delete (Agents.remove) both drop. */
512
+ async function dropAgentPrivate(tx, agentId) {
513
+ await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
514
+ await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
515
+ await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
516
+ }
517
+ /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge, when its
518
+ * checkpoint could not truncate the log) and removes once no file of the store keeps the bytes they replaced: a start
519
+ * that finds it finishes the scrub. */
494
520
  const SCRUB_SUFFIX = ".scrub";
495
521
  /** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
496
522
  const VACUUM_RETRY_MS = 400;
497
- /** The marker at `path`, written and synced (its directory too) before the rewrite it marks changes a byte. */
523
+ /** The marker at `path`, written and synced (its directory too): before the rewrite it marks changes a byte, or once a
524
+ * purge's checkpoint left the log. */
498
525
  function markScrub(path) {
499
526
  const fd = openSync(path, "w", 0o600);
500
527
  try {
501
- writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear may have left its old bytes in the store's free pages; the next start scrubs them and removes this file.\n");
528
+ writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear, or a purge, may have left old bytes in the store's free pages or its WAL; the next start scrubs them and removes this file.\n");
502
529
  fsyncSync(fd);
503
530
  }
504
531
  finally {
@@ -554,12 +581,13 @@ class SqliteStore {
554
581
  #released = new Map();
555
582
  /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
556
583
  #scrubMarker;
557
- /** Told what a person should know that no caller is answered (a purge's checkpoint that left the WAL as it was). */
558
- #warn;
559
- constructor(db, now, origin, scrubMarker, warn = stderrWarn) {
584
+ /** How many times a purge left the marker (#purged). The marker has two owners: secureRewrite removes it only when no
585
+ * purge left it since the step that covers that purge's log (its own start, or the checkpoint it asked), so a marker a
586
+ * purge left is never removed without a checkpoint that truncated the purge's frames. */
587
+ #purgeMarks = 0;
588
+ constructor(db, now, origin, scrubMarker) {
560
589
  this.#db = db;
561
590
  this.#scrubMarker = scrubMarker;
562
- this.#warn = warn;
563
591
  this.#now = now;
564
592
  this.origin = origin ?? this;
565
593
  this.where = db.where;
@@ -732,9 +760,7 @@ class SqliteStore {
732
760
  if (left.length)
733
761
  throw new TriggersLeft(agentId, left.map((one) => one.id));
734
762
  await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
735
- await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
736
- await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
737
- await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
763
+ await dropAgentPrivate(tx, agentId);
738
764
  // Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
739
765
  // agent's pointer at its current one cleared first.
740
766
  await tx.run("UPDATE agents SET current_revision = NULL WHERE id = ?", agentId);
@@ -755,9 +781,7 @@ class SqliteStore {
755
781
  const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
756
782
  if (triggersLeft.length)
757
783
  throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
758
- await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
759
- await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
760
- await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
784
+ await dropAgentPrivate(tx, agentId);
761
785
  // The answer a template apply kept under its key, which holds the agent as it was made.
762
786
  await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
763
787
  // Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
@@ -767,7 +791,7 @@ class SqliteStore {
767
791
  return true;
768
792
  });
769
793
  if (purged)
770
- await this.#purged(`agent ${agentId}`);
794
+ await this.#purged();
771
795
  },
772
796
  };
773
797
  this.templates = {
@@ -1279,18 +1303,7 @@ class SqliteStore {
1279
1303
  }
1280
1304
  if (left.length)
1281
1305
  throw new RunsMadeFromLeft(runId, left);
1282
- for (const table of PI_TABLES)
1283
- await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
1284
- await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
1285
- await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
1286
- await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
1287
- await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
1288
- await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
1289
- await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
1290
- await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
1291
- await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
1292
- await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
1293
- await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
1306
+ await dropRunContent(tx, runId);
1294
1307
  // What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
1295
1308
  // fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
1296
1309
  // trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
@@ -1313,7 +1326,7 @@ class SqliteStore {
1313
1326
  return true;
1314
1327
  });
1315
1328
  if (purged)
1316
- await this.#purged(`run ${runId}`);
1329
+ await this.#purged();
1317
1330
  },
1318
1331
  remove: async (runId) => {
1319
1332
  await db.transaction(async (tx) => {
@@ -1324,19 +1337,9 @@ class SqliteStore {
1324
1337
  return;
1325
1338
  if (!FINAL_STATES.includes(run.state))
1326
1339
  throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
1327
- for (const table of PI_TABLES)
1328
- await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
1329
- await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
1330
- await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
1331
- await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
1332
- await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
1333
- await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
1334
- await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
1335
- await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
1336
- await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
1340
+ await dropRunContent(tx, runId);
1337
1341
  await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
1338
- await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
1339
- await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
1342
+ // Its computers' usage, which a purge keeps (figures, no words).
1340
1343
  await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
1341
1344
  await tx.run("DELETE FROM runs WHERE id = ?", runId);
1342
1345
  });
@@ -1811,8 +1814,8 @@ class SqliteStore {
1811
1814
  this.computerIntervals = {
1812
1815
  opened: async (row) => {
1813
1816
  await db.write([{
1814
- sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
1815
- params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.startedAt],
1817
+ sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
1818
+ params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.diskGb, row.startedAt],
1816
1819
  }]);
1817
1820
  },
1818
1821
  kept: async (provider, providerId) => {
@@ -1821,7 +1824,12 @@ class SqliteStore {
1821
1824
  ended: async (provider, providerId, at) => {
1822
1825
  await db.write([{ sql: "UPDATE computer_intervals SET ended_at = ? WHERE provider = ? AND provider_id = ? AND ended_at IS NULL", params: [at, provider, providerId] }]);
1823
1826
  },
1824
- forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at, kept, ended_at FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
1827
+ booked: async (provider, providerId, ms) => {
1828
+ if (!Number.isSafeInteger(ms) || ms <= 0)
1829
+ return;
1830
+ await db.write([{ sql: "UPDATE computer_intervals SET booked_ms = booked_ms + ? WHERE provider = ? AND provider_id = ?", params: [ms, provider, providerId] }]);
1831
+ },
1832
+ forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, disk_gb, started_at, kept, ended_at, booked_ms FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
1825
1833
  };
1826
1834
  const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
1827
1835
  this.pairedComputers = {
@@ -2122,46 +2130,46 @@ class SqliteStore {
2122
2130
  handedAny: async () => (await handedAnyIn(db))?.id,
2123
2131
  };
2124
2132
  }
2125
- /** After a purge of `what` committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint
2126
- * (TRUNCATE). secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are
2127
- * new frames in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint
2128
- * copies the zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a
2129
- * backup) may hold the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy
2130
- * wait, since every request of the store's one connection queues behind it (the purge already committed). One retry
2131
- * after a short pause, then a warning, and the old frames stay until the next purge's checkpoint (or the last
2132
- * connection's close, which checkpoints and removes the log). An automatic checkpoint (PASSIVE) copies the zeroed
2133
- * pages into the file but leaves the log's old frames in place. Never fails the purge, which committed. */
2134
- async #purged(what) {
2133
+ /** After a purge committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint (TRUNCATE).
2134
+ * secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are new frames
2135
+ * in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint copies the
2136
+ * zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a backup) may hold
2137
+ * the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every
2138
+ * request of the store's one connection queues behind it (the purge already committed). One it held back (or that
2139
+ * failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
2140
+ * that cannot be written (a full disk) throws, the purge committed: its caller answers it as the fault it is (a 500 the
2141
+ * server logs), and drops what it served of the purged run all the same (agent-delete.ts purgeOneOrRefuse). */
2142
+ async #purged() {
2143
+ const marker = this.#scrubMarker;
2135
2144
  const db = this.#db;
2136
- if (this.#scrubMarker === undefined || !(db instanceof Connection))
2145
+ if (marker === undefined || !(db instanceof Connection))
2137
2146
  return;
2138
- let why = "";
2139
- for (let tries = 1; tries <= 2; tries++) {
2140
- try {
2141
- const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS);
2142
- if (checkpoint?.busy === 0)
2143
- return;
2144
- why = "another connection held the log";
2145
- }
2146
- catch (error) {
2147
- why = error instanceof StoreBusy ? "another connection held the log" : `the checkpoint failed: ${error instanceof Error ? error.message : String(error)}`;
2148
- }
2149
- if (tries === 1)
2150
- await new Promise((resolve) => setTimeout(resolve, PURGE_CHECKPOINT_RETRY_MS));
2147
+ const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined);
2148
+ if (checkpoint?.busy === 0)
2149
+ return;
2150
+ this.#purgeMarks++;
2151
+ try {
2152
+ markScrub(marker);
2153
+ }
2154
+ catch (error) {
2155
+ throw new Error(`The purge committed, but its WAL checkpoint was held back and the scrub's marker could not be written (${error.message}): the log may keep the purged bytes until a later checkpoint truncates it.`, { cause: error });
2151
2156
  }
2152
- this.#warn(`the purge of ${what} committed, but its WAL checkpoint did not finish (${why}): the purged content's earlier page images may stay in the store's file and its -wal until the next purge's checkpoint or the server's stop`);
2153
2157
  }
2154
2158
  async secureRewrite(work, options = {}) {
2155
2159
  const marker = this.#scrubMarker;
2156
- if (this.#db.dialect.name !== "sqlite" || marker === undefined)
2160
+ const db = this.#db;
2161
+ if (marker === undefined || !(db instanceof Connection))
2157
2162
  return { rewritten: await work() };
2158
2163
  // Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
2159
2164
  // leaves it, and its next start scrubs though no row is left in the clear.
2160
2165
  const pending = existsSync(marker);
2166
+ const purgesBefore = this.#purgeMarks;
2161
2167
  markScrub(marker);
2162
2168
  // secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
2163
2169
  const rewritten = await work();
2164
- if (rewritten === 0 && !pending) {
2170
+ // Nothing rewritten, and the marker is this call's alone: no purge left it while the work ran (#purgeMarks). One that
2171
+ // did needs the checkpoint below, or the next start's scrub.
2172
+ if (rewritten === 0 && !pending && this.#purgeMarks === purgesBefore) {
2165
2173
  rmSync(marker, { force: true });
2166
2174
  return { rewritten };
2167
2175
  }
@@ -2179,10 +2187,12 @@ class SqliteStore {
2179
2187
  await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
2180
2188
  await this.#db.all("VACUUM");
2181
2189
  });
2182
- const [checkpoint] = await this.#db.all("PRAGMA wal_checkpoint(TRUNCATE)");
2190
+ const purgesBefore = this.#purgeMarks;
2191
+ const checkpoint = await db.checkpoint();
2183
2192
  // A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
2184
- // checkpoint is done, so the marker stays.
2185
- if (checkpoint?.busy !== 0)
2193
+ // checkpoint is done, so the marker stays. So does one a purge left after this checkpoint was asked: its frames may
2194
+ // be past it.
2195
+ if (checkpoint?.busy !== 0 || this.#purgeMarks !== purgesBefore)
2186
2196
  return { rewritten, left: "busy" };
2187
2197
  }
2188
2198
  catch (error) {
@@ -1432,21 +1432,28 @@ export interface ComputerIntervalRow {
1432
1432
  readonly gpuCount: number | null;
1433
1433
  readonly cpus: number | null;
1434
1434
  readonly memoryMb: number | null;
1435
+ /** Its disk in GB, where its provider said it; null else. */
1436
+ readonly diskGb: number | null;
1435
1437
  readonly startedAt: number;
1436
1438
  readonly kept: boolean;
1437
1439
  readonly endedAt: number | null;
1440
+ /** How much of its time a claim of its run booked on the run's ledger (compute-cost.ts), in ms; 0 for none. */
1441
+ readonly bookedMs: number;
1438
1442
  }
1439
1443
  /** Each computer a run made, from its create to its proven delete: how long it lived for its run, and one left running
1440
1444
  * after its run (no `endedAt`). Every write is idempotent. */
1441
1445
  export interface ComputerIntervals {
1442
1446
  /** The computer's row, made: a second call for the same provider and id changes nothing (a retried create answers the
1443
1447
  * computer it made). */
1444
- opened(row: Omit<ComputerIntervalRow, "kept" | "endedAt">): Promise<void>;
1448
+ opened(row: Omit<ComputerIntervalRow, "kept" | "endedAt" | "bookedMs">): Promise<void>;
1445
1449
  /** The computer was kept past its claim (the run's park). */
1446
1450
  kept(provider: string, providerId: string): Promise<void>;
1447
1451
  /** The provider's delete of the computer answered ok at `at`: its end, written only while none is (a later delete of
1448
1452
  * one already ended never moves it). A computer with no row is left without one. */
1449
1453
  ended(provider: string, providerId: string, at: number): Promise<void>;
1454
+ /** A claim booked `ms` more of the computer's time on its run's ledger: added to its booked time (a figure that is not
1455
+ * a whole number of ms above 0 adds nothing). A computer with no row is left without one. */
1456
+ booked(provider: string, providerId: string, ms: number): Promise<void>;
1450
1457
  /** The run's computers, by when each was made. */
1451
1458
  forRun(runId: string): Promise<ComputerIntervalRow[]>;
1452
1459
  }
@@ -16,13 +16,17 @@ export declare function spendOverStore(store: Store, runId: string, context: Con
16
16
  usd: number | null;
17
17
  basis: CostBasis | undefined;
18
18
  }>;
19
- /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
20
- * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
21
- * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
22
- export declare function metersOverStore(store: Store, runId: string, context: Context): Promise<Meters & {
19
+ /** A run's /usage meters, with each meter's known dollars. */
20
+ type KnownMeters = Meters & {
23
21
  known: {
24
22
  tokens: number;
25
23
  browser: number;
26
24
  others: number;
27
25
  };
28
- }>;
26
+ };
27
+ /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
28
+ * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
29
+ * file-backed run held each on its root, and the decisions Parallel charged on its own API (parallelDecisionsOn) on its
30
+ * tools meter beside them. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
31
+ export declare function metersOverStore(store: Store, runId: string, context: Context): Promise<KnownMeters>;
32
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { meterFiguresFrom, spentFrom } from "../cap.js";
2
- import { bookedListSpend, bookedSpend, cliModelWorked, costBasisOf, costIsBooked } from "../runner/metrics.js";
2
+ import { bookedDecisionsOf, bookedListSpend, bookedSpend, cliModelWorked, costBasisOf, costIsBooked } from "../runner/metrics.js";
3
+ import { booksDecisions, decisionsOverStore, parallelChargedDecisions } from "./decisions.js";
3
4
  import { isCliRecord, runEntries, withPaidCosts } from "./journal.js";
4
5
  /** A CLI run whose model answered or called a tool with no model request booked (metrics.ts cliModelWorked): what it
5
6
  * spent no booking read, so its spend is unknown. */
@@ -56,9 +57,34 @@ function spentOf(entries) {
56
57
  }
57
58
  /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
58
59
  * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
59
- * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
60
+ * file-backed run held each on its root, and the decisions Parallel charged on its own API (parallelDecisionsOn) on its
61
+ * tools meter beside them. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
60
62
  export async function metersOverStore(store, runId, context) {
61
63
  const raw = await runEntries(store, runId, context);
64
+ if (!raw.length)
65
+ return metersOfEntries(store, runId, raw);
66
+ return parallelDecisionsOn(store, runId, raw, context, await metersOfEntries(store, runId, raw));
67
+ }
68
+ /** A run's decisions Parallel charged on its own API (store-reads/decisions.ts chargedByParallel) on its tools meter, as
69
+ * GET /runs/{run_id}/usage puts them on Parallel's tools line: each a paid call, at its list price. They leave the rest
70
+ * of the run's cost (its tokens meter, which /usage reads as its cost less its tools) as they join its tools, so no
71
+ * total moves. As for a paid call, /usage says no "at most": one booked at its hold, or of no known cost, makes the
72
+ * meter unknown, its exact charges known beside it. */
73
+ async function parallelDecisionsOn(store, runId, raw, context, meters) {
74
+ if (!booksDecisions(raw))
75
+ return meters;
76
+ const ids = parallelChargedDecisions(await decisionsOverStore(store, runId, context));
77
+ if (!ids.size)
78
+ return meters;
79
+ const charged = bookedDecisionsOf(raw, ids);
80
+ if (!charged.requests)
81
+ return meters;
82
+ const usd = charged.unpriced > 0 || charged.bounded > 0 ? null : charged.known;
83
+ const plus = (figure) => (figure === null || usd === null ? null : figure + usd);
84
+ return { ...meters, tools: plus(meters.tools), others: plus(meters.others), known: { ...meters.known, others: meters.known.others + charged.known } };
85
+ }
86
+ /** metersOverStore's figures over `raw`, the run's entries, before its Parallel decisions join its tools meter. */
87
+ async function metersOfEntries(store, runId, raw) {
62
88
  if (!raw.length) {
63
89
  // A purged run's journal is gone: its figures are the ones its purge read from it (Runs.purge, PurgeKept).
64
90
  const kept = await purgeKept(store, runId);