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

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 (216) hide show
  1. package/CHANGELOG.md +173 -9
  2. package/README.md +246 -39
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/agents-store.js +7 -3
  6. package/dist/api-only.d.ts +8 -10
  7. package/dist/api-only.js +11 -12
  8. package/dist/capacity.d.ts +50 -0
  9. package/dist/capacity.js +49 -0
  10. package/dist/cli-learning/claude-wire.d.ts +41 -0
  11. package/dist/cli-learning/claude-wire.js +258 -0
  12. package/dist/cli-learning/cli.d.ts +11 -0
  13. package/dist/cli-learning/cli.js +241 -0
  14. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  15. package/dist/cli-learning/codex-worktree.js +119 -0
  16. package/dist/cli-learning/connections.d.ts +62 -0
  17. package/dist/cli-learning/connections.js +87 -0
  18. package/dist/cli-learning/entry.d.ts +1 -0
  19. package/dist/cli-learning/entry.js +4 -0
  20. package/dist/cli-learning/evidence.d.ts +78 -0
  21. package/dist/cli-learning/evidence.js +492 -0
  22. package/dist/cli-learning/hook.d.ts +33 -0
  23. package/dist/cli-learning/hook.js +544 -0
  24. package/dist/cli-learning/install.d.ts +33 -0
  25. package/dist/cli-learning/install.js +335 -0
  26. package/dist/cli-learning/observation-proof.d.ts +14 -0
  27. package/dist/cli-learning/observation-proof.js +10 -0
  28. package/dist/cli-learning/policy.d.ts +48 -0
  29. package/dist/cli-learning/policy.js +363 -0
  30. package/dist/cli-learning/schema.d.ts +16 -0
  31. package/dist/cli-learning/schema.js +27 -0
  32. package/dist/cli-learning/state.d.ts +23 -0
  33. package/dist/cli-learning/state.js +61 -0
  34. package/dist/cli.js +24 -2
  35. package/dist/compute-cost.d.ts +101 -0
  36. package/dist/compute-cost.js +250 -0
  37. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  38. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/email/email-faux.d.ts +3 -1
  41. package/dist/email/email-faux.js +3 -2
  42. package/dist/email/routes.js +22 -12
  43. package/dist/eval-previous.d.ts +52 -0
  44. package/dist/eval-previous.js +164 -0
  45. package/dist/file-types.d.ts +2 -0
  46. package/dist/file-types.js +3 -1
  47. package/dist/harness-install.d.ts +6 -2
  48. package/dist/harness-install.js +40 -8
  49. package/dist/harness.d.ts +1 -1
  50. package/dist/harness.js +3 -2
  51. package/dist/learn/check.d.ts +8 -5
  52. package/dist/learn/check.js +25 -24
  53. package/dist/learn/repick.d.ts +22 -13
  54. package/dist/learn/repick.js +57 -56
  55. package/dist/learn/secrets.js +14 -3
  56. package/dist/learn/workflow-draft.d.ts +4 -0
  57. package/dist/learn/workflow-draft.js +10 -7
  58. package/dist/learned-workflow.js +8 -8
  59. package/dist/learning-setting.js +2 -2
  60. package/dist/learning-words.d.ts +1 -1
  61. package/dist/learning-words.js +1 -1
  62. package/dist/mcp-pin-first.js +2 -1
  63. package/dist/mcp-private-hosts.d.ts +24 -3
  64. package/dist/mcp-private-hosts.js +53 -3
  65. package/dist/model-gateway.d.ts +2 -0
  66. package/dist/model-gateway.js +3 -1
  67. package/dist/native/runtimes.d.ts +2 -0
  68. package/dist/native/runtimes.js +2 -0
  69. package/dist/observation/learning.d.ts +32 -0
  70. package/dist/observation/learning.js +66 -0
  71. package/dist/observation/observer.d.ts +8 -1
  72. package/dist/observation/observer.js +89 -9
  73. package/dist/observation/schema.js +12 -4
  74. package/dist/observation/usage-identity.d.ts +9 -0
  75. package/dist/observation/usage-identity.js +11 -0
  76. package/dist/openapi.js +113 -29
  77. package/dist/paid-calls.d.ts +13 -6
  78. package/dist/paid-calls.js +14 -8
  79. package/dist/run-launch.d.ts +16 -2
  80. package/dist/run-launch.js +6 -1
  81. package/dist/run-timeline-served.js +5 -3
  82. package/dist/run-usage.d.ts +23 -8
  83. package/dist/run-usage.js +100 -18
  84. package/dist/run-view.d.ts +2 -0
  85. package/dist/run-view.js +12 -7
  86. package/dist/runner/adapter-loop.d.ts +4 -0
  87. package/dist/runner/adapter-loop.js +44 -27
  88. package/dist/runner/adapter-run-spec.d.ts +8 -3
  89. package/dist/runner/adapter-run-spec.js +15 -8
  90. package/dist/runner/beside.d.ts +13 -0
  91. package/dist/runner/beside.js +27 -8
  92. package/dist/runner/big-writes.d.ts +33 -0
  93. package/dist/runner/big-writes.js +105 -0
  94. package/dist/runner/cli-run-spec.js +16 -8
  95. package/dist/runner/disk-free.d.ts +44 -0
  96. package/dist/runner/disk-free.js +96 -0
  97. package/dist/runner/feedback-round.d.ts +12 -8
  98. package/dist/runner/feedback-round.js +16 -30
  99. package/dist/runner/harness-loops.js +3 -1
  100. package/dist/runner/held.d.ts +4 -1
  101. package/dist/runner/journal-kinds.d.ts +1 -1
  102. package/dist/runner/learning-end.js +13 -4
  103. package/dist/runner/main.d.ts +17 -6
  104. package/dist/runner/main.js +187 -45
  105. package/dist/runner/metrics.d.ts +4 -0
  106. package/dist/runner/metrics.js +9 -0
  107. package/dist/runner/presence.d.ts +11 -2
  108. package/dist/runner/presence.js +31 -3
  109. package/dist/runner/run-child-host.d.ts +27 -17
  110. package/dist/runner/run-child-host.js +70 -116
  111. package/dist/runner/run-child.js +3 -0
  112. package/dist/runner/run-errors.js +2 -0
  113. package/dist/runner/runner-check.d.ts +51 -0
  114. package/dist/runner/runner-check.js +206 -0
  115. package/dist/runner/runner-metrics.d.ts +19 -0
  116. package/dist/runner/runner-metrics.js +49 -0
  117. package/dist/runner/runner.d.ts +37 -0
  118. package/dist/runner/runner.js +43 -3
  119. package/dist/runner/save-slots.d.ts +9 -0
  120. package/dist/runner/save-slots.js +91 -0
  121. package/dist/runner/sdk-loop.js +34 -22
  122. package/dist/runs-over-store.d.ts +8 -1
  123. package/dist/runs-over-store.js +57 -9
  124. package/dist/sdk/runs.d.ts +25 -6
  125. package/dist/sdk/runs.js +107 -35
  126. package/dist/sdk/runtimes.d.ts +19 -0
  127. package/dist/sdk/runtimes.js +23 -0
  128. package/dist/sdk/schema.d.ts +14 -8
  129. package/dist/sdk/schema.js +18 -6
  130. package/dist/server.d.ts +7 -0
  131. package/dist/server.js +151 -28
  132. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  133. package/dist/start-switches.js +2 -0
  134. package/dist/stats.d.ts +4 -0
  135. package/dist/stats.js +1 -1
  136. package/dist/store/agent-body.d.ts +13 -2
  137. package/dist/store/agent-body.js +19 -4
  138. package/dist/store/dialect.d.ts +2 -0
  139. package/dist/store/dialect.js +1 -0
  140. package/dist/store/index.d.ts +3 -3
  141. package/dist/store/index.js +2 -2
  142. package/dist/store/postgres/connection.d.ts +5 -2
  143. package/dist/store/postgres/connection.js +19 -7
  144. package/dist/store/postgres/dialect.js +1 -0
  145. package/dist/store/postgres/migrate.d.ts +30 -0
  146. package/dist/store/postgres/migrate.js +72 -5
  147. package/dist/store/postgres/migration-lint.d.ts +8 -0
  148. package/dist/store/postgres/migration-lint.js +119 -0
  149. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  150. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  151. package/dist/store/postgres/store.d.ts +8 -3
  152. package/dist/store/postgres/store.js +31 -11
  153. package/dist/store/schema.d.ts +26 -4
  154. package/dist/store/schema.js +45 -4
  155. package/dist/store/sqlite/connection.d.ts +3 -3
  156. package/dist/store/sqlite/connection.js +3 -3
  157. package/dist/store/sqlite/run-launch.d.ts +9 -1
  158. package/dist/store/sqlite/run-launch.js +44 -0
  159. package/dist/store/sqlite/store.d.ts +19 -4
  160. package/dist/store/sqlite/store.js +180 -93
  161. package/dist/store/store-schema.d.ts +34 -0
  162. package/dist/store/store-schema.js +125 -0
  163. package/dist/store/store.d.ts +61 -2
  164. package/dist/store/store.js +13 -0
  165. package/dist/store-reads/analytics.d.ts +3 -2
  166. package/dist/store-reads/analytics.js +20 -8
  167. package/dist/store-reads/cap.d.ts +9 -5
  168. package/dist/store-reads/cap.js +28 -2
  169. package/dist/store-reads/decisions.d.ts +21 -0
  170. package/dist/store-reads/decisions.js +22 -0
  171. package/dist/store-reads/journal.d.ts +8 -2
  172. package/dist/store-reads/journal.js +27 -8
  173. package/dist/store-view.d.ts +9 -4
  174. package/dist/store-view.js +48 -25
  175. package/dist/template-eval.d.ts +15 -1
  176. package/dist/template-eval.js +92 -13
  177. package/dist/templates.d.ts +4 -3
  178. package/dist/templates.js +4 -3
  179. package/dist/timeline/labels.js +17 -0
  180. package/dist/tool-gate.d.ts +4 -2
  181. package/dist/tool-list.js +1 -0
  182. package/dist/tools.d.ts +6 -2
  183. package/dist/tools.js +13 -1
  184. package/dist/trigger-targets.d.ts +21 -5
  185. package/dist/trigger-targets.js +13 -10
  186. package/dist/unified-usage.d.ts +24 -0
  187. package/dist/unified-usage.js +400 -0
  188. package/dist/uploads-archil.d.ts +100 -0
  189. package/dist/uploads-archil.js +430 -0
  190. package/dist/uploads.d.ts +55 -1
  191. package/dist/uploads.js +185 -98
  192. package/dist/validate.js +1 -1
  193. package/dist/web-fake.d.ts +25 -0
  194. package/dist/web-fake.js +38 -1
  195. package/dist/web-save.d.ts +75 -0
  196. package/dist/web-save.js +235 -0
  197. package/dist/workspace/archil-claim.d.ts +5 -2
  198. package/dist/workspace/archil-claim.js +5 -2
  199. package/dist/workspace/archil-disk.d.ts +11 -1
  200. package/dist/workspace/archil-disk.js +43 -10
  201. package/dist/workspace/archil.d.ts +3 -0
  202. package/dist/workspace/archil.js +102 -16
  203. package/dist/workspace/computer-for-claim.d.ts +14 -0
  204. package/dist/workspace/computer-for-claim.js +46 -7
  205. package/dist/workspace/computer-intervals.d.ts +9 -3
  206. package/dist/workspace/computer-intervals.js +17 -8
  207. package/dist/workspace/pieced.d.ts +14 -0
  208. package/dist/workspace/pieced.js +23 -0
  209. package/dist/workspace/run-disk.js +32 -12
  210. package/dist/workspace/run-workspace.d.ts +1 -1
  211. package/dist/workspace/run-workspace.js +11 -6
  212. package/package.json +10 -10
  213. package/skills/agentrun-serve/SKILL.md +52 -7
  214. package/templates/README.md +36 -7
  215. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
  216. package/dist/console/assets/index-CR2ZGei1.css +0 -1
@@ -1,11 +1,15 @@
1
1
  // The Store on Postgres: the same domain code as SQLite's (sqlite/store.ts storeOver) over a Postgres connection
2
2
  // (connection.ts) in the store's own schema (default "agentrun"). The server sets the schema up (migrate.ts) and holds the
3
- // owner lock, one server per schema; runners are many, set nothing up, and refuse a schema version they do not know.
3
+ // owner lock, one server per schema; runners are many, set nothing up, wait for the server on a schema behind them, and
4
+ // run on one ahead of them while its runner floor is at most what they know (migrate.ts runnerFloorOf).
4
5
  import { SchemaVersionUnknown, StoreAwaitsServer } from "../store.js";
5
6
  import { backfillNativeCommandOwners } from '../native-command-owner.js';
6
7
  import { storeOver } from "../sqlite/store.js";
7
8
  import { PgConnection, SCHEMA_NAME } from "./connection.js";
8
- import { migrate, migrationsIn, placeOf, versionOf } from "./migrate.js";
9
+ import { migrate, migrationsIn, placeOf, refuseBelowFloor, runnerFloorOf, versionOf } from "./migrate.js";
10
+ /** How long Store.schemaState waits for the database before it is Unanswered and its connection is dropped (ms): under
11
+ * the runner's 10 s floor read, so a read that hangs never outlasts the next one. */
12
+ export const SCHEMA_STATE_MS = 5_000;
9
13
  /** The schema a store is in when none is named. */
10
14
  export const DEFAULT_SCHEMA = "agentrun";
11
15
  /** How far a runner's clock may be from the database's before it says so at its start (ms). Leases are 30 s, so a gap this
@@ -13,9 +17,11 @@ export const DEFAULT_SCHEMA = "agentrun";
13
17
  export const CLOCK_WARN_MS = 2_000;
14
18
  export { postgresWhere } from "./connection.js";
15
19
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
16
- * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
17
- * clock is far from the database's. Either refuses a schema version this build does not know (SchemaVersionUnknown), a
18
- * runner also a schema not set up yet, and one this build's server has yet to migrate (StoreAwaitsServer). */
20
+ * another server holds the schema) and applies the pending migrations; it refuses a schema a later build migrated
21
+ * (SchemaVersionUnknown). As a runner: sets nothing up, and warns when its clock is far from the database's. It refuses a
22
+ * schema not set up yet (SchemaVersionUnknown) and one this build's server has yet to migrate (StoreAwaitsServer), and
23
+ * opens one a later build migrated while that schema's runner floor is at most this build's version (RunnerBelowFloor
24
+ * past it). The store it answers reads the version and the floor again (Store.schemaState). */
19
25
  export async function openPostgresStore(options) {
20
26
  const schema = options.schema ?? DEFAULT_SCHEMA;
21
27
  if (!SCHEMA_NAME.test(schema))
@@ -41,11 +47,21 @@ export async function openPostgresStore(options) {
41
47
  },
42
48
  });
43
49
  try {
44
- const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
45
- if (role === "runner" && found !== null && found < known)
46
- throw new StoreAwaitsServer(`bring this store from version ${found} to ${known}`);
47
- if (found !== known)
48
- throw new SchemaVersionUnknown(placeOf(schema), found, known);
50
+ if (role === "server") {
51
+ const found = await connection.withClient((client) => migrate(client, schema, now(), migrations));
52
+ if (found !== known)
53
+ throw new SchemaVersionUnknown(placeOf(schema), found, known);
54
+ }
55
+ else {
56
+ const state = await connection.withClient((client) => runnerFloorOf(client, schema));
57
+ const found = state.version;
58
+ if (found !== null && found < known)
59
+ throw new StoreAwaitsServer(`bring this store from version ${found} to ${known}`);
60
+ if (found === null)
61
+ throw new SchemaVersionUnknown(placeOf(schema), found, known);
62
+ // Ahead of this build: additive migrations leave the floor where it was, and this runner runs on them.
63
+ refuseBelowFloor(schema, state, known);
64
+ }
49
65
  if (role === "server")
50
66
  await backfillNativeCommandOwners(connection);
51
67
  if (role === "runner" && options.warn) {
@@ -59,5 +75,9 @@ export async function openPostgresStore(options) {
59
75
  await connection.close().catch(() => undefined);
60
76
  throw error;
61
77
  }
62
- return storeOver(connection, now);
78
+ const store = storeOver(connection, now);
79
+ // Bounded: a runner reads it on a timer, and a database that stops answering must neither hold that timer's read for good
80
+ // nor the store's close, which waits for every call in flight.
81
+ const schemaState = async () => ({ ...(await connection.withClient((client) => runnerFloorOf(client, schema), SCHEMA_STATE_MS)), known });
82
+ return Object.assign(store, { schemaState });
63
83
  }
@@ -42,13 +42,18 @@ export declare const IMPORTED_TEMPLATES: string;
42
42
  export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (\n machine TEXT PRIMARY KEY,\n token_sha256 TEXT NOT NULL UNIQUE,\n kind TEXT NOT NULL,\n os TEXT NOT NULL,\n arch TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL,\n runner TEXT,\n incarnation TEXT,\n run TEXT,\n refused TEXT\n ) STRICT";
43
43
  /** Each computer a run's claim made through its provider (a sandbox, a desktop, a phone), by the provider's own id for it:
44
44
  * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
45
- * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`), as its create
46
- * asked, null where the create asked none (a hosted vendor that sizes its own machines): never a guess. `kept`: 1 once
45
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
46
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
47
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
48
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
47
49
  * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
48
50
  * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
49
51
  * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
50
52
  * a store an earlier build of this version made, as MINTED_TOKENS is. */
51
- export declare const COMPUTER_INTERVALS = "CREATE TABLE IF NOT EXISTS computer_intervals (\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n kind TEXT,\n gpu_type TEXT,\n gpu_count INTEGER,\n cpus REAL,\n memory_mb INTEGER,\n started_at INTEGER NOT NULL,\n kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),\n ended_at INTEGER,\n PRIMARY KEY (provider, provider_id)\n ) STRICT";
53
+ export declare const COMPUTER_INTERVALS = "CREATE TABLE IF NOT EXISTS computer_intervals (\n provider TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n kind TEXT,\n gpu_type TEXT,\n gpu_count INTEGER,\n cpus REAL,\n memory_mb INTEGER,\n disk_gb REAL,\n started_at INTEGER NOT NULL,\n kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),\n ended_at INTEGER,\n booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),\n PRIMARY KEY (provider, provider_id)\n ) STRICT";
54
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
55
+ * added at a server open where missing (sqlite/store.ts). */
56
+ export declare const COMPUTER_INTERVALS_ADDED: Readonly<Record<string, string>>;
52
57
  /** A run's computers, read by its run (store.computerIntervals.forRun). */
53
58
  export declare const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
54
59
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
@@ -60,7 +65,24 @@ export declare const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS comput
60
65
  * STORE_DDL. A store an earlier build of version 13 made kept the relays in a table of their own (runner_relays): the
61
66
  * server's open drops it and makes this one (sqlite/store.ts), as it drops browser_viewers, with no version: the rows
62
67
  * are heartbeats renewed every 10 s, so none is copied, and a runner waits for that server (StoreAwaitsServer). */
63
- 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";
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 version TEXT,\n slots INTEGER\n ) STRICT";
69
+ /** What a runner says of itself for the server's capacity read (GET /v2/capacity, capacity.ts): its build's version
70
+ * (`version`) and the most runs it holds at once (`slots`), each null on a row an earlier build wrote. In RUNNERS, and
71
+ * added where missing at a server open to a runners table an earlier build of this version made, as
72
+ * COMPUTER_INTERVALS_ADDED is: nullable, so nothing is copied and no row is refused. */
73
+ export declare const RUNNERS_ADDED: Readonly<Record<string, string>>;
74
+ /** Each hand-back (store.release that leaves its run running: a runner's drain, a loop that closed itself, a claim given
75
+ * back): the run, the runner that let it go, the epoch it let go of and when, on the deadlines' clock. Counts and ids
76
+ * only; the capacity read (capacity.ts) counts the rows within its window. A release's own write keeps it, in the same
77
+ * transaction, and removes the rows older than HAND_BACKS_KEPT_MS. In STORE_DDL, and made at a server open on a store an
78
+ * earlier build of this version made. */
79
+ export declare const HAND_BACKS = "CREATE TABLE IF NOT EXISTS hand_backs (\n run_id TEXT NOT NULL,\n runner TEXT NOT NULL,\n epoch INTEGER NOT NULL,\n at INTEGER NOT NULL\n ) STRICT";
80
+ /** The hand-backs by time, for the capacity read's window and the release's prune. */
81
+ export declare const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_backs (at)";
82
+ /** A run's hand-backs, for its purge and its delete (dropRunContent), so neither scans every hand-back kept. */
83
+ export declare const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
84
+ /** How long a hand-back's row is kept: the longest window the capacity read takes. */
85
+ export declare const HAND_BACKS_KEPT_MS: number;
64
86
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
65
87
  * run and each agent was purged (null: none was), and the version, in one durable write. */
66
88
  export declare function purgeUpgrade(runColumns: ReadonlySet<string>, agentColumns: ReadonlySet<string>): readonly string[];
@@ -19,7 +19,8 @@
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
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
+ // and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS). Each runner's
23
+ // version and slots (runners.version, .slots: RUNNERS_ADDED) and each hand-back (hand_backs, HAND_BACKS) are added the same way.
23
24
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
24
25
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
25
26
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -106,8 +107,10 @@ export const MINTED_TOKENS = `CREATE TABLE IF NOT EXISTS minted_tokens (
106
107
  ) STRICT`;
107
108
  /** 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
109
  * so an operator can see how long each lived for its run, find one left running after its run, and match the provider's
109
- * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`), as its create
110
- * asked, null where the create asked none (a hosted vendor that sizes its own machines): never a guess. `kept`: 1 once
110
+ * invoice by its id. `kind`, and what it was made with (`gpu_type` and `gpu_count`, `cpus`, `memory_mb`, `disk_gb`): the
111
+ * provider's own figures where its answer gave them (CreatedComputer.resources), else what its create asked, null where
112
+ * neither says (a hosted vendor that sizes its own machines and says nothing): never a guess. `booked_ms`: how much of
113
+ * its time a claim of its run booked on the run's ledger (compute-cost.ts), the rest being time no claim held. `kept`: 1 once
111
114
  * the run's park kept it past the claim (computer-kept.ts). `ended_at`: written once, only when the provider's delete of
112
115
  * it answered ok; null while none did (still running, or its delete failed or was never asked), never a guessed end. Not
113
116
  * the agent's own computer (it outlives every run), a paired one or --faux's. In STORE_DDL, and added at a server open to
@@ -121,11 +124,19 @@ export const COMPUTER_INTERVALS = `CREATE TABLE IF NOT EXISTS computer_intervals
121
124
  gpu_count INTEGER,
122
125
  cpus REAL,
123
126
  memory_mb INTEGER,
127
+ disk_gb REAL,
124
128
  started_at INTEGER NOT NULL,
125
129
  kept INTEGER NOT NULL DEFAULT 0 CHECK (kept IN (0, 1)),
126
130
  ended_at INTEGER,
131
+ booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0),
127
132
  PRIMARY KEY (provider, provider_id)
128
133
  ) STRICT`;
134
+ /** The columns a computer_intervals an earlier build of this version made lacks (its disk and its booked time), each
135
+ * added at a server open where missing (sqlite/store.ts). */
136
+ export const COMPUTER_INTERVALS_ADDED = {
137
+ disk_gb: "ALTER TABLE computer_intervals ADD COLUMN disk_gb REAL",
138
+ booked_ms: "ALTER TABLE computer_intervals ADD COLUMN booked_ms INTEGER NOT NULL DEFAULT 0 CHECK (booked_ms >= 0)",
139
+ };
129
140
  /** A run's computers, read by its run (store.computerIntervals.forRun). */
130
141
  export const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS computer_intervals_run ON computer_intervals (run_id, started_at)";
131
142
  /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
@@ -143,8 +154,35 @@ export const RUNNERS = `CREATE TABLE IF NOT EXISTS runners (
143
154
  refused TEXT,
144
155
  host TEXT,
145
156
  port INTEGER,
146
- seen_at INTEGER NOT NULL
157
+ seen_at INTEGER NOT NULL,
158
+ version TEXT,
159
+ slots INTEGER
160
+ ) STRICT`;
161
+ /** What a runner says of itself for the server's capacity read (GET /v2/capacity, capacity.ts): its build's version
162
+ * (`version`) and the most runs it holds at once (`slots`), each null on a row an earlier build wrote. In RUNNERS, and
163
+ * added where missing at a server open to a runners table an earlier build of this version made, as
164
+ * COMPUTER_INTERVALS_ADDED is: nullable, so nothing is copied and no row is refused. */
165
+ export const RUNNERS_ADDED = {
166
+ version: "ALTER TABLE runners ADD COLUMN version TEXT",
167
+ slots: "ALTER TABLE runners ADD COLUMN slots INTEGER",
168
+ };
169
+ /** Each hand-back (store.release that leaves its run running: a runner's drain, a loop that closed itself, a claim given
170
+ * back): the run, the runner that let it go, the epoch it let go of and when, on the deadlines' clock. Counts and ids
171
+ * only; the capacity read (capacity.ts) counts the rows within its window. A release's own write keeps it, in the same
172
+ * transaction, and removes the rows older than HAND_BACKS_KEPT_MS. In STORE_DDL, and made at a server open on a store an
173
+ * earlier build of this version made. */
174
+ export const HAND_BACKS = `CREATE TABLE IF NOT EXISTS hand_backs (
175
+ run_id TEXT NOT NULL,
176
+ runner TEXT NOT NULL,
177
+ epoch INTEGER NOT NULL,
178
+ at INTEGER NOT NULL
147
179
  ) STRICT`;
180
+ /** The hand-backs by time, for the capacity read's window and the release's prune. */
181
+ export const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_backs (at)";
182
+ /** A run's hand-backs, for its purge and its delete (dropRunContent), so neither scans every hand-back kept. */
183
+ export const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
184
+ /** How long a hand-back's row is kept: the longest window the capacity read takes. */
185
+ export const HAND_BACKS_KEPT_MS = 24 * 60 * 60_000;
148
186
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
149
187
  * run and each agent was purged (null: none was), and the version, in one durable write. */
150
188
  export function purgeUpgrade(runColumns, agentColumns) {
@@ -591,6 +629,9 @@ export const STORE_DDL = [
591
629
  IMPORTED_TEMPLATES,
592
630
  MINTED_TOKENS,
593
631
  RUNNERS,
632
+ HAND_BACKS,
633
+ HAND_BACKS_AT,
634
+ HAND_BACKS_RUN,
594
635
  COMPUTER_INTERVALS,
595
636
  COMPUTER_INTERVALS_RUN,
596
637
  // An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
@@ -95,9 +95,9 @@ export declare class Connection implements SqliteDatabase, StoreConnection {
95
95
  runCounted(sql: string, ...params: SqliteValue[]): Promise<number>;
96
96
  get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
97
97
  all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
98
- /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer, never the
99
- * connection's own busy wait: every call queued behind it waits that long at most for it. Busy (1) when one held it. */
100
- checkpoint(busyMs: number): Promise<CheckpointResult | undefined>;
98
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
99
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
100
+ checkpoint(busyMs?: number): Promise<CheckpointResult | undefined>;
101
101
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
102
102
  * FULL commit, durable against a lost box together with every commit before it. */
103
103
  write(statements: readonly Statement[], { full }?: {
@@ -291,9 +291,9 @@ export class Connection {
291
291
  all(sql, ...params) {
292
292
  return this.#queued(async () => (await this.#stmt(sql, params, "all")));
293
293
  }
294
- /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer, never the
295
- * connection's own busy wait: every call queued behind it waits that long at most for it. Busy (1) when one held it. */
296
- checkpoint(busyMs) {
294
+ /** A WAL checkpoint (TRUNCATE) that waits `busyMs` at most for another connection's reader or writer (default: the
295
+ * connection's own busy wait): every call queued behind it waits that long at most for it. Busy (1) when one held it. */
296
+ checkpoint(busyMs = this.#busyTimeoutMs) {
297
297
  return this.#queued(async () => ((await this.#send({ op: "checkpoint", busyMs })) ?? undefined));
298
298
  }
299
299
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
@@ -1,4 +1,4 @@
1
- import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow } from "../store.js";
1
+ import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow, type Runs } from "../store.js";
2
2
  import type { Dialect } from "../dialect.js";
3
3
  import type { SqliteExecutor } from "./connection.js";
4
4
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
@@ -10,6 +10,14 @@ export declare function writeLaunchSealed(tx: Pick<SqliteExecutor, "run" | "get"
10
10
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
11
11
  * none, never a default. */
12
12
  export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
13
+ /** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
14
+ * the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
15
+ * Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
16
+ export declare function readUsageMetadata(executor: Pick<SqliteExecutor, "get"> & {
17
+ readonly dialect: Dialect;
18
+ }, runId: string, { completion }: {
19
+ completion: boolean;
20
+ }): ReturnType<Runs["usageMetadata"]>;
13
21
  /** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
14
22
  * the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
15
23
  * and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
@@ -30,6 +30,50 @@ export async function readLaunch(executor, runId) {
30
30
  throw new StoreLaunchMissing(runId);
31
31
  return runLaunchOf(row);
32
32
  }
33
+ /** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
34
+ * the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
35
+ * Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
36
+ export async function readUsageMetadata(executor, runId, { completion }) {
37
+ const keys = ["runtime", "session_id", "turn_id"];
38
+ const counters = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"];
39
+ const columns = keys.map(key => `${executor.dialect.jsonValue("l.body", ["cli_learning", key])} AS ${key}`);
40
+ // Launch bodies are written with JSON.stringify: zero is canonically `0`. Read only the historical
41
+ // binding's truthiness, never its potentially private or large provider configuration.
42
+ const grading = executor.dialect.jsonValue("l.body", ["cli_learning", "native_grading"]);
43
+ columns.push(`CASE WHEN ${grading} IS NULL OR ${grading} IN ('null', 'false', '0', '""') THEN 0 ELSE 1 END AS native_grading`);
44
+ if (completion)
45
+ columns.push(...counters.map(key => `${executor.dialect.jsonValue("s.value", ["completion", "usage", key])} AS ${key}`));
46
+ const from = `FROM runs r LEFT JOIN run_launch l ON l.run_id = r.id${completion ? " LEFT JOIN settings s ON s.key = ?" : ""} WHERE r.id = ?`;
47
+ const params = [...(completion ? [`sdk-run:${runId}`] : []), runId];
48
+ let row;
49
+ try {
50
+ row = await executor.get(`SELECT ${columns.join(", ")} ${from}`, ...params);
51
+ }
52
+ catch (error) {
53
+ // PostgreSQL accepts escaped NUL/lone-surrogate strings in JSON TEXT but cannot extract ANY member of
54
+ // such a document. Only its exact Unicode refusal permits the former JS read/parse cost for that row.
55
+ // 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)
61
+ throw error;
62
+ const raw = await executor.get(`SELECT l.body${completion ? ", s.value AS inbox" : ""} ${from}`, ...params);
63
+ if (!raw)
64
+ return undefined;
65
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
66
+ const cli = object(object(raw.body == null ? undefined : JSON.parse(raw.body)).cli_learning);
67
+ const usage = object(object(object(raw.inbox == null ? undefined : JSON.parse(raw.inbox)).completion).usage);
68
+ return { cli: { ...Object.fromEntries(keys.map(key => [key, cli[key]])), native_grading: Boolean(cli.native_grading) },
69
+ ...(completion ? { completionUsage: Object.fromEntries(counters.map(key => [key, usage[key]])) } : {}) };
70
+ }
71
+ if (!row)
72
+ return undefined;
73
+ const value = (key) => row[key] == null ? undefined : JSON.parse(String(row[key]));
74
+ return { cli: { ...Object.fromEntries(keys.map(key => [key, value(key)])), native_grading: Boolean(row.native_grading) },
75
+ ...(completion ? { completionUsage: Object.fromEntries(counters.map(key => [key, value(key)])) } : {}) };
76
+ }
33
77
  /** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
34
78
  * the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
35
79
  * and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
@@ -21,9 +21,24 @@ export type SqliteStoreOptions = (
21
21
  now?: () => number;
22
22
  /** How long a write waits for another process's lock before StoreBusy. */
23
23
  busyTimeoutMs?: number;
24
- /** Told what a person should know that no caller is answered (a purge's checkpoint that left the WAL): stderr by default. */
25
- warn?: (message: string) => void;
26
24
  };
25
+ /** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
26
+ * at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
27
+ * words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
28
+ export declare const SQLITE_RUNNER_NEEDS: readonly {
29
+ readonly table: string;
30
+ readonly columns: readonly string[];
31
+ readonly why: string;
32
+ }[];
33
+ /** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
34
+ * or undefined when it opens; `columnsOf` reads a table's columns. */
35
+ export declare function runnerWaitsFor(columnsOf: (table: string) => Promise<ReadonlySet<string>> | ReadonlySet<string>): Promise<string | undefined>;
36
+ /** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
37
+ * store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
38
+ * disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
39
+ * (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
40
+ * this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
41
+ export declare function earlierVersionIn(dataDir: string, busyTimeoutMs: number): string[];
27
42
  /** Opens the store in `dataDir` (its file is STORE_FILE there), or at `file` (the store's own tests). As the server (the
28
43
  * default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
29
44
  * no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
@@ -33,5 +48,5 @@ export declare function openSqliteStore(options: SqliteStoreOptions): Promise<St
33
48
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
34
49
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
35
50
  * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
36
- * purge checkpoints. `warn`: told when that checkpoint could not empty the WAL (stderr by default). */
37
- export declare function storeOver(connection: StoreConnection, now: () => number, file?: string, warn?: (message: string) => void): Store;
51
+ * purge checkpoints. */
52
+ export declare function storeOver(connection: StoreConnection, now: () => number, file?: string): Store;