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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -10,9 +10,9 @@ import { DatabaseSync } from "node:sqlite";
10
10
  import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } from '../native-command-owner.js';
11
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
- import { RunStorage } from "../journal/storage.js";
13
+ import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
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";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, 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) => {
@@ -33,7 +33,7 @@ import { cleanText, settledBody } from "../dialect.js";
33
33
  import { inMemory } from "./memory.js";
34
34
  import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
35
35
  import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
36
- import { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
36
+ import { launchDiskOf, postgresReadableJson, postgresUnicodeRefusal, readableJson, readLaunch, readLearningStarts, readSeededBefore, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
37
37
  import { canonical } from "../agent-body.js";
38
38
  import { aadOf, sealedAt } from "../seal.js";
39
39
  /** A claim's length when the caller names none. */
@@ -102,7 +102,7 @@ const claimableIn = (d, n) => ({
102
102
  (wake_at IS NOT NULL AND wake_at <= ${n.sql})
103
103
  OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
104
104
  OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
105
- AND ${d.jsonNotFalse("commands.body", ["answers"])})))))`,
105
+ AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))))`,
106
106
  params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
107
107
  });
108
108
  /** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
@@ -169,6 +169,10 @@ const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.mcp_pin), pinnedA
169
169
  const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
170
170
  const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
171
171
  const orNull = (value) => (value === null ? null : Number(value));
172
+ const attemptOf = (r) => ({
173
+ runId: r.run_id, epoch: Number(r.epoch), turn: Number(r.turn), attempt: Number(r.attempt), cause: r.cause, cut: r.cut,
174
+ runner: r.runner, from: r.from_state, journalFrom: Number(r.journal_from), claimedAt: Number(r.claimed_at),
175
+ });
172
176
  const intervalOf = (r) => ({
173
177
  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
178
  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),
@@ -176,7 +180,7 @@ const intervalOf = (r) => ({
176
180
  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
181
  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 });
178
182
  const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at, runner: r.runner, incarnation: r.incarnation, run: r.run, refused: r.refused });
179
- const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at) });
183
+ const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at), version: r.version, slots: r.slots === null ? null : Number(r.slots) });
180
184
  const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
181
185
  const mcpOauthOf = (r) => ({ state: r.state, server: r.server, sealed: Uint8Array.from(r.sealed), working: r.working === null ? null : JSON.parse(r.working), expiresAt: r.expires_at });
182
186
  const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
@@ -198,12 +202,36 @@ async function versionOf(db) {
198
202
  * (webhook.json, webhook-outbox.json) do not refuse the directory either: nothing reads them, and the webhook, now in
199
203
  * the store, is set again. */
200
204
  const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
205
+ /** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
206
+ * at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
207
+ * words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
208
+ export const SQLITE_RUNNER_NEEDS = [
209
+ { table: "revisions", columns: ["mcp_pin", "monid_pin"], why: "install MCP and Monid revision metadata" },
210
+ { table: "settings", columns: ["connector_id"], why: "add native command ownership metadata" },
211
+ { table: "runs", columns: ["cost_upper_bound"], why: "add the bound beside each run's cost" },
212
+ { table: "runs", columns: ["labels"], why: "add each run's labels" },
213
+ { table: "triggers", columns: ["template_id"], why: "add each trigger's package mark" },
214
+ { table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
215
+ { table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
216
+ { table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
217
+ { table: "run_attempts", columns: ["run_id"], why: "keep each claim's turn and attempt (run_attempts)" },
218
+ ];
219
+ /** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
220
+ * or undefined when it opens; `columnsOf` reads a table's columns. */
221
+ export async function runnerWaitsFor(columnsOf) {
222
+ for (const need of SQLITE_RUNNER_NEEDS) {
223
+ const present = await columnsOf(need.table);
224
+ if (need.columns.some((column) => !present.has(column)))
225
+ return need.why;
226
+ }
227
+ return undefined;
228
+ }
201
229
  /** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
202
230
  * store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
203
231
  * disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
204
232
  * (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
205
233
  * this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
206
- function earlierVersionIn(dataDir, busyTimeoutMs) {
234
+ export function earlierVersionIn(dataDir, busyTimeoutMs) {
207
235
  if (!existsSync(dataDir))
208
236
  return [];
209
237
  const found = [];
@@ -322,13 +350,21 @@ export async function openSqliteStore(options) {
322
350
  // in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
323
351
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
324
352
  // (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
325
- // purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
326
- const upgrading = found === 11 || found === 12 || found === 13;
353
+ // purgeUpgrade). Version 14 keeps no disk on a run: the server adds it and writes each run's from its launch (schema.ts
354
+ // diskUpgrade). A runner refuses 11 to 14 until that server has.
355
+ const upgrading = found === 11 || found === 12 || found === 13 || found === 14;
327
356
  if (upgrading && role === "runner")
328
357
  throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
329
358
  if (found !== SCHEMA_VERSION && !upgrading)
330
359
  throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
331
360
  const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
361
+ // Every column a runner of this build needs that an earlier build of this version may lack (SQLITE_RUNNER_NEEDS), read
362
+ // at once: the same list store-schema reports from. Each check below says the same, where the server adds it.
363
+ if (role === "runner") {
364
+ const waits = await runnerWaitsFor(async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name)));
365
+ if (waits !== undefined)
366
+ throw new StoreAwaitsServer(waits);
367
+ }
332
368
  if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
333
369
  throw new StoreAwaitsServer("install MCP and Monid revision metadata");
334
370
  const nativeOwners = (await connection.all("PRAGMA table_info(settings)")).some(column => column.name === 'connector_id');
@@ -363,9 +399,20 @@ export async function openSqliteStore(options) {
363
399
  // An earlier build of version 13 kept each runner's relay in a table of its own (runner_relays), which the server's
364
400
  // open below drops for runners (schema.ts RUNNERS). A runner says it is there, and where its relay answers, through
365
401
  // runners alone, so it waits for that server.
366
- if (role === "runner" && !(await connection.all("SELECT name FROM pragma_table_info('runners')")).some((column) => column.name === "host")) {
402
+ const runnerColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
403
+ if (role === "runner" && !runnerColumns.has("host")) {
367
404
  throw new StoreAwaitsServer("keep each runner's word that it is there and its relay in one table (runners)");
368
405
  }
406
+ // An earlier build of this version kept no runner's version and slots (schema.ts RUNNERS_ADDED) and no hand-backs
407
+ // (HAND_BACKS): a runner writes both (its presence, its releases), so it waits for the server that adds them below.
408
+ if (role === "runner" && (Object.keys(RUNNERS_ADDED).some((column) => !runnerColumns.has(column)) || (await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'hand_backs'")).length === 0)) {
409
+ throw new StoreAwaitsServer("keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)");
410
+ }
411
+ // A claim writes its turn and attempt (schema.ts RUN_ATTEMPTS) in its own transaction: a runner waits for the server
412
+ // that adds the table.
413
+ if (role === "runner" && (await connection.all("SELECT name FROM pragma_table_info('run_attempts')")).length === 0) {
414
+ throw new StoreAwaitsServer("keep each claim's turn and attempt (run_attempts)");
415
+ }
369
416
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
370
417
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
371
418
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -393,9 +440,15 @@ export async function openSqliteStore(options) {
393
440
  // dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
394
441
  { sql: "DROP TABLE IF EXISTS runner_relays" },
395
442
  { sql: RUNNERS },
443
+ // Nor any hand-back (schema.ts HAND_BACKS): a release before it kept none.
444
+ { sql: HAND_BACKS },
445
+ { sql: HAND_BACKS_AT },
446
+ { sql: HAND_BACKS_RUN },
396
447
  // Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
397
448
  { sql: COMPUTER_INTERVALS },
398
449
  { sql: COMPUTER_INTERVALS_RUN },
450
+ // Nor any claim's turn and attempt (schema.ts RUN_ATTEMPTS): a claim made before it has no row.
451
+ { sql: RUN_ATTEMPTS },
399
452
  { sql: NATIVE_COMMANDS_INDEX },
400
453
  ], { full: true });
401
454
  // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
@@ -404,6 +457,12 @@ export async function openSqliteStore(options) {
404
457
  const missing = Object.entries(COMPUTER_INTERVALS_ADDED).filter(([column]) => !intervalColumns.has(column)).map(([, sql]) => ({ sql }));
405
458
  if (missing.length > 0)
406
459
  await connection.write(missing, { full: true });
460
+ // A runners table an earlier build of this version made has no version or slots (schema.ts RUNNERS_ADDED): each added
461
+ // where missing, every row's unknown (null) until its runner's next put.
462
+ const runnersNow = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
463
+ const runnersMissing = Object.entries(RUNNERS_ADDED).filter(([column]) => !runnersNow.has(column)).map(([, sql]) => ({ sql }));
464
+ if (runnersMissing.length > 0)
465
+ await connection.write(runnersMissing, { full: true });
407
466
  await backfillNativeCommandOwners(connection);
408
467
  if (found === 11) {
409
468
  const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
@@ -415,7 +474,9 @@ export async function openSqliteStore(options) {
415
474
  }
416
475
  if (upgrading) {
417
476
  const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
418
- await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
477
+ if (found !== 14)
478
+ await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
479
+ await connection.write(diskUpgrade(await named("runs")).map((sql) => ({ sql })), { full: true });
419
480
  }
420
481
  }
421
482
  }
@@ -423,7 +484,14 @@ export async function openSqliteStore(options) {
423
484
  await connection.close().catch(() => undefined);
424
485
  throw error;
425
486
  }
426
- return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
487
+ const store = storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
488
+ // A SQLite runner opens only its own version (the server upgrades the file in place at its start, never beside a
489
+ // runner on another build): its floor is the version itself.
490
+ const schemaState = async () => {
491
+ const version = await versionOf(connection);
492
+ return { version, runnerFloor: version, known: SCHEMA_VERSION };
493
+ };
494
+ return Object.assign(store, { schemaState });
427
495
  }
428
496
  /** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
429
497
  const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
@@ -506,6 +574,9 @@ async function dropRunContent(tx, runId) {
506
574
  await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
507
575
  await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
508
576
  await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
577
+ await tx.run("DELETE FROM hand_backs WHERE run_id = ?", runId);
578
+ // Its claims' attempts: what each cost is in its tombstone's money, and no read of a purged run splits it.
579
+ await tx.run("DELETE FROM run_attempts WHERE run_id = ?", runId);
509
580
  }
510
581
  /** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
511
582
  * purge (Agents.purge) and its delete (Agents.remove) both drop. */
@@ -554,6 +625,7 @@ class SqliteStore {
554
625
  sealedKeys;
555
626
  computerLedger;
556
627
  computerIntervals;
628
+ runAttempts;
557
629
  pairedComputers;
558
630
  mintedTokens;
559
631
  runners;
@@ -581,7 +653,7 @@ class SqliteStore {
581
653
  #released = new Map();
582
654
  /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
583
655
  #scrubMarker;
584
- /** How many times a purge left the marker (#purged). The marker has two owners: secureRewrite removes it only when no
656
+ /** How many times a purge left the marker (#purged), or a retried purge found it there (purgeScrub). The marker has two owners: secureRewrite removes it only when no
585
657
  * 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
658
  * purge left is never removed without a checkpoint that truncated the purge's frames. */
587
659
  #purgeMarks = 0;
@@ -640,8 +712,9 @@ class SqliteStore {
640
712
  throw new AgentDeleting(agentId);
641
713
  };
642
714
  /** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
643
- * launch is read (no index names its source): a purge's read, never a hot path. */
644
- const launchedFrom = async (ex, runId) => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText("body", ["replay", "of"])} = ? OR ${d.jsonText("body", ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
715
+ * launch is read (no index names its source): a purge's read, never a hot path. `body`: the body column as read
716
+ * (readableJson's copy inside a transaction). */
717
+ const launchedFrom = async (ex, runId, body = "body") => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText(body, ["replay", "of"])} = ? OR ${d.jsonText(body, ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
645
718
  /** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
646
719
  * while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
647
720
  * distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
@@ -980,7 +1053,7 @@ class SqliteStore {
980
1053
  const firing = await tx.get("SELECT status FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
981
1054
  if (!firing || firing.status !== "due")
982
1055
  return undefined;
983
- const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText("body", ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
1056
+ const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText(readableJson(d, "body"), ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
984
1057
  const clear = "retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, attempts = 0";
985
1058
  if (waiting >= bound.max) {
986
1059
  await tx.run(`UPDATE trigger_firings SET status = 'skipped', reason = ?, ${clear} WHERE trigger_id = ? AND key = ?`, bound.reason, triggerId, key);
@@ -1054,7 +1127,7 @@ class SqliteStore {
1054
1127
  await d.lockRow(tx, "triggers", "id", firing.triggerId);
1055
1128
  // Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
1056
1129
  await refuseArchived(tx, run.agentId);
1057
- const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, at);
1130
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, launchDiskOf(launch), at);
1058
1131
  // The run's launch row lands with it, through the store's one writer, or neither does.
1059
1132
  if (launch)
1060
1133
  await writeLaunch(tx, run.id, launch, at);
@@ -1072,7 +1145,7 @@ class SqliteStore {
1072
1145
  this.runs = {
1073
1146
  create: async ({ id, agentId, revisionId, origin, labels }, launch) => {
1074
1147
  // sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
1075
- const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
1148
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
1076
1149
  const labelled = labelsColumn(labels);
1077
1150
  // The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
1078
1151
  // never lands, and a run never exists without the launch it was started with. Never a run of an agent being
@@ -1090,7 +1163,7 @@ class SqliteStore {
1090
1163
  if (source && source.purged_at !== null)
1091
1164
  throw new RunPurged(of, id);
1092
1165
  }
1093
- const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
1166
+ const row = await tx.get(insert, id, agentId, revisionId, labelled, launchDiskOf(launch), at);
1094
1167
  if (origin)
1095
1168
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
1096
1169
  if (launch)
@@ -1099,7 +1172,7 @@ class SqliteStore {
1099
1172
  }));
1100
1173
  },
1101
1174
  createInline: async ({ agent, revision, run, launch }) => {
1102
- const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
1175
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
1103
1176
  const made = await db.transaction(async (tx) => {
1104
1177
  const at = now();
1105
1178
  // Hold the external reference, so two first uses of the same expert serialize (SQLite's one writer already does).
@@ -1124,7 +1197,7 @@ class SqliteStore {
1124
1197
  await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
1125
1198
  }
1126
1199
  // The run, its origin and its launch, in the same transaction as the agent and the revision.
1127
- const row = await tx.get(insert, run.id, mapped.id, revisionId, labelsColumn(run.labels), at);
1200
+ const row = await tx.get(insert, run.id, mapped.id, revisionId, labelsColumn(run.labels), launchDiskOf(launch), at);
1128
1201
  if (run.origin)
1129
1202
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", run.origin.key, run.id, run.origin.fingerprint ?? null, at);
1130
1203
  await writeLaunch(tx, run.id, launch, at);
@@ -1137,8 +1210,10 @@ class SqliteStore {
1137
1210
  return row && runOf(row);
1138
1211
  },
1139
1212
  launch: (runId) => readLaunch(db, runId),
1213
+ usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
1140
1214
  learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
1141
- list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
1215
+ seededBefore: (agentId, at) => readSeededBefore(db, agentId, at),
1216
+ list: async ({ agentId, revisionId, state, archived, labels, disk, limit, purged = false }) => {
1142
1217
  // A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
1143
1218
  // count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
1144
1219
  const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
@@ -1154,6 +1229,10 @@ class SqliteStore {
1154
1229
  // Each label, key and value bound as parameters (never spliced into a JSON path), all of them held.
1155
1230
  for (const [key, value] of Object.entries(labels ?? {}))
1156
1231
  (where.push(d.jsonObjectHas("labels")), params.push(key, value));
1232
+ if (disk === null)
1233
+ where.push("disk IS NULL");
1234
+ else if (disk !== undefined)
1235
+ (where.push("disk = ?"), params.push(disk));
1157
1236
  const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
1158
1237
  if (bounded)
1159
1238
  params.push(limit);
@@ -1245,11 +1324,22 @@ class SqliteStore {
1245
1324
  // itself (turnCostOf over each turn's data), which no column holds.
1246
1325
  costUnknown: async ({ limit, after }) => {
1247
1326
  const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
1248
- const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
1327
+ const read = (readable) => db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
1249
1328
  AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
1250
- AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${db.dialect.jsonText("run_launch.body", ["native"])} IS NOT NULL))
1251
- AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${db.dialect.jsonText("entry.record", ["kind"])} = ?)
1329
+ AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText(readable("run_launch.body"), ["native"])} IS NOT NULL))
1330
+ AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${d.jsonText(readable("entry.record"), ["kind"])} = ?)
1252
1331
  ${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
1332
+ let rows;
1333
+ try {
1334
+ rows = await read((column) => column);
1335
+ }
1336
+ catch (error) {
1337
+ // A run's input or journal holding an escaped NUL or a lone surrogate makes Postgres refuse the read: read again
1338
+ // from copies with those escapes blanked (whether `native` is there, a record's kind), never a run's text.
1339
+ if (d.name !== "postgres" || !postgresUnicodeRefusal(error))
1340
+ throw error;
1341
+ rows = await read(postgresReadableJson);
1342
+ }
1253
1343
  return rows.map((row) => row.id);
1254
1344
  },
1255
1345
  relist: async ({ flags, agentId }) => {
@@ -1279,11 +1369,22 @@ class SqliteStore {
1279
1369
  // Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
1280
1370
  await db.write([archived ? { sql: "UPDATE runs SET archived_at = COALESCE(archived_at, ?) WHERE id = ?", params: [now(), runId] } : { sql: "UPDATE runs SET archived_at = NULL WHERE id = ?", params: [runId] }]);
1281
1371
  },
1282
- every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1283
- .map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null })),
1372
+ every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at, disk FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1373
+ .map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null, disk: row.disk ?? null })),
1284
1374
  madeFrom: async (runId) => {
1285
1375
  const learning = (await db.all("SELECT DISTINCT learning_run_id AS id FROM learning_proposals WHERE run_id = ? AND learning_run_id IS NOT NULL AND learning_run_id <> ?", runId, runId)).map((row) => row.id);
1286
- return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
1376
+ let launched;
1377
+ try {
1378
+ launched = await launchedFrom(db, runId);
1379
+ }
1380
+ catch (error) {
1381
+ // Another run's body holding an escaped NUL or a lone surrogate (its input) makes Postgres refuse the read: the
1382
+ // ids are read again from copies with those escapes blanked, outside any transaction.
1383
+ if (d.name !== "postgres" || !postgresUnicodeRefusal(error))
1384
+ throw error;
1385
+ launched = await launchedFrom(db, runId, postgresReadableJson("body"));
1386
+ }
1387
+ return [...new Set([...launched, ...learning])].sort();
1287
1388
  },
1288
1389
  purge: async (runId, kept) => {
1289
1390
  const purged = await db.transaction(async (tx) => {
@@ -1297,7 +1398,7 @@ class SqliteStore {
1297
1398
  // A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
1298
1399
  // its input: each is purged first.
1299
1400
  const left = [];
1300
- for (const id of await launchedFrom(tx, runId)) {
1401
+ for (const id of await launchedFrom(tx, runId, readableJson(d, "body"))) {
1301
1402
  if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
1302
1403
  left.push(id);
1303
1404
  }
@@ -1831,6 +1932,19 @@ class SqliteStore {
1831
1932
  },
1832
1933
  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),
1833
1934
  };
1935
+ this.runAttempts = {
1936
+ lapsed: async (runId, epoch) => {
1937
+ await db.transaction(async (tx) => {
1938
+ // Held as a claim holds it, from its UPDATE of the run to its attempt row: a takeover in flight writes its row
1939
+ // (with the cause it read) before this reads it, and one after this reads the cut. Never a cause left unsaid.
1940
+ await d.lockRow(tx, "runs", "id", runId);
1941
+ await tx.run("UPDATE run_attempts SET cut = 'lease_lapse' WHERE run_id = ? AND epoch = ? AND cut IS NULL", runId, epoch);
1942
+ // The claim that took the run over read the lapse as a crash, if it came first: this says what it was.
1943
+ await tx.run("UPDATE run_attempts SET cause = 'lease_lapse' WHERE run_id = ? AND cause = 'crash' AND epoch = (SELECT min(epoch) FROM run_attempts WHERE run_id = ? AND epoch > ?)", runId, runId, epoch);
1944
+ });
1945
+ },
1946
+ forRun: async (runId) => (await db.all("SELECT run_id, epoch, turn, attempt, cause, cut, runner, from_state, journal_from, claimed_at FROM run_attempts WHERE run_id = ? ORDER BY epoch", runId)).map(attemptOf),
1947
+ };
1834
1948
  const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
1835
1949
  this.pairedComputers = {
1836
1950
  addCode: async (id, codeSha256, expiresAt) => {
@@ -1896,9 +2010,9 @@ class SqliteStore {
1896
2010
  };
1897
2011
  // Stamped and judged on the deadlines' clock (fence.ts storeNow: the database's on Postgres), the one a claim's lease
1898
2012
  // runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
1899
- const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
2013
+ const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at, version, slots FROM runners";
1900
2014
  this.runners = {
1901
- put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
2015
+ put: async ({ runner, incarnation, refused, host = null, port = null, version = null, slots = null }, { unlessLiveMs } = {}) => {
1902
2016
  const n = clock();
1903
2017
  // With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
1904
2018
  // statement: no read between, so a later process's put can never land between a look and this write.
@@ -1906,8 +2020,8 @@ class SqliteStore {
1906
2020
  const [, result] = await db.write([
1907
2021
  { sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
1908
2022
  {
1909
- sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at${unlessLive}`,
1910
- params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
2023
+ sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at, version, slots) VALUES (?, ?, ?, ?, ?, ${n.sql}, ?, ?) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at, version = excluded.version, slots = excluded.slots${unlessLive}`,
2024
+ params: [runner, incarnation, refused, host, port, ...n.params, version, slots, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
1911
2025
  },
1912
2026
  ]);
1913
2027
  return (result?.changes ?? 0) === 1;
@@ -1925,6 +2039,22 @@ class SqliteStore {
1925
2039
  remove: async (runner, incarnation) => {
1926
2040
  await db.write([{ sql: "DELETE FROM runners WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
1927
2041
  },
2042
+ capacity: async (windowMs) => {
2043
+ // One read snapshot (Postgres: REPEATABLE READ READ ONLY; SQLite: one read transaction), so a claim or a release
2044
+ // that lands meanwhile never counts a run as both waiting and held, or as neither. The deadlines' clock is read
2045
+ // once in it, then bound into every count, so the counts judge one "now".
2046
+ return db.transaction(async (tx) => {
2047
+ const now = clock();
2048
+ const [read] = await tx.all(`SELECT ${now.sql} AS at`, ...now.params);
2049
+ const at = Number(read.at);
2050
+ const n = { sql: d.bigintParam, params: [at] };
2051
+ const claimable = claimableIn(d, n);
2052
+ const [queued] = await tx.all(`SELECT count(*) AS count FROM runs WHERE ${claimable.sql}`, ...claimable.params);
2053
+ const held = await tx.all(`SELECT runner, count(*) AS count FROM runs WHERE state IN ('running', 'parked') AND runner IS NOT NULL AND claimed_until >= ${n.sql} GROUP BY runner ORDER BY runner`, ...n.params);
2054
+ const [handBacks] = await tx.all(`SELECT count(*) AS count FROM hand_backs WHERE at >= ${n.sql} - ${d.bigintParam}`, ...n.params, windowMs);
2055
+ return { at, queued: Number(queued?.count ?? 0), held: new Map(held.map((row) => [row.runner, Number(row.count)])), handBacks: Number(handBacks?.count ?? 0) };
2056
+ }, { read: true });
2057
+ },
1928
2058
  };
1929
2059
  this.importedTemplates = {
1930
2060
  list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
@@ -2138,7 +2268,8 @@ class SqliteStore {
2138
2268
  * request of the store's one connection queues behind it (the purge already committed). One it held back (or that
2139
2269
  * failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
2140
2270
  * 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). */
2271
+ * server logs), and drops what it served of the purged run all the same (agent-delete.ts purgeOneOrRefuse); the
2272
+ * client's retry finds the row purged and runs this again through purgeScrub. */
2142
2273
  async #purged() {
2143
2274
  const marker = this.#scrubMarker;
2144
2275
  const db = this.#db;
@@ -2155,6 +2286,16 @@ class SqliteStore {
2155
2286
  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 });
2156
2287
  }
2157
2288
  }
2289
+ async purgeScrub() {
2290
+ const marker = this.#scrubMarker;
2291
+ if (marker === undefined)
2292
+ return;
2293
+ // A marker there may be a rewrite's, under way (secureRewrite): counted as one a purge left, so that rewrite keeps it
2294
+ // unless a checkpoint asked after this truncates the log.
2295
+ if (existsSync(marker))
2296
+ return void this.#purgeMarks++;
2297
+ await this.#purged();
2298
+ }
2158
2299
  async secureRewrite(work, options = {}) {
2159
2300
  const marker = this.#scrubMarker;
2160
2301
  const db = this.#db;
@@ -2237,9 +2378,48 @@ class SqliteStore {
2237
2378
  for (const { id } of picked)
2238
2379
  this.#released.delete(id);
2239
2380
  // A running run that still names its runner was taken from it: that runner's lease ran out mid-run (CLAIMABLE).
2240
- return picked.map(({ id, state, runner: held }) => ({ runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(state === "running" && held !== null ? { lost: { runner: held } } : {}) }));
2381
+ const lostOf = (state, held) => (state === "running" && held !== null ? held : undefined);
2382
+ const attempts = await this.#attemptsAt(tx, runner, stamp, picked.map(({ id, state, runner: held }) => ({ runId: id, epoch: epochs.get(id), from: state, lost: lostOf(state, held) !== undefined })));
2383
+ return picked.map(({ id, state, runner: held }) => {
2384
+ const lost = lostOf(state, held);
2385
+ const at = attempts.get(id);
2386
+ return { runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(lost !== undefined ? { lost: { runner: lost } } : {}), ...(at ? { turn: at.turn, attempt: at.attempt } : {}) };
2387
+ });
2241
2388
  });
2242
2389
  }
2390
+ /** Each claim's turn and attempt (run_attempts), written in the claim's transaction `tx`, in three statements for the
2391
+ * whole batch: the run's latest claim before it, and the run's next journal id now (no write under an older claim can
2392
+ * land after this one: each commit is fenced on the run's row, which this transaction holds). A claim that takes a run
2393
+ * still running from a claim that was cut (that claim's release said why, or its lease ran out) works that claim's turn
2394
+ * again, one attempt more; any other claim starts the run's next turn (a follow-up, a resume after a park, the first).
2395
+ * The cause is the cut claim's word, else a crash (a lease that ran out with no word), else a retry. Only when the
2396
+ * latest row is that cut claim's own: a claim moves the epoch one and a release one more, so the claim taken over is at
2397
+ * epoch - 1 (its lease ran out) or epoch - 2 (released). A row further back belongs to an earlier claim, past one that
2398
+ * wrote none (a runner of an earlier build, beside this server): that unrecorded claim's turn is not that row's, so this
2399
+ * claim starts a new turn, and nothing that row's claim did is read as redone. */
2400
+ async #attemptsAt(tx, runner, stamp, claims) {
2401
+ const out = new Map();
2402
+ if (claims.length === 0)
2403
+ return out;
2404
+ const ids = claims.map((claim) => claim.runId);
2405
+ const marks = ids.map(() => "?").join(", ");
2406
+ const before = new Map((await tx.all(`SELECT run_id, epoch, turn, attempt, cut FROM run_attempts a WHERE run_id IN (${marks}) AND epoch = (SELECT max(epoch) FROM run_attempts b WHERE b.run_id = a.run_id)`, ...ids)).map((row) => [row.run_id, row]));
2407
+ const next = new Map((await tx.all(`SELECT run_id, next_id FROM pi_metadata WHERE run_id IN (${marks})`, ...ids)).map((row) => [row.run_id, Number(row.next_id)]));
2408
+ const rows = [];
2409
+ for (const claim of claims) {
2410
+ const prev = before.get(claim.runId);
2411
+ // The claim taken over is the latest row's only at epoch - 1 (lost: no release moved it) or epoch - 2 (released, cut).
2412
+ const replaced = prev !== undefined && Number(prev.epoch) === claim.epoch - (claim.lost ? 1 : 2) ? prev : undefined;
2413
+ const redone = claim.from === "running" && replaced !== undefined && (claim.lost || replaced.cut !== null) ? replaced : undefined;
2414
+ const turn = prev === undefined ? 1 : Number(prev.turn) + (redone ? 0 : 1);
2415
+ const attempt = redone ? Number(redone.attempt) + 1 : 1;
2416
+ const cause = redone ? (redone.cut ?? (claim.lost ? "crash" : "retry")) : null;
2417
+ out.set(claim.runId, { turn, attempt });
2418
+ rows.push([claim.runId, claim.epoch, turn, attempt, cause, runner, claim.from, next.get(claim.runId) ?? JOURNAL_FIRST_ID]);
2419
+ }
2420
+ await tx.run(`INSERT INTO run_attempts (run_id, epoch, turn, attempt, cause, runner, from_state, journal_from, claimed_at) VALUES ${rows.map(() => `(?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql})`).join(", ")} ON CONFLICT (run_id, epoch) DO NOTHING`, ...rows.flatMap((row) => [...row, ...stamp.params]));
2421
+ return out;
2422
+ }
2243
2423
  /** Holds the run's row before a fenced write reads the store's clock: the lease is checked, and runs, from when the write
2244
2424
  * holds the row, never from before a wait for another writer (a no-op on SQLite, whose BEGIN IMMEDIATE already holds
2245
2425
  * the writer lock when the clock is read). */
@@ -2287,7 +2467,7 @@ class SqliteStore {
2287
2467
  // On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
2288
2468
  }, { lease: true });
2289
2469
  }
2290
- async release(claim, { state, wakeAt = null, backoffUntil = null } = {}) {
2470
+ async release(claim, { state, wakeAt = null, backoffUntil = null, cut } = {}) {
2291
2471
  // The end commit is the one write that makes a run final (applyRunPatch: the leftover rows refused and the run_live
2292
2472
  // row deleted with it). A release never does: asked to, it is refused before anything is written.
2293
2473
  if (state !== undefined && FINAL_STATES.includes(state))
@@ -2311,6 +2491,15 @@ class SqliteStore {
2311
2491
  // never live until the next claim. A claim whose lease ran out releases nothing: the run, running with its lease run
2312
2492
  // out, is claimable at once, never stuck.
2313
2493
  `UPDATE runs SET epoch = epoch + 1, runner = NULL, claimed_until = NULL, wake_at = ?, backoff_until = ?, state = coalesce(?, state)${leaving ? `, left_running_at = ${now.sql}` : ""} WHERE ${fence.where} AND runner = ?`, [wakeAt, backoffUntil, state ?? null, ...(leaving ? now.params : []), ...fence.params, claim.runner]));
2494
+ // A release that leaves the run running is a hand-back (schema.ts HAND_BACKS): kept in this same write for the
2495
+ // capacity read, with the rows past HAND_BACKS_KEPT_MS removed. A park, or a release of a parked run, is none.
2496
+ if ((state ?? final?.state) === "running") {
2497
+ await tx.run(`DELETE FROM hand_backs WHERE at < ${now.sql} - ${this.#db.dialect.bigintParam}`, ...now.params, HAND_BACKS_KEPT_MS);
2498
+ await tx.run(`INSERT INTO hand_backs (run_id, runner, epoch, at) VALUES (?, ?, ?, ${now.sql})`, claim.runId, claim.runner, claim.epoch, ...now.params);
2499
+ }
2500
+ // Why the claim let its run go unfinished, on its own row, in the release's transaction: the next claim reads it.
2501
+ if (cut !== undefined)
2502
+ await tx.run("UPDATE run_attempts SET cut = ? WHERE run_id = ? AND epoch = ? AND cut IS NULL", cut, claim.runId, claim.epoch);
2314
2503
  }, { full: true });
2315
2504
  // The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
2316
2505
  this.#journals.delete(journalKey(claim));
@@ -2434,8 +2623,8 @@ class SqliteStore {
2434
2623
  // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
2435
2624
  // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
2436
2625
  // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
2437
- const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, started_at, ended_at)
2438
- VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), run.startedAt, run.endedAt ?? at);
2626
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, disk, started_at, ended_at)
2627
+ VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), launchDiskOf(run.launch), run.startedAt, run.endedAt ?? at);
2439
2628
  await writeLaunch(tx, run.id, run.launch, at);
2440
2629
  await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
2441
2630
  return runOf(row);
@@ -0,0 +1,34 @@
1
+ import { type SchemaState } from "./postgres/migrate.js";
2
+ import { type StoreTarget } from "./open.js";
3
+ /** The line `agentrun-serve store-schema` prints. */
4
+ export interface StoreSchemaReport {
5
+ readonly store: StoreTarget["kind"];
6
+ /** Where the store is, in words: the SQLite file, or the Postgres schema (never its URL). */
7
+ readonly where: string;
8
+ readonly schema: number | null;
9
+ readonly runnerFloor: number | null;
10
+ readonly build: number;
11
+ readonly server: "sets up" | "opens" | "migrates" | "refuses";
12
+ readonly runner: "opens" | "waits" | "refused";
13
+ }
14
+ /** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
15
+ * version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
16
+ * on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
17
+ * its server adds at its start: the runner waits for it, as openSqliteStore makes it. */
18
+ export declare function storeSchemaReport(target: StoreTarget, state: SchemaState, build: number, earlier?: boolean, awaits?: boolean): StoreSchemaReport;
19
+ /** How long the read waits on Postgres (ms): for a lock (a server migrating holds the ledger's), for its one statement, and
20
+ * for any answer at all (a database that took the connection and went silent). Past one, the read fails: exit 1. */
21
+ export declare const STORE_SCHEMA_LOCK_MS = 2000;
22
+ export declare const STORE_SCHEMA_STATEMENT_MS = 5000;
23
+ export declare const STORE_SCHEMA_ANSWER_MS = 6000;
24
+ /** Reads the store `dataDir` and `env` name (and the URL, this process's AGENTRUN_STORE_URL secret unless given). */
25
+ export declare function readStoreSchema(dataDir: string, env?: NodeJS.ProcessEnv, url?: string): Promise<StoreSchemaReport>;
26
+ /** The versions this build knows, read from its own files, with no store: `postgres`, its newest migration; `sqlite`,
27
+ * SCHEMA_VERSION. */
28
+ export declare const buildSchema: () => {
29
+ readonly postgres: number;
30
+ readonly sqlite: number;
31
+ };
32
+ /** `agentrun-serve store-schema [--data DIR]`, or `--build` (this build's versions, no store read): the exit code (the
33
+ * file's head). */
34
+ export declare function storeSchemaMain(argv: readonly string[], defaultDataDir: string, usage: string): Promise<number>;