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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +236 -26
  3. package/dist/agent-delete.d.ts +36 -12
  4. package/dist/agent-delete.js +213 -30
  5. package/dist/agents-store.d.ts +6 -2
  6. package/dist/agents-store.js +18 -5
  7. package/dist/agents.d.ts +8 -1
  8. package/dist/agents.js +14 -4
  9. package/dist/answer-json.d.ts +2 -2
  10. package/dist/answer-json.js +3 -4
  11. package/dist/api-only.d.ts +7 -10
  12. package/dist/api-only.js +9 -11
  13. package/dist/archil-routes.d.ts +1 -1
  14. package/dist/archil-routes.js +4 -3
  15. package/dist/browser-sessions.d.ts +56 -0
  16. package/dist/browser-sessions.js +117 -0
  17. package/dist/compute-cost.d.ts +101 -0
  18. package/dist/compute-cost.js +250 -0
  19. package/dist/computer-routes.d.ts +4 -15
  20. package/dist/computer-routes.js +6 -10
  21. package/dist/console/assets/index-D0mr9wfZ.css +1 -0
  22. package/dist/console/assets/index-D7G6o-1E.js +720 -0
  23. package/dist/console/index.html +2 -2
  24. package/dist/errors.d.ts +4 -1
  25. package/dist/errors.js +15 -5
  26. package/dist/eval-previous.d.ts +52 -0
  27. package/dist/eval-previous.js +164 -0
  28. package/dist/file-types.d.ts +2 -0
  29. package/dist/file-types.js +3 -1
  30. package/dist/harness.js +2 -1
  31. package/dist/import.js +4 -3
  32. package/dist/learn/check.d.ts +16 -4
  33. package/dist/learn/check.js +30 -26
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +47 -0
  36. package/dist/learn/repick.d.ts +43 -0
  37. package/dist/learn/repick.js +202 -0
  38. package/dist/learn/workflow-draft.d.ts +4 -0
  39. package/dist/learn/workflow-draft.js +10 -7
  40. package/dist/learned-workflow.d.ts +2 -0
  41. package/dist/learned-workflow.js +19 -2
  42. package/dist/learning-setting.d.ts +13 -0
  43. package/dist/learning-setting.js +23 -1
  44. package/dist/llms.txt +1 -1
  45. package/dist/openapi.js +180 -14
  46. package/dist/paid-calls.d.ts +17 -7
  47. package/dist/paid-calls.js +15 -9
  48. package/dist/run-launch.d.ts +2 -2
  49. package/dist/run-launch.js +2 -1
  50. package/dist/run-learning-served.d.ts +1 -1
  51. package/dist/run-timeline-served.js +5 -3
  52. package/dist/run-usage.d.ts +125 -0
  53. package/dist/run-usage.js +394 -0
  54. package/dist/runner/adapter-loop.d.ts +4 -0
  55. package/dist/runner/adapter-loop.js +66 -21
  56. package/dist/runner/adapter-run-spec.d.ts +8 -3
  57. package/dist/runner/adapter-run-spec.js +13 -6
  58. package/dist/runner/big-writes.d.ts +33 -0
  59. package/dist/runner/big-writes.js +105 -0
  60. package/dist/runner/cli-run-spec.js +14 -6
  61. package/dist/runner/conformance/harness.d.ts +2 -0
  62. package/dist/runner/conformance/harness.js +18 -4
  63. package/dist/runner/feedback-round.d.ts +29 -1
  64. package/dist/runner/feedback-round.js +54 -3
  65. package/dist/runner/held.d.ts +4 -1
  66. package/dist/runner/journal-kinds.d.ts +3 -1
  67. package/dist/runner/learning-end.js +54 -18
  68. package/dist/runner/loop-contract.d.ts +3 -0
  69. package/dist/runner/metrics.d.ts +4 -0
  70. package/dist/runner/metrics.js +9 -0
  71. package/dist/runner/monid-run.js +2 -2
  72. package/dist/runner/promotion.js +8 -2
  73. package/dist/runner/reflect-hook.js +3 -2
  74. package/dist/runner/run-child-host.d.ts +15 -2
  75. package/dist/runner/run-child-host.js +24 -8
  76. package/dist/runner/run-child.js +3 -0
  77. package/dist/runner/save-slots.d.ts +9 -0
  78. package/dist/runner/save-slots.js +91 -0
  79. package/dist/runs-over-store.d.ts +3 -2
  80. package/dist/runs-over-store.js +9 -7
  81. package/dist/sdk/runs.d.ts +3 -4
  82. package/dist/sdk/runs.js +10 -7
  83. package/dist/sdk/runtimes.d.ts +19 -0
  84. package/dist/sdk/runtimes.js +23 -0
  85. package/dist/sdk/schema.d.ts +14 -8
  86. package/dist/sdk/schema.js +18 -6
  87. package/dist/server.d.ts +7 -3
  88. package/dist/server.js +223 -100
  89. package/dist/store/agent-body.d.ts +2 -3
  90. package/dist/store/agent-body.js +3 -2
  91. package/dist/store/index.d.ts +2 -2
  92. package/dist/store/index.js +1 -1
  93. package/dist/store/journal/storage.js +1 -1
  94. package/dist/store/open.d.ts +1 -1
  95. package/dist/store/open.js +1 -1
  96. package/dist/store/postgres/migrations/0021_purged.sql +13 -0
  97. package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
  98. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  99. package/dist/store/schema.d.ts +20 -1
  100. package/dist/store/schema.js +60 -5
  101. package/dist/store/sqlite/connection.d.ts +4 -1
  102. package/dist/store/sqlite/connection.js +5 -0
  103. package/dist/store/sqlite/run-patch.d.ts +8 -3
  104. package/dist/store/sqlite/run-patch.js +15 -7
  105. package/dist/store/sqlite/store.d.ts +2 -1
  106. package/dist/store/sqlite/store.js +279 -68
  107. package/dist/store/sqlite/worker.d.ts +9 -0
  108. package/dist/store/sqlite/worker.js +18 -1
  109. package/dist/store/store.d.ts +149 -9
  110. package/dist/store/store.js +63 -0
  111. package/dist/store-reads/analytics.js +2 -1
  112. package/dist/store-reads/cap.d.ts +17 -7
  113. package/dist/store-reads/cap.js +54 -4
  114. package/dist/store-reads/decisions.d.ts +21 -0
  115. package/dist/store-reads/decisions.js +22 -0
  116. package/dist/store-reads/journal.d.ts +8 -2
  117. package/dist/store-reads/journal.js +27 -8
  118. package/dist/store-reads/learning.d.ts +1 -1
  119. package/dist/store-reads/learning.js +5 -2
  120. package/dist/store-reads/runs.js +2 -0
  121. package/dist/store-reads/stats.js +4 -2
  122. package/dist/store-view.d.ts +12 -1
  123. package/dist/store-view.js +98 -38
  124. package/dist/template-eval.d.ts +15 -1
  125. package/dist/template-eval.js +92 -13
  126. package/dist/templates.d.ts +1 -1
  127. package/dist/templates.js +4 -3
  128. package/dist/timeline/labels.js +17 -0
  129. package/dist/tool-list.js +1 -0
  130. package/dist/tools.d.ts +6 -2
  131. package/dist/tools.js +22 -1
  132. package/dist/trigger-targets.d.ts +28 -9
  133. package/dist/trigger-targets.js +19 -16
  134. package/dist/triggers.d.ts +2 -1
  135. package/dist/triggers.js +5 -2
  136. package/dist/validate.d.ts +4 -2
  137. package/dist/validate.js +13 -3
  138. package/dist/viewer-credential.d.ts +3 -4
  139. package/dist/viewer-credential.js +6 -4
  140. package/dist/web-fake.d.ts +25 -0
  141. package/dist/web-fake.js +38 -1
  142. package/dist/web-save.d.ts +75 -0
  143. package/dist/web-save.js +235 -0
  144. package/dist/workspace/archil-claim.d.ts +5 -2
  145. package/dist/workspace/archil-claim.js +5 -2
  146. package/dist/workspace/archil-disk.d.ts +10 -1
  147. package/dist/workspace/archil-disk.js +19 -1
  148. package/dist/workspace/archil.d.ts +3 -0
  149. package/dist/workspace/archil.js +101 -16
  150. package/dist/workspace/computer-for-claim.d.ts +19 -1
  151. package/dist/workspace/computer-for-claim.js +88 -20
  152. package/dist/workspace/computer-intervals.d.ts +26 -0
  153. package/dist/workspace/computer-intervals.js +58 -0
  154. package/dist/workspace/computer-janitor.d.ts +7 -3
  155. package/dist/workspace/computer-janitor.js +14 -6
  156. package/dist/workspace/computer-kept.d.ts +7 -2
  157. package/dist/workspace/computer-kept.js +9 -2
  158. package/dist/workspace/pieced.d.ts +14 -0
  159. package/dist/workspace/pieced.js +23 -0
  160. package/dist/workspace/resolve-computer.d.ts +7 -4
  161. package/dist/workspace/resolve-computer.js +21 -32
  162. package/dist/workspace/run-disk.js +32 -12
  163. package/dist/workspace/run-end-computers.d.ts +1 -0
  164. package/dist/workspace/run-end-computers.js +4 -1
  165. package/dist/workspace/run-workspace.d.ts +1 -1
  166. package/dist/workspace/run-workspace.js +11 -6
  167. package/package.json +10 -10
  168. package/templates/README.md +36 -7
  169. package/dist/console/assets/index-CTGegcKt.css +0 -1
  170. package/dist/console/assets/index-D1Se6mgG.js +0 -715
@@ -1,3 +1,4 @@
1
+ import { type SdkBinding } from "../sdk/runtimes.js";
1
2
  import type { NativeBinding } from "../native/types.js";
2
3
  import { type LearningSetting } from "../learning-setting.js";
3
4
  /** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
@@ -59,9 +60,7 @@ export type MonidPinBody = Readonly<Record<string, {
59
60
  readonly input: Record<string, unknown>;
60
61
  readonly usd: number | null;
61
62
  }>>;
62
- export type SdkBinding = {
63
- runtime: "claude-agent-sdk" | "codex-sdk" | "eve";
64
- };
63
+ export type { SdkBinding } from "../sdk/runtimes.js";
65
64
  export type AgenticBody = {
66
65
  sdk?: SdkBinding;
67
66
  native?: NativeBinding;
@@ -5,6 +5,7 @@
5
5
  // revision's own row (store schema `revisions`). Everything the old validator accepted it accepts, plus the agent-level
6
6
  // argument `pin` form in tool settings (the lead's ruling): at most 8 arguments mapped to JSON scalars, keys sorted, so
7
7
  // two equal pins are one revision.
8
+ import { sdkBindingOf } from "../sdk/runtimes.js";
8
9
  import { createHash } from "node:crypto";
9
10
  import { nativeBindingOf } from "../native/binding.js";
10
11
  import { learningSettingIssue, learningSettingOf } from "../learning-setting.js";
@@ -127,8 +128,8 @@ export function bodyOf(input) {
127
128
  invalid("the checkout is not pull_request");
128
129
  if (input.modelTiers !== undefined && !(isObject(input.modelTiers) && Object.keys(input.modelTiers).length && Object.entries(input.modelTiers).every(([tier, ref]) => (tier === "fast" || tier === "strong") && typeof ref === "string" && ref !== "")))
129
130
  invalid("the modelTiers are not fast and strong to a non-empty model");
130
- if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime") || !["claude-agent-sdk", "codex-sdk", "eve"].includes(input.sdk.runtime)))
131
- invalid("sdk is {runtime: claude-agent-sdk, codex-sdk or eve}");
131
+ if (input.sdk !== undefined && (!isObject(input.sdk) || Object.keys(input.sdk).some(key => key !== "runtime" && key !== "platform") || !sdkBindingOf(input.sdk)))
132
+ invalid("sdk is {runtime: claude-agent-sdk, codex-sdk or eve}, or {runtime: external, platform: a label of 1–80 characters without surrounding whitespace, controls or lone surrogates}");
132
133
  if (input.sdk && input.native)
133
134
  invalid("sdk and native connections are mutually exclusive");
134
135
  const body = {
@@ -1,5 +1,5 @@
1
- export { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
- export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
1
+ export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export { AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -324,7 +324,7 @@ export class RunStorage {
324
324
  // A run patch that made the run final: its other untaken rows are refused in this commit, after its own takes.
325
325
  // A person's message that came while it was ending opens a completed run again instead (refuseLeftovers).
326
326
  if (patching)
327
- await refuseLeftovers(tx, this.#runId, staged?.run?.state, now, this.#dialect);
327
+ await refuseLeftovers(tx, this.#runId, staged?.run?.state, now, this.#dialect, staged?.run?.keepsEnd === true);
328
328
  }
329
329
  });
330
330
  this.#nextId = Math.max(this.#nextId, candidateNextId);
@@ -37,7 +37,7 @@ export interface OpenStoreOptions {
37
37
  /** The environment AGENTRUN_STORE_SCHEMA and AGENTRUN_STORE_POOL_SIZE are read from (process.env). Neither is a secret. */
38
38
  readonly env?: NodeJS.ProcessEnv;
39
39
  /** Told what a person should know at the open (a runner's clock far from Postgres's; a server waiting for another to
40
- * let the Postgres schema go). */
40
+ * let the Postgres schema go), or later (a SQLite purge's checkpoint that left the WAL as it was). */
41
41
  readonly warn?: (message: string) => void;
42
42
  /** A server's, on Postgres: told when its owner lock is lost for good (PostgresStoreOptions.onOwnerLost). */
43
43
  readonly onOwnerLost?: (error: StoreOwned) => void;
@@ -45,6 +45,6 @@ export async function openStore({ dataDir, role = "server", now, url, env = proc
45
45
  const target = storeTarget(dataDir, env, url ?? storeUrl());
46
46
  const poolSize = storePoolSize(env);
47
47
  if (target.kind === "sqlite")
48
- return openSqliteStore({ dataDir, role, ...(now ? { now } : {}) });
48
+ return openSqliteStore({ dataDir, role, ...(now ? { now } : {}), ...(warn ? { warn } : {}) });
49
49
  return openPostgresStore({ url: target.url, schema: target.schema, role, poolSize, ...(now ? { now } : {}), ...(warn ? { warn } : {}), ...(onOwnerLost ? { onOwnerLost } : {}) });
50
50
  }
@@ -0,0 +1,13 @@
1
+ -- The store's schema on Postgres, version 21: when a run or an agent was purged, as store/schema.ts keeps it on SQLite
2
+ -- (runs.purged_at, agents.purged_at). Applied once, after 0020, inside the transaction migrate.ts opens. Never edit this
3
+ -- file once applied: a change is a new file.
4
+ --
5
+ -- A purged run (DELETE /v2/runs/{id}) keeps its row as a tombstone: its id, agent, state, times and cost, every record of
6
+ -- what it was given or did gone, so every total that summed its cost sums it still. A purged agent (DELETE
7
+ -- /v2/agents/{id} of an archived agent made here) keeps its row the same way, its name, description and revisions'
8
+ -- content blanked. Null: not purged. In place: every row reads as not purged.
9
+
10
+ ALTER TABLE runs ADD COLUMN IF NOT EXISTS purged_at BIGINT;
11
+ ALTER TABLE agents ADD COLUMN IF NOT EXISTS purged_at BIGINT;
12
+
13
+ UPDATE store_meta SET schema_version = 21 WHERE singleton = 1;
@@ -0,0 +1,27 @@
1
+ -- The store's schema on Postgres, version 22: each computer a run made, from its create to its proven delete, as
2
+ -- store/schema.ts keeps it on SQLite (COMPUTER_INTERVALS). Applied once, after 0021, inside the transaction migrate.ts
3
+ -- opens. Never edit this file once applied: a change is a new file.
4
+ --
5
+ -- computer_intervals: one row per computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the
6
+ -- provider's own id for it; what its create asked for (kind, GPU, CPUs, memory; null where it asked none), when it was
7
+ -- made, whether the run's park kept it past its claim (kept, 0 or 1), and ended_at, written only when the provider's
8
+ -- delete of it answered ok (null while none did). A computer made before this file has no row. The table and its index are
9
+ -- made only where missing, so a store whose record of this file was lost applies it again unharmed.
10
+
11
+ CREATE TABLE IF NOT EXISTS computer_intervals (
12
+ provider TEXT COLLATE "C" NOT NULL,
13
+ provider_id TEXT COLLATE "C" NOT NULL,
14
+ run_id TEXT COLLATE "C" NOT NULL,
15
+ kind TEXT COLLATE "C",
16
+ gpu_type TEXT COLLATE "C",
17
+ gpu_count BIGINT,
18
+ cpus DOUBLE PRECISION,
19
+ memory_mb BIGINT,
20
+ started_at BIGINT NOT NULL,
21
+ kept BIGINT NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),
22
+ ended_at BIGINT,
23
+ PRIMARY KEY (provider, provider_id)
24
+ );
25
+ CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at);
26
+
27
+ UPDATE store_meta SET schema_version = 22 WHERE singleton = 1;
@@ -0,0 +1,14 @@
1
+ -- The store's schema on Postgres, version 23: a computer's disk and the time its run's claims booked, as store/schema.ts
2
+ -- keeps them on SQLite (COMPUTER_INTERVALS). Applied once, after 0022, inside the transaction migrate.ts opens. Never edit
3
+ -- this file once applied: a change is a new file.
4
+ --
5
+ -- computer_intervals.disk_gb: the computer's disk in GB, where its provider said it; null else (never a guess).
6
+ -- computer_intervals.booked_ms: how much of the computer's time a claim of its run booked on the run's ledger; the rest
7
+ -- of its life is time no claim held (kept for a follow-up, deleted after its run, still running). A row from before this
8
+ -- file has none booked. Each column is added only where missing, so a store whose record of this file was lost applies
9
+ -- it again unharmed.
10
+
11
+ ALTER TABLE computer_intervals ADD COLUMN IF NOT EXISTS disk_gb DOUBLE PRECISION;
12
+ ALTER TABLE computer_intervals ADD COLUMN IF NOT EXISTS booked_ms BIGINT NOT NULL DEFAULT 0 CHECK (booked_ms >= 0);
13
+
14
+ UPDATE store_meta SET schema_version = 23 WHERE singleton = 1;
@@ -1,4 +1,4 @@
1
- export declare const SCHEMA_VERSION = 13;
1
+ export declare const SCHEMA_VERSION = 14;
2
2
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
3
3
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
4
4
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
@@ -40,6 +40,22 @@ export declare const IMPORTED_TEMPLATES: string;
40
40
  * end its wait; null while none was, and again at a mint. In STORE_DDL, and added at a server open to a store an earlier
41
41
  * build of this version made. */
42
42
  export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (\n machine TEXT PRIMARY KEY,\n token_sha256 TEXT NOT NULL UNIQUE,\n kind TEXT NOT NULL,\n os TEXT NOT NULL,\n arch TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL,\n runner TEXT,\n incarnation TEXT,\n run TEXT,\n refused TEXT\n ) STRICT";
43
+ /** Each computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the provider's own id for it:
44
+ * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
45
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
46
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
47
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
48
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
49
+ * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
50
+ * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
51
+ * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
52
+ * a store an earlier build of this version made, as MINTED_TOKENS is. */
53
+ export declare const COMPUTER_INTERVALS = "CREATE TABLE IF NOT EXISTS computer_intervals (\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n kind TEXT,\n gpu_type TEXT,\n gpu_count INTEGER,\n cpus REAL,\n memory_mb INTEGER,\n disk_gb REAL,\n started_at INTEGER NOT NULL,\n kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),\n ended_at INTEGER,\n booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),\n PRIMARY KEY (provider, provider_id)\n ) STRICT";
54
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
55
+ * added at a server open where missing (sqlite/store.ts). */
56
+ export declare const COMPUTER_INTERVALS_ADDED: Readonly<Record<string, string>>;
57
+ /** A run's computers, read by its run (store.computerIntervals.forRun). */
58
+ export declare const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
43
59
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
44
60
  * its name, its incarnation (its process since its start, the one its relay's minted tokens and proofs name), why it
45
61
  * refused to claim any run (`refused`, its words; null for one that claims), where its relay's attach listener takes the
@@ -50,6 +66,9 @@ export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (
50
66
  * server's open drops it and makes this one (sqlite/store.ts), as it drops browser_viewers, with no version: the rows
51
67
  * are heartbeats renewed every 10 s, so none is copied, and a runner waits for that server (StoreAwaitsServer). */
52
68
  export declare const RUNNERS = "CREATE TABLE IF NOT EXISTS runners (\n runner TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n refused TEXT,\n host TEXT,\n port INTEGER,\n seen_at INTEGER NOT NULL\n ) STRICT";
69
+ /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
70
+ * run and each agent was purged (null: none was), and the version, in one durable write. */
71
+ export declare function purgeUpgrade(runColumns: ReadonlySet<string>, agentColumns: ReadonlySet<string>): readonly string[];
53
72
  /** Version 12 → 13 on SQLite (the server's open, sqlite/store.ts), given minted_tokens' columns now: the minting runner,
54
73
  * its incarnation, the machine's run and a refused relay's words on each token's row (none of the rows there has one: the
55
74
  * server's own process minted them, naming no run), the runners (where their relays answer), and the version, in one
@@ -18,7 +18,8 @@
18
18
  // The template packages imported from GitHub (imported_templates) are a table of their own that nothing
19
19
  // else reads, so it needs no version: the server adds it at its open to a store an earlier build of this version made
20
20
  // (IMPORTED_TEMPLATES), as it does the one-answer index. A hosted machine's minted token (minted_tokens, MINTED_TOKENS) is
21
- // added the same way, and so is each runner's word that it is there and whether it refused to claim (runners, RUNNERS).
21
+ // added the same way, and so is each runner's word that it is there and whether it refused to claim (runners, RUNNERS),
22
+ // and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS).
22
23
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
23
24
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
24
25
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -32,8 +33,11 @@
32
33
  // Version 12 keeps each run's listing on its row (RUN_LISTING_COLUMNS): what a runs list shows of it, so a list reads rows
33
34
  // alone. Version 13 names the runner in a process of its own that minted a hosted machine's token (minted_tokens.runner,
34
35
  // .incarnation), the run the machine works for (.run), why the server refused to relay its dial (.refused), and where each
35
- // such runner takes the dials the server relays to it (runners.host and .port, dial-relay.ts). The server upgrades these two in place at its open (listingUpgrade from 11, then relayUpgrade from 12); a runner waits for it.
36
- export const SCHEMA_VERSION = 13;
36
+ // such runner takes the dials the server relays to it (runners.host and .port, dial-relay.ts). Version 14 keeps when a run or
37
+ // an agent was purged (runs.purged_at, agents.purged_at; DELETE /runs/{id} and /agents/{id}, agent-delete.ts): its row is
38
+ // then a tombstone, its content gone and its cost kept. The server upgrades these in place at its open (listingUpgrade from
39
+ // 11, relayUpgrade from 12, then purgeUpgrade from 13); a runner waits for it.
40
+ export const SCHEMA_VERSION = 14;
37
41
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
38
42
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
39
43
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
@@ -100,6 +104,40 @@ export const MINTED_TOKENS = `CREATE TABLE IF NOT EXISTS minted_tokens (
100
104
  run TEXT,
101
105
  refused TEXT
102
106
  ) STRICT`;
107
+ /** Each computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the provider's own id for it:
108
+ * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
109
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
110
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
111
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
112
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
113
+ * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
114
+ * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
115
+ * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
116
+ * a store an earlier build of this version made, as MINTED_TOKENS is. */
117
+ export const COMPUTER_INTERVALS = `CREATE TABLE IF NOT EXISTS computer_intervals (
118
+ provider TEXT NOT NULL,
119
+ provider_id TEXT NOT NULL,
120
+ run_id TEXT NOT NULL,
121
+ kind TEXT,
122
+ gpu_type TEXT,
123
+ gpu_count INTEGER,
124
+ cpus REAL,
125
+ memory_mb INTEGER,
126
+ disk_gb REAL,
127
+ started_at INTEGER NOT NULL,
128
+ kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),
129
+ ended_at INTEGER,
130
+ booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),
131
+ PRIMARY KEY (provider, provider_id)
132
+ ) STRICT`;
133
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
134
+ * added at a server open where missing (sqlite/store.ts). */
135
+ export const COMPUTER_INTERVALS_ADDED = {
136
+ disk_gb: "ALTER TABLE computer_intervals ADD COLUMN disk_gb REAL",
137
+ booked_ms: "ALTER TABLE computer_intervals ADD COLUMN booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0)",
138
+ };
139
+ /** A run's computers, read by its run (store.computerIntervals.forRun). */
140
+ export const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
103
141
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
104
142
  * its name, its incarnation (its process since its start, the one its relay's minted tokens and proofs name), why it
105
143
  * refused to claim any run (`refused`, its words; null for one that claims), where its relay's attach listener takes the
@@ -117,6 +155,15 @@ export const RUNNERS = `CREATE TABLE IF NOT EXISTS runners (
117
155
  port INTEGER,
118
156
  seen_at INTEGER NOT NULL
119
157
  ) STRICT`;
158
+ /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
159
+ * run and each agent was purged (null: none was), and the version, in one durable write. */
160
+ export function purgeUpgrade(runColumns, agentColumns) {
161
+ return [
162
+ ...(runColumns.has("purged_at") ? [] : ["ALTER TABLE runs ADD COLUMN purged_at INTEGER"]),
163
+ ...(agentColumns.has("purged_at") ? [] : ["ALTER TABLE agents ADD COLUMN purged_at INTEGER"]),
164
+ "UPDATE store_meta SET schema_version = 14 WHERE singleton = 1",
165
+ ];
166
+ }
120
167
  /** Version 12 → 13 on SQLite (the server's open, sqlite/store.ts), given minted_tokens' columns now: the minting runner,
121
168
  * its incarnation, the machine's run and a refused relay's words on each token's row (none of the rows there has one: the
122
169
  * server's own process minted them, naming no run), the runners (where their relays answer), and the version, in one
@@ -232,7 +279,10 @@ export const STORE_DDL = [
232
279
  current_revision TEXT,
233
280
  created_at INTEGER NOT NULL,
234
281
  archived_at INTEGER,
235
- external_ref TEXT
282
+ external_ref TEXT,
283
+ -- When the agent was purged (DELETE /agents/{id} of an archived agent made here): its row is then a tombstone, its
284
+ -- name, description and revisions' content blanked, kept for its runs' tombstones and their cost. Null: not purged.
285
+ purged_at INTEGER
236
286
  ) STRICT`,
237
287
  `CREATE UNIQUE INDEX IF NOT EXISTS agents_external ON agents (external_ref) WHERE external_ref IS NOT NULL`,
238
288
  // A revision's skills (the P4 fold of the old agent store's skill table): the revision's own skill files, a JSON object
@@ -305,7 +355,10 @@ export const STORE_DDL = [
305
355
  started_at INTEGER NOT NULL,
306
356
  ended_at INTEGER,
307
357
  -- The run's listing (RUN_LISTING_COLUMNS): what a runs list shows of it, kept on its row so a list reads rows alone.
308
- ${RUN_LISTING_COLUMNS.join(",\n ")}
358
+ ${RUN_LISTING_COLUMNS.join(",\n ")},
359
+ -- When the run was purged (DELETE /runs/{id}, Runs.purge): its row is then a tombstone, every record of what it was
360
+ -- given or did gone and its cost kept, which no list shows and every total still sums. Null: not purged.
361
+ purged_at INTEGER
309
362
  ) STRICT`,
310
363
  `CREATE INDEX IF NOT EXISTS runs_by_agent ON runs (agent_id, started_at)`,
311
364
  `CREATE INDEX IF NOT EXISTS runs_by_revision ON runs (revision_id, started_at)`,
@@ -548,6 +601,8 @@ export const STORE_DDL = [
548
601
  IMPORTED_TEMPLATES,
549
602
  MINTED_TOKENS,
550
603
  RUNNERS,
604
+ COMPUTER_INTERVALS,
605
+ COMPUTER_INTERVALS_RUN,
551
606
  // An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
552
607
  // pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
553
608
  // sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
@@ -1,6 +1,6 @@
1
1
  import { Worker } from "node:worker_threads";
2
2
  import { type Dialect } from "../dialect.js";
3
- import type { Statement, StatementResult } from "./worker.js";
3
+ import type { CheckpointResult, Statement, StatementResult } from "./worker.js";
4
4
  export type { Params, Statement, StatementResult } from "./worker.js";
5
5
  /** How long a transaction may stay open (it holds every other call of the process) before it is rolled back. */
6
6
  export declare const DEFAULT_TRANSACTION_DEADLINE_MS = 10000;
@@ -95,6 +95,9 @@ export declare class Connection implements SqliteDatabase, StoreConnection {
95
95
  runCounted(sql: string, ...params: SqliteValue[]): Promise<number>;
96
96
  get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
97
97
  all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
98
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
99
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
100
+ checkpoint(busyMs?: number): Promise<CheckpointResult | undefined>;
98
101
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
99
102
  * FULL commit, durable against a lost box together with every commit before it. */
100
103
  write(statements: readonly Statement[], { full }?: {
@@ -291,6 +291,11 @@ export class Connection {
291
291
  all(sql, ...params) {
292
292
  return this.#queued(async () => (await this.#stmt(sql, params, "all")));
293
293
  }
294
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
295
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
296
+ checkpoint(busyMs = this.#busyTimeoutMs) {
297
+ return this.#queued(async () => ((await this.#send({ op: "checkpoint", busyMs })) ?? undefined));
298
+ }
294
299
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
295
300
  * FULL commit, durable against a lost box together with every commit before it. */
296
301
  write(statements, { full = false } = {}) {
@@ -29,8 +29,9 @@ export type RunRecord = {
29
29
  labels: string | null;
30
30
  started_at: number;
31
31
  ended_at: number | null;
32
+ purged_at: number | null;
32
33
  };
33
- 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";
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";
34
35
  /** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
35
36
  * stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
36
37
  export declare const EXACT_COST_USD: (alias: string) => string;
@@ -62,5 +63,9 @@ export declare const reopenableWhere: (d: Dialect) => string;
62
63
  * before the end, it opens the run here; after it, the store refuses a new row (RunFinal) and runs.reopen takes it.
63
64
  * A person's stop is the same (reopenableWhere): a message waiting at it is the run's next turn, as main's stop leaves a
64
65
  * message submitted before it to run; a cancel's refuses it. A run left final here has its launch secrets erased (its
65
- * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote. */
66
- export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, state: RunState | undefined, now: number, dialect?: Dialect): Promise<void>;
66
+ * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote.
67
+ * An end that keeps its job's end (`keepsEnd`: a look-back's, RunPatch.keepsEnd) is that end, which every reader served
68
+ * while the run looked back: a cancel at it cut the look-back alone and is refused with the rest. Only with a person's
69
+ * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
70
+ * taken in this commit, that message's run's: it ends cancelled, at this commit's time. */
71
+ export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, state: RunState | undefined, now: number, dialect?: Dialect, keepsEnd?: boolean): Promise<void>;
@@ -12,7 +12,7 @@ export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learni
12
12
  /** 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
13
  * the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
14
14
  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";
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
16
  /** 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
17
  * 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
18
  export const EXACT_COST_USD = (alias) => `CASE WHEN ${alias}.cost_upper_bound = 1 THEN NULL ELSE ${alias}.cost_usd END`;
@@ -25,7 +25,7 @@ export const runOf = (r) => ({
25
25
  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
26
  outcome: r.outcome ?? null, archivedAt: r.archived_at, importedFrom: r.imported_from === null ? null : JSON.parse(r.imported_from),
27
27
  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,
28
+ startedAt: r.started_at, endedAt: r.ended_at, purgedAt: r.purged_at ?? null,
29
29
  });
30
30
  /** Applies `patch` to the claim's run, then writes `also`, through `tx` (an open transaction's handle). Fenced, with nothing
31
31
  * 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
@@ -108,7 +108,7 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
108
108
  * outcome 'stopped': its turn ended, never the run, as main's stop leaves one), not imported and not a learning run. A
109
109
  * cancelled run, a failed one and a workflow run are over for good. */
110
110
  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
- export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AND outcome = 'stopped')) AND imported_from IS NULL
111
+ export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AND outcome = 'stopped')) AND imported_from IS NULL AND purged_at IS NULL
112
112
  AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
113
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
114
  /** After a write that made the run final has taken its own rows: every command row of the run still untaken is refused
@@ -122,8 +122,12 @@ export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AN
122
122
  * before the end, it opens the run here; after it, the store refuses a new row (RunFinal) and runs.reopen takes it.
123
123
  * A person's stop is the same (reopenableWhere): a message waiting at it is the run's next turn, as main's stop leaves a
124
124
  * message submitted before it to run; a cancel's refuses it. A run left final here has its launch secrets erased (its
125
- * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote. */
126
- export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE) {
125
+ * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote.
126
+ * An end that keeps its job's end (`keepsEnd`: a look-back's, RunPatch.keepsEnd) is that end, which every reader served
127
+ * while the run looked back: a cancel at it cut the look-back alone and is refused with the rest. Only with a person's
128
+ * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
129
+ * taken in this commit, that message's run's: it ends cancelled, at this commit's time. */
130
+ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, keepsEnd = false) {
127
131
  if (state !== "ended" && state !== "stopped" && state !== "failed")
128
132
  return;
129
133
  // A cancel the API accepted (202, not refused) promised a cancelled run, and the view reads cancelled from that 202 on.
@@ -132,8 +136,12 @@ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE) {
132
136
  // A stop's end is the same (state 'stopped', outcome 'stopped': a CLI turn its harness interrupted on its own, or a
133
137
  // person's stop): it would leave the run open to a message, so the cancel wins it too, and the run takes no more.
134
138
  if (state === "ended" || state === "stopped") {
135
- const won = await tx.get(`UPDATE runs SET state = 'stopped', outcome = 'cancelled', summary = 'cancelled' WHERE id = ? AND (state = 'ended' OR (state = 'stopped' AND outcome = 'stopped'))
136
- AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.refused IS NULL AND commands.kind = 'cancel') RETURNING id`, runId);
139
+ const cancel = keepsEnd
140
+ ? `EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.refused IS NULL AND commands.kind = 'cancel' AND (commands.taken_at IS NULL OR commands.taken_at = ?))
141
+ AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind = 'steer')`
142
+ : "EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.refused IS NULL AND commands.kind = 'cancel')";
143
+ const won = await tx.get(`UPDATE runs SET state = 'stopped', outcome = 'cancelled', summary = 'cancelled'${keepsEnd ? ", ended_at = ?" : ""} WHERE id = ? AND (state = 'ended' OR (state = 'stopped' AND outcome = 'stopped'))
144
+ AND ${cancel} RETURNING id`, ...(keepsEnd ? [now, runId, now] : [runId]));
137
145
  if (won) {
138
146
  await tx.run("UPDATE commands SET taken_at = ? WHERE run_id = ? AND taken_at IS NULL AND refused IS NULL AND kind = 'cancel'", now, runId);
139
147
  await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE run_id = ? AND taken_at IS NULL", now, endedReason("stopped"), runId);
@@ -30,5 +30,6 @@ export type SqliteStoreOptions = (
30
30
  export declare function openSqliteStore(options: SqliteStoreOptions): Promise<Store>;
31
31
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
32
32
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
33
- * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX). */
33
+ * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
34
+ * purge checkpoints. */
34
35
  export declare function storeOver(connection: StoreConnection, now: () => number, file?: string): Store;