@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58

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 (312) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +246 -66
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +15 -5
  11. package/dist/api-only.js +32 -8
  12. package/dist/box-paths.d.ts +4 -3
  13. package/dist/box-paths.js +7 -4
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/chatgpt-plan.d.ts +18 -8
  19. package/dist/chatgpt-plan.js +91 -34
  20. package/dist/claude-login-token.d.ts +117 -0
  21. package/dist/claude-login-token.js +737 -0
  22. package/dist/claude-login.d.ts +120 -22
  23. package/dist/claude-login.js +347 -63
  24. package/dist/claude-sign-in.d.ts +17 -6
  25. package/dist/claude-sign-in.js +42 -39
  26. package/dist/cli.js +33 -10
  27. package/dist/composio-made.d.ts +4 -0
  28. package/dist/composio-made.js +4 -0
  29. package/dist/composio-preset.d.ts +43 -2
  30. package/dist/composio-preset.js +92 -4
  31. package/dist/computer-attach.d.ts +35 -17
  32. package/dist/computer-attach.js +301 -49
  33. package/dist/computer-held-routes.d.ts +5 -4
  34. package/dist/computer-held-routes.js +29 -8
  35. package/dist/computer-held.d.ts +6 -1
  36. package/dist/computer-held.js +14 -0
  37. package/dist/computer-record.js +4 -2
  38. package/dist/computer-viewer.js +4 -1
  39. package/dist/computers.d.ts +10 -10
  40. package/dist/computers.js +5 -5
  41. package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
  42. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  43. package/dist/console/assets/index-DPh29cyz.js +747 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/decisions.d.ts +1 -1
  46. package/dist/decisions.js +1 -1
  47. package/dist/dial-relay.d.ts +25 -4
  48. package/dist/dial-relay.js +129 -1
  49. package/dist/docker-host-addresses.d.ts +22 -11
  50. package/dist/docker-host-addresses.js +38 -26
  51. package/dist/env-switch.d.ts +8 -0
  52. package/dist/env-switch.js +31 -2
  53. package/dist/errors.d.ts +1 -0
  54. package/dist/errors.js +2 -0
  55. package/dist/fal-price.d.ts +56 -20
  56. package/dist/fal-price.js +400 -90
  57. package/dist/handed-values.d.ts +43 -1
  58. package/dist/handed-values.js +119 -2
  59. package/dist/harness-archive.d.ts +13 -10
  60. package/dist/harness-archive.js +60 -34
  61. package/dist/harness-check.d.ts +3 -1
  62. package/dist/harness-check.js +25 -46
  63. package/dist/harness-keys.d.ts +73 -27
  64. package/dist/harness-keys.js +194 -61
  65. package/dist/harness-recipe-entry.d.ts +8 -7
  66. package/dist/harness-recipe-entry.js +21 -32
  67. package/dist/harness-recipe.d.ts +38 -25
  68. package/dist/harness-recipe.js +49 -36
  69. package/dist/harness-sign-in.js +12 -23
  70. package/dist/harness-table.d.ts +10 -3
  71. package/dist/harness-table.js +26 -21
  72. package/dist/harness.d.ts +1 -0
  73. package/dist/harness.js +17 -5
  74. package/dist/hosted-search.d.ts +1 -1
  75. package/dist/hosted-search.js +1 -2
  76. package/dist/import-worker.d.ts +4 -2
  77. package/dist/import-worker.js +9 -2
  78. package/dist/in-flight.d.ts +26 -0
  79. package/dist/in-flight.js +52 -0
  80. package/dist/key-refusal.d.ts +9 -4
  81. package/dist/key-refusal.js +107 -25
  82. package/dist/learn/ledger.d.ts +170 -0
  83. package/dist/learn/ledger.js +218 -0
  84. package/dist/learn/promote.d.ts +3 -3
  85. package/dist/learn/promote.js +1 -1
  86. package/dist/learn/secrets.d.ts +13 -3
  87. package/dist/learn/secrets.js +118 -17
  88. package/dist/learning-cost.d.ts +28 -23
  89. package/dist/learning-cost.js +19 -23
  90. package/dist/link-check.js +1 -1
  91. package/dist/live-reach.d.ts +2 -0
  92. package/dist/live-reach.js +2 -0
  93. package/dist/llms.txt +1 -1
  94. package/dist/marketplace.d.ts +77 -0
  95. package/dist/marketplace.js +224 -0
  96. package/dist/mcp-api-only-origins.d.ts +35 -0
  97. package/dist/mcp-api-only-origins.js +57 -0
  98. package/dist/mcp-gateway.d.ts +7 -5
  99. package/dist/mcp-gateway.js +9 -12
  100. package/dist/mcp-secret-writes.js +5 -3
  101. package/dist/mcp-servers-store.d.ts +28 -6
  102. package/dist/mcp-servers-store.js +53 -4
  103. package/dist/media-duration.d.ts +3 -0
  104. package/dist/media-duration.js +90 -9
  105. package/dist/micro.d.ts +2 -0
  106. package/dist/micro.js +2 -0
  107. package/dist/model-form.d.ts +5 -4
  108. package/dist/model-form.js +11 -7
  109. package/dist/model.d.ts +10 -6
  110. package/dist/model.js +16 -11
  111. package/dist/monid.d.ts +14 -1
  112. package/dist/monid.js +103 -26
  113. package/dist/ollama-provider.d.ts +7 -1
  114. package/dist/ollama-provider.js +14 -2
  115. package/dist/openapi.js +210 -37
  116. package/dist/otel/genai.d.ts +65 -0
  117. package/dist/otel/genai.js +116 -0
  118. package/dist/otel/tracer.d.ts +55 -0
  119. package/dist/otel/tracer.js +308 -0
  120. package/dist/page.d.ts +2 -0
  121. package/dist/page.js +3 -1
  122. package/dist/paid-calls.d.ts +1 -32
  123. package/dist/paid-calls.js +4 -39
  124. package/dist/place-offers.d.ts +4 -0
  125. package/dist/place-offers.js +7 -4
  126. package/dist/provider.d.ts +11 -2
  127. package/dist/provider.js +59 -8
  128. package/dist/redact/match.d.ts +30 -3
  129. package/dist/redact/match.js +422 -41
  130. package/dist/refusal-words.d.ts +11 -0
  131. package/dist/refusal-words.js +11 -0
  132. package/dist/run-census.d.ts +67 -0
  133. package/dist/run-census.js +240 -0
  134. package/dist/run-computer.d.ts +6 -3
  135. package/dist/run-computer.js +4 -1
  136. package/dist/run-cut.d.ts +15 -6
  137. package/dist/run-cut.js +30 -9
  138. package/dist/run-files.d.ts +3 -0
  139. package/dist/run-files.js +3 -0
  140. package/dist/run-launch.d.ts +12 -1
  141. package/dist/run-launch.js +9 -10
  142. package/dist/run-learning-served.d.ts +4 -2
  143. package/dist/run-model-key.d.ts +8 -0
  144. package/dist/run-model-key.js +31 -1
  145. package/dist/run-reads-over-store.d.ts +24 -6
  146. package/dist/run-reads-over-store.js +67 -23
  147. package/dist/run-recordings.d.ts +5 -1
  148. package/dist/run-recordings.js +39 -14
  149. package/dist/run-timeline-served.d.ts +2 -0
  150. package/dist/run-timeline-served.js +2 -2
  151. package/dist/run-usage.d.ts +1 -0
  152. package/dist/run-view.d.ts +1 -2
  153. package/dist/run-view.js +2 -1
  154. package/dist/runnable.d.ts +10 -1
  155. package/dist/runnable.js +20 -8
  156. package/dist/runner/adapter-loop.d.ts +11 -0
  157. package/dist/runner/adapter-loop.js +58 -26
  158. package/dist/runner/adapter-run-spec.d.ts +55 -11
  159. package/dist/runner/adapter-run-spec.js +183 -52
  160. package/dist/runner/adapters/pi.js +25 -3
  161. package/dist/runner/beside.d.ts +9 -2
  162. package/dist/runner/beside.js +27 -9
  163. package/dist/runner/big-writes.js +1 -10
  164. package/dist/runner/claim-secrets.d.ts +27 -10
  165. package/dist/runner/claim-secrets.js +49 -22
  166. package/dist/runner/cli-run-spec.d.ts +6 -0
  167. package/dist/runner/cli-run-spec.js +97 -38
  168. package/dist/runner/computer-journal.d.ts +9 -1
  169. package/dist/runner/computer-journal.js +26 -0
  170. package/dist/runner/conformance/harness.js +1 -1
  171. package/dist/runner/feedback-round.js +3 -0
  172. package/dist/runner/harness-loops.d.ts +6 -5
  173. package/dist/runner/harness-loops.js +7 -7
  174. package/dist/runner/held.d.ts +24 -6
  175. package/dist/runner/journal-kinds.d.ts +5 -0
  176. package/dist/runner/journal-kinds.js +5 -0
  177. package/dist/runner/main.d.ts +11 -6
  178. package/dist/runner/main.js +19 -9
  179. package/dist/runner/mcp-claim.js +31 -3
  180. package/dist/runner/mcp-run.d.ts +9 -0
  181. package/dist/runner/mcp-run.js +11 -5
  182. package/dist/runner/model-route.d.ts +17 -0
  183. package/dist/runner/model-route.js +120 -2
  184. package/dist/runner/presence.d.ts +11 -1
  185. package/dist/runner/presence.js +7 -0
  186. package/dist/runner/reflect-hook.js +1 -1
  187. package/dist/runner/run-child-host.d.ts +22 -8
  188. package/dist/runner/run-child-host.js +128 -41
  189. package/dist/runner/run-child.js +5 -2
  190. package/dist/runner/runner.d.ts +17 -3
  191. package/dist/runner/runner.js +130 -34
  192. package/dist/runner/save-slots.js +2 -1
  193. package/dist/runner/store-port.d.ts +1 -1
  194. package/dist/runner/store-secrets.d.ts +6 -0
  195. package/dist/runner/store-secrets.js +49 -7
  196. package/dist/runner/subagent.d.ts +11 -0
  197. package/dist/runner/subagent.js +16 -38
  198. package/dist/runner/workflow-first.d.ts +35 -15
  199. package/dist/runner/workflow-first.js +38 -25
  200. package/dist/runner/workflow-spec.js +4 -3
  201. package/dist/runs-over-store.d.ts +15 -6
  202. package/dist/runs-over-store.js +33 -21
  203. package/dist/scrub-command.d.ts +73 -0
  204. package/dist/scrub-command.js +307 -0
  205. package/dist/secret-cut.d.ts +73 -0
  206. package/dist/secret-cut.js +291 -4
  207. package/dist/secret-rules.d.ts +143 -0
  208. package/dist/secret-rules.js +2564 -0
  209. package/dist/secrets.d.ts +7 -0
  210. package/dist/secrets.js +20 -0
  211. package/dist/server-keys.d.ts +20 -0
  212. package/dist/server-keys.js +25 -6
  213. package/dist/server.d.ts +65 -13
  214. package/dist/server.js +470 -157
  215. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  216. package/dist/slots.d.ts +9 -0
  217. package/dist/slots.js +45 -0
  218. package/dist/store/index.d.ts +1 -1
  219. package/dist/store/index.js +1 -1
  220. package/dist/store/journal/storage.js +1 -1
  221. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  222. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  223. package/dist/store/schema.d.ts +23 -0
  224. package/dist/store/schema.js +58 -2
  225. package/dist/store/seal.d.ts +6 -1
  226. package/dist/store/seal.js +5 -3
  227. package/dist/store/sqlite/run-launch.d.ts +9 -1
  228. package/dist/store/sqlite/run-launch.js +24 -13
  229. package/dist/store/sqlite/run-patch.d.ts +12 -2
  230. package/dist/store/sqlite/run-patch.js +42 -5
  231. package/dist/store/sqlite/store.js +105 -12
  232. package/dist/store/store.d.ts +57 -2
  233. package/dist/store/store.js +20 -0
  234. package/dist/store-reads/learning.d.ts +84 -124
  235. package/dist/store-reads/learning.js +210 -274
  236. package/dist/store-view.d.ts +3 -0
  237. package/dist/store-view.js +3 -3
  238. package/dist/suggestions.js +3 -2
  239. package/dist/template-eval.d.ts +39 -9
  240. package/dist/template-eval.js +191 -60
  241. package/dist/template-import.js +6 -2
  242. package/dist/templates.d.ts +10 -2
  243. package/dist/templates.js +28 -8
  244. package/dist/timeline/labels.d.ts +6 -4
  245. package/dist/timeline/labels.js +18 -6
  246. package/dist/timeline/timeline.d.ts +5 -0
  247. package/dist/timeline/timeline.js +14 -8
  248. package/dist/timeline/util.js +1 -1
  249. package/dist/timeline/web-calls.d.ts +22 -7
  250. package/dist/timeline/web-calls.js +106 -35
  251. package/dist/tool-gate.d.ts +42 -3
  252. package/dist/tool-gate.js +66 -5
  253. package/dist/tool-keys-store.d.ts +2 -4
  254. package/dist/tool-keys-store.js +5 -21
  255. package/dist/tool-keys.d.ts +2 -2
  256. package/dist/tool-keys.js +2 -2
  257. package/dist/tool-list.js +1 -1
  258. package/dist/tool-plane.d.ts +2 -2
  259. package/dist/tool-plane.js +35 -33
  260. package/dist/tools.js +13 -7
  261. package/dist/trigger-targets.d.ts +4 -0
  262. package/dist/trigger-targets.js +9 -2
  263. package/dist/triggers.d.ts +67 -4
  264. package/dist/triggers.js +171 -22
  265. package/dist/until.d.ts +3 -0
  266. package/dist/until.js +11 -0
  267. package/dist/web-fake.d.ts +1 -3
  268. package/dist/web-fake.js +7 -18
  269. package/dist/web-fetch.d.ts +6 -72
  270. package/dist/web-fetch.js +11 -265
  271. package/dist/web-run.d.ts +31 -0
  272. package/dist/web-run.js +90 -0
  273. package/dist/web-save.d.ts +10 -13
  274. package/dist/web-save.js +13 -55
  275. package/dist/web-search.d.ts +9 -127
  276. package/dist/web-search.js +23 -259
  277. package/dist/wires.d.ts +13 -0
  278. package/dist/wires.js +11 -0
  279. package/dist/workflow-run.d.ts +5 -4
  280. package/dist/workflow-run.js +5 -4
  281. package/dist/workspace/attached-computers.d.ts +32 -9
  282. package/dist/workspace/attached-computers.js +77 -13
  283. package/dist/workspace/computer-deps.d.ts +8 -2
  284. package/dist/workspace/computer-deps.js +10 -3
  285. package/dist/workspace/computer-for-claim.d.ts +12 -1
  286. package/dist/workspace/computer-for-claim.js +83 -11
  287. package/dist/workspace/computer-kept.d.ts +3 -0
  288. package/dist/workspace/computer-kept.js +11 -2
  289. package/dist/workspace/index.d.ts +1 -1
  290. package/dist/workspace/index.js +1 -1
  291. package/dist/workspace/kind-skills.d.ts +4 -0
  292. package/dist/workspace/kind-skills.js +9 -0
  293. package/dist/workspace/paired-route.d.ts +91 -0
  294. package/dist/workspace/paired-route.js +153 -0
  295. package/dist/workspace/synced-folder.js +3 -4
  296. package/dist/wrapped.d.ts +20 -6
  297. package/dist/wrapped.js +66 -25
  298. package/package.json +17 -11
  299. package/skills/agentrun-serve/SKILL.md +4 -0
  300. package/templates/README.md +32 -10
  301. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  302. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  303. package/dist/exa-keyless.d.ts +0 -34
  304. package/dist/exa-keyless.js +0 -118
  305. package/dist/firecrawl-keyless.d.ts +0 -41
  306. package/dist/firecrawl-keyless.js +0 -152
  307. package/dist/keyless-mcp.d.ts +0 -36
  308. package/dist/keyless-mcp.js +0 -127
  309. package/dist/text-urls.d.ts +0 -38
  310. package/dist/text-urls.js +0 -170
  311. package/dist/web-fetch-direct.d.ts +0 -119
  312. package/dist/web-fetch-direct.js +0 -190
@@ -20,6 +20,10 @@ forbidden` with `error.details.console_url`, the console's form with the rest fi
20
20
  Open that link in the person's browser for them and tell them to paste the secret there and save. Never ask for a
21
21
  secret in the chat.
22
22
 
23
+ An API key for an app (`AGENTRUN_API_KEY`) is made the same way: the owner makes it in the console at
24
+ `<console>/#/settings/api-keys`, where it is shown once. `POST /v2/settings/api-keys` with the token is `403
25
+ forbidden`. A key the owner hands you is sent as the token is, as `Authorization: Bearer <key>`.
26
+
23
27
  ## Choose the onboarding path
24
28
 
25
29
  For general setup, establish whether the user wants to **start a new agent** or **bring an existing agent**.
@@ -0,0 +1,9 @@
1
+ /** Slots handed out first come first served. `take` answers the slot's release (once), or rejects with the signal's
2
+ * reason if it aborts first, leaving the queue; with no signal it waits until a slot is free. */
3
+ export type Slots = {
4
+ readonly size: number;
5
+ readonly busy: number;
6
+ readonly waiting: number;
7
+ take(signal?: AbortSignal): Promise<() => void>;
8
+ };
9
+ export declare function slots(size: number): Slots;
package/dist/slots.js ADDED
@@ -0,0 +1,45 @@
1
+ // A gate of n slots, handed out first come first served: web_save's downloads (web-save.ts), Mode 2's pieced writes
2
+ // (runner/big-writes.ts) and a run's subagents (runner/subagent.ts). A leaf module: it imports nothing.
3
+ export function slots(size) {
4
+ let busy = 0;
5
+ const queue = [];
6
+ const releaser = () => {
7
+ let done = false;
8
+ return () => {
9
+ if (done)
10
+ return;
11
+ done = true;
12
+ // The slot goes straight to the next waiter, so busy only drops when no one waits.
13
+ const next = queue.shift();
14
+ if (next)
15
+ next();
16
+ else
17
+ busy--;
18
+ };
19
+ };
20
+ return {
21
+ size,
22
+ get busy() { return busy; },
23
+ get waiting() { return queue.length; },
24
+ take(signal) {
25
+ if (signal?.aborted)
26
+ return Promise.reject(signal.reason);
27
+ if (busy < size) {
28
+ busy++;
29
+ return Promise.resolve(releaser());
30
+ }
31
+ return new Promise((resolve, reject) => {
32
+ const leave = () => {
33
+ queue.splice(queue.indexOf(grant), 1);
34
+ reject(signal.reason);
35
+ };
36
+ const grant = () => {
37
+ signal?.removeEventListener("abort", leave);
38
+ resolve(releaser());
39
+ };
40
+ queue.push(grant);
41
+ signal?.addEventListener("abort", leave, { once: true });
42
+ });
43
+ },
44
+ };
45
+ }
@@ -1,4 +1,4 @@
1
- export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
1
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CENSUS_PENDING, CENSUS_UNSCANNED, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, FiringMoved, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
2
  export type { ConstraintRule, SettingsGuard, McpGuard, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpTokensMark, McpOwnersMark, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CENSUS_PENDING, CENSUS_UNSCANNED, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, FiringMoved, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -325,7 +325,7 @@ export class RunStorage {
325
325
  // A run patch that made the run final: its other untaken rows are refused in this commit, after its own takes.
326
326
  // A person's message that came while it was ending opens a completed run again instead (refuseLeftovers).
327
327
  if (patching)
328
- await refuseLeftovers(tx, this.#runId, staged?.run?.state, now, this.#dialect, staged?.run?.keepsEnd === true);
328
+ await refuseLeftovers(tx, this.#runId, staged?.run?.state, now, this.#dialect, staged?.run?.keepsEnd === true, staged?.run?.census);
329
329
  }
330
330
  });
331
331
  this.#nextId = Math.max(this.#nextId, candidateNextId);
@@ -0,0 +1,31 @@
1
+ -- Version 27: a run's census (run_launch.census, as store/schema.ts keeps it on SQLite): where in each of the run's files
2
+ -- the secrets its caller handed it sat when its end erased them (run-census.ts), never the secrets; "pending" from when
3
+ -- a launch first holds sealed secrets until an end counts them (each launch holding them now is marked so here);
4
+ -- "unscanned" when an end erased them with no census made under them; null when a launch never held any (none handed,
5
+ -- or a run ended before this). Applied once, after 0026, inside the transaction migrate.ts opens. Never edit this file once
6
+ -- applied: a change is a new file.
7
+ ALTER TABLE run_launch ADD COLUMN IF NOT EXISTS census TEXT COLLATE "C" CHECK (census IS NULL OR census::json IS NOT NULL);
8
+ UPDATE run_launch SET census = '"pending"' WHERE sealed IS NOT NULL AND census IS NULL;
9
+
10
+ -- The same census rule for a write that never names it (store/sqlite/run-launch.ts censusOnSeal), held by the table: a
11
+ -- server of an earlier build still serving while this applies (a rolling deploy) writes sealed bytes and no census. Its
12
+ -- insert of a launch holding sealed bytes takes "pending", so an end by an earlier runner (which erases them and writes no
13
+ -- census) leaves "pending", read as uncounted, never as a launch handed nothing. Its seal over a "pending" whose sealed
14
+ -- bytes an end erased turns it to "unscanned", as this build's does: that end counted nothing, so the files it left stay
15
+ -- withheld, not cut of the new values alone. A write that names a census (this build's) keeps it.
16
+ CREATE OR REPLACE FUNCTION run_launch_census_on_seal() RETURNS trigger LANGUAGE plpgsql AS $$
17
+ BEGIN
18
+ IF NEW.sealed IS NOT NULL THEN
19
+ IF TG_OP = 'UPDATE' AND OLD.sealed IS NULL AND OLD.census = '"pending"' AND NEW.census IS NOT DISTINCT FROM OLD.census THEN
20
+ NEW.census := '"unscanned"';
21
+ ELSE
22
+ NEW.census := COALESCE(NEW.census, '"pending"');
23
+ END IF;
24
+ END IF;
25
+ RETURN NEW;
26
+ END
27
+ $$;
28
+ DROP TRIGGER IF EXISTS run_launch_census_on_seal ON run_launch;
29
+ CREATE TRIGGER run_launch_census_on_seal BEFORE INSERT OR UPDATE OF sealed ON run_launch
30
+ FOR EACH ROW EXECUTE FUNCTION run_launch_census_on_seal();
31
+ UPDATE store_meta SET schema_version = 27 WHERE singleton = 1;
@@ -0,0 +1,44 @@
1
+ -- The store's schema on Postgres, version 28: the learning ledger (learn/ledger.ts), as store/schema.ts keeps it on
2
+ -- SQLite (LEARNING_LEDGER, LEARNING_SPEND). Applied once, after 0027, inside the transaction migrate.ts opens. Never edit
3
+ -- this file once applied: a change is a new file. Additive: a runner of version 27 or earlier never writes it; a run it
4
+ -- ends has no row, or a row for an earlier end (`epoch` is the run's epoch after the end it was written for, and every
5
+ -- end moves the epoch), and the reader records it from the run's row as it reads either way (store-reads/learning.ts).
6
+ --
7
+ -- learning_ledger: one row a run, written by each patch that leaves the run ended (run-patch.ts applyRunPatch, in that
8
+ -- patch's transaction): who answered it (path, null when its end named none), the revision that ran it, why it was not
9
+ -- served alone, the job's own $ and its rounds' look-back, and whether its cost is known. Gone with its run's purge.
10
+ -- learning_spend: each learning cost by the revision it is for (a compile turn by its round, a check's replay run, an
11
+ -- audit's shadow run with the run it audits), written with its run's ledger row. Figures only, no run text. Made only
12
+ -- where missing, so a store whose record of this file was lost applies it again unharmed.
13
+
14
+ CREATE TABLE IF NOT EXISTS learning_ledger (
15
+ run_id TEXT COLLATE "C" PRIMARY KEY,
16
+ agent_id TEXT COLLATE "C" NOT NULL,
17
+ started_at BIGINT NOT NULL,
18
+ path TEXT COLLATE "C" CHECK (path IS NULL OR path IN ('agent', 'handed_back', 'workflow', 'replay', 'audit')),
19
+ workflow TEXT COLLATE "C",
20
+ digest TEXT COLLATE "C",
21
+ not_served TEXT COLLATE "C" CHECK (not_served IS NULL OR not_served IN ('cost_stop', 'cut')),
22
+ job_usd DOUBLE PRECISION,
23
+ look_back_usd DOUBLE PRECISION,
24
+ cost TEXT COLLATE "C" NOT NULL CHECK (cost IN ('known', 'unknown', 'at_most')),
25
+ epoch BIGINT NOT NULL
26
+ );
27
+ CREATE INDEX IF NOT EXISTS learning_ledger_agent ON learning_ledger (agent_id);
28
+
29
+ CREATE TABLE IF NOT EXISTS learning_spend (
30
+ run_id TEXT COLLATE "C" NOT NULL,
31
+ kind TEXT COLLATE "C" NOT NULL CHECK (kind IN ('compile', 'check', 'audit')),
32
+ round BIGINT NOT NULL CHECK (round >= 0),
33
+ agent_id TEXT COLLATE "C" NOT NULL,
34
+ of_run TEXT COLLATE "C",
35
+ workflow TEXT COLLATE "C",
36
+ digest TEXT COLLATE "C",
37
+ usd DOUBLE PRECISION,
38
+ at BIGINT NOT NULL,
39
+ PRIMARY KEY (run_id, kind, round)
40
+ );
41
+ CREATE INDEX IF NOT EXISTS learning_spend_agent ON learning_spend (agent_id);
42
+ CREATE INDEX IF NOT EXISTS learning_spend_of_run ON learning_spend (of_run) WHERE of_run IS NOT NULL;
43
+
44
+ UPDATE store_meta SET schema_version = 28 WHERE singleton = 1;
@@ -28,6 +28,12 @@ export declare function diskUpgrade(runColumns: ReadonlySet<string>): readonly s
28
28
  * for one a person made. In STORE_DDL, and added at a server open to a store an earlier build of this version made, as
29
29
  * RUNS_LABELS is (a trigger made before reads as no package's). */
30
30
  export declare const TRIGGERS_TEMPLATE_ID = "ALTER TABLE triggers ADD COLUMN template_id TEXT";
31
+ /** A run's census (RunLaunchRow.census, run-census.ts): in STORE_DDL, and added at a server open to a store an earlier
32
+ * build of this version made, as RUNS_LABELS is (a run ended before reads as never handed a secret). */
33
+ export declare const RUN_LAUNCH_CENSUS: string;
34
+ /** Every launch holding sealed bytes when the census was added (RUN_LAUNCH_CENSUS) marked CENSUS_PENDING (store.ts): its
35
+ * end counts them, or its files read as uncounted. */
36
+ export declare const RUN_LAUNCH_CENSUS_PENDING = "UPDATE run_launch SET census = '\"pending\"' WHERE sealed IS NOT NULL AND census IS NULL";
31
37
  /** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
32
38
  * source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
33
39
  * (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
@@ -97,6 +103,23 @@ export declare const HAND_BACKS_KEPT_MS: number;
97
103
  * added at a server open to a store an earlier build of this version made, as COMPUTER_INTERVALS is: a claim made before
98
104
  * it has no row. */
99
105
  export declare const RUN_ATTEMPTS = "CREATE TABLE IF NOT EXISTS run_attempts (\n run_id TEXT NOT NULL,\n epoch INTEGER NOT NULL,\n turn INTEGER NOT NULL CHECK (turn >= 1),\n attempt INTEGER NOT NULL CHECK (attempt >= 1),\n cause TEXT CHECK (cause IS NULL OR cause IN ('drain', 'crash', 'lease_lapse', 'retry')),\n cut TEXT CHECK (cut IS NULL OR cut IN ('drain', 'lease_lapse', 'retry')),\n runner TEXT NOT NULL,\n from_state TEXT NOT NULL,\n journal_from INTEGER NOT NULL,\n claimed_at INTEGER NOT NULL,\n PRIMARY KEY (run_id, epoch)\n ) STRICT";
106
+ /** The learning ledger (learn/ledger.ts): one row a run, written by each patch that leaves the run ended (applyRunPatch,
107
+ * in that patch's transaction) and by a healed cost: who answered it (`path`, null when its end named none), the
108
+ * revision that ran it, why it was not served alone, the job's own $ and its rounds' look-back, and whether its cost is
109
+ * known (`cost`), and the end it was written for (`epoch`: the run's epoch after that end, which every end moves).
110
+ * Gone with the run's purge or delete (its cost stays on the run's tombstone). Figures only, no run text. In STORE_DDL,
111
+ * and made at a server open on a store an earlier build of this version made: a run that ended before it has no row,
112
+ * and one a runner of that build ended again has a row for an earlier end; its reader records it from its run row
113
+ * either way (store-reads/learning.ts). */
114
+ export declare const LEARNING_LEDGER = "CREATE TABLE IF NOT EXISTS learning_ledger (\n run_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n path TEXT CHECK (path IS NULL OR path IN ('agent', 'handed_back', 'workflow', 'replay', 'audit')),\n workflow TEXT,\n digest TEXT,\n not_served TEXT CHECK (not_served IS NULL OR not_served IN ('cost_stop', 'cut')),\n job_usd REAL,\n look_back_usd REAL,\n cost TEXT NOT NULL CHECK (cost IN ('known', 'unknown', 'at_most')),\n epoch INTEGER NOT NULL\n ) STRICT";
115
+ export declare const LEARNING_LEDGER_AGENT = "CREATE INDEX IF NOT EXISTS learning_ledger_agent ON learning_ledger (agent_id)";
116
+ /** Each learning cost, by the revision it is for (learn/ledger.ts SpendRow): a compile turn (`round`, the round that asked
117
+ * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits), with its $ (null: unknown).
118
+ * Written with its run's ledger row, replaced whole each time; gone with its run's purge or delete, and with the purge
119
+ * or delete of the run it audits. */
120
+ 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";
121
+ export declare const LEARNING_SPEND_AGENT = "CREATE INDEX IF NOT EXISTS learning_spend_agent ON learning_spend (agent_id)";
122
+ 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";
100
123
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
101
124
  * run and each agent was purged (null: none was), and the version, in one durable write. */
102
125
  export declare function purgeUpgrade(runColumns: ReadonlySet<string>, agentColumns: ReadonlySet<string>): readonly string[];
@@ -21,7 +21,8 @@
21
21
  // added the same way, and so is each runner's word that it is there and whether it refused to claim (runners, RUNNERS),
22
22
  // and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS). Each runner's
23
23
  // version and slots (runners.version, .slots: RUNNERS_ADDED), each hand-back (hand_backs, HAND_BACKS) and each claim of a
24
- // run with the turn it works and its attempt at it (run_attempts, RUN_ATTEMPTS) are added the same way.
24
+ // run with the turn it works and its attempt at it (run_attempts, RUN_ATTEMPTS) are added the same way, and so is the
25
+ // learning ledger (learning_ledger, learning_spend: LEARNING_LEDGER, LEARNING_SPEND).
25
26
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
26
27
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
27
28
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -81,6 +82,12 @@ export function diskUpgrade(runColumns) {
81
82
  * for one a person made. In STORE_DDL, and added at a server open to a store an earlier build of this version made, as
82
83
  * RUNS_LABELS is (a trigger made before reads as no package's). */
83
84
  export const TRIGGERS_TEMPLATE_ID = "ALTER TABLE triggers ADD COLUMN template_id TEXT";
85
+ /** A run's census (RunLaunchRow.census, run-census.ts): in STORE_DDL, and added at a server open to a store an earlier
86
+ * build of this version made, as RUNS_LABELS is (a run ended before reads as never handed a secret). */
87
+ export const RUN_LAUNCH_CENSUS = `ALTER TABLE run_launch ADD COLUMN ${json("census", true)}`;
88
+ /** Every launch holding sealed bytes when the census was added (RUN_LAUNCH_CENSUS) marked CENSUS_PENDING (store.ts): its
89
+ * end counts them, or its files read as uncounted. */
90
+ export const RUN_LAUNCH_CENSUS_PENDING = `UPDATE run_launch SET census = '"pending"' WHERE sealed IS NOT NULL AND census IS NULL`;
84
91
  /** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
85
92
  * source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
86
93
  * (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
@@ -217,6 +224,46 @@ export const RUN_ATTEMPTS = `CREATE TABLE IF NOT EXISTS run_attempts (
217
224
  claimed_at INTEGER NOT NULL,
218
225
  PRIMARY KEY (run_id, epoch)
219
226
  ) STRICT`;
227
+ /** The learning ledger (learn/ledger.ts): one row a run, written by each patch that leaves the run ended (applyRunPatch,
228
+ * in that patch's transaction) and by a healed cost: who answered it (`path`, null when its end named none), the
229
+ * revision that ran it, why it was not served alone, the job's own $ and its rounds' look-back, and whether its cost is
230
+ * known (`cost`), and the end it was written for (`epoch`: the run's epoch after that end, which every end moves).
231
+ * Gone with the run's purge or delete (its cost stays on the run's tombstone). Figures only, no run text. In STORE_DDL,
232
+ * and made at a server open on a store an earlier build of this version made: a run that ended before it has no row,
233
+ * and one a runner of that build ended again has a row for an earlier end; its reader records it from its run row
234
+ * either way (store-reads/learning.ts). */
235
+ export const LEARNING_LEDGER = `CREATE TABLE IF NOT EXISTS learning_ledger (
236
+ run_id TEXT PRIMARY KEY,
237
+ agent_id TEXT NOT NULL,
238
+ started_at INTEGER NOT NULL,
239
+ path TEXT CHECK (path IS NULL OR path IN ('agent', 'handed_back', 'workflow', 'replay', 'audit')),
240
+ workflow TEXT,
241
+ digest TEXT,
242
+ not_served TEXT CHECK (not_served IS NULL OR not_served IN ('cost_stop', 'cut')),
243
+ job_usd REAL,
244
+ look_back_usd REAL,
245
+ cost TEXT NOT NULL CHECK (cost IN ('known', 'unknown', 'at_most')),
246
+ epoch INTEGER NOT NULL
247
+ ) STRICT`;
248
+ export const LEARNING_LEDGER_AGENT = "CREATE INDEX IF NOT EXISTS learning_ledger_agent ON learning_ledger (agent_id)";
249
+ /** Each learning cost, by the revision it is for (learn/ledger.ts SpendRow): a compile turn (`round`, the round that asked
250
+ * it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits), with its $ (null: unknown).
251
+ * Written with its run's ledger row, replaced whole each time; gone with its run's purge or delete, and with the purge
252
+ * or delete of the run it audits. */
253
+ export const LEARNING_SPEND = `CREATE TABLE IF NOT EXISTS learning_spend (
254
+ run_id TEXT NOT NULL,
255
+ kind TEXT NOT NULL CHECK (kind IN ('compile', 'check', 'audit')),
256
+ round INTEGER NOT NULL CHECK (round >= 0),
257
+ agent_id TEXT NOT NULL,
258
+ of_run TEXT,
259
+ workflow TEXT,
260
+ digest TEXT,
261
+ usd REAL,
262
+ at INTEGER NOT NULL,
263
+ PRIMARY KEY (run_id, kind, round)
264
+ ) STRICT`;
265
+ export const LEARNING_SPEND_AGENT = "CREATE INDEX IF NOT EXISTS learning_spend_agent ON learning_spend (agent_id)";
266
+ export 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";
220
267
  /** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
221
268
  * run and each agent was purged (null: none was), and the version, in one durable write. */
222
269
  export function purgeUpgrade(runColumns, agentColumns) {
@@ -676,6 +723,11 @@ export const STORE_DDL = [
676
723
  COMPUTER_INTERVALS,
677
724
  COMPUTER_INTERVALS_RUN,
678
725
  RUN_ATTEMPTS,
726
+ LEARNING_LEDGER,
727
+ LEARNING_LEDGER_AGENT,
728
+ LEARNING_SPEND,
729
+ LEARNING_SPEND_AGENT,
730
+ LEARNING_SPEND_OF_RUN,
679
731
  // An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
680
732
  // pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
681
733
  // sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
@@ -749,11 +801,15 @@ export const STORE_DDL = [
749
801
  // its claim to build the run's spec. It replaces the per-run serve.json the old per-run process read: one row per run,
750
802
  // written in the same transaction as the queued run, never after. `body` is the launch JSON (run-launch.ts: the first
751
803
  // input, title, place, effort, cap, and the trigger and origin that started it); `sealed` holds any secret sealed with
752
- // the server's key outside the store (AAD run_launch|<run_id>|sealed), or null when the launch holds none.
804
+ // the server's key outside the store (AAD run_launch|<run_id>|sealed), or null when the launch holds none. `census` is
805
+ // null when the launch never held any; "pending" from when it first does until an end counts them; then where in the
806
+ // run's files they sat when that end erased them (run-census.ts), never the secrets, or "unscanned" when it erased them
807
+ // with no census made under them (store.ts CENSUS_PENDING, CENSUS_UNSCANNED).
753
808
  `CREATE TABLE IF NOT EXISTS run_launch (
754
809
  run_id TEXT PRIMARY KEY REFERENCES runs (id),
755
810
  ${json("body")},
756
811
  sealed BLOB,
812
+ ${json("census", true)},
757
813
  created_at INTEGER NOT NULL
758
814
  ) STRICT`,
759
815
  // A running run's live view (the tool it runs now, its partial text): one row, outside the journal, overwritten in place
@@ -76,11 +76,16 @@ export type RunModelKey = {
76
76
  /** A run's own tool keys (`keys` at its start or with a message, run-keys.ts), by name. */
77
77
  export type RunToolKeys = Readonly<Record<string, string>>;
78
78
  /** What a run's launch holds sealed: its handed MCP credentials, its own model key and its own tool keys, each when it
79
- * has one. */
79
+ * has one. `retired`: each value an earlier seal of the launch held that a message replaced since its turn began (a
80
+ * host that hands a fresh key with each message), kept only to be cut (the runner's cut, a served read's, its end's
81
+ * census) and never used, erased with the rest at the run's end. `lost`: a message sealed over bytes that did not open
82
+ * here, so what they held is not known: every cut of the run is unreadable until its end, which writes no census. */
80
83
  export type RunLaunchSecrets = {
81
84
  readonly mcp?: RunMcpAuth;
82
85
  readonly model?: RunModelKey;
83
86
  readonly keys?: RunToolKeys;
87
+ readonly retired?: readonly string[];
88
+ readonly lost?: true;
84
89
  };
85
90
  /** Seals a run's launch secrets as its launch's sealed column (AAD run_launch|<run_id>|sealed); null when it holds none. */
86
91
  export declare function sealRunLaunch(key: Buffer, runId: string, secrets: RunLaunchSecrets): Uint8Array | null;
@@ -74,9 +74,10 @@ export function openMcpCredential(key, row) {
74
74
  export function sealRunLaunch(key, runId, secrets) {
75
75
  const mcp = secrets.mcp && Object.keys(secrets.mcp).length ? secrets.mcp : undefined;
76
76
  const keys = secrets.keys && Object.keys(secrets.keys).length ? secrets.keys : undefined;
77
- if (!mcp && !secrets.model && !keys)
77
+ const retired = secrets.retired?.length ? secrets.retired : undefined;
78
+ if (!mcp && !secrets.model && !keys && !retired && !secrets.lost)
78
79
  return null;
79
- return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ ...(mcp ? { mcp } : {}), ...(secrets.model ? { model: secrets.model } : {}), ...(keys ? { keys } : {}) }));
80
+ return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ ...(mcp ? { mcp } : {}), ...(secrets.model ? { model: secrets.model } : {}), ...(keys ? { keys } : {}), ...(retired ? { retired } : {}), ...(secrets.lost ? { lost: true } : {}) }));
80
81
  }
81
82
  /** The tool keys of an opened launch: each name with text for its value, none else. */
82
83
  const toolKeysOf = (keys) => {
@@ -94,7 +95,8 @@ export function openRunLaunch(key, runId, sealed) {
94
95
  const opened = JSON.parse(unsealColumn(key, sealedAt.runLaunch(runId), sealed).toString("utf8"));
95
96
  const model = typeof opened.model?.key === "string" && typeof opened.model.origin === "string" ? { key: opened.model.key, origin: opened.model.origin } : undefined;
96
97
  const keys = toolKeysOf(opened.keys);
97
- return { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) };
98
+ const retired = Array.isArray(opened.retired) ? opened.retired.filter((value) => typeof value === "string") : [];
99
+ return { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}), ...(retired.length ? { retired } : {}), ...(opened.lost === true ? { lost: true } : {}) };
98
100
  }
99
101
  catch {
100
102
  return undefined;
@@ -7,8 +7,16 @@ import type { SqliteExecutor } from "./connection.js";
7
7
  * member as written (readUsageMetadata, readLearningStarts) reads the column and retries on postgresUnicodeRefusal. */
8
8
  export declare const readableJson: (dialect: Dialect, column: string) => string;
9
9
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
10
- * trigger path both call it, so the row lands with its run or not at all. */
10
+ * trigger path both call it, so the row lands with its run or not at all. A launch with sealed bytes takes the census
11
+ * CENSUS_PENDING with them. */
11
12
  export declare function writeLaunch(tx: Pick<SqliteExecutor, "run">, runId: string, launch: RunLaunchInput, at: number): Promise<void>;
13
+ /** The census a launch whose census is `census` and sealed bytes `sealed` takes when `next` is written as its sealed
14
+ * bytes: as it is when `next` holds none, or an end counted what it held before (its census); CENSUS_PENDING when it
15
+ * never held any; CENSUS_UNSCANNED over a CENSUS_PENDING whose sealed bytes an end erased without writing a census (a
16
+ * runner from before the census), so the files that end left are still read as uncounted. On Postgres the table holds
17
+ * the same rule too (migration 0027's trigger), for a server of an earlier build still writing during a rolling deploy.
18
+ * A SQLite store has one server, so no earlier server writes beside this one: the rule lives here alone. */
19
+ export declare function censusOnSeal(census: string | null, sealed: Uint8Array | null, next: Uint8Array | null): string | null;
12
20
  /** The disk a launch body names as the run's own (runs.disk, RunRow.disk): its `archil_disk` of kind "launch", by its id
13
21
  * (run-launch.ts launchBody writes it so); null for none, or its agent's own disk (the default disk). The one read of the
14
22
  * body's disk the store makes, at every create of a run, so no path that queues a run can leave it out. */
@@ -2,18 +2,33 @@
2
2
  // trigger path (store.triggers.fire) both write a run's launch row inside their own transaction, through one
3
3
  // helper, with no second copy of the SQL. The launch body itself is opaque here (run-launch.ts owns its shape); sealed
4
4
  // bytes are the caller's, which the store never opens.
5
- import { StoreLaunchMissing } from "../store.js";
6
- const RUN_LAUNCH_COLUMNS = "run_id, body, sealed, created_at";
7
- const runLaunchOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), createdAt: r.created_at });
5
+ import { CENSUS_PENDING, CENSUS_UNSCANNED, StoreLaunchMissing } from "../store.js";
6
+ const RUN_LAUNCH_COLUMNS = "run_id, body, sealed, census, created_at";
7
+ const runLaunchOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), census: r.census, createdAt: r.created_at });
8
8
  /** JSON text `column` (a launch body, a command's body, a journal record) as every read of one id, number or flag out of
9
9
  * it takes it: on Postgres its copy with escaped NULs and lone surrogates blanked (postgresReadableJson), so a run's text
10
10
  * never makes the read fail; on SQLite (whose json functions read them) the column itself. Only a read that returns a
11
11
  * member as written (readUsageMetadata, readLearningStarts) reads the column and retries on postgresUnicodeRefusal. */
12
12
  export const readableJson = (dialect, column) => (dialect.name === "postgres" ? postgresReadableJson(column) : column);
13
13
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
14
- * trigger path both call it, so the row lands with its run or not at all. */
14
+ * trigger path both call it, so the row lands with its run or not at all. A launch with sealed bytes takes the census
15
+ * CENSUS_PENDING with them. */
15
16
  export function writeLaunch(tx, runId, launch, at) {
16
- return tx.run("INSERT INTO run_launch (run_id, body, sealed, created_at) VALUES (?, ?, ?, ?)", runId, JSON.stringify(launch.body ?? null), launch.sealed ?? null, at);
17
+ const sealed = launch.sealed ?? null;
18
+ return tx.run("INSERT INTO run_launch (run_id, body, sealed, census, created_at) VALUES (?, ?, ?, ?, ?)", runId, JSON.stringify(launch.body ?? null), sealed, sealed === null ? null : CENSUS_PENDING, at);
19
+ }
20
+ /** The census a launch whose census is `census` and sealed bytes `sealed` takes when `next` is written as its sealed
21
+ * bytes: as it is when `next` holds none, or an end counted what it held before (its census); CENSUS_PENDING when it
22
+ * never held any; CENSUS_UNSCANNED over a CENSUS_PENDING whose sealed bytes an end erased without writing a census (a
23
+ * runner from before the census), so the files that end left are still read as uncounted. On Postgres the table holds
24
+ * the same rule too (migration 0027's trigger), for a server of an earlier build still writing during a rolling deploy.
25
+ * A SQLite store has one server, so no earlier server writes beside this one: the rule lives here alone. */
26
+ export function censusOnSeal(census, sealed, next) {
27
+ if (next === null)
28
+ return census;
29
+ if (census === null)
30
+ return CENSUS_PENDING;
31
+ return census === CENSUS_PENDING && sealed === null ? CENSUS_UNSCANNED : census;
17
32
  }
18
33
  /** The disk a launch body names as the run's own (runs.disk, RunRow.disk): its `archil_disk` of kind "launch", by its id
19
34
  * (run-launch.ts launchBody writes it so); null for none, or its agent's own disk (the default disk). The one read of the
@@ -31,14 +46,10 @@ export function launchDiskOf(launch) {
31
46
  /** A message's launch secrets written over the run's (runs.command, runs.reopen), inside `tx`: the bytes as given, or a
32
47
  * function's answer to the bytes the launch holds now, read in the same transaction. */
33
48
  export async function writeLaunchSealed(tx, runId, launchSealed) {
34
- let next;
35
- if (typeof launchSealed === "function") {
36
- const row = await tx.get("SELECT sealed FROM run_launch WHERE run_id = ?", runId);
37
- next = launchSealed(row?.sealed == null ? null : Uint8Array.from(row.sealed));
38
- }
39
- else
40
- next = launchSealed;
41
- await tx.run("UPDATE run_launch SET sealed = ? WHERE run_id = ?", next, runId);
49
+ const row = await tx.get("SELECT sealed, census FROM run_launch WHERE run_id = ?", runId);
50
+ const sealed = row?.sealed == null ? null : Uint8Array.from(row.sealed);
51
+ const next = typeof launchSealed === "function" ? launchSealed(sealed) : launchSealed;
52
+ await tx.run("UPDATE run_launch SET sealed = ?, census = ? WHERE run_id = ?", next, censusOnSeal(row?.census ?? null, sealed, next), runId);
42
53
  }
43
54
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
44
55
  * none, never a default. */
@@ -45,7 +45,17 @@ export declare const runOf: (r: RunRecord) => RunRow;
45
45
  * `now` (the store's clock, read in the transaction). A final state with no `endedAt` is stamped `now`, and releases the
46
46
  * run in the same statement. `dialect`: the connection's (store/dialect.ts), SQLite's by default. `clock`: the deadlines'
47
47
  * clock (fence.ts storeNow) the fence and left_running_at read; `now` bound by default. */
48
- export declare function applyRunPatch(tx: Pick<SqliteExecutor, "run" | "get">, claim: Pick<Claim, "runId" | "epoch">, patch: RunPatch, also: readonly AlsoRow[], now: number, dialect?: Dialect, clock?: StoreNow): Promise<RunRow>;
48
+ export declare function applyRunPatch(tx: Pick<SqliteExecutor, "run" | "get" | "all">, claim: Pick<Claim, "runId" | "epoch">, patch: RunPatch, also: readonly AlsoRow[], now: number, dialect?: Dialect, clock?: StoreNow): Promise<RunRow>;
49
+ /** Writes run `run`'s ledger row and spend rows (learn/ledger.ts record) through `tx`, from its row and every round its
50
+ * learning kept, in place of any it had: the one writer of learning_ledger and learning_spend (a run's end, and a heal
51
+ * of its cost). Each row says the end it was written for (`epoch`: the run's epoch after that end), which a reader
52
+ * checks against the run's (store-reads/learning.ts ledgerRowStands). Every end moves the epoch (applyRunPatch's
53
+ * `ending`, Runs.failUnclaimed), on every build, and so does every claim before one; an end that keeps its job's end
54
+ * (`keepsEnd`: a grade's round) leaves ended_at where it was, so ended_at never says which end a row is for. A runner
55
+ * or server of the build before the ledger, ending the run again, writes none, and its row reads as stale until a later
56
+ * end writes it again. A cancel that wins an end (refuseLeftovers, after this) moves ended_at, never the epoch: the row
57
+ * still stands. */
58
+ export declare function recordLedger(tx: Pick<SqliteExecutor, "run" | "all">, run: RunRow, now: number): Promise<void>;
49
59
  /** The one reopen a run that ended may take (runs.reopen, and a run's end with a person's message waiting): back to running
50
60
  * with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
51
61
  * metrics kept. `where` holds only for an agentic run that ended completed or that a person stopped (state 'stopped',
@@ -69,4 +79,4 @@ export declare const reopenableWhere: (d: Dialect) => string;
69
79
  * while the run looked back: a cancel at it cut the look-back alone and is refused with the rest. Only with a person's
70
80
  * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
71
81
  * taken in this commit, that message's run's: it ends cancelled, at this commit's time. */
72
- export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, state: RunState | undefined, now: number, dialect?: Dialect, keepsEnd?: boolean): Promise<void>;
82
+ export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, state: RunState | undefined, now: number, dialect?: Dialect, keepsEnd?: boolean, census?: RunPatch["census"]): Promise<void>;
@@ -3,10 +3,11 @@
3
3
  // runs.update and for the journal's commit (store/journal), which stages the patch and calls this inside its own
4
4
  // transaction: the run's end and its outbox rows commit with the journal's last entry, or none of them do. The fence is
5
5
  // the first statement: `WHERE id = ? AND epoch = ?` changing no row throws Fenced, and the caller's transaction rolls back.
6
- import { endedReason, FINAL_STATES, Fenced } from "../store.js";
6
+ 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 } from "./run-launch.js";
10
+ import { record } from "../../learn/ledger.js";
10
11
  /** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
11
12
  * list of runs names. */
12
13
  export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
@@ -101,7 +102,34 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
101
102
  break;
102
103
  }
103
104
  }
104
- return runOf(row);
105
+ const run = runOf(row);
106
+ // A run this patch leaves ended has its ledger row and spend rows (learn/ledger.ts record) in this same commit, over
107
+ // every round its learning kept, this patch's included: an end, a later end after a follow-up and a patch of an ended
108
+ // run's metrics each write them whole again.
109
+ if (FINAL_STATES.includes(run.state))
110
+ await recordLedger(tx, run, now);
111
+ return run;
112
+ }
113
+ /** Writes run `run`'s ledger row and spend rows (learn/ledger.ts record) through `tx`, from its row and every round its
114
+ * learning kept, in place of any it had: the one writer of learning_ledger and learning_spend (a run's end, and a heal
115
+ * of its cost). Each row says the end it was written for (`epoch`: the run's epoch after that end), which a reader
116
+ * checks against the run's (store-reads/learning.ts ledgerRowStands). Every end moves the epoch (applyRunPatch's
117
+ * `ending`, Runs.failUnclaimed), on every build, and so does every claim before one; an end that keeps its job's end
118
+ * (`keepsEnd`: a grade's round) leaves ended_at where it was, so ended_at never says which end a row is for. A runner
119
+ * or server of the build before the ledger, ending the run again, writes none, and its row reads as stale until a later
120
+ * end writes it again. A cancel that wins an end (refuseLeftovers, after this) moves ended_at, never the epoch: the row
121
+ * still stands. */
122
+ export async function recordLedger(tx, run, now) {
123
+ const rounds = (await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ? ORDER BY round", run.id))
124
+ .map((one) => ({ round: Number(one.round), proposal: JSON.parse(one.proposal) }));
125
+ const { row, spend } = record({ id: run.id, agentId: run.agentId, startedAt: run.startedAt, costUsd: run.costUsd, costAtMostUsd: run.costAtMostUsd, metrics: run.metrics, rounds });
126
+ await tx.run(`INSERT INTO learning_ledger (run_id, agent_id, started_at, path, workflow, digest, not_served, job_usd, look_back_usd, cost, epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
127
+ 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,
128
+ not_served = excluded.not_served, job_usd = excluded.job_usd, look_back_usd = excluded.look_back_usd, cost = excluded.cost, epoch = excluded.epoch`, row.runId, row.agentId, row.startedAt, row.path, row.workflow, row.digest, row.notServed, row.jobUsd, row.lookBackUsd, row.cost, run.epoch);
129
+ await tx.run("DELETE FROM learning_spend WHERE run_id = ?", run.id);
130
+ for (const one of spend) {
131
+ await tx.run("INSERT INTO learning_spend (run_id, kind, round, agent_id, of_run, workflow, digest, usd, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", one.runId, one.kind, one.round, one.agentId, one.ofRun, one.workflow, one.digest, one.usd, now);
132
+ }
105
133
  }
106
134
  /** The one reopen a run that ended may take (runs.reopen, and a run's end with a person's message waiting): back to running
107
135
  * with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
@@ -128,7 +156,7 @@ export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AN
128
156
  * while the run looked back: a cancel at it cut the look-back alone and is refused with the rest. Only with a person's
129
157
  * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
130
158
  * taken in this commit, that message's run's: it ends cancelled, at this commit's time. */
131
- export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, keepsEnd = false) {
159
+ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, keepsEnd = false, census) {
132
160
  if (state !== "ended" && state !== "stopped" && state !== "failed")
133
161
  return;
134
162
  // A cancel the API accepted (202, not refused) promised a cancelled run, and the view reads cancelled from that 202 on.
@@ -146,7 +174,7 @@ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, k
146
174
  if (won) {
147
175
  await tx.run("UPDATE commands SET taken_at = ? WHERE run_id = ? AND taken_at IS NULL AND refused IS NULL AND kind = 'cancel'", now, runId);
148
176
  await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE run_id = ? AND taken_at IS NULL", now, endedReason("stopped"), runId);
149
- await tx.run("UPDATE run_launch SET sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", runId);
177
+ await eraseLaunchSecrets(tx, runId, census);
150
178
  return;
151
179
  }
152
180
  }
@@ -161,5 +189,14 @@ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, k
161
189
  await tx.run(`UPDATE commands SET taken_at = ?, refused = ?, ${settledBody(dialect)} WHERE run_id = ? AND taken_at IS NULL`, now, endedReason(state), runId);
162
190
  // The run is over: the secrets its launch held for its life go with this same commit. A message that opens it again
163
191
  // hands its own (runs.reopen).
164
- await tx.run("UPDATE run_launch SET sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", runId);
192
+ await eraseLaunchSecrets(tx, runId, census);
193
+ }
194
+ /** A final run's launch secrets erased, in its end's commit, and what that end knew of where they sat written in their
195
+ * place: `census` when it was made under the sealed bytes erased here, else CENSUS_UNSCANNED (an end with none, or one
196
+ * whose launch a message sealed anew after the census read it). A launch with no sealed bytes is left as it is: its
197
+ * census, if any, is the end's that erased them. */
198
+ async function eraseLaunchSecrets(tx, runId, census) {
199
+ if (census)
200
+ await tx.run("UPDATE run_launch SET census = ?, sealed = NULL WHERE run_id = ? AND sealed = ?", census.json, runId, census.sealed);
201
+ await tx.run("UPDATE run_launch SET census = ?, sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", CENSUS_UNSCANNED, runId);
165
202
  }