@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
@@ -0,0 +1,125 @@
1
+ // `agentrun-serve store-schema [--data DIR]`: the live store's schema version and runner floor, beside the version this
2
+ // build knows, as one line of JSON, for a deploy pipeline's skew guard. It reads, and nothing else: no owner lock, no
3
+ // migration, no schema made, no runner presence. The store is the one the server and a runner open (store/open.ts:
4
+ // Postgres when AGENTRUN_STORE_URL names one, in AGENTRUN_STORE_SCHEMA; else SQLite in --data), and its URL is never
5
+ // printed. Exit 0 once read (whatever it says), 1 when the store could not be read, 2 for bad arguments. `--build` reads no
6
+ // store: it prints the versions this build knows, `{"build":{"postgres":N,"sqlite":M}}`, for a label an image build stamps.
7
+ //
8
+ // What the line says, run with the build about to be deployed:
9
+ // schema the store's version now (null: none set up yet)
10
+ // runnerFloor the oldest version a runner's build must know to run on it (null: none set up yet)
11
+ // build the version this build knows
12
+ // server what this build's server does at its start: "sets up", "opens", "migrates", or "refuses" (the store is
13
+ // ahead of this build: a rollback across a migration, which the skew guard refuses)
14
+ // runner what this build's runner does: "opens", "waits" (for the server to migrate), or "refused" (none set up,
15
+ // or the floor is above this build)
16
+ import { existsSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { DatabaseSync } from "node:sqlite";
19
+ import { parseArgs } from "node:util";
20
+ import { migrationsIn, runnerFloorOf, runnerOn } from "./postgres/migrate.js";
21
+ import { STORE_CONNECT_TIMEOUT_MS } from "./postgres/connection.js";
22
+ import { storePlace, storeTarget } from "./open.js";
23
+ import { SCHEMA_VERSION } from "./schema.js";
24
+ import { earlierVersionIn, runnerWaitsFor, STORE_FILE } from "./sqlite/store.js";
25
+ /** The SQLite store's versions the server upgrades in place (sqlite/store.ts openSqliteStore). */
26
+ const SQLITE_UPGRADES = new Set([11, 12, 13]);
27
+ /** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
28
+ * version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
29
+ * on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
30
+ * its server adds at its start: the runner waits for it, as openSqliteStore makes it. */
31
+ export function storeSchemaReport(target, state, build, earlier = false, awaits = false) {
32
+ const { version } = state;
33
+ const server = earlier
34
+ ? "refuses"
35
+ : version === null ? "sets up" : version === build ? "opens" : version > build ? "refuses" : target.kind === "postgres" || SQLITE_UPGRADES.has(version) ? "migrates" : "refuses";
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.
38
+ const runner = target.kind === "sqlite" && version !== null && version < build && !SQLITE_UPGRADES.has(version)
39
+ ? "refused"
40
+ : awaits && version === build ? "waits" : runnerOn(target.kind === "sqlite" ? { version, runnerFloor: version } : state, build);
41
+ return { store: target.kind, where: storePlace(target), schema: version, runnerFloor: state.runnerFloor, build, server, runner };
42
+ }
43
+ /** The SQLite store's version in `dataDir`, read-only: null when there is no file, or no schema in it; and whether a
44
+ * runner of this build would wait for its server to add a column (SQLITE_RUNNER_NEEDS). */
45
+ async function sqliteState(dataDir) {
46
+ const file = join(dataDir, STORE_FILE);
47
+ if (!existsSync(file))
48
+ return { version: null, runnerFloor: null, awaits: false };
49
+ const db = new DatabaseSync(file, { readOnly: true, timeout: 5_000 });
50
+ try {
51
+ const table = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'store_meta'").get();
52
+ const row = table ? db.prepare("SELECT schema_version FROM store_meta WHERE singleton = 1").get() : undefined;
53
+ const version = row?.schema_version ?? null;
54
+ const columnsOf = (name) => new Set(db.prepare("SELECT name FROM pragma_table_info(?)").all(name).map((column) => column.name));
55
+ const awaits = version !== null && (await runnerWaitsFor(columnsOf)) !== undefined;
56
+ return { version, runnerFloor: version, awaits };
57
+ }
58
+ finally {
59
+ db.close();
60
+ }
61
+ }
62
+ /** How long the read waits on Postgres (ms): for a lock (a server migrating holds the ledger's), for its one statement, and
63
+ * for any answer at all (a database that took the connection and went silent). Past one, the read fails: exit 1. */
64
+ export const STORE_SCHEMA_LOCK_MS = 2_000;
65
+ export const STORE_SCHEMA_STATEMENT_MS = 5_000;
66
+ export const STORE_SCHEMA_ANSWER_MS = 6_000;
67
+ /** The Postgres schema's version and floor, on a connection of its own that writes nothing and is ended at once. Its
68
+ * session's timeouts bound it: a deploy check never waits on a server's migration or on a silent database. */
69
+ async function postgresState(url, schema) {
70
+ const { default: pg } = await import("pg");
71
+ const client = new pg.Client({
72
+ connectionString: url,
73
+ connectionTimeoutMillis: STORE_CONNECT_TIMEOUT_MS,
74
+ lock_timeout: STORE_SCHEMA_LOCK_MS,
75
+ statement_timeout: STORE_SCHEMA_STATEMENT_MS,
76
+ query_timeout: STORE_SCHEMA_ANSWER_MS,
77
+ application_name: "agentrun-store-schema",
78
+ });
79
+ client.on("error", () => undefined);
80
+ await client.connect();
81
+ try {
82
+ return await runnerFloorOf(client, schema);
83
+ }
84
+ finally {
85
+ await client.end().catch(() => undefined);
86
+ }
87
+ }
88
+ /** Reads the store `dataDir` and `env` name (and the URL, this process's AGENTRUN_STORE_URL secret unless given). */
89
+ export async function readStoreSchema(dataDir, env = process.env, url) {
90
+ const target = url === undefined ? storeTarget(dataDir, env) : storeTarget(dataDir, env, url);
91
+ if (target.kind === "sqlite") {
92
+ const { awaits, ...state } = await sqliteState(dataDir);
93
+ return storeSchemaReport(target, state, SCHEMA_VERSION, earlierVersionIn(dataDir, 5_000).length > 0, awaits);
94
+ }
95
+ return storeSchemaReport(target, await postgresState(target.url, target.schema), migrationsIn().at(-1).version);
96
+ }
97
+ /** The versions this build knows, read from its own files, with no store: `postgres`, its newest migration; `sqlite`,
98
+ * SCHEMA_VERSION. */
99
+ export const buildSchema = () => ({ postgres: migrationsIn().at(-1).version, sqlite: SCHEMA_VERSION });
100
+ /** `agentrun-serve store-schema [--data DIR]`, or `--build` (this build's versions, no store read): the exit code (the
101
+ * file's head). */
102
+ export async function storeSchemaMain(argv, defaultDataDir, usage) {
103
+ let data;
104
+ let build;
105
+ try {
106
+ ({ data, build } = parseArgs({ args: [...argv], options: { data: { type: "string" }, build: { type: "boolean" } } }).values);
107
+ }
108
+ catch (error) {
109
+ console.error(`agentrun-serve store-schema: ${error.message}\n\n${usage}`);
110
+ return 2;
111
+ }
112
+ if (build) {
113
+ console.log(JSON.stringify({ build: buildSchema() }));
114
+ return 0;
115
+ }
116
+ try {
117
+ console.log(JSON.stringify(await readStoreSchema(data ?? defaultDataDir)));
118
+ return 0;
119
+ }
120
+ catch (error) {
121
+ // Never the URL: a connection error's own words name the host at most.
122
+ console.error(`agentrun-serve store-schema: the store could not be read: ${error?.message ?? String(error)}`);
123
+ return 1;
124
+ }
125
+ }
@@ -947,6 +947,17 @@ export interface Runs {
947
947
  /** The run's launch row (the runner reads it at its claim; the server for views). StoreLaunchMissing when the run has
948
948
  * none (it was not started with one), never a default. */
949
949
  launch(runId: string): Promise<RunLaunchRow>;
950
+ /** Only the immutable CLI accounting identity/turn and (when requested) SDK completion usage. Projects these JSON
951
+ * members in the database: no launch input, policy, sealed bytes, completion answer or replay events are returned.
952
+ * Undefined for an absent run; absent members stay undefined. Historical identity may be read without completion.
953
+ * An ordinary-store analytics read, not for Store.snapshot: PostgreSQL's specific NUL/surrogate extraction refusal falls back
954
+ * to JS parsing that row's text at the prior full-row cost (never sealed bytes); other database failures propagate. */
955
+ usageMetadata(runId: string, options: {
956
+ completion: boolean;
957
+ }): Promise<{
958
+ cli: Readonly<Record<string, unknown>>;
959
+ completionUsage?: unknown;
960
+ } | undefined>;
950
961
  /** The learning start (the launch body's `learning` member, as stored: undefined when the body names none) of every run of
951
962
  * agent `agentId` (no built-in learning run's) that has a launch row, in one read: what an agent-wide read (its cost per
952
963
  * run, its learning view) needs of its runs at once, never a read a run. Only that member is read: no run's input, no
@@ -1432,21 +1443,28 @@ export interface ComputerIntervalRow {
1432
1443
  readonly gpuCount: number | null;
1433
1444
  readonly cpus: number | null;
1434
1445
  readonly memoryMb: number | null;
1446
+ /** Its disk in GB, where its provider said it; null else. */
1447
+ readonly diskGb: number | null;
1435
1448
  readonly startedAt: number;
1436
1449
  readonly kept: boolean;
1437
1450
  readonly endedAt: number | null;
1451
+ /** How much of its time a claim of its run booked on the run's ledger (compute-cost.ts), in ms; 0 for none. */
1452
+ readonly bookedMs: number;
1438
1453
  }
1439
1454
  /** Each computer a run made, from its create to its proven delete: how long it lived for its run, and one left running
1440
1455
  * after its run (no `endedAt`). Every write is idempotent. */
1441
1456
  export interface ComputerIntervals {
1442
1457
  /** The computer's row, made: a second call for the same provider and id changes nothing (a retried create answers the
1443
1458
  * computer it made). */
1444
- opened(row: Omit<ComputerIntervalRow, "kept" | "endedAt">): Promise<void>;
1459
+ opened(row: Omit<ComputerIntervalRow, "kept" | "endedAt" | "bookedMs">): Promise<void>;
1445
1460
  /** The computer was kept past its claim (the run's park). */
1446
1461
  kept(provider: string, providerId: string): Promise<void>;
1447
1462
  /** The provider's delete of the computer answered ok at `at`: its end, written only while none is (a later delete of
1448
1463
  * one already ended never moves it). A computer with no row is left without one. */
1449
1464
  ended(provider: string, providerId: string, at: number): Promise<void>;
1465
+ /** A claim booked `ms` more of the computer's time on its run's ledger: added to its booked time (a figure that is not
1466
+ * a whole number of ms above 0 adds nothing). A computer with no row is left without one. */
1467
+ booked(provider: string, providerId: string, ms: number): Promise<void>;
1450
1468
  /** The run's computers, by when each was made. */
1451
1469
  forRun(runId: string): Promise<ComputerIntervalRow[]>;
1452
1470
  }
@@ -1578,6 +1596,23 @@ export interface RunnerRow {
1578
1596
  readonly host: string | null;
1579
1597
  readonly port: number | null;
1580
1598
  readonly seenAt: number;
1599
+ /** The runner's build (the serve package's version), and the most runs it holds at once (its loops): each null on a
1600
+ * row a runner of an earlier build wrote, or one that said neither (a refusing runner says no slots). */
1601
+ readonly version: string | null;
1602
+ readonly slots: number | null;
1603
+ }
1604
+ /** The store's runs and hand-backs as the capacity read counts them (GET /v2/capacity, capacity.ts), on the deadlines'
1605
+ * clock (fence.ts storeNow), read once for the whole answer. Counts and runner names only. */
1606
+ export interface RunCapacity {
1607
+ /** The deadlines' clock when it was read. */
1608
+ readonly at: number;
1609
+ /** Runs a runner may claim now, by the claim's own rule (queued; handed back or its claim run out, past any backoff; a
1610
+ * parked run something wakes). */
1611
+ readonly queued: number;
1612
+ /** Runs a claim holds now (its lease not run out), by the runner that holds them. */
1613
+ readonly held: ReadonlyMap<string, number>;
1614
+ /** The hand-backs (hand_backs) within the window asked for. */
1615
+ readonly handBacks: number;
1581
1616
  }
1582
1617
  /** How long a runner's row is kept once it stopped saying it is there (a runner that died without its close): its next
1583
1618
  * put removes every row older than this. */
@@ -1589,9 +1624,11 @@ export interface Runners {
1589
1624
  * `unlessLiveMs`, not over another incarnation's row of the same name seen within that: a process's put again of a row
1590
1625
  * that went (pruned, a store restored) never takes back a later process's live one. False when such a row is there and
1591
1626
  * nothing was written. */
1592
- put(row: Omit<RunnerRow, "seenAt" | "host" | "port"> & {
1627
+ put(row: Omit<RunnerRow, "seenAt" | "host" | "port" | "version" | "slots"> & {
1593
1628
  readonly host?: string | null;
1594
1629
  readonly port?: number | null;
1630
+ readonly version?: string | null;
1631
+ readonly slots?: number | null;
1595
1632
  }, options?: {
1596
1633
  readonly unlessLiveMs?: number;
1597
1634
  }): Promise<boolean>;
@@ -1608,6 +1645,8 @@ export interface Runners {
1608
1645
  live(staleMs: number): Promise<RunnerRow[]>;
1609
1646
  /** The runner's row gone, while it is still this incarnation's. */
1610
1647
  remove(runner: string, incarnation: string): Promise<void>;
1648
+ /** The runs waiting for a runner and held by one, and the hand-backs within the last `windowMs` (RunCapacity). */
1649
+ capacity(windowMs: number): Promise<RunCapacity>;
1611
1650
  }
1612
1651
  /** A template package imported from GitHub (store schema `imported_templates`, POST /v2/templates/import): its id
1613
1652
  * (`github:<owner>/<repo>[/<path>]`), its source as given, the commit SHA read, its publisher (the GitHub account), and
@@ -1887,6 +1926,9 @@ export interface Store {
1887
1926
  * done; `left` says why it was kept, for the next start to finish. Postgres: `work` alone (a replaced row version is
1888
1927
  * the database's until its vacuum). */
1889
1928
  secureRewrite?(work: () => Promise<number>, options?: SecureRewriteOptions): Promise<SecureRewrite>;
1929
+ /** Reads the store's schema version and its runner floor now, without a lock or a write: a runner reads it at each
1930
+ * renewal (runner/main.ts), and stops once the floor is above the version its build knows. */
1931
+ schemaState?(): Promise<StoreSchemaState>;
1890
1932
  /** Claims the run for `runner` until now + `leaseMs`: the run's epoch + 1 when it is claimable (runs.claimable); null when
1891
1933
  * another claim holds it, or it is final, or parked with nothing to wake it. A queued or parked run becomes running. */
1892
1934
  claim(runId: string, runner: string, options?: {
@@ -2031,6 +2073,23 @@ export declare class SchemaVersionUnknown extends Error {
2031
2073
  readonly known: number;
2032
2074
  constructor(file: string, found: number | null, known: number);
2033
2075
  }
2076
+ /** A store a later build migrated past what this runner can run beside: its schema is ahead of the version this build
2077
+ * knows, and its runner floor (a breaking migration's version) is above it. Run a runner of the server's release. A
2078
+ * SchemaVersionUnknown, so every caller that refuses an unknown schema refuses this one the same way (a runner's exit 3). */
2079
+ export declare class RunnerBelowFloor extends SchemaVersionUnknown {
2080
+ readonly floor: number;
2081
+ constructor(place: string, found: number, known: number, floor: number);
2082
+ }
2083
+ /** A store's schema version and its runner floor (Store.schemaState). */
2084
+ export interface StoreSchemaState {
2085
+ /** The store's schema version; null when none is set up. */
2086
+ readonly version: number | null;
2087
+ /** The oldest schema version a runner's build must know to run on this store: a runner whose build knows less stops
2088
+ * claiming, hands its runs back and exits. On SQLite the version itself (a SQLite runner opens only its own version). */
2089
+ readonly runnerFloor: number | null;
2090
+ /** The version this build knows (its newest migration on Postgres, SCHEMA_VERSION on SQLite). */
2091
+ readonly known: number;
2092
+ }
2034
2093
  /** A command for a run that is final, or that does not exist. */
2035
2094
  export declare class RunFinal extends Error {
2036
2095
  readonly runId: string;
@@ -224,6 +224,19 @@ export class SchemaVersionUnknown extends Error {
224
224
  this.known = known;
225
225
  }
226
226
  }
227
+ /** A store a later build migrated past what this runner can run beside: its schema is ahead of the version this build
228
+ * knows, and its runner floor (a breaking migration's version) is above it. Run a runner of the server's release. A
229
+ * SchemaVersionUnknown, so every caller that refuses an unknown schema refuses this one the same way (a runner's exit 3). */
230
+ export class RunnerBelowFloor extends SchemaVersionUnknown {
231
+ floor;
232
+ constructor(place, found, known, floor) {
233
+ super(place, found, known);
234
+ const store = place.startsWith("the ") ? place : `the store at ${place}`;
235
+ this.message = `${store} is schema version ${found}, and a runner on it must know version ${floor} or later (its runner floor: a later release changed the schema in a way an earlier runner cannot run beside); this runner knows ${known}. Run a runner of the server's release.`;
236
+ this.name = "RunnerBelowFloor";
237
+ this.floor = floor;
238
+ }
239
+ }
227
240
  /** A command for a run that is final, or that does not exist. */
228
241
  export class RunFinal extends Error {
229
242
  runId;
@@ -8,14 +8,15 @@ export type AnalyticsFilter = {
8
8
  agent?: string;
9
9
  pending?: Readonly<Record<string, PendingEnd>>;
10
10
  };
11
- /** Runs counted together: how many, how many completed (escalated included) and failed, how many have metrics, their
12
- * tokens, and their cost as stats sums it (null when none ended with one; unknownCostRuns the rest). */
11
+ /** Runs counted together: how many completed (escalated included) and failed, how many have metrics and how many
12
+ * report every token counter, their known token total, and their cost (null when none ended with one). */
13
13
  export type AnalyticsGroup = {
14
14
  runs: number;
15
15
  completed: number;
16
16
  needsReview: number;
17
17
  failed: number;
18
18
  runsWithMetrics: number;
19
+ runsWithTokenMetrics: number;
19
20
  tokens: number | null;
20
21
  costUsd: number | null;
21
22
  unknownCostRuns: number;
@@ -4,13 +4,21 @@
4
4
  // given. A pending run (its end on the caller's way, not yet in the store) is counted at the state its end will have, in
5
5
  // the totals alone; its metrics, cost and effort wait for its end. No journal is read: the figures are the row's.
6
6
  import { sdkOf } from "../sdk/runs.js";
7
+ import { cliLearningOf } from "../store/agent-body.js";
8
+ import { NATIVE_RUNTIME_FACTS } from "../native/runtimes.js";
7
9
  import { DEFAULT_HARNESS } from "../harness.js";
8
10
  import { costOfRun, runReadState } from "./runs.js";
9
11
  import { isShadowRun, shadowRunId } from "../learn/audit.js";
10
12
  const PENDING_ENDS = new Set(["completed", "escalated", "failed", "stopped"]);
11
13
  const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
12
14
  const metricsOf = (run) => (run.metrics !== null && typeof run.metrics === "object" && !Array.isArray(run.metrics) ? run.metrics : null);
13
- const tokensOf = (m) => num(m.input) + num(m.cacheRead) + num(m.cacheWrite) + num(m.output);
15
+ const TOKEN_KEYS = ["input", "cacheRead", "cacheWrite", "output"];
16
+ /** A metrics object may hold only tools or null native counters. Count coverage only when its whole total is known. */
17
+ const tokensOf = (m) => {
18
+ if (!TOKEN_KEYS.every((key) => typeof m[key] === "number" && Number.isSafeInteger(m[key]) && m[key] >= 0))
19
+ return null;
20
+ return num(m.input) + num(m.cacheRead) + num(m.cacheWrite) + num(m.output);
21
+ };
14
22
  /** The runs and their metrics summed (the old AgentStoreReader.analytics), from A's run rows. */
15
23
  export async function analytics(store, filter = {}) {
16
24
  const pending = {};
@@ -41,7 +49,10 @@ export async function analytics(store, filter = {}) {
41
49
  continue;
42
50
  if (!harnessOf.has(run.revisionId)) {
43
51
  const revision = await store.agents.revision(run.revisionId);
44
- harnessOf.set(run.revisionId, revision?.kind === "workflow" ? "workflow" : (sdkOf(revision?.body)?.runtime ?? revision?.body?.harness ?? DEFAULT_HARNESS));
52
+ const cli = cliLearningOf(revision?.body);
53
+ harnessOf.set(run.revisionId, revision?.kind === "workflow" ? "workflow" : cli
54
+ ? NATIVE_RUNTIME_FACTS[cli.runtime].captureRuntime
55
+ : sdkOf(revision?.body)?.runtime ?? revision?.body?.harness ?? DEFAULT_HARNESS);
45
56
  }
46
57
  const read = runReadState(run, harnessOf.get(run.revisionId) === "workflow" ? "workflow" : "agentic");
47
58
  const running = read === "running";
@@ -67,8 +78,7 @@ export async function analytics(store, filter = {}) {
67
78
  });
68
79
  }
69
80
  const counted = (group) => {
70
- let unknownTokens = false;
71
- let runsN = 0, completed = 0, needsReview = 0, failed = 0, metered = 0, tokens = 0, costUsd = 0, known = 0, pend = 0;
81
+ let runsN = 0, completed = 0, needsReview = 0, failed = 0, metered = 0, tokenMetered = 0, tokens = 0, costUsd = 0, known = 0, pend = 0;
72
82
  let shadowUsd = 0;
73
83
  for (const f of group) {
74
84
  shadowUsd += f.shadowUsd;
@@ -81,16 +91,18 @@ export async function analytics(store, filter = {}) {
81
91
  failed += 1;
82
92
  if (f.metered) {
83
93
  metered += 1;
84
- tokens += tokensOf(f.metrics);
85
- if (['input', 'cacheRead', 'cacheWrite', 'output'].some(key => f.metrics?.[key] === null))
86
- unknownTokens = true;
94
+ const reported = tokensOf(f.metrics);
95
+ if (reported !== null) {
96
+ tokenMetered += 1;
97
+ tokens += reported;
98
+ }
87
99
  }
88
100
  if (!f.running && !f.pending && f.costUsd !== null)
89
101
  (costUsd += f.costUsd, (known += 1));
90
102
  if (f.pending)
91
103
  pend += 1;
92
104
  }
93
- return { runs: runsN, completed, needsReview, failed, runsWithMetrics: metered, tokens: unknownTokens ? null : tokens, costUsd: known > 0 || shadowUsd > 0 ? costUsd + shadowUsd : null, unknownCostRuns: runsN - known - pend };
105
+ return { runs: runsN, completed, needsReview, failed, runsWithMetrics: metered, runsWithTokenMetrics: tokenMetered, tokens: tokenMetered > 0 || runsN === 0 ? tokens : null, costUsd: known > 0 || shadowUsd > 0 ? costUsd + shadowUsd : null, unknownCostRuns: runsN - known - pend };
94
106
  };
95
107
  // Totals over the whole scope: the group counts, the token sums, and the time figures.
96
108
  let input = 0, cacheRead = 0, cacheWrite = 0, output = 0, requests = 0, unmetered = 0;
@@ -16,13 +16,17 @@ export declare function spendOverStore(store: Store, runId: string, context: Con
16
16
  usd: number | null;
17
17
  basis: CostBasis | undefined;
18
18
  }>;
19
- /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
20
- * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
21
- * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
22
- export declare function metersOverStore(store: Store, runId: string, context: Context): Promise<Meters & {
19
+ /** A run's /usage meters, with each meter's known dollars. */
20
+ type KnownMeters = Meters & {
23
21
  known: {
24
22
  tokens: number;
25
23
  browser: number;
26
24
  others: number;
27
25
  };
28
- }>;
26
+ };
27
+ /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
28
+ * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
29
+ * file-backed run held each on its root, and the decisions Parallel charged on its own API (parallelDecisionsOn) on its
30
+ * tools meter beside them. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
31
+ export declare function metersOverStore(store: Store, runId: string, context: Context): Promise<KnownMeters>;
32
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { meterFiguresFrom, spentFrom } from "../cap.js";
2
- import { bookedListSpend, bookedSpend, cliModelWorked, costBasisOf, costIsBooked } from "../runner/metrics.js";
2
+ import { bookedDecisionsOf, bookedListSpend, bookedSpend, cliModelWorked, costBasisOf, costIsBooked } from "../runner/metrics.js";
3
+ import { booksDecisions, decisionsOverStore, parallelChargedDecisions } from "./decisions.js";
3
4
  import { isCliRecord, runEntries, withPaidCosts } from "./journal.js";
4
5
  /** A CLI run whose model answered or called a tool with no model request booked (metrics.ts cliModelWorked): what it
5
6
  * spent no booking read, so its spend is unknown. */
@@ -56,9 +57,34 @@ function spentOf(entries) {
56
57
  }
57
58
  /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
58
59
  * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
59
- * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
60
+ * file-backed run held each on its root, and the decisions Parallel charged on its own API (parallelDecisionsOn) on its
61
+ * tools meter beside them. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
60
62
  export async function metersOverStore(store, runId, context) {
61
63
  const raw = await runEntries(store, runId, context);
64
+ if (!raw.length)
65
+ return metersOfEntries(store, runId, raw);
66
+ return parallelDecisionsOn(store, runId, raw, context, await metersOfEntries(store, runId, raw));
67
+ }
68
+ /** A run's decisions Parallel charged on its own API (store-reads/decisions.ts chargedByParallel) on its tools meter, as
69
+ * GET /runs/{run_id}/usage puts them on Parallel's tools line: each a paid call, at its list price. They leave the rest
70
+ * of the run's cost (its tokens meter, which /usage reads as its cost less its tools) as they join its tools, so no
71
+ * total moves. As for a paid call, /usage says no "at most": one booked at its hold, or of no known cost, makes the
72
+ * meter unknown, its exact charges known beside it. */
73
+ async function parallelDecisionsOn(store, runId, raw, context, meters) {
74
+ if (!booksDecisions(raw))
75
+ return meters;
76
+ const ids = parallelChargedDecisions(await decisionsOverStore(store, runId, context));
77
+ if (!ids.size)
78
+ return meters;
79
+ const charged = bookedDecisionsOf(raw, ids);
80
+ if (!charged.requests)
81
+ return meters;
82
+ const usd = charged.unpriced > 0 || charged.bounded > 0 ? null : charged.known;
83
+ const plus = (figure) => (figure === null || usd === null ? null : figure + usd);
84
+ return { ...meters, tools: plus(meters.tools), others: plus(meters.others), known: { ...meters.known, others: meters.known.others + charged.known } };
85
+ }
86
+ /** metersOverStore's figures over `raw`, the run's entries, before its Parallel decisions join its tools meter. */
87
+ async function metersOfEntries(store, runId, raw) {
62
88
  if (!raw.length) {
63
89
  // A purged run's journal is gone: its figures are the ones its purge read from it (Runs.purge, PurgeKept).
64
90
  const kept = await purgeKept(store, runId);
@@ -1,5 +1,26 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import type { Store } from "../store/store.js";
3
+ /** Who charges for a decision Parallel answered on its own API, on this server's key: Parallel, the same name its web
4
+ * tools' charges carry (paid-calls.ts). */
5
+ export declare const PARALLEL_CHARGER = "parallel";
6
+ /** Whether a decision's receipt says Parallel charged for it as a paid call: answered by the `parallel` provider on
7
+ * Parallel's own API, booked at Parallel's list price (`cost_basis` "estimate", @parcha/agentrun-decisions
8
+ * PARALLEL_LIST_PRICE_USD). One the same provider sent through OpenRouter (Parallel's model there) is booked at the cost
9
+ * OpenRouter reported ("reported", or "unknown"): OpenRouter charged it, a model's cost, and it stays one. */
10
+ export declare const chargedByParallel: (receipt: {
11
+ readonly provider?: unknown;
12
+ readonly cost_basis?: unknown;
13
+ }) => boolean;
14
+ /** A receipt's decision id, the one its booking names (`decision:<id>`). */
15
+ export declare const receiptIdOf: (receipt: Record<string, unknown>) => string;
16
+ /** The ids of the decisions among `receipts` Parallel charged as a paid call (chargedByParallel). */
17
+ export declare function parallelChargedDecisions(receipts: Iterable<Record<string, unknown>>): Set<string>;
18
+ /** Whether a run's journal `entries` book a workflow decision (a request named `decision:<id>`), so its receipts are
19
+ * worth reading. */
20
+ export declare const booksDecisions: (entries: readonly {
21
+ readonly kind: string;
22
+ readonly data?: unknown;
23
+ }[]) => boolean;
3
24
  /** A run's decision receipts: the keyed `.count` and family rows in order, read through
4
25
  * the one store's journal. */
5
26
  export declare function decisionsOverStore(store: Store, runId: string, context: Context): Promise<Array<Record<string, unknown>>>;
@@ -1,3 +1,4 @@
1
+ import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
1
2
  import { decisionKey } from "../workflow/decisions.js";
2
3
  /** A session-scoped document's current value, by kind and (for a family) key: findDocument, then its stored value. */
3
4
  async function sessionDocValue(reads, kind, key, context) {
@@ -7,6 +8,27 @@ async function sessionDocValue(reads, kind, key, context) {
7
8
  const stored = await reads.document(record.id, "current", context);
8
9
  return stored ? stored.value : undefined;
9
10
  }
11
+ /** Who charges for a decision Parallel answered on its own API, on this server's key: Parallel, the same name its web
12
+ * tools' charges carry (paid-calls.ts). */
13
+ export const PARALLEL_CHARGER = "parallel";
14
+ /** Whether a decision's receipt says Parallel charged for it as a paid call: answered by the `parallel` provider on
15
+ * Parallel's own API, booked at Parallel's list price (`cost_basis` "estimate", @parcha/agentrun-decisions
16
+ * PARALLEL_LIST_PRICE_USD). One the same provider sent through OpenRouter (Parallel's model there) is booked at the cost
17
+ * OpenRouter reported ("reported", or "unknown"): OpenRouter charged it, a model's cost, and it stays one. */
18
+ export const chargedByParallel = (receipt) => receipt.provider === "parallel" && receipt.cost_basis === "estimate";
19
+ /** A receipt's decision id, the one its booking names (`decision:<id>`). */
20
+ export const receiptIdOf = (receipt) => String(receipt.decision_id ?? receipt.id);
21
+ /** The ids of the decisions among `receipts` Parallel charged as a paid call (chargedByParallel). */
22
+ export function parallelChargedDecisions(receipts) {
23
+ const ids = new Set();
24
+ for (const receipt of receipts)
25
+ if (chargedByParallel(receipt))
26
+ ids.add(receiptIdOf(receipt));
27
+ return ids;
28
+ }
29
+ /** Whether a run's journal `entries` book a workflow decision (a request named `decision:<id>`), so its receipts are
30
+ * worth reading. */
31
+ export const booksDecisions = (entries) => entries.some((e) => e.kind === RUNNER_RECORDS.request && String(e.data?.model ?? "").startsWith("decision:"));
10
32
  /** A run's decision receipts: the keyed `.count` and family rows in order, read through
11
33
  * the one store's journal. */
12
34
  export async function decisionsOverStore(store, runId, context) {
@@ -66,14 +66,20 @@ export type WholeAnswer = {
66
66
  };
67
67
  /** The WholeAnswer of a run whose served words are cut of `values` (run-cut.ts runCutValues). */
68
68
  export declare const wholeAnswerFor: (values: readonly string[]) => WholeAnswer;
69
+ export declare const servedSince: (store: Store) => number;
70
+ /** Run `runId`'s answer rows dropped from what the readers of `store` last served (wholeAnswers): a purged or deleted
71
+ * run's text kept in no memory of this process (store-view.ts forgetServed). Counted (servedSince), so no read begun
72
+ * before it keeps what it read. The keys it dropped. */
73
+ export declare function forgetServedAnswers(store: Store, runId: string): string[];
69
74
  /** `rows` (runTimeline's, rendered with `options`) with each final answer whole, as main served a run's answer: the renderer
70
75
  * cuts a row's text at CAPS.text, and its redactor (`options.redact`, key-refusal.ts redacted) reads only the head a row
71
76
  * shows and cuts the rest, ending what it cut in "..." (short of the cap when it replaced a held value there), or giving
72
77
  * "[redacted]" alone when all it read was redacted. A final answer row at the cap, ending so or reading so is read again
73
78
  * from the journal, settled as the rows were, with no text cap and none
74
79
  * of the rows' redactor, the same row by its id (its entry's), and given through `whole.serve`, which reads every byte
75
- * of it and never cuts. Every other row is as it was. */
76
- export declare function wholeAnswers(store: Store, runId: string, context: Context, rows: TimelineEvent[], options: TimelineOptions, whole: WholeAnswer): Promise<TimelineEvent[]>;
80
+ * of it and never cuts. Every other row is as it was. What it read is kept only while no run's text was forgotten since
81
+ * `since` (servedSince, taken before the read began). */
82
+ export declare function wholeAnswers(store: Store, runId: string, context: Context, rows: TimelineEvent[], options: TimelineOptions, whole: WholeAnswer, since: number): Promise<TimelineEvent[]>;
77
83
  /** What was said to a run (its hearing), from the one store's entries, as runs.ts noteTurns fed it from the stream: each
78
84
  * user entry noted in log order, its origin read by the same matcher. */
79
85
  export declare function runHearing(store: Store, runId: string, context: Context): Promise<Hearing>;
@@ -426,14 +426,31 @@ export const wholeAnswerFor = (values) => ({
426
426
  * entry's, whose words never change. Kept by store, the newest ANSWERS_KEPT of each. */
427
427
  const answersServed = new WeakMap();
428
428
  const ANSWERS_KEPT = 32;
429
+ /** How many times the readers of each store were told to forget a run's text (forgetServedAnswers). A read takes it
430
+ * before it reads anything (servedSince) and keeps what it made only while it is the same, so a read begun before a
431
+ * purge, which may still hold the purged run's text, never puts that text back once the purge dropped it. */
432
+ const forgetsOf = new WeakMap();
433
+ export const servedSince = (store) => forgetsOf.get(store.origin) ?? 0;
434
+ /** Run `runId`'s answer rows dropped from what the readers of `store` last served (wholeAnswers): a purged or deleted
435
+ * run's text kept in no memory of this process (store-view.ts forgetServed). Counted (servedSince), so no read begun
436
+ * before it keeps what it read. The keys it dropped. */
437
+ export function forgetServedAnswers(store, runId) {
438
+ forgetsOf.set(store.origin, servedSince(store) + 1);
439
+ const kept = answersServed.get(store.origin);
440
+ const dropped = [...(kept?.keys() ?? [])].filter((key) => key.startsWith(`${runId}\0`));
441
+ for (const key of dropped)
442
+ kept.delete(key);
443
+ return dropped;
444
+ }
429
445
  /** `rows` (runTimeline's, rendered with `options`) with each final answer whole, as main served a run's answer: the renderer
430
446
  * cuts a row's text at CAPS.text, and its redactor (`options.redact`, key-refusal.ts redacted) reads only the head a row
431
447
  * shows and cuts the rest, ending what it cut in "..." (short of the cap when it replaced a held value there), or giving
432
448
  * "[redacted]" alone when all it read was redacted. A final answer row at the cap, ending so or reading so is read again
433
449
  * from the journal, settled as the rows were, with no text cap and none
434
450
  * of the rows' redactor, the same row by its id (its entry's), and given through `whole.serve`, which reads every byte
435
- * of it and never cuts. Every other row is as it was. */
436
- export async function wholeAnswers(store, runId, context, rows, options, whole) {
451
+ * of it and never cuts. Every other row is as it was. What it read is kept only while no run's text was forgotten since
452
+ * `since` (servedSince, taken before the read began). */
453
+ export async function wholeAnswers(store, runId, context, rows, options, whole, since) {
437
454
  // The rows' redactor gives exactly "[redacted]" for a text whose head it read was all held or secret-shaped values: the
438
455
  // rest of the answer is past what it read, so that row is read again too.
439
456
  const cut = (row) => row.kind === "final_answer" && row.text !== null && (row.text.length >= CAPS.text || row.text.endsWith("...") || row.text === "[redacted]");
@@ -461,12 +478,14 @@ export async function wholeAnswers(store, runId, context, rows, options, whole)
461
478
  continue;
462
479
  }
463
480
  served = whole.serve(text);
464
- kept.delete(key);
465
- kept.set(key, served);
466
- for (const oldest of kept.keys()) {
467
- if (kept.size <= ANSWERS_KEPT)
468
- break;
469
- kept.delete(oldest);
481
+ if (servedSince(store) === since) {
482
+ kept.delete(key);
483
+ kept.set(key, served);
484
+ for (const oldest of kept.keys()) {
485
+ if (kept.size <= ANSWERS_KEPT)
486
+ break;
487
+ kept.delete(oldest);
488
+ }
470
489
  }
471
490
  }
472
491
  out.push({ ...row, text: served });
@@ -39,6 +39,10 @@ export declare const settledStatusOf: (state: RunReadState) => Status | undefine
39
39
  * that withheld the run for a sign-in it could not read back (listingOverStore), and the lister's build that failed
40
40
  * (run-listing.ts). */
41
41
  export declare const LISTING_RETRY_MS = 30000;
42
+ /** Run `runId`'s text dropped from what the readers of `store` last served: its view's slots (its answer's, its input's)
43
+ * and its whole answer rows (store-reads/journal.ts forgetServedAnswers), so a purged or deleted run's text stays in no
44
+ * memory of this process (agent-delete.ts). What it dropped, by slot and key. */
45
+ export declare function forgetServed(store: Store, runId: string): string[];
42
46
  /** A run's whole answer as answerOfRun read it from the rows: its newest final-answer row, never the learning turn's, and
43
47
  * never an earlier turn's: a final answer row before the person's last message belongs to the turn that message
44
48
  * followed, so a follow-up whose own stop said nothing (no text block: a thinking-only stop) has no answer, null, not
@@ -50,6 +54,7 @@ export declare const answerOf: (timeline: readonly TimelineEvent[]) => string |
50
54
  interface StoreRun {
51
55
  readonly native?: Record<string, unknown>;
52
56
  readonly sdk?: Record<string, unknown>;
57
+ readonly cli_learning?: Record<string, unknown>;
53
58
  readonly row: NonNullable<Awaited<ReturnType<typeof readRun>>>;
54
59
  readonly runRow: RunRow;
55
60
  readonly launch: RunLaunch | undefined;
@@ -143,12 +148,12 @@ export declare function standsOnPerson(approvals: ReadonlyMap<string, {
143
148
  * True when written; false when another write got there first, or when the write failed (said, never thrown: a read
144
149
  * never fails on its heal, and the next read or start sweep writes it again). */
145
150
  export declare function healStoredCost(store: Store, runId: string, heal: NonNullable<StoreRun["heal"]>): Promise<boolean>;
146
- /** The end run `runId` keeps while it looks back after its job ended, as every reader serves it (lookingBackOf), else
147
- * undefined: a run that reads ended while it is still learning from that end. */
148
- export declare function lookingBackEnd(store: Store, runId: string): Promise<KeptEnd | undefined>;
151
+ /** The end run `stored` (its row as the caller read it) keeps while it looks back after its job ended, as every reader
152
+ * serves it (lookingBackOf), else undefined: a run that reads ended while it is still learning from that end. */
153
+ export declare function lookingBackEnd(store: Store, stored: RunRow): Promise<KeptEnd | undefined>;
149
154
  /** What run `runId`'s paid tool calls cost, the run read's `cost.tools_usd` (server.ts allInViewOf): the charges its
150
155
  * paid-tools session booked (a monid endpoint's, a priced MCP tool's, Parallel's behind the web tools, the browser's
151
- * time), joined and rounded by the one rule its `usd` is (costWordsOf), less those in its end-of-run turn, which are
156
+ * time) and the decisions Parallel charged on its own API (store-reads/decisions.ts chargedByParallel), joined and rounded by the one rule its `usd` is (costWordsOf), less those in its end-of-run turn, which are
152
157
  * learning's as that turn's model requests are (runCostOf). A part of `usd`, never added to it; 0 with none. Null when
153
158
  * one's charge is unknown (charged an unknown amount, cut, or still out) or counted at its hold; while the run is at work
154
159
  * (not ended, stopped or failed), as its `usd` is the view's snapshot and a paid call booked after it would be read here