@parcha/agentrun-serve 0.1.0-beta.61 → 0.1.0-beta.63

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +128 -20
  3. package/dist/adapters.js +4 -2
  4. package/dist/agent-delete.d.ts +3 -3
  5. package/dist/agent-delete.js +50 -4
  6. package/dist/api-only.d.ts +4 -0
  7. package/dist/api-only.js +5 -1
  8. package/dist/archil-settings.d.ts +9 -0
  9. package/dist/archil-settings.js +8 -1
  10. package/dist/bash-read-only.d.ts +3 -0
  11. package/dist/bash-read-only.js +6 -3
  12. package/dist/chatgpt-plan.d.ts +33 -8
  13. package/dist/chatgpt-plan.js +141 -24
  14. package/dist/claude-login.d.ts +12 -5
  15. package/dist/claude-login.js +28 -3
  16. package/dist/cli.js +19 -8
  17. package/dist/composio-triggers.d.ts +9 -3
  18. package/dist/computers.d.ts +3 -0
  19. package/dist/computers.js +2 -1
  20. package/dist/console/assets/{backend-C9ffXUR5.js → backend-BxQ2G1M0.js} +2 -2
  21. package/dist/console/assets/index-C8Y5Zl8x.js +639 -0
  22. package/dist/console/assets/share-CjBJ_rxP.js +6 -0
  23. package/dist/console/assets/{styles-fjQBFfMv.css → styles-D0SufbzK.css} +1 -1
  24. package/dist/console/index.html +3 -3
  25. package/dist/console/share.html +3 -3
  26. package/dist/cut-pool.d.ts +14 -0
  27. package/dist/cut-pool.js +98 -0
  28. package/dist/cut-worker.d.ts +14 -0
  29. package/dist/cut-worker.js +16 -0
  30. package/dist/decisions.d.ts +4 -0
  31. package/dist/decisions.js +9 -1
  32. package/dist/env-switch.d.ts +3 -0
  33. package/dist/env-switch.js +3 -0
  34. package/dist/harness-opencode/adapter.d.ts +3 -1
  35. package/dist/harness-opencode/adapter.js +6 -2
  36. package/dist/harness-opencode/harness.d.ts +4 -0
  37. package/dist/harness-opencode/harness.js +6 -1
  38. package/dist/harness-table.d.ts +7 -0
  39. package/dist/harness-table.js +6 -3
  40. package/dist/host-tools.d.ts +18 -3
  41. package/dist/host-tools.js +27 -4
  42. package/dist/import.d.ts +8 -1
  43. package/dist/import.js +36 -5
  44. package/dist/key-check.js +22 -8
  45. package/dist/learn/ledger.d.ts +37 -16
  46. package/dist/learn/ledger.js +56 -24
  47. package/dist/learn/promote.d.ts +4 -1
  48. package/dist/learned-nodes.d.ts +2 -1
  49. package/dist/learned-nodes.js +2 -1
  50. package/dist/learning-cost.d.ts +5 -3
  51. package/dist/learning-model.js +7 -5
  52. package/dist/learning-work.d.ts +69 -0
  53. package/dist/learning-work.js +148 -0
  54. package/dist/mcp-gateway.d.ts +24 -0
  55. package/dist/mcp-gateway.js +97 -8
  56. package/dist/mcp-servers-store.d.ts +7 -10
  57. package/dist/mcp-servers-store.js +15 -9
  58. package/dist/native/cli.js +5 -1
  59. package/dist/ollama-provider.d.ts +10 -3
  60. package/dist/ollama-provider.js +17 -7
  61. package/dist/openapi.js +51 -20
  62. package/dist/otel/tracer.d.ts +6 -3
  63. package/dist/otel/tracer.js +24 -6
  64. package/dist/page.d.ts +7 -0
  65. package/dist/page.js +17 -4
  66. package/dist/place.d.ts +25 -9
  67. package/dist/place.js +37 -11
  68. package/dist/print.d.ts +3 -2
  69. package/dist/print.js +8 -6
  70. package/dist/run-export.js +7 -4
  71. package/dist/run-launch.d.ts +6 -1
  72. package/dist/run-launch.js +26 -6
  73. package/dist/run-model-key.d.ts +2 -1
  74. package/dist/run-model-key.js +2 -1
  75. package/dist/run-reads-over-store.d.ts +7 -0
  76. package/dist/run-reads-over-store.js +32 -4
  77. package/dist/run-view.js +9 -3
  78. package/dist/runnable.d.ts +6 -3
  79. package/dist/runnable.js +21 -11
  80. package/dist/runner/adapter-loop.js +95 -28
  81. package/dist/runner/adapter-run-spec.d.ts +20 -4
  82. package/dist/runner/adapter-run-spec.js +64 -30
  83. package/dist/runner/adapters/index.d.ts +6 -0
  84. package/dist/runner/adapters/index.js +5 -1
  85. package/dist/runner/adapters/pi.d.ts +42 -3
  86. package/dist/runner/adapters/pi.js +114 -13
  87. package/dist/runner/audit.d.ts +8 -2
  88. package/dist/runner/audit.js +34 -18
  89. package/dist/runner/book-cut.d.ts +6 -0
  90. package/dist/runner/book-cut.js +38 -0
  91. package/dist/runner/claim-secrets.d.ts +12 -5
  92. package/dist/runner/claim-secrets.js +28 -12
  93. package/dist/runner/cli-run-spec.d.ts +0 -2
  94. package/dist/runner/cli-run-spec.js +54 -25
  95. package/dist/runner/dispatch.js +2 -0
  96. package/dist/runner/harness-loops.d.ts +5 -0
  97. package/dist/runner/harness-loops.js +4 -1
  98. package/dist/runner/held.d.ts +6 -3
  99. package/dist/runner/learned-first.d.ts +5 -0
  100. package/dist/runner/learned-first.js +1 -1
  101. package/dist/runner/learning-end.d.ts +15 -8
  102. package/dist/runner/learning-end.js +23 -7
  103. package/dist/runner/live-ticker.js +3 -1
  104. package/dist/runner/loop-contract.d.ts +8 -1
  105. package/dist/runner/main.js +2 -0
  106. package/dist/runner/mcp-run.d.ts +5 -0
  107. package/dist/runner/mcp-run.js +18 -0
  108. package/dist/runner/meta-tools.js +4 -4
  109. package/dist/runner/metrics.d.ts +4 -2
  110. package/dist/runner/metrics.js +5 -3
  111. package/dist/runner/model-route.d.ts +4 -0
  112. package/dist/runner/model-route.js +1 -1
  113. package/dist/runner/native-loop.js +2 -2
  114. package/dist/runner/pr-checkout.d.ts +12 -0
  115. package/dist/runner/pr-checkout.js +21 -2
  116. package/dist/runner/promotion.d.ts +9 -2
  117. package/dist/runner/promotion.js +79 -28
  118. package/dist/runner/reflect-hook.d.ts +7 -0
  119. package/dist/runner/reflect-hook.js +2 -1
  120. package/dist/runner/run-child-host.d.ts +10 -6
  121. package/dist/runner/run-child-host.js +65 -41
  122. package/dist/runner/run-child.js +2 -0
  123. package/dist/runner/runner.d.ts +9 -0
  124. package/dist/runner/runner.js +158 -25
  125. package/dist/runner/store-port.d.ts +4 -1
  126. package/dist/runner/workflow-calls.d.ts +4 -3
  127. package/dist/runner/workflow-calls.js +41 -12
  128. package/dist/runner/workflow-first.js +4 -3
  129. package/dist/runner/workflow-loop.js +13 -1
  130. package/dist/runner/workflow-spec.js +1 -1
  131. package/dist/secret-cut.d.ts +4 -0
  132. package/dist/secret-cut.js +1 -1
  133. package/dist/secret-rules.d.ts +2 -1
  134. package/dist/secret-rules.js +88 -24
  135. package/dist/server.d.ts +10 -1
  136. package/dist/server.js +131 -44
  137. package/dist/share-host.d.ts +111 -0
  138. package/dist/share-host.js +669 -0
  139. package/dist/store/schema.d.ts +4 -3
  140. package/dist/store/schema.js +4 -3
  141. package/dist/store/seal.d.ts +8 -2
  142. package/dist/store/seal.js +13 -2
  143. package/dist/store/sqlite/learning-rows.js +2 -1
  144. package/dist/store/sqlite/run-patch.js +4 -4
  145. package/dist/store/sqlite/store.js +28 -4
  146. package/dist/store/store.d.ts +5 -0
  147. package/dist/store-reads/analytics.d.ts +15 -0
  148. package/dist/store-reads/analytics.js +17 -0
  149. package/dist/store-reads/journal.d.ts +2 -0
  150. package/dist/store-reads/journal.js +1 -1
  151. package/dist/store-reads/learning.d.ts +4 -3
  152. package/dist/store-reads/learning.js +62 -18
  153. package/dist/store-view.d.ts +3 -0
  154. package/dist/store-view.js +18 -1
  155. package/dist/suggestions.js +32 -3
  156. package/dist/templates.d.ts +3 -1
  157. package/dist/templates.js +7 -3
  158. package/dist/tool-gate.d.ts +25 -9
  159. package/dist/tool-gate.js +58 -19
  160. package/dist/tool-list.d.ts +4 -0
  161. package/dist/tool-list.js +4 -0
  162. package/dist/tool-plane.d.ts +1 -0
  163. package/dist/tool-plane.js +6 -2
  164. package/dist/tools.js +2 -2
  165. package/dist/trigger-composio.js +1 -1
  166. package/dist/webhooks.d.ts +3 -0
  167. package/dist/webhooks.js +5 -0
  168. package/dist/workspace/archil-claim.d.ts +7 -3
  169. package/dist/workspace/archil-claim.js +13 -5
  170. package/dist/workspace/archil-mount-credential.d.ts +6 -0
  171. package/dist/workspace/archil-mount-credential.js +11 -0
  172. package/dist/workspace/attach.js +22 -5
  173. package/dist/workspace/computer-deps.d.ts +5 -3
  174. package/dist/workspace/computer-deps.js +11 -9
  175. package/dist/workspace/computer-for-claim.d.ts +6 -2
  176. package/dist/workspace/computer-for-claim.js +43 -12
  177. package/dist/workspace/computer-janitor.d.ts +7 -4
  178. package/dist/workspace/computer-janitor.js +7 -4
  179. package/dist/workspace/computer-kept.d.ts +7 -1
  180. package/dist/workspace/computer-kept.js +7 -1
  181. package/dist/workspace/kind-skills/desktop/SKILL.md +17 -4
  182. package/dist/workspace/mount-revoke-left.d.ts +16 -4
  183. package/dist/workspace/mount-revoke-left.js +42 -22
  184. package/dist/workspace/resolve-computer.d.ts +11 -5
  185. package/dist/workspace/resolve-computer.js +22 -13
  186. package/dist/workspace/run-end-computers.js +1 -1
  187. package/dist/workspace/run-tools.d.ts +10 -3
  188. package/dist/workspace/run-tools.js +5 -4
  189. package/dist/wrapped.d.ts +29 -2
  190. package/dist/wrapped.js +20 -3
  191. package/launcher/agentrun-serve +1 -1
  192. package/package.json +12 -12
  193. package/templates/kyb/agent.md +7 -1
  194. package/templates/kyb/evals/list-file-fuzzy-alias/case.yaml +10 -0
  195. package/templates/kyb/evals/list-file-fuzzy-alias/fixtures/web.json +58 -0
  196. package/templates/kyb/evals/list-file-fuzzy-alias/graders/finds-the-transliteration.md +17 -0
  197. package/templates/kyb/evals/list-file-fuzzy-alias/graders/greps-the-files.md +11 -0
  198. package/templates/kyb/evals/list-file-fuzzy-alias/graders/saves-the-uk-file.md +8 -0
  199. package/templates/kyb/evals/list-file-fuzzy-alias/prompt.md +7 -0
  200. package/templates/kyb/evals/list-file-hit/case.yaml +10 -0
  201. package/templates/kyb/evals/list-file-hit/fixtures/web.json +58 -0
  202. package/templates/kyb/evals/list-file-hit/graders/greps-the-files.md +11 -0
  203. package/templates/kyb/evals/list-file-hit/graders/hits-by-company-number.md +18 -0
  204. package/templates/kyb/evals/list-file-hit/graders/saves-the-uk-file.md +8 -0
  205. package/templates/kyb/evals/list-file-hit/prompt.md +7 -0
  206. package/templates/kyb/evals/list-file-no-hit/case.yaml +10 -0
  207. package/templates/kyb/evals/list-file-no-hit/fixtures/web.json +58 -0
  208. package/templates/kyb/evals/list-file-no-hit/graders/greps-the-files.md +11 -0
  209. package/templates/kyb/evals/list-file-no-hit/graders/no-hit-by-whole-file.md +12 -0
  210. package/templates/kyb/evals/list-file-no-hit/graders/saves-the-uk-file.md +8 -0
  211. package/templates/kyb/evals/list-file-no-hit/prompt.md +7 -0
  212. package/templates/kyb/evals/list-file-short-name/case.yaml +9 -0
  213. package/templates/kyb/evals/list-file-short-name/fixtures/web.json +58 -0
  214. package/templates/kyb/evals/list-file-short-name/graders/finds-the-short-name.md +19 -0
  215. package/templates/kyb/evals/list-file-short-name/graders/greps-the-files.md +11 -0
  216. package/templates/kyb/evals/list-file-short-name/graders/saves-the-uk-file.md +8 -0
  217. package/templates/kyb/evals/list-file-short-name/prompt.md +7 -0
  218. package/templates/kyb/evals/list-file-split-name/case.yaml +11 -0
  219. package/templates/kyb/evals/list-file-split-name/fixtures/web.json +58 -0
  220. package/templates/kyb/evals/list-file-split-name/graders/finds-the-director.md +18 -0
  221. package/templates/kyb/evals/list-file-split-name/graders/greps-the-files.md +11 -0
  222. package/templates/kyb/evals/list-file-split-name/graders/saves-the-uk-file.md +8 -0
  223. package/templates/kyb/evals/list-file-split-name/prompt.md +7 -0
  224. package/templates/kyb/kyb.schema.json +2 -2
  225. package/templates/kyb/rules/SANCTIONS.md +82 -13
  226. package/dist/console/assets/index-BnZV3lvW.js +0 -639
  227. package/dist/console/assets/share-B1o5mJ56.js +0 -6
  228. /package/dist/console/assets/{styles-D_znYrHR.js → styles-BGZxYkky.js} +0 -0
@@ -163,9 +163,10 @@ export declare const LEARNING_LEDGER_REPAIR: readonly string[];
163
163
  export declare function ledgerUpgrade(ledgerColumns: ReadonlySet<string>): readonly string[];
164
164
  export declare const STORE_META_LEDGER_BACKFILLED = "ALTER TABLE store_meta ADD COLUMN ledger_backfilled INTEGER NOT NULL DEFAULT 0 CHECK (ledger_backfilled IN (0, 1))";
165
165
  /** Each learning cost, by the revision it is for (learn/ledger.ts SpendRow): a compile turn (`round`, the round that asked
166
- * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits), with its $ (null: unknown).
167
- * Written with its run's ledger row, replaced whole each time; gone with its run's purge or delete, and with the purge
168
- * or delete of the run it audits. */
166
+ * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits or whose key paid it), with its
167
+ * $ (null: unknown). Written with its run's ledger row, replaced whole each time; gone with its run's delete, and with
168
+ * the purge or delete of its `of_run`; its run's purge takes it, but one with an `of_run`, kept as that run's figure with
169
+ * no revision named (workflow, digest null: sqlite/store.ts dropLedger). */
169
170
  export declare const LEARNING_SPEND = "CREATE TABLE IF NOT EXISTS learning_spend (\n run_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('compile', 'check', 'audit')),\n round INTEGER NOT NULL CHECK (round >= 0),\n agent_id TEXT NOT NULL,\n of_run TEXT,\n workflow TEXT,\n digest TEXT,\n usd REAL,\n at INTEGER NOT NULL,\n PRIMARY KEY (run_id, kind, round)\n ) STRICT";
170
171
  export declare const LEARNING_SPEND_AGENT = "CREATE INDEX IF NOT EXISTS learning_spend_agent ON learning_spend (agent_id)";
171
172
  export declare const LEARNING_SPEND_OF_RUN = "CREATE INDEX IF NOT EXISTS learning_spend_of_run ON learning_spend (of_run) WHERE of_run IS NOT NULL";
@@ -374,9 +374,10 @@ export function ledgerUpgrade(ledgerColumns) {
374
374
  const LEDGER_BACKFILLED = "ledger_backfilled INTEGER NOT NULL DEFAULT 0 CHECK (ledger_backfilled IN (0, 1))";
375
375
  export const STORE_META_LEDGER_BACKFILLED = `ALTER TABLE store_meta ADD COLUMN ${LEDGER_BACKFILLED}`;
376
376
  /** Each learning cost, by the revision it is for (learn/ledger.ts SpendRow): a compile turn (`round`, the round that asked
377
- * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits), with its $ (null: unknown).
378
- * Written with its run's ledger row, replaced whole each time; gone with its run's purge or delete, and with the purge
379
- * or delete of the run it audits. */
377
+ * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits or whose key paid it), with its
378
+ * $ (null: unknown). Written with its run's ledger row, replaced whole each time; gone with its run's delete, and with
379
+ * the purge or delete of its `of_run`; its run's purge takes it, but one with an `of_run`, kept as that run's figure with
380
+ * no revision named (workflow, digest null: sqlite/store.ts dropLedger). */
380
381
  export const LEARNING_SPEND = `CREATE TABLE IF NOT EXISTS learning_spend (
381
382
  run_id TEXT NOT NULL,
382
383
  kind TEXT NOT NULL CHECK (kind IN ('compile', 'check', 'audit')),
@@ -95,8 +95,14 @@ export declare function sealRunLaunch(key: Buffer, runId: string, secrets: RunLa
95
95
  /** A run's launch secrets, opened: none when its launch holds none; undefined when the bytes do not open under `key` for
96
96
  * this run (sealed for another run, or under another key). */
97
97
  export declare function openRunLaunch(key: Buffer, runId: string, sealed: Uint8Array | null): RunLaunchSecrets | undefined;
98
- /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed): a run started
99
- * by the runner from another (a replay, an audit) takes its MCP credentials, never its model key. */
98
+ /** What a run the runner starts from run `from` (a check's replay, an audit's shadow) takes of `from`'s launch secrets
99
+ * (`sealed`, its launch's sealed column), sealed for run `id` alone (AAD run_launch|<id>|sealed): its handed MCP
100
+ * credentials, and, when `keyed` (the claim of `from` holds its own model key now), that model key with the origin it was
101
+ * handed for, so the child spends on the key its run brought and never on the server's. Never its tool keys, nor a value
102
+ * a message retired. The child's copy is erased at the child's own end, as any run's launch secrets are. Undefined when
103
+ * it takes nothing, or the bytes do not open for `from`. */
104
+ export declare function sealHandedLaunch(key: Buffer, from: string, sealed: Uint8Array | null, id: string, keyed: boolean): Uint8Array | undefined;
105
+ /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
100
106
  export declare function sealRunMcpAuth(key: Buffer, runId: string, auth: RunMcpAuth): Uint8Array;
101
107
  /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
102
108
  * `key` for this run (sealed for another run, or under another key). */
@@ -102,8 +102,19 @@ export function openRunLaunch(key, runId, sealed) {
102
102
  return undefined;
103
103
  }
104
104
  }
105
- /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed): a run started
106
- * by the runner from another (a replay, an audit) takes its MCP credentials, never its model key. */
105
+ /** What a run the runner starts from run `from` (a check's replay, an audit's shadow) takes of `from`'s launch secrets
106
+ * (`sealed`, its launch's sealed column), sealed for run `id` alone (AAD run_launch|<id>|sealed): its handed MCP
107
+ * credentials, and, when `keyed` (the claim of `from` holds its own model key now), that model key with the origin it was
108
+ * handed for, so the child spends on the key its run brought and never on the server's. Never its tool keys, nor a value
109
+ * a message retired. The child's copy is erased at the child's own end, as any run's launch secrets are. Undefined when
110
+ * it takes nothing, or the bytes do not open for `from`. */
111
+ export function sealHandedLaunch(key, from, sealed, id, keyed) {
112
+ const opened = openRunLaunch(key, from, sealed);
113
+ if (!opened)
114
+ return undefined;
115
+ return sealRunLaunch(key, id, { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(keyed && opened.model ? { model: opened.model } : {}) }) ?? undefined;
116
+ }
117
+ /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
107
118
  export function sealRunMcpAuth(key, runId, auth) {
108
119
  return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ mcp: auth }));
109
120
  }
@@ -212,7 +212,8 @@ async function keptRevision(tx, agentId, runId, name, digest, unledgered) {
212
212
  }
213
213
  /** Whether a run of agent `agentId` other than `runId` is billed against revision `name` at `digest` (learn/ledger.ts
214
214
  * summarize spreads a revision's compile and check over its served runs), read inside the caller's transaction, with
215
- * run `runId`'s own ledger and spend rows left out (its purge drops them after this, dropLedger): a ledger row names it
215
+ * run `runId`'s own ledger and spend rows left out (its purge drops them after this, or keeps one on another run's
216
+ * account naming no revision, dropLedger): a ledger row names it
216
217
  * (a run it served), a spend row names it (a compile turn, a check's replay, an audit's shadow), or, for an unpurged run
217
218
  * with no ledger row (`unledgered`: one that ended before the ledger, whose reader records it from its metrics), its
218
219
  * metrics name it. */
@@ -7,7 +7,7 @@ import { CENSUS_UNSCANNED, endedReason, FINAL_STATES, Fenced } from "../store.js
7
7
  import { settledBody, SQLITE } from "../dialect.js";
8
8
  import { claimFence, storeNow } from "../fence.js";
9
9
  import { readableJson, readLaunch } from "./run-launch.js";
10
- import { auditOfLaunch, learnsOfLaunch, record } from "../../learn/ledger.js";
10
+ import { record, runEndOfLaunch } from "../../learn/ledger.js";
11
11
  /** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
12
12
  * list of runs names. */
13
13
  export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
@@ -127,10 +127,10 @@ export async function recordLedger(tx, run, now) {
127
127
  const rounds = (await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ? ORDER BY round", run.id))
128
128
  .map((one) => ({ round: Number(one.round), proposal: JSON.parse(one.proposal) }));
129
129
  // An audit's shadow is booked on the run its launch audits, whatever its end named (one that failed first names none);
130
- // a run whose end named no path is the agent's when its launch does not learn (learnsOfLaunch).
130
+ // a check's replay is its revision's check (on the key its launch names) whatever its end named; a run whose end named
131
+ // no path is the agent's when its launch does not learn (learn/ledger.ts runEndOfLaunch).
131
132
  const body = (await readLaunch(tx, run.id).catch(() => undefined))?.body;
132
- const auditOf = auditOfLaunch(run.id, body);
133
- const { row, spend } = record({ id: run.id, agentId: run.agentId, startedAt: run.startedAt, costUsd: run.costUsd, costAtMostUsd: run.costAtMostUsd, metrics: run.metrics, rounds, learns: learnsOfLaunch(body), ...(auditOf === undefined ? {} : { auditOf }) });
133
+ const { row, spend } = record(runEndOfLaunch(run, rounds, body));
134
134
  await tx.run(`INSERT INTO learning_ledger (run_id, agent_id, started_at, path, workflow, digest, not_served, job_usd, look_back_usd, cost, workflow_calls) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
135
135
  ON CONFLICT (run_id) DO UPDATE SET agent_id = excluded.agent_id, started_at = excluded.started_at, path = excluded.path, workflow = excluded.workflow, digest = excluded.digest,
136
136
  not_served = excluded.not_served, job_usd = excluded.job_usd, look_back_usd = excluded.look_back_usd, cost = excluded.cost, workflow_calls = excluded.workflow_calls`, row.runId, row.agentId, row.startedAt, row.path, row.workflow, row.digest, row.notServed, row.jobUsd, row.lookBackUsd, row.cost, JSON.stringify(row.workflowCalls));
@@ -712,10 +712,20 @@ export function storeOver(connection, now, file) {
712
712
  * start's scrub: short, since every other request of the store's connection queues behind it. */
713
713
  const PURGE_CHECKPOINT_BUSY_MS = 20;
714
714
  /** Run `runId`'s learning ledger (learn/ledger.ts), gone: its row, each spend row it booked, and an audit's spend row of
715
- * it (its shadow's, of_run). What a run's purge (Runs.purge) and its delete (Runs.remove) both drop. */
716
- async function dropLedger(tx, runId) {
715
+ * it (its shadow's, of_run). What a run's purge (Runs.purge) and its delete (Runs.remove) both drop, but that a purge
716
+ * (`purge`) keeps the figure of each spend row it booked on another run's account (of_run: a keyed replay's check on
717
+ * the paying run's key, an audit's shadow's cost), which is that run's learning and is not purged with it: its $ alone,
718
+ * the revision it named gone (no read of a kept row reads one: ownCheck and the audit's cost read of_run and usd), so
719
+ * the paying run's view (runFiguresOf), the agent's ledger (summarize) and the learning total read the one row. The
720
+ * paying run's own purge takes it (of_run). */
721
+ async function dropLedger(tx, runId, { purge = false } = {}) {
717
722
  await tx.run("DELETE FROM learning_ledger WHERE run_id = ?", runId);
718
- await tx.run("DELETE FROM learning_spend WHERE run_id = ? OR of_run = ?", runId, runId);
723
+ if (!purge) {
724
+ await tx.run("DELETE FROM learning_spend WHERE run_id = ? OR of_run = ?", runId, runId);
725
+ return;
726
+ }
727
+ await tx.run("DELETE FROM learning_spend WHERE of_run = ? OR (run_id = ? AND of_run IS NULL)", runId, runId);
728
+ await tx.run("UPDATE learning_spend SET workflow = NULL, digest = NULL WHERE run_id = ?", runId);
719
729
  }
720
730
  /** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
721
731
  * (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
@@ -1445,6 +1455,19 @@ class SqliteStore {
1445
1455
  return row && runOf(row);
1446
1456
  },
1447
1457
  launch: (runId) => readLaunch(db, runId),
1458
+ learningDeadlines: async (runIds) => {
1459
+ const out = new Map();
1460
+ if (runIds.length === 0)
1461
+ return out;
1462
+ const body = readableJson(d, "body");
1463
+ const rows = await db.all(`SELECT run_id, ${d.jsonText(body, ["replay", "deadline_at"])} AS replay, ${d.jsonText(body, ["audit", "deadline_at"])} AS audit FROM run_launch WHERE run_id IN (${runIds.map(() => "?").join(", ")})`, ...runIds);
1464
+ for (const row of rows) {
1465
+ const at = Date.parse(row.replay ?? row.audit ?? "");
1466
+ if (Number.isFinite(at))
1467
+ out.set(row.run_id, at);
1468
+ }
1469
+ return out;
1470
+ },
1448
1471
  usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
1449
1472
  projectCheckpoints: (filter) => readProjectCheckpoints(db, filter),
1450
1473
  learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
@@ -1675,7 +1698,8 @@ class SqliteStore {
1675
1698
  }
1676
1699
  // Its ledger row and every spend row it booked or that audits it, as a remove takes them: what it cost stays on its
1677
1700
  // tombstone (cost_usd, the metrics' figures), which the readers of money (usage, stats) read; no series shows it.
1678
- await dropLedger(tx, runId);
1701
+ // What it booked on another run's account stays that run's, its figure alone (dropLedger `purge`).
1702
+ await dropLedger(tx, runId, { purge: true });
1679
1703
  // Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
1680
1704
  // read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
1681
1705
  const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
@@ -1304,6 +1304,11 @@ export interface Runs {
1304
1304
  /** The run's launch row (the runner reads it at its claim; the server for views). StoreLaunchMissing when the run has
1305
1305
  * none (it was not started with one), never a default. */
1306
1306
  launch(runId: string): Promise<RunLaunchRow>;
1307
+ /** The learning deadlines (ms) of those of `runIds` that are learning children (a check's replay run, an audit's shadow
1308
+ * run): its launch's replay or audit `deadline_at` (run-launch.ts Replay.deadlineAt). One read for every id, projecting
1309
+ * that member alone: what a runner reads for a whole batch of claims before any loop starts on them. A run that is no
1310
+ * learning child, or has no launch row, is absent. */
1311
+ learningDeadlines(runIds: readonly string[]): Promise<Map<string, number>>;
1307
1312
  /** Only the immutable CLI accounting identity/turn and (when requested) SDK completion usage. Projects these JSON
1308
1313
  * members in the database: no launch input, policy, sealed bytes, completion answer or replay events are returned.
1309
1314
  * Undefined for an absent run; absent members stay undefined. Historical identity may be read without completion.
@@ -52,6 +52,21 @@ export type StoreAnalytics = {
52
52
  calls: number;
53
53
  errors: number;
54
54
  }>;
55
+ /** The imported runs' cache, summed (import.ts RunCache): how many runs were analyzed, their cache read and whole
56
+ * prompt (the hit rate's parts), breaks by cause, extra cost by cause (USD) and unpriced breaks. A run imported
57
+ * before the import analyzed it, or of a source with no chain, is in no figure here. */
58
+ cache: StoredCache & {
59
+ runs: number;
60
+ };
61
+ };
62
+ /** A run's cache as the import keeps it in the run's metrics (import.ts RunCache). */
63
+ type StoredCache = {
64
+ read: number;
65
+ prompt: number;
66
+ breaks: Record<string, number>;
67
+ extraCost: Record<string, number>;
68
+ unpriced: number;
55
69
  };
56
70
  /** The runs and their metrics summed (the old AgentStoreReader.analytics), from A's run rows. */
57
71
  export declare function analytics(store: Store, filter?: AnalyticsFilter): Promise<StoreAnalytics>;
72
+ export {};
@@ -168,6 +168,22 @@ export async function analytics(store, filter = {}) {
168
168
  }
169
169
  }
170
170
  const tools = [...calls.entries()].map(([tool, c]) => ({ tool, calls: c.calls, errors: c.errors })).sort((a, b) => b.calls - a.calls || (a.tool < b.tool ? -1 : a.tool > b.tool ? 1 : 0)).slice(0, 20);
171
+ // The cache over the runs in scope that keep one, ended (an import writes its run ended).
172
+ const cache = { runs: 0, read: 0, prompt: 0, breaks: {}, extraCost: {}, unpriced: 0 };
173
+ for (const f of notPending) {
174
+ const kept = f.metered ? f.metrics?.cache : undefined;
175
+ if (!kept || typeof kept !== "object")
176
+ continue;
177
+ cache.runs += 1;
178
+ cache.read += num(kept.read);
179
+ cache.prompt += num(kept.prompt);
180
+ cache.unpriced += num(kept.unpriced);
181
+ for (const [cause, n] of Object.entries(kept.breaks ?? {}))
182
+ cache.breaks[cause] = (cache.breaks[cause] ?? 0) + num(n);
183
+ // Summed in micro-dollars: USD figures of six places added as floats drift.
184
+ for (const [cause, usd] of Object.entries(kept.extraCost ?? {}))
185
+ cache.extraCost[cause] = Math.round(((cache.extraCost[cause] ?? 0) + num(usd)) * 1e6) / 1e6;
186
+ }
171
187
  const totalsGroup = counted(facts);
172
188
  return {
173
189
  totals: { ...totalsGroup, input: unknownTokens.has('input') ? null : input, cacheRead: unknownTokens.has('cacheRead') ? null : cacheRead, cacheWrite: unknownTokens.has('cacheWrite') ? null : cacheWrite, output: unknownTokens.has('output') ? null : output, requests: unknownRequests ? null : requests, unmetered: unknownRequests ? null : unmetered },
@@ -176,5 +192,6 @@ export async function analytics(store, filter = {}) {
176
192
  byDay,
177
193
  bySource,
178
194
  tools,
195
+ cache,
179
196
  };
180
197
  }
@@ -7,6 +7,8 @@ import type { Store } from "../store/store.js";
7
7
  /** A run's entries from the one store, in log order (by id across every conversation), as the old "SELECT record FROM
8
8
  * entries ORDER BY id" read them for a settled run. A run with no journal reads as none. */
9
9
  export declare function runEntries(store: Store, runId: string, context: Context): Promise<EntryLike[]>;
10
+ /** `entries` (a journal read's, conversation by conversation) in log order: by id across every conversation. */
11
+ export declare const inLogOrder: (entries: readonly unknown[]) => EntryLike[];
10
12
  /** Where a run's end-of-run turn is in its journal, as the server's Reflect names it for labelled(): its newest round's
11
13
  * `after`, the entry before its input, and `until`, the run's end entry once written; `earlier`, each earlier round's (a
12
14
  * follow-up opened the run again after it). Undefined for a run that asked none. */
@@ -25,7 +25,7 @@ export async function runEntries(store, runId, context) {
25
25
  return inLogOrder(await journalEntries(store.readJournal(runId), context));
26
26
  }
27
27
  /** `entries` (a journal read's, conversation by conversation) in log order: by id across every conversation. */
28
- const inLogOrder = (entries) => entries.slice().sort((a, b) => Number(a.id ?? 0) - Number(b.id ?? 0));
28
+ export const inLogOrder = (entries) => entries.slice().sort((a, b) => Number(a.id ?? 0) - Number(b.id ?? 0));
29
29
  /** Where a run's end-of-run turn is in its journal, as the server's Reflect names it for labelled(): its newest round's
30
30
  * `after`, the entry before its input, and `until`, the run's end entry once written; `earlier`, each earlier round's (a
31
31
  * follow-up opened the run again after it). Undefined for a run that asked none. */
@@ -105,13 +105,14 @@ export declare function revisionsOf(records: readonly PromotionRecord[], reset?:
105
105
  /** A run's costs as GET /runs/{id} shows them (RunAllIn, runAllInOverStore). */
106
106
  export type RunAllIn = {
107
107
  path: RunPath | null;
108
- } & Pick<RunFigures, "usd" | "learning_usd" | "all_in_usd" | "compile_usd" | "followup_usd" | "shadow_usd" | "share_usd">;
108
+ } & Pick<RunFigures, "usd" | "learning_usd" | "all_in_usd" | "compile_usd" | "followup_usd" | "shadow_usd" | "check_usd" | "share_usd">;
109
109
  /** Run `runId`'s path and its costs as GET /runs/{id} shows them (A8), the figures GET .../learning/cost reads for it
110
110
  * (learn/ledger.ts figuresOf over its ledger row: one formula): `path` its record's (metrics.path, RUN_PATHS: `agent`
111
111
  * for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that learns
112
112
  * whose end named none); `usd` its own spend, the job's (its look-back left out); `learning_usd` what learning spent for
113
- * it: its follow-up rounds' turns, its audit shadow's cost, and its share of its revision's compile and check (its own
114
- * compile turns are its revision's: `compile_usd`); `all_in_usd` the two; and `learning_usd`'s parts. A replay or a
113
+ * it: its follow-up rounds' turns, its audit shadow's cost, the replays of a check it started on its own model key
114
+ * (`check_usd`, null while one runs), and its share of its revision's compile and check (its own compile turns are its
115
+ * revision's: `compile_usd`); `all_in_usd` the two; and `learning_usd`'s parts. A replay or a
115
116
  * shadow run carries none: its spend is on the runs it serves, so its `learning_usd` and `all_in_usd` are 0, and the sum
116
117
  * of every run's `all_in_usd` and the bill's `unattributed_usd` is the booked total. `rowUsd`: the cost its view reads
117
118
  * (its row's when absent); one other than its row's (an imported run's estimate, a booking where its end stored none)
@@ -11,7 +11,8 @@ import { learningStartOf, learningStartOfStored, readLaunchBody, seedFailed } fr
11
11
  import { said, seedStopped } from "../learning-words.js";
12
12
  import { learningImpact } from "../learning-run.js";
13
13
  import { COST_WINDOW, JOB_PATHS, noiseOff, RUN_PATHS, SERVED_PATHS, workflowCallsIn } from "../learning-cost.js";
14
- import { answeredOf, auditOfLaunch, figuresOf, record, roundsLooked, roundsSpentIn, shadowCostOf, spendByRun, summarize } from "../learn/ledger.js";
14
+ import { answeredOf, figuresOf, ownCheck, record, roundsLooked, roundsSpentIn, runEndOfLaunch, shadowCostOf, spendByRun, summarize } from "../learn/ledger.js";
15
+ import { learningChildrenOf } from "../learning-work.js";
15
16
  import { COMPILE_AFTER_DEFAULT } from "../learning-setting.js";
16
17
  import { modelsOwn, runPathOf } from "../runner/learning-end.js";
17
18
  import { feedbackStatus } from "../runner/feedback-round.js";
@@ -246,7 +247,8 @@ const zipWith = (keys, values) => keys.map((key, at) => [key, values[at]]);
246
247
  /** What summarize reads of agent `agentId` (LedgerRead, its revisions aside), over `listed` (its runs, as runs.list read
247
248
  * them): the ledger rows of its ended runs that do a job or check one (neither imported nor archived, no workflow
248
249
  * revision's run, no shadow), each on the path its end wrote, each with the workflow name its launch
249
- * offered; every spend row; each run's audit shadow (open or ended); and the runs on no named disk (learn/learning-of.ts:
250
+ * offered; every spend row; each run's audit shadow (open or ended); the runs whose own-key check has a replay still at
251
+ * work (`openChecks`, one launch read per run of `listed` not yet final); and the runs on no named disk (learn/learning-of.ts:
250
252
  * one on a named disk learns nothing and serves nothing). Each ended run has its row: its end wrote it, or the server's
251
253
  * open (run-patch.ts backfillLedger) for one an earlier build ended; none is recorded here. `runIds`: the runs whose
252
254
  * ledger is read (Learning.ledger), the agent's every run when absent. `named` false: no workflow name is read for the
@@ -275,8 +277,25 @@ async function ledgerReadOf(store, agentId, listed, records, { runIds, named = t
275
277
  if (shadow)
276
278
  shadows.set(run.id, shadow);
277
279
  }
280
+ // The runs whose own-key check still runs: each replay not yet final names the run that pays it (its launch's
281
+ // `replay.paid_by`), whose check stays unknown until it ends, as that run's own read says (runFiguresOf). A replay's end
282
+ // writes its spend row with its ledger row, so one that ended is counted there.
283
+ const openChecks = new Set();
284
+ for (const run of listed) {
285
+ if (FINAL_STATES.includes(run.state))
286
+ continue;
287
+ // A run with no launch row was started by no check (a replay's launch is written with it).
288
+ const launch = await records.runs.launch(run.id).catch((error) => {
289
+ if (error instanceof StoreLaunchMissing)
290
+ return undefined;
291
+ throw error;
292
+ });
293
+ const paidBy = readLaunchBody(launch?.body)?.replay?.paidBy;
294
+ if (paidBy)
295
+ openChecks.add(paidBy);
296
+ }
278
297
  // Only a name the launch offered is shown.
279
- return { rows, spend, shadows, learning, compileAfter: COMPILE_AFTER_DEFAULT, ...(named ? { named: (row) => offeredName(row.workflow, offered.get(row.runId)) } : {}) };
298
+ return { rows, spend, shadows, openChecks, learning, compileAfter: COMPILE_AFTER_DEFAULT, ...(named ? { named: (row) => offeredName(row.workflow, offered.get(row.runId)) } : {}) };
280
299
  }
281
300
  /** Run `runId`'s audit shadow among `byId` (open while queued or running, ended once final), undefined with none. */
282
301
  const shadowOf = (byId, runId) => {
@@ -288,11 +307,11 @@ async function ledgerRowsOf(store, agentId, runIds) {
288
307
  const ledger = await store.learning.ledger(agentId, runIds);
289
308
  return { recorded: new Map(ledger.rows.map((row) => [row.runId, row])), spend: ledger.spend };
290
309
  }
291
- /** What record() reads of an ended run: its row, every round its learning kept and, for a shadow, the run it audits. */
310
+ /** What record() reads of an ended run: its row, every round its learning kept and its launch, as its end's ledger write
311
+ * reads them (learn/ledger.ts runEndOfLaunch). */
292
312
  async function runEndOf(records, run) {
293
313
  const rounds = (await roundsOf(records, run.id)).map((one) => ({ round: one.round, proposal: one.proposal }));
294
- const auditOf = auditOfLaunch(run.id, isShadowRun(run.id) ? (await records.runs.launch(run.id).catch(() => undefined))?.body : undefined);
295
- return { id: run.id, agentId: run.agentId, startedAt: run.startedAt, costUsd: run.costUsd, costAtMostUsd: run.costAtMostUsd, metrics: run.metrics, rounds, ...(auditOf === undefined ? {} : { auditOf }) };
314
+ return runEndOfLaunch(run, rounds, (await records.runs.launch(run.id).catch(() => undefined))?.body);
296
315
  }
297
316
  /** Each hold of the agent's learned workflows (its promotion records that say hold), placed on the series: at the first
298
317
  * run that does a job from it on, by its number among them (the points' `n`), null when none has run since. */
@@ -333,8 +352,9 @@ export function revisionsOf(records, reset = []) {
333
352
  * (learn/ledger.ts figuresOf over its ledger row: one formula): `path` its record's (metrics.path, RUN_PATHS: `agent`
334
353
  * for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that learns
335
354
  * whose end named none); `usd` its own spend, the job's (its look-back left out); `learning_usd` what learning spent for
336
- * it: its follow-up rounds' turns, its audit shadow's cost, and its share of its revision's compile and check (its own
337
- * compile turns are its revision's: `compile_usd`); `all_in_usd` the two; and `learning_usd`'s parts. A replay or a
355
+ * it: its follow-up rounds' turns, its audit shadow's cost, the replays of a check it started on its own model key
356
+ * (`check_usd`, null while one runs), and its share of its revision's compile and check (its own compile turns are its
357
+ * revision's: `compile_usd`); `all_in_usd` the two; and `learning_usd`'s parts. A replay or a
338
358
  * shadow run carries none: its spend is on the runs it serves, so its `learning_usd` and `all_in_usd` are 0, and the sum
339
359
  * of every run's `all_in_usd` and the bill's `unattributed_usd` is the booked total. `rowUsd`: the cost its view reads
340
360
  * (its row's when absent); one other than its row's (an imported run's estimate, a booking where its end stored none)
@@ -351,25 +371,44 @@ export async function runAllInOverStore(store, runId, rowUsd) {
351
371
  const path = !ended || kind === "workflow" ? null : (pathOfRow(run.metrics, started)?.path ?? null);
352
372
  if (!ended) {
353
373
  const row = rowUsd === undefined ? (typeof run.costAtMostUsd === "number" ? null : run.costUsd) : rowUsd;
354
- return { path, usd: row, learning_usd: null, all_in_usd: null, compile_usd: null, followup_usd: null, shadow_usd: null, share_usd: null };
374
+ return { path, usd: row, learning_usd: null, all_in_usd: null, compile_usd: null, followup_usd: null, shadow_usd: null, check_usd: null, share_usd: null };
355
375
  }
356
- // A served run carries a share of its revision's spend: its figures are the series' own, over the agent's ledger.
376
+ // A served run carries a share of its revision's spend: its figures are the series' own, over the agent's ledger, its
377
+ // own-key check unknown while a replay of it runs (as runFiguresOf reads it).
357
378
  const served = path !== null && SERVED_PATHS.includes(path) && revisionOfRow(run) !== undefined;
358
- const figures = (served ? (await agentLedgerOverStore(store, run.agentId)).out.figures.get(run.id) : undefined) ?? (await runFiguresOf(store, run));
379
+ const series = served ? (await agentLedgerOverStore(store, run.agentId)).out.figures.get(run.id) : undefined;
380
+ const figures = series ? ((await ownCheckOf(store, run.id)).some((one) => !one.ended) ? checkOpen(series) : series) : await runFiguresOf(store, run);
359
381
  // The run's view priced it other than its row does (`rowUsd`: an imported run's catalog estimate, or its booking where
360
382
  // its end stored none): its job is that figure, as its end would have recorded it at that cost (record: less its
361
383
  // look-back), its learning's parts the ledger's.
362
- const { usd, learning_usd, all_in_usd, compile_usd, followup_usd, shadow_usd, share_usd } = typeof rowUsd === "number" && rowUsd !== run.costUsd ? await pricedAt(store, run, rowUsd, figures) : figures;
363
- return { path, usd, learning_usd, all_in_usd, compile_usd, followup_usd, shadow_usd, share_usd };
384
+ const { usd, learning_usd, all_in_usd, compile_usd, followup_usd, shadow_usd, check_usd, share_usd } = typeof rowUsd === "number" && rowUsd !== run.costUsd ? await pricedAt(store, run, rowUsd, figures) : figures;
385
+ return { path, usd, learning_usd, all_in_usd, compile_usd, followup_usd, shadow_usd, check_usd, share_usd };
364
386
  }
365
387
  /** Run `run`'s figures with its row's cost read as `usd` (runAllInOverStore's `rowUsd`): its row as its end would have
366
- * recorded it at that cost, with `figures`' compile, shadow and share. */
388
+ * recorded it at that cost, with `figures`' compile, shadow, own-key check and share. */
367
389
  async function pricedAt(store, run, usd, figures) {
368
390
  const row = record(await runEndOf(store, { ...run, costUsd: usd, costAtMostUsd: null })).row;
369
- return figuresOf(row, { compile: figures.compile_usd, shadow: figures.shadow_usd, share: figures.share_usd });
391
+ return figuresOf(row, { compile: figures.compile_usd, shadow: figures.shadow_usd, check: figures.check_usd, share: figures.share_usd });
392
+ }
393
+ /** The replay runs of a check run `runId` started on its own model key (learning-work.ts names them), each with whether
394
+ * it has ended: what they spent is its learning (learn/ledger.ts `check_usd`), unknown while one runs. */
395
+ async function ownCheckOf(store, runId) {
396
+ const out = [];
397
+ for (const child of await learningChildrenOf(store.settings, runId)) {
398
+ if (!child.keyed || child.kind !== "replay" || child.run === null)
399
+ continue;
400
+ const row = await store.runs.get(child.run);
401
+ if (row)
402
+ out.push({ row, ended: FINAL_STATES.includes(row.state) });
403
+ }
404
+ return out;
370
405
  }
406
+ /** `figures` with its own-key check unknown (a replay of it still running): its learning and all-in with it, never $0. */
407
+ const checkOpen = (figures) => ({ ...figures, check_usd: null, learning_usd: null, all_in_usd: null, series_learning_usd: null, series_total_usd: null });
371
408
  /** One run's figures (learn/ledger.ts figuresOf) with no share of its revision's (a run that carries none: not served, or
372
- * out of the series), over the ledger of it and its audit's shadow (ledgerRowsOf), as summarize reads them. */
409
+ * out of the series), over the ledger of it and its audit's shadow (ledgerRowsOf), as summarize reads them. Its own-key
410
+ * check's replays are read as summarize reads them (their check rows of it, `ofRun`): unknown while one runs, and one
411
+ * that ended with no row of its own yet at its row's cost. */
373
412
  async function runFiguresOf(store, run) {
374
413
  const shadow = isShadowRun(run.id) ? undefined : await store.runs.get(shadowRunId(run.id));
375
414
  const listed = shadow ? [run, shadow] : [run];
@@ -377,12 +416,17 @@ async function runFiguresOf(store, run) {
377
416
  // Every ended run has its row (its end's, or backfillLedger's at the server's open); one read without it reads as its
378
417
  // end records it, never as nothing.
379
418
  const row = recorded.get(run.id) ?? record(await runEndOf(store, run)).row;
380
- const { compile, audit } = spendByRun(spend);
419
+ const replays = await ownCheckOf(store, run.id);
420
+ const unbooked = replays.flatMap(({ row: replay, ended }) => ended && !spend.some((one) => ownCheck(one) && one.runId === replay.id)
421
+ ? [{ runId: replay.id, agentId: replay.agentId, round: 0, kind: "check", ofRun: run.id, workflow: null, digest: null, usd: typeof replay.costAtMostUsd === "number" ? null : replay.costUsd }]
422
+ : []);
423
+ const { compile, audit, check } = spendByRun([...spend, ...unbooked]);
381
424
  const shadows = new Map();
382
425
  const state = shadowOf(new Map(listed.map((one) => [one.id, one])), run.id);
383
426
  if (state)
384
427
  shadows.set(run.id, state);
385
- return figuresOf(row, { compile: compile.has(run.id) ? compile.get(run.id) : 0, shadow: shadowCostOf(run.id, audit, shadows), share: 0 });
428
+ const checked = replays.some((one) => !one.ended) ? null : check.has(run.id) ? check.get(run.id) : 0;
429
+ return figuresOf(row, { compile: compile.has(run.id) ? compile.get(run.id) : 0, shadow: shadowCostOf(run.id, audit, shadows), check: checked, share: 0 });
386
430
  }
387
431
  /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
388
432
  * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
@@ -10,6 +10,7 @@ import type { PendingAsk } from "./browser-person.js";
10
10
  import { type Approvals } from "./approvals.js";
11
11
  import { type KeptListing, type RunListing, type RunRow, type Store } from "./store/store.js";
12
12
  import type { RecordingView } from "./run-recordings.js";
13
+ import { type OwnLearning } from "./learning-work.js";
13
14
  import { type FactoryActivity, type FactoryObserved } from "./factory-activity.js";
14
15
  /** What the store-backed view needs beside the store: where its console lives, every secret it never shows (read now, so
15
16
  * one rotated is cut at once), and the agents' saved sign-ins (for the handed-pointer cut). The server passes the same it
@@ -140,6 +141,8 @@ interface StoreRun {
140
141
  /** The run looks back after its job's end (`row` and `runRow` read as that end): nothing of it is settled until the
141
142
  * look-back's own end is in (poll_after_ms 1000, the timeline not final). */
142
143
  readonly lookingBack?: true;
144
+ /** What its view's learning_work reads of the run's own learning (learning-work.ts learningWorkOf), from the reads above. */
145
+ readonly ownLearning: OwnLearning;
143
146
  }
144
147
  /** A runner holds the run's claim now: it is not in a final state, a runner is named on its row, and its lease has not run
145
148
  * out (claimed_until >= now, the predicate the claimable query's `claimed_until < ?` is the negation of). `now` is the
@@ -41,6 +41,8 @@ import { approvalsOf } from "./approvals.js";
41
41
  import { FINAL_STATES, stoppedByPerson } from "./store/store.js";
42
42
  import { LISTING_HELD, LISTING_KEYED } from "./store/schema.js";
43
43
  import { createHash } from "node:crypto";
44
+ import { learningWorkOf } from "./learning-work.js";
45
+ import { COMPILE_TIMEOUT_MS } from "./learn/compile.js";
44
46
  import { factoryChildren, factoryGithub, factoryLastActivity, factoryObservation, factoryObserved, factorySource } from "./factory-activity.js";
45
47
  /** A run that has ended reads one of these (the old RunRow state → the v2 status: an escalation is a completion with a
46
48
  * review; a stopped run is a cancellation), as runs.ts's STATUS_OF mapped them. A running run reads its status from the
@@ -312,6 +314,18 @@ async function storeRunIn(store, runId, deps, cut, since) {
312
314
  // A run looking back after its job's end reads reflecting from that end on, a graded one too (its last end's learning
313
315
  // is the earlier round's).
314
316
  const shownEnd = lookingBack && started && !started.use ? { state: "reflecting", reason: null, detail: said.reflecting, at: iso(lookingBack.endedAt) } : ended ?? under;
317
+ // Its own learning, as learning_work reads it: a run that learns (a learning start, and no replay or shadow run), its
318
+ // compile turn going (it looks back), one begun (its job's end kept for an end-of-run step), and, once its end is in,
319
+ // when that learning ended (its learning end's time, else its end's). While it looks back, its compile turn's bound as
320
+ // far as the view knows it: the job's end + the turn's timeout (the turn's own start, later, is kept with its children).
321
+ const learnedAt = !lookingBack && stored.state !== "running" ? Math.max(stored.endedAt ?? 0, ended ? Date.parse(ended.at) || 0 : 0) : 0;
322
+ const ownLearning = {
323
+ learns: started !== undefined && !launch?.replay && !launch?.audit,
324
+ compiling: lookingBack !== undefined,
325
+ compiled: records.entries.some((entry) => entry.kind === KINDS.jobEnd),
326
+ endedAt: learnedAt > 0 ? learnedAt : null,
327
+ compileBy: lookingBack ? lookingBack.endedAt + COMPILE_TIMEOUT_MS : null,
328
+ };
315
329
  const turns = new Turns();
316
330
  turns.note(recordOf(records.entries), records.submissions ?? [], skip, liveRow?.updatedAt ?? deps.now?.() ?? Date.now());
317
331
  const working = !lookingBack && live && turns.open > 0;
@@ -434,7 +448,7 @@ async function storeRunIn(store, runId, deps, cut, since) {
434
448
  github: unshown ? null : factoryGithub(launch, (text) => withoutLoopback(redacted(text, values))),
435
449
  children: terminal || FINAL_STATES.includes(runRow.state) || unshown ? [] : await factoryChildren(store, runId, records, (text) => withoutLoopback(redacted(text, values))),
436
450
  } : undefined;
437
- return { ...(factory ? { factory } : {}), ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, model, windDown, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}) };
451
+ return { ...(factory ? { factory } : {}), ...(cli_learning ? { cli_learning } : {}), ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, model, windDown, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}), ...(lookingBack ? { lookingBack: true } : {}), ownLearning };
438
452
  }
439
453
  /** Run read `read` (a run still going, as the store holds it) as the end `ended` keeps (its state, summary and end time:
440
454
  * the end a run looking back keeps), its cost as read. */
@@ -705,6 +719,9 @@ async function viewOfRun(store, runId, deps, run, read) {
705
719
  budget_refused_calls: run.windDown.refusedCalls,
706
720
  // The run an audit's shadow run audits (launch.audit, runner/audit.ts); null for any other run.
707
721
  audit_of: launch?.audit?.of ?? null,
722
+ // The learning work the run started beside its turn (its compile turn, its check's replays, its audit's shadow), what
723
+ // a caller revokes the run's own key on once the run is terminal and this is not running (learning-work.ts).
724
+ learning_work: await learningWorkOf(store, runId, run.ownLearning),
708
725
  // The path it took and the learned workflow that served it, as its record keeps them: the read the cost per run makes
709
726
  // (store-reads/learning.ts pathViewOf).
710
727
  ...pathViewOf(runRow, row.kind, launch ? learningStartOf(launch) : undefined),
@@ -313,16 +313,29 @@ ${cjs ? "async function" : "export async function"} ${fn}(input${t(`: ${input}`)
313
313
  // The address with or without /v2, as AgentRun's own clients and CLI take AGENTRUN_BASE_URL.
314
314
  const url = (() => { try { return new URL(address); } catch { return undefined; } })();
315
315
  if (!url || !/^https?:$/.test(url.protocol)) throw new Error("AGENTRUN_BASE_URL must be an http or https URL, like https://agentrun.example.com/v2.");
316
+ // A user, a password or a query may be a key, and fetch's errors print the whole URL: AgentRun's SDK takes none of them,
317
+ // nor a fragment, and neither does this, naming the origin alone.
318
+ if (url.username || url.password || /[?#]/.test(address)) throw new Error(\`AGENTRUN_BASE_URL takes no user, password, query or fragment, like https://agentrun.example.com/v2: \${url.origin}\`);
316
319
  const base = url.pathname.split("/").includes("v2") ? address : \`\${address}/v2\`;
317
320
  const headers = { authorization: \`Bearer \${key}\`, "content-type": "application/json" };
318
- const started = await fetch(\`\${base}/agents/\${encodeURIComponent(agent)}/runs\`, { method: "POST", headers, body: JSON.stringify({ input }), signal: options.signal });
321
+ // No redirect is followed, as AgentRun's SDK follows none that leaves the base: a fetch other than Node's may carry the
322
+ // key's header to wherever one points. Its body is let go of first, so an unread one never holds the connection open.
323
+ const started = await fetch(\`\${base}/agents/\${encodeURIComponent(agent)}/runs\`, { method: "POST", headers, body: JSON.stringify({ input }), signal: options.signal, redirect: "manual" });
324
+ if (started.status >= 300 && started.status < 400) {
325
+ await started.body?.cancel().catch(() => undefined);
326
+ throw new Error(\`AgentRun answered POST with a redirect (HTTP \${started.status}); not followed, so the API key stays with AGENTRUN_BASE_URL.\`);
327
+ }
319
328
  if (!started.ok) throw new Error(\`AgentRun did not start the ${s.key} agent (HTTP \${started.status}): \${await started.text()}\`);
320
329
  let run = (await started.json())${t(" as Run")};
321
330
  const until = Date.now() + (options.timeoutMs ?? 300_000);
322
331
  while (!ENDED.includes(run.status)) {
323
332
  if (Date.now() > until) throw new Error(\`The ${s.key} agent's run \${run.run_id} did not end in time.\`);
324
333
  await new Promise((resolve) => setTimeout(resolve, 1_500));
325
- const read = await fetch(\`\${base}/runs/\${encodeURIComponent(run.run_id)}\`, { headers, signal: options.signal });
334
+ const read = await fetch(\`\${base}/runs/\${encodeURIComponent(run.run_id)}\`, { headers, signal: options.signal, redirect: "manual" });
335
+ if (read.status >= 300 && read.status < 400) {
336
+ await read.body?.cancel().catch(() => undefined);
337
+ throw new Error(\`AgentRun answered GET with a redirect (HTTP \${read.status}); not followed, so the API key stays with AGENTRUN_BASE_URL.\`);
338
+ }
326
339
  if (!read.ok) throw new Error(\`AgentRun did not read the run \${run.run_id} (HTTP \${read.status}).\`);
327
340
  run = (await read.json())${t(" as Run")};
328
341
  }
@@ -353,6 +366,7 @@ ${s.agent.output.map((f) => `# ${f.name}: ${oneLine(f.description)}`).join("\n
353
366
  import json
354
367
  import os
355
368
  import time
369
+ import urllib.error
356
370
  import urllib.parse
357
371
  import urllib.request
358
372
  from typing import Any, Dict, Optional, TypedDict
@@ -363,10 +377,20 @@ _REQUIRED = (${required.join(", ")}${required.length === 1 ? "," : ""})
363
377
  _ENDED = {"completed", "failed", "cancelled", "input_required", "paused"}
364
378
 
365
379
 
380
+ # urllib copies the authorization header onto a redirect to any host, http included: no redirect is followed, so the key
381
+ # goes to AGENTRUN_BASE_URL alone, as AgentRun's SDK sends it.
382
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
383
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
384
+ raise urllib.error.HTTPError(req.full_url, code, f"AgentRun answered {req.get_method()} with a redirect (HTTP {code}); not followed, so the API key stays with AGENTRUN_BASE_URL", headers, fp)
385
+
386
+
387
+ _OPENER = urllib.request.build_opener(_NoRedirect)
388
+
389
+
366
390
  def _call(method: str, url: str, key: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
367
391
  data = json.dumps(body).encode("utf-8") if body is not None else None
368
392
  request = urllib.request.Request(url, data=data, method=method, headers={"authorization": f"Bearer {key}", "content-type": "application/json"})
369
- with urllib.request.urlopen(request, timeout=60) as response:
393
+ with _OPENER.open(request, timeout=60) as response:
370
394
  return json.loads(response.read().decode("utf-8"))
371
395
 
372
396
 
@@ -387,6 +411,11 @@ def run_${py}(inputs: ${input}, timeout_s: float = 300.0) -> Dict[str, Any]:
387
411
  url = None
388
412
  if url is None or url.scheme not in ("http", "https") or not url.netloc:
389
413
  raise RuntimeError("AGENTRUN_BASE_URL must be an http or https URL, like https://agentrun.example.com/v2.")
414
+ # A user, a password or a query may be a key, and an error may print the whole URL: AgentRun's SDK takes none of them,
415
+ # nor a fragment, and neither does this, naming the origin alone.
416
+ if "@" in url.netloc or "?" in address or "#" in address:
417
+ host = url.netloc.rpartition("@")[2].lower()
418
+ raise RuntimeError(f"AGENTRUN_BASE_URL takes no user, password, query or fragment, like https://agentrun.example.com/v2: {url.scheme}://{host}")
390
419
  base = address if "v2" in url.path.split("/") else f"{address}/v2"
391
420
  run = _call("POST", f"{base}/agents/{agent}/runs", key, {"input": fields})
392
421
  until = time.monotonic() + timeout_s
@@ -474,13 +474,15 @@ export type PickedSetting = {
474
474
  needs?: string[];
475
475
  };
476
476
  /** The shell this server can give an agent now (server.ts shellHere): the computer setting that gives it, the shell
477
- * tools a run there has (tools.ts shellTools), and the shell in words; else, `none`, why it has none. */
477
+ * tools a run there has (tools.ts shellTools), and the shell in words; else, `none`, why it has none, and `fix`, what to
478
+ * do where COMPUTER_FIX is not it (a Mode 2 server whose Archil region has no serverless exec). */
478
479
  export type ShellHere = {
479
480
  computer: PickedSetting;
480
481
  tools: readonly string[];
481
482
  words: string;
482
483
  } | {
483
484
  none: string;
485
+ fix?: string;
484
486
  };
485
487
  /** What a package's computer list picks here: the entry, the setting the agent is saved with, the shell in words (null
486
488
  * for none), the package's shell tools that shell does not run (`dropped`, never granted), the shell tools a package