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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +94 -13
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +10 -4
  8. package/dist/api-only.d.ts +4 -2
  9. package/dist/api-only.js +5 -3
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/computer-setting.d.ts +8 -0
  13. package/dist/computer-setting.js +11 -0
  14. package/dist/computers.d.ts +6 -2
  15. package/dist/computers.js +2 -2
  16. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  17. package/dist/console/assets/index-DlQepP2J.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/fal-price.d.ts +76 -0
  20. package/dist/fal-price.js +368 -0
  21. package/dist/learn/commit.d.ts +5 -0
  22. package/dist/learn/commit.js +4 -1
  23. package/dist/learn/compile.d.ts +13 -5
  24. package/dist/learn/compile.js +24 -7
  25. package/dist/learn/delete.d.ts +12 -6
  26. package/dist/learn/delete.js +17 -11
  27. package/dist/learn/folder.d.ts +11 -0
  28. package/dist/learn/folder.js +20 -3
  29. package/dist/learn/learning-of.d.ts +8 -0
  30. package/dist/learn/learning-of.js +8 -0
  31. package/dist/learn/learning.sh +14 -1
  32. package/dist/learn/promote.d.ts +51 -7
  33. package/dist/learn/promote.js +51 -8
  34. package/dist/learning-reset.d.ts +18 -0
  35. package/dist/learning-reset.js +115 -0
  36. package/dist/learning-routes.d.ts +1 -1
  37. package/dist/learning-words.d.ts +5 -0
  38. package/dist/learning-words.js +5 -0
  39. package/dist/learning.d.ts +8 -6
  40. package/dist/learning.js +5 -4
  41. package/dist/llms.txt +1 -0
  42. package/dist/mcp-gateway.d.ts +39 -2
  43. package/dist/mcp-gateway.js +41 -10
  44. package/dist/mcp-pin-first.js +1 -1
  45. package/dist/mcp-servers-store.d.ts +1 -0
  46. package/dist/mcp-servers-store.js +2 -1
  47. package/dist/media-duration.d.ts +2 -0
  48. package/dist/media-duration.js +136 -0
  49. package/dist/openapi.js +45 -12
  50. package/dist/provider.d.ts +8 -0
  51. package/dist/provider.js +14 -2
  52. package/dist/refusal-words.d.ts +0 -3
  53. package/dist/refusal-words.js +0 -3
  54. package/dist/request-metadata.d.ts +20 -0
  55. package/dist/request-metadata.js +24 -0
  56. package/dist/run-launch.d.ts +13 -4
  57. package/dist/run-launch.js +14 -3
  58. package/dist/run-learning-served.d.ts +2 -2
  59. package/dist/run-usage.d.ts +48 -4
  60. package/dist/run-usage.js +156 -39
  61. package/dist/run-view.d.ts +1 -1
  62. package/dist/run-view.js +3 -7
  63. package/dist/runner/adapter-loop.d.ts +3 -1
  64. package/dist/runner/adapter-loop.js +12 -9
  65. package/dist/runner/adapter-run-spec.d.ts +1 -1
  66. package/dist/runner/adapter-run-spec.js +13 -13
  67. package/dist/runner/audit.d.ts +8 -3
  68. package/dist/runner/audit.js +21 -6
  69. package/dist/runner/claim-secrets.d.ts +2 -1
  70. package/dist/runner/claim-secrets.js +5 -3
  71. package/dist/runner/cli-run-spec.d.ts +1 -1
  72. package/dist/runner/cli-run-spec.js +12 -11
  73. package/dist/runner/conformance/harness.js +4 -2
  74. package/dist/runner/dispatch.js +4 -2
  75. package/dist/runner/harness-loops.js +5 -2
  76. package/dist/runner/journal-kinds.d.ts +3 -0
  77. package/dist/runner/learning-end.d.ts +2 -1
  78. package/dist/runner/learning-end.js +47 -22
  79. package/dist/runner/mcp-claim.js +1 -1
  80. package/dist/runner/mcp-run.d.ts +9 -0
  81. package/dist/runner/mcp-run.js +16 -1
  82. package/dist/runner/model-route.js +7 -4
  83. package/dist/runner/promotion.d.ts +40 -21
  84. package/dist/runner/promotion.js +130 -59
  85. package/dist/runner/run-child-host.js +6 -4
  86. package/dist/runner/runner.js +15 -3
  87. package/dist/runner/sdk-loop.d.ts +2 -2
  88. package/dist/runner/sdk-loop.js +3 -3
  89. package/dist/runner/store-port.d.ts +3 -0
  90. package/dist/runner/workflow-spec.js +3 -3
  91. package/dist/runs-over-store.d.ts +5 -2
  92. package/dist/runs-over-store.js +14 -7
  93. package/dist/sdk/check.d.ts +6 -5
  94. package/dist/sdk/check.js +17 -16
  95. package/dist/sdk/runs.js +81 -65
  96. package/dist/server.js +84 -20
  97. package/dist/store/agent-body.d.ts +4 -0
  98. package/dist/store/agent-body.js +4 -1
  99. package/dist/store/index.d.ts +1 -1
  100. package/dist/store/journal/storage.d.ts +2 -0
  101. package/dist/store/journal/storage.js +2 -1
  102. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  103. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  104. package/dist/store/schema.d.ts +14 -1
  105. package/dist/store/schema.js +42 -4
  106. package/dist/store/sqlite/run-launch.d.ts +22 -0
  107. package/dist/store/sqlite/run-launch.js +72 -7
  108. package/dist/store/sqlite/run-patch.d.ts +2 -1
  109. package/dist/store/sqlite/run-patch.js +4 -3
  110. package/dist/store/sqlite/store.js +141 -29
  111. package/dist/store/store-schema.js +2 -2
  112. package/dist/store/store.d.ts +67 -4
  113. package/dist/store-reads/learning.d.ts +12 -8
  114. package/dist/store-reads/learning.js +33 -24
  115. package/dist/store-reads/loop.d.ts +4 -3
  116. package/dist/store-reads/loop.js +7 -5
  117. package/dist/template-eval.js +4 -4
  118. package/dist/templates.d.ts +3 -0
  119. package/dist/templates.js +7 -5
  120. package/dist/timeline/labels.js +1 -1
  121. package/dist/tools.js +1 -1
  122. package/dist/uploads-archil.js +2 -1
  123. package/dist/uploads.d.ts +0 -3
  124. package/dist/uploads.js +2 -11
  125. package/dist/validate.js +5 -1
  126. package/dist/web-save.d.ts +3 -0
  127. package/dist/web-save.js +17 -2
  128. package/dist/workspace/archil-exec.js +1 -1
  129. package/dist/workspace/archil.js +1 -1
  130. package/dist/workspace/revision-skills.js +24 -11
  131. package/dist/workspace/synced-folder.d.ts +3 -3
  132. package/dist/workspace/synced-folder.js +7 -6
  133. package/package.json +10 -10
  134. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  135. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -5,11 +5,31 @@
5
5
  import { StoreLaunchMissing } from "../store.js";
6
6
  const RUN_LAUNCH_COLUMNS = "run_id, body, sealed, created_at";
7
7
  const runLaunchOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), createdAt: r.created_at });
8
+ // For the store's other reads of a run's JSON (a launch body, a command's body, a journal record): one id or flag out of
9
+ // a document whose strings may hold an escaped NUL or a lone surrogate.
10
+ export { postgresReadableJson, postgresUnicodeRefusal };
11
+ /** JSON text `column` as a read of one id or flag out of it inside a transaction takes it, where a refused statement
12
+ * aborts the transaction and can't be read again: on Postgres its copy with those escapes blanked (postgresReadableJson),
13
+ * on SQLite (whose json functions read them) the column itself. */
14
+ export const readableJson = (dialect, column) => (dialect.name === "postgres" ? postgresReadableJson(column) : column);
8
15
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
9
16
  * trigger path both call it, so the row lands with its run or not at all. */
10
17
  export function writeLaunch(tx, runId, launch, at) {
11
18
  return tx.run("INSERT INTO run_launch (run_id, body, sealed, created_at) VALUES (?, ?, ?, ?)", runId, JSON.stringify(launch.body ?? null), launch.sealed ?? null, at);
12
19
  }
20
+ /** The disk a launch body names as the run's own (runs.disk, RunRow.disk): its `archil_disk` of kind "launch", by its id
21
+ * (run-launch.ts launchBody writes it so); null for none, or its agent's own disk (the default disk). The one read of the
22
+ * body's disk the store makes, at every create of a run, so no path that queues a run can leave it out. */
23
+ export function launchDiskOf(launch) {
24
+ const body = launch?.body;
25
+ if (typeof body !== "object" || body === null)
26
+ return null;
27
+ const disk = body.archil_disk;
28
+ if (typeof disk !== "object" || disk === null)
29
+ return null;
30
+ const { disk_id: id, kind } = disk;
31
+ return kind === "launch" && typeof id === "string" && id !== "" ? id : null;
32
+ }
13
33
  /** A message's launch secrets written over the run's (runs.command, runs.reopen), inside `tx`: the bytes as given, or a
14
34
  * function's answer to the bytes the launch holds now, read in the same transaction. */
15
35
  export async function writeLaunchSealed(tx, runId, launchSealed) {
@@ -30,6 +50,19 @@ export async function readLaunch(executor, runId) {
30
50
  throw new StoreLaunchMissing(runId);
31
51
  return runLaunchOf(row);
32
52
  }
53
+ /** Whether `error` (or a cause of it, six deep) is Postgres refusing a JSON document for an escaped NUL or a lone
54
+ * surrogate in it: the text type keeps them, but every json function decodes the whole document's strings. */
55
+ function postgresUnicodeRefusal(error) {
56
+ for (let cause = error, depth = 0; cause && depth < 6; cause = cause.cause, depth++)
57
+ if (cause.code === "22P05" || (cause.code === "22P02" && cause.reason === "json_surrogate"))
58
+ return true;
59
+ return false;
60
+ }
61
+ /** Postgres SQL for JSON text `column` with its escaped NULs and surrogates (\u0000, \ud800-\udfff) read as escaped
62
+ * spaces, for a read of one number or id out of a document whose other strings may hold one (0026_run_disk.sql blanks
63
+ * them for its backfill). A replaced escape stays an escape, so it is still JSON. Only an escape is replaced: u0000 after
64
+ * an escaped backslash (the text \u0000 in an id, written \\u0000) is text and is kept, so an id reads as it is. */
65
+ const postgresReadableJson = (column) => `regexp_replace(${column}, '(?<!\\\\)((?:\\\\\\\\)*)\\\\u(0000|[dD][89a-fA-F][0-9a-fA-F]{2})', '\\1\\\\u0020', 'g')`;
33
66
  /** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
34
67
  * the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
35
68
  * Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
@@ -53,11 +86,7 @@ export async function readUsageMetadata(executor, runId, { completion }) {
53
86
  // PostgreSQL accepts escaped NUL/lone-surrogate strings in JSON TEXT but cannot extract ANY member of
54
87
  // such a document. Only its exact Unicode refusal permits the former JS read/parse cost for that row.
55
88
  // Never sanitize native identities or silently lose known counters to an unrelated replay string.
56
- let unicode = false;
57
- for (let cause = error, depth = 0; cause && depth < 6; cause = cause.cause, depth++)
58
- if (cause.code === "22P05" || (cause.code === "22P02" && cause.reason === "json_surrogate"))
59
- unicode = true;
60
- if (executor.dialect.name !== "postgres" || !unicode)
89
+ if (executor.dialect.name !== "postgres" || !postgresUnicodeRefusal(error))
61
90
  throw error;
62
91
  const raw = await executor.get(`SELECT l.body${completion ? ", s.value AS inbox" : ""} ${from}`, ...params);
63
92
  if (!raw)
@@ -79,6 +108,42 @@ export async function readUsageMetadata(executor, runId, { completion }) {
79
108
  * and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
80
109
  * is the member's JSON text, null when the run's body names none. */
81
110
  export async function readLearningStarts(executor, agentId, where) {
82
- const rows = await executor.all(`SELECT run_id, ${executor.dialect.jsonText("body", ["learning"])} AS learning FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND ${where})`, agentId);
83
- return rows.map((row) => ({ runId: row.run_id, learning: row.learning === null ? undefined : JSON.parse(row.learning) }));
111
+ const learning = executor.dialect.jsonText("body", ["learning"]);
112
+ const runs = `run_id IN (SELECT id FROM runs WHERE agent_id = ? AND ${where})`;
113
+ let rows;
114
+ try {
115
+ rows = await executor.all(`SELECT run_id, ${learning} AS learning FROM run_launch WHERE ${runs}`, agentId);
116
+ }
117
+ catch (error) {
118
+ // A body holding an escaped NUL or a lone surrogate anywhere (a run's input) makes Postgres refuse the whole read. Read
119
+ // again: `learning` out of each body that holds none, and each body that does whole, parsed here, so a run's notes
120
+ // come back as written, never blanked. On an ordinary store connection, as readUsageMetadata's, so the read again is
121
+ // outside a failed transaction.
122
+ if (executor.dialect.name !== "postgres" || !postgresUnicodeRefusal(error))
123
+ throw error;
124
+ rows = await executor.all(`SELECT run_id, CASE WHEN odd THEN NULL ELSE ${learning} END AS learning, CASE WHEN odd THEN body END AS body
125
+ FROM (SELECT run_id, body, ${postgresReadableJson("body")} <> body AS odd FROM run_launch WHERE ${runs}) AS launch`, agentId);
126
+ }
127
+ return rows.map((row) => ({
128
+ runId: row.run_id,
129
+ learning: row.body != null ? (JSON.parse(row.body)?.learning ?? undefined) : row.learning === null ? undefined : JSON.parse(row.learning),
130
+ }));
131
+ }
132
+ /** The ids of agent `agentId`'s runs started after `at` whose learning seed was read at or before it (the launch body's
133
+ * `learning.seededAt`), in one read of that one number a run started after `at`: never a run's section or input. */
134
+ export async function readSeededBefore(executor, agentId, at) {
135
+ const read = (body) => executor.all(`SELECT run_id, ${executor.dialect.jsonText(body, ["learning", "seededAt"])} AS seeded_at FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND started_at > ?)`, agentId, at);
136
+ let rows;
137
+ try {
138
+ rows = await read("body");
139
+ }
140
+ catch (error) {
141
+ // A body holding an escaped NUL or a lone surrogate anywhere (a run's input) makes Postgres refuse the whole read: the
142
+ // one number is read again from copies with those escapes blanked (postgresReadableJson), never a run's text. On an
143
+ // ordinary store connection, as readUsageMetadata's, so the retry is outside a failed transaction.
144
+ if (executor.dialect.name !== "postgres" || !postgresUnicodeRefusal(error))
145
+ throw error;
146
+ rows = await read(postgresReadableJson("body"));
147
+ }
148
+ return rows.flatMap((row) => (row.seeded_at !== null && Number(row.seeded_at) <= at ? [row.run_id] : []));
84
149
  }
@@ -27,11 +27,12 @@ export type RunRecord = {
27
27
  imported_from: string | null;
28
28
  sign_in_handed: string | null;
29
29
  labels: string | null;
30
+ disk: string | null;
30
31
  started_at: number;
31
32
  ended_at: number | null;
32
33
  purged_at: number | null;
33
34
  };
34
- export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, started_at, ended_at, purged_at";
35
+ export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, disk, started_at, ended_at, purged_at";
35
36
  /** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
36
37
  * stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
37
38
  export declare const EXACT_COST_USD: (alias: string) => string;
@@ -6,13 +6,14 @@
6
6
  import { endedReason, FINAL_STATES, Fenced } from "../store.js";
7
7
  import { settledBody, SQLITE } from "../dialect.js";
8
8
  import { claimFence, storeNow } from "../fence.js";
9
+ import { readableJson } from "./run-launch.js";
9
10
  /** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
10
11
  * list of runs names. */
11
12
  export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
12
13
  /** The lock a write of a run's sign_in_handed and a sign-in's forget both take (Dialect.lockKey): the forget's check of
13
14
  * the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
14
15
  export const SIGN_IN_HANDED_LOCK = "sign_in_handed";
15
- export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, started_at, ended_at, purged_at";
16
+ export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, disk, started_at, ended_at, purged_at";
16
17
  /** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
17
18
  * stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
18
19
  export const EXACT_COST_USD = (alias) => `CASE WHEN ${alias}.cost_upper_bound = 1 THEN NULL ELSE ${alias}.cost_usd END`;
@@ -25,7 +26,7 @@ export const runOf = (r) => ({
25
26
  wakeAt: r.wake_at, backoffUntil: r.backoff_until, ...costOf(r.cost_usd, r.cost_upper_bound), metrics: r.metrics === null ? null : JSON.parse(r.metrics), summary: r.summary,
26
27
  outcome: r.outcome ?? null, archivedAt: r.archived_at, importedFrom: r.imported_from === null ? null : JSON.parse(r.imported_from),
27
28
  signInHanded: r.sign_in_handed === null ? null : JSON.parse(r.sign_in_handed), labels: r.labels === null ? {} : JSON.parse(r.labels),
28
- startedAt: r.started_at, endedAt: r.ended_at, purgedAt: r.purged_at ?? null,
29
+ disk: r.disk, startedAt: r.started_at, endedAt: r.ended_at, purgedAt: r.purged_at ?? null,
29
30
  });
30
31
  /** Applies `patch` to the claim's run, then writes `also`, through `tx` (an open transaction's handle). Fenced, with nothing
31
32
  * of it written once the caller rolls back, when the run's epoch is not the claim's or the claim's lease ran out before
@@ -110,7 +111,7 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
110
111
  export const REOPEN_SET = "state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL";
111
112
  export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AND outcome = 'stopped')) AND imported_from IS NULL AND purged_at IS NULL
112
113
  AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
113
- AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText("run_launch.body", ["harness"])} = 'learning')`;
114
+ AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText(readableJson(d, "run_launch.body"), ["harness"])} = 'learning')`;
114
115
  /** After a write that made the run final has taken its own rows: every command row of the run still untaken is refused
115
116
  * with the end's reason, in that same transaction. The store takes no new row on a final run (RunFinal), so a row the
116
117
  * end left untaken would stay so for good, as it would if the runner died right after the end.
@@ -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, 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, RUNNERS, RUNNERS_ADDED, 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, readUsageMetadata, 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),
@@ -210,6 +214,7 @@ export const SQLITE_RUNNER_NEEDS = [
210
214
  { table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
211
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)" },
212
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)" },
213
218
  ];
214
219
  /** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
215
220
  * or undefined when it opens; `columnsOf` reads a table's columns. */
@@ -345,8 +350,9 @@ export async function openSqliteStore(options) {
345
350
  // in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
346
351
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
347
352
  // (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
348
- // purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
349
- 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;
350
356
  if (upgrading && role === "runner")
351
357
  throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
352
358
  if (found !== SCHEMA_VERSION && !upgrading)
@@ -402,6 +408,11 @@ export async function openSqliteStore(options) {
402
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)) {
403
409
  throw new StoreAwaitsServer("keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)");
404
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
+ }
405
416
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
406
417
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
407
418
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -436,6 +447,8 @@ export async function openSqliteStore(options) {
436
447
  // Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
437
448
  { sql: COMPUTER_INTERVALS },
438
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 },
439
452
  { sql: NATIVE_COMMANDS_INDEX },
440
453
  ], { full: true });
441
454
  // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
@@ -461,7 +474,9 @@ export async function openSqliteStore(options) {
461
474
  }
462
475
  if (upgrading) {
463
476
  const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
464
- 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 });
465
480
  }
466
481
  }
467
482
  }
@@ -560,6 +575,8 @@ async function dropRunContent(tx, runId) {
560
575
  await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
561
576
  await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
562
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);
563
580
  }
564
581
  /** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
565
582
  * purge (Agents.purge) and its delete (Agents.remove) both drop. */
@@ -608,6 +625,7 @@ class SqliteStore {
608
625
  sealedKeys;
609
626
  computerLedger;
610
627
  computerIntervals;
628
+ runAttempts;
611
629
  pairedComputers;
612
630
  mintedTokens;
613
631
  runners;
@@ -635,7 +653,7 @@ class SqliteStore {
635
653
  #released = new Map();
636
654
  /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
637
655
  #scrubMarker;
638
- /** 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
639
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
640
658
  * purge left is never removed without a checkpoint that truncated the purge's frames. */
641
659
  #purgeMarks = 0;
@@ -694,8 +712,9 @@ class SqliteStore {
694
712
  throw new AgentDeleting(agentId);
695
713
  };
696
714
  /** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
697
- * launch is read (no index names its source): a purge's read, never a hot path. */
698
- 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);
699
718
  /** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
700
719
  * while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
701
720
  * distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
@@ -1034,7 +1053,7 @@ class SqliteStore {
1034
1053
  const firing = await tx.get("SELECT status FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
1035
1054
  if (!firing || firing.status !== "due")
1036
1055
  return undefined;
1037
- 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;
1038
1057
  const clear = "retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, attempts = 0";
1039
1058
  if (waiting >= bound.max) {
1040
1059
  await tx.run(`UPDATE trigger_firings SET status = 'skipped', reason = ?, ${clear} WHERE trigger_id = ? AND key = ?`, bound.reason, triggerId, key);
@@ -1108,7 +1127,7 @@ class SqliteStore {
1108
1127
  await d.lockRow(tx, "triggers", "id", firing.triggerId);
1109
1128
  // Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
1110
1129
  await refuseArchived(tx, run.agentId);
1111
- 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);
1112
1131
  // The run's launch row lands with it, through the store's one writer, or neither does.
1113
1132
  if (launch)
1114
1133
  await writeLaunch(tx, run.id, launch, at);
@@ -1126,7 +1145,7 @@ class SqliteStore {
1126
1145
  this.runs = {
1127
1146
  create: async ({ id, agentId, revisionId, origin, labels }, launch) => {
1128
1147
  // sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
1129
- 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}`;
1130
1149
  const labelled = labelsColumn(labels);
1131
1150
  // The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
1132
1151
  // never lands, and a run never exists without the launch it was started with. Never a run of an agent being
@@ -1144,7 +1163,7 @@ class SqliteStore {
1144
1163
  if (source && source.purged_at !== null)
1145
1164
  throw new RunPurged(of, id);
1146
1165
  }
1147
- 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);
1148
1167
  if (origin)
1149
1168
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
1150
1169
  if (launch)
@@ -1153,7 +1172,7 @@ class SqliteStore {
1153
1172
  }));
1154
1173
  },
1155
1174
  createInline: async ({ agent, revision, run, launch }) => {
1156
- 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}`;
1157
1176
  const made = await db.transaction(async (tx) => {
1158
1177
  const at = now();
1159
1178
  // Hold the external reference, so two first uses of the same expert serialize (SQLite's one writer already does).
@@ -1178,7 +1197,7 @@ class SqliteStore {
1178
1197
  await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
1179
1198
  }
1180
1199
  // The run, its origin and its launch, in the same transaction as the agent and the revision.
1181
- 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);
1182
1201
  if (run.origin)
1183
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);
1184
1203
  await writeLaunch(tx, run.id, launch, at);
@@ -1193,7 +1212,8 @@ class SqliteStore {
1193
1212
  launch: (runId) => readLaunch(db, runId),
1194
1213
  usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
1195
1214
  learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
1196
- 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 }) => {
1197
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,
1198
1218
  // count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
1199
1219
  const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
@@ -1209,6 +1229,10 @@ class SqliteStore {
1209
1229
  // Each label, key and value bound as parameters (never spliced into a JSON path), all of them held.
1210
1230
  for (const [key, value] of Object.entries(labels ?? {}))
1211
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));
1212
1236
  const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
1213
1237
  if (bounded)
1214
1238
  params.push(limit);
@@ -1300,11 +1324,22 @@ class SqliteStore {
1300
1324
  // itself (turnCostOf over each turn's data), which no column holds.
1301
1325
  costUnknown: async ({ limit, after }) => {
1302
1326
  const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
1303
- 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}
1304
1328
  AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
1305
- 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))
1306
- 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"])} = ?)
1307
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
+ }
1308
1343
  return rows.map((row) => row.id);
1309
1344
  },
1310
1345
  relist: async ({ flags, agentId }) => {
@@ -1334,11 +1369,22 @@ class SqliteStore {
1334
1369
  // Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
1335
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] }]);
1336
1371
  },
1337
- every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
1338
- .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 })),
1339
1374
  madeFrom: async (runId) => {
1340
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);
1341
- 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();
1342
1388
  },
1343
1389
  purge: async (runId, kept) => {
1344
1390
  const purged = await db.transaction(async (tx) => {
@@ -1352,7 +1398,7 @@ class SqliteStore {
1352
1398
  // A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
1353
1399
  // its input: each is purged first.
1354
1400
  const left = [];
1355
- for (const id of await launchedFrom(tx, runId)) {
1401
+ for (const id of await launchedFrom(tx, runId, readableJson(d, "body"))) {
1356
1402
  if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
1357
1403
  left.push(id);
1358
1404
  }
@@ -1886,6 +1932,19 @@ class SqliteStore {
1886
1932
  },
1887
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),
1888
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
+ };
1889
1948
  const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
1890
1949
  this.pairedComputers = {
1891
1950
  addCode: async (id, codeSha256, expiresAt) => {
@@ -2209,7 +2268,8 @@ class SqliteStore {
2209
2268
  * request of the store's one connection queues behind it (the purge already committed). One it held back (or that
2210
2269
  * failed) leaves secureRewrite's marker, so the next start's scrub truncates the log, a crash between included. A marker
2211
2270
  * that cannot be written (a full disk) throws, the purge committed: its caller answers it as the fault it is (a 500 the
2212
- * 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. */
2213
2273
  async #purged() {
2214
2274
  const marker = this.#scrubMarker;
2215
2275
  const db = this.#db;
@@ -2226,6 +2286,16 @@ class SqliteStore {
2226
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 });
2227
2287
  }
2228
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
+ }
2229
2299
  async secureRewrite(work, options = {}) {
2230
2300
  const marker = this.#scrubMarker;
2231
2301
  const db = this.#db;
@@ -2308,9 +2378,48 @@ class SqliteStore {
2308
2378
  for (const { id } of picked)
2309
2379
  this.#released.delete(id);
2310
2380
  // A running run that still names its runner was taken from it: that runner's lease ran out mid-run (CLAIMABLE).
2311
- 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
+ });
2312
2388
  });
2313
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
+ }
2314
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
2315
2424
  * holds the row, never from before a wait for another writer (a no-op on SQLite, whose BEGIN IMMEDIATE already holds
2316
2425
  * the writer lock when the clock is read). */
@@ -2358,7 +2467,7 @@ class SqliteStore {
2358
2467
  // On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
2359
2468
  }, { lease: true });
2360
2469
  }
2361
- async release(claim, { state, wakeAt = null, backoffUntil = null } = {}) {
2470
+ async release(claim, { state, wakeAt = null, backoffUntil = null, cut } = {}) {
2362
2471
  // The end commit is the one write that makes a run final (applyRunPatch: the leftover rows refused and the run_live
2363
2472
  // row deleted with it). A release never does: asked to, it is refused before anything is written.
2364
2473
  if (state !== undefined && FINAL_STATES.includes(state))
@@ -2388,6 +2497,9 @@ class SqliteStore {
2388
2497
  await tx.run(`DELETE FROM hand_backs WHERE at < ${now.sql} - ${this.#db.dialect.bigintParam}`, ...now.params, HAND_BACKS_KEPT_MS);
2389
2498
  await tx.run(`INSERT INTO hand_backs (run_id, runner, epoch, at) VALUES (?, ?, ?, ${now.sql})`, claim.runId, claim.runner, claim.epoch, ...now.params);
2390
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);
2391
2503
  }, { full: true });
2392
2504
  // The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
2393
2505
  this.#journals.delete(journalKey(claim));
@@ -2511,8 +2623,8 @@ class SqliteStore {
2511
2623
  // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
2512
2624
  // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
2513
2625
  // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
2514
- 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)
2515
- 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);
2516
2628
  await writeLaunch(tx, run.id, run.launch, at);
2517
2629
  await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
2518
2630
  return runOf(row);
@@ -23,7 +23,7 @@ import { storePlace, storeTarget } from "./open.js";
23
23
  import { SCHEMA_VERSION } from "./schema.js";
24
24
  import { earlierVersionIn, runnerWaitsFor, STORE_FILE } from "./sqlite/store.js";
25
25
  /** The SQLite store's versions the server upgrades in place (sqlite/store.ts openSqliteStore). */
26
- const SQLITE_UPGRADES = new Set([11, 12, 13]);
26
+ const SQLITE_UPGRADES = new Set([11, 12, 13, 14]);
27
27
  /** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
28
28
  * version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
29
29
  * on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
@@ -34,7 +34,7 @@ export function storeSchemaReport(target, state, build, earlier = false, awaits
34
34
  ? "refuses"
35
35
  : version === null ? "sets up" : version === build ? "opens" : version > build ? "refuses" : target.kind === "postgres" || SQLITE_UPGRADES.has(version) ? "migrates" : "refuses";
36
36
  // A SQLite runner opens only its own version: its floor is the version (sqlite/store.ts schemaState).
37
- // On SQLite a runner waits only for a version its server upgrades in place (11-13), and refuses any other earlier one.
37
+ // On SQLite a runner waits only for a version its server upgrades in place (11-14), and refuses any other earlier one.
38
38
  const runner = target.kind === "sqlite" && version !== null && version < build && !SQLITE_UPGRADES.has(version)
39
39
  ? "refused"
40
40
  : awaits && version === build ? "waits" : runnerOn(target.kind === "sqlite" ? { version, runnerFloor: version } : state, build);