@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.57

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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  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/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. 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**.
@@ -10,6 +10,9 @@ export interface Dialect {
10
10
  jsonValue(column: string, path: readonly string[]): string;
11
11
  /** True unless the JSON TEXT column's value at `path` is false or 0 (absent or null count as true). */
12
12
  jsonNotFalse(column: string, path: readonly string[]): string;
13
+ /** The JSON TEXT column's value at `path` as a number to compare with one, or SQL NULL when it is absent or not a JSON
14
+ * number (never a cast that fails on a row's text). */
15
+ jsonNumber(column: string, path: readonly string[]): string;
13
16
  /** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
14
17
  jsonArrayHas(column: string): string;
15
18
  /** True when the JSON object of strings in TEXT column `column` holds the key and the value of the two string parameters
@@ -15,6 +15,7 @@ export const SQLITE = {
15
15
  jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
16
16
  jsonValue: (column, path) => `${column} -> ${jsonPath(path)}`,
17
17
  jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
18
+ jsonNumber: (column, path) => `(CASE WHEN json_type(${column}, ${jsonPath(path)}) IN ('integer', 'real') THEN json_extract(${column}, ${jsonPath(path)}) END)`,
18
19
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
19
20
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
20
21
  jsonArrayLength: (column) => `json_array_length(${column})`,
@@ -1,4 +1,4 @@
1
- export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, 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, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, 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);
@@ -12,6 +12,9 @@ export function postgresDialect(schema, { testClock = false } = {}) {
12
12
  jsonValue: (column, keys) => `(${column}::json #> ${path(keys)})::text`,
13
13
  // SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
14
14
  jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
15
+ // SQLite's json_type(...) IN ('integer', 'real'): a JSON number read as numeric, anything else NULL, never a cast of
16
+ // text that would fail the statement.
17
+ jsonNumber: (column, keys) => `(CASE WHEN json_typeof(${column}::json #> ${path(keys)}) = 'number' THEN (${column}::json #>> ${path(keys)})::numeric END)`,
15
18
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
16
19
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each_text(${column}::json) AS entry(key, value) WHERE entry.key = ? AND entry.value = ?)`,
17
20
  jsonArrayLength: (column) => `json_array_length(${column}::json)`,
@@ -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;
@@ -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
@@ -81,6 +81,12 @@ export function diskUpgrade(runColumns) {
81
81
  * 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
82
  * RUNS_LABELS is (a trigger made before reads as no package's). */
83
83
  export const TRIGGERS_TEMPLATE_ID = "ALTER TABLE triggers ADD COLUMN template_id TEXT";
84
+ /** A run's census (RunLaunchRow.census, run-census.ts): in STORE_DDL, and added at a server open to a store an earlier
85
+ * build of this version made, as RUNS_LABELS is (a run ended before reads as never handed a secret). */
86
+ export const RUN_LAUNCH_CENSUS = `ALTER TABLE run_launch ADD COLUMN ${json("census", true)}`;
87
+ /** Every launch holding sealed bytes when the census was added (RUN_LAUNCH_CENSUS) marked CENSUS_PENDING (store.ts): its
88
+ * end counts them, or its files read as uncounted. */
89
+ export const RUN_LAUNCH_CENSUS_PENDING = `UPDATE run_launch SET census = '"pending"' WHERE sealed IS NOT NULL AND census IS NULL`;
84
90
  /** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
85
91
  * source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
86
92
  * (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
@@ -749,11 +755,15 @@ export const STORE_DDL = [
749
755
  // 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
756
  // written in the same transaction as the queued run, never after. `body` is the launch JSON (run-launch.ts: the first
751
757
  // 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.
758
+ // the server's key outside the store (AAD run_launch|<run_id>|sealed), or null when the launch holds none. `census` is
759
+ // null when the launch never held any; "pending" from when it first does until an end counts them; then where in the
760
+ // run's files they sat when that end erased them (run-census.ts), never the secrets, or "unscanned" when it erased them
761
+ // with no census made under them (store.ts CENSUS_PENDING, CENSUS_UNSCANNED).
753
762
  `CREATE TABLE IF NOT EXISTS run_launch (
754
763
  run_id TEXT PRIMARY KEY REFERENCES runs (id),
755
764
  ${json("body")},
756
765
  sealed BLOB,
766
+ ${json("census", true)},
757
767
  created_at INTEGER NOT NULL
758
768
  ) STRICT`,
759
769
  // 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. */
@@ -69,4 +69,4 @@ export declare const reopenableWhere: (d: Dialect) => string;
69
69
  * 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
70
  * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
71
71
  * 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>;
72
+ 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,7 +3,7 @@
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";
@@ -128,7 +128,7 @@ export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AN
128
128
  * 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
129
  * message waiting (the run read as going on from it, as a completed run a message opens again) is a cancel, waiting or
130
130
  * 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) {
131
+ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, keepsEnd = false, census) {
132
132
  if (state !== "ended" && state !== "stopped" && state !== "failed")
133
133
  return;
134
134
  // A cancel the API accepted (202, not refused) promised a cancelled run, and the view reads cancelled from that 202 on.
@@ -146,7 +146,7 @@ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, k
146
146
  if (won) {
147
147
  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
148
  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);
149
+ await eraseLaunchSecrets(tx, runId, census);
150
150
  return;
151
151
  }
152
152
  }
@@ -161,5 +161,14 @@ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE, k
161
161
  await tx.run(`UPDATE commands SET taken_at = ?, refused = ?, ${settledBody(dialect)} WHERE run_id = ? AND taken_at IS NULL`, now, endedReason(state), runId);
162
162
  // The run is over: the secrets its launch held for its life go with this same commit. A message that opens it again
163
163
  // hands its own (runs.reopen).
164
- await tx.run("UPDATE run_launch SET sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", runId);
164
+ await eraseLaunchSecrets(tx, runId, census);
165
+ }
166
+ /** A final run's launch secrets erased, in its end's commit, and what that end knew of where they sat written in their
167
+ * place: `census` when it was made under the sealed bytes erased here, else CENSUS_UNSCANNED (an end with none, or one
168
+ * whose launch a message sealed anew after the census read it). A launch with no sealed bytes is left as it is: its
169
+ * census, if any, is the end's that erased them. */
170
+ async function eraseLaunchSecrets(tx, runId, census) {
171
+ if (census)
172
+ await tx.run("UPDATE run_launch SET census = ?, sealed = NULL WHERE run_id = ? AND sealed = ?", census.json, runId, census.sealed);
173
+ await tx.run("UPDATE run_launch SET census = ?, sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", CENSUS_UNSCANNED, runId);
165
174
  }
@@ -12,8 +12,8 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
- import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
- import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUN_LAUNCH_CENSUS, RUN_LAUNCH_CENSUS_PENDING, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
+ import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, FiringMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, KEPT_PREFIX, RUNNER_ROWS_KEPT_MS, RUNNER_STALE_MS, tombstoneMetrics, } from "../store.js";
17
17
  /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
18
  const madeOf = (body) => {
19
19
  for (const link of ["replay", "audit"]) {
@@ -132,17 +132,44 @@ const lockCommandsOf = (tx, runId) => tx.dialect.lockKey(tx, `commands:${runId}`
132
132
  * its claim run out, once its backoff (an interrupted run's) has passed; parked, once no claim holds it (a run parks
133
133
  * under its claim and is released a few seconds later), with its wake_at passed, an untaken stop or cancel, or an untaken command
134
134
  * that can answer it once its backoff (a failed resume's) has passed. A row marked `answers: false` (a trigger's
135
- * follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run. */
136
- const claimableIn = (d, n) => ({
137
- sql: `(state = 'queued'
135
+ * follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run.
136
+ * With `claimer` (a claim's runner), a parked run whose computer is pinned to another runner (keptElsewhere) is left
137
+ * out while only its wake or an answering command makes it claimable; without it (a count of what waits) it is in.
138
+ * An untaken stop or cancel row is its own branch, outside the pin: a person's stop never waits on a pin, and any
139
+ * runner claims the run at once to end it (runner.ts claimMore ends it without a loop, never taking the kept machine).
140
+ * The SQL tells the branches apart by place: the stop/cancel EXISTS is OR'ed beside a parenthesis holding the wake and
141
+ * the answer, and only that parenthesis carries `AND NOT keptElsewhere`. */
142
+ const claimableIn = (d, n, claimer) => {
143
+ const pin = claimer === undefined ? undefined : keptElsewhere(d, n, claimer);
144
+ return {
145
+ sql: `(state = 'queued'
138
146
  OR (state = 'running' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (backoff_until IS NULL OR backoff_until <= ${n.sql}))
139
147
  OR (state = 'parked' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (
140
- (wake_at IS NOT NULL AND wake_at <= ${n.sql})
141
- OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
142
- OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
143
- AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))))`,
144
- params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
145
- });
148
+ EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
149
+ OR (((wake_at IS NOT NULL AND wake_at <= ${n.sql})
150
+ OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
151
+ AND ${d.jsonNotFalse(readableJson(d, "commands.body"), ["answers"])})))${pin ? `
152
+ AND NOT ${pin.sql}` : ""}))))`,
153
+ params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params, ...(pin?.params ?? [])],
154
+ };
155
+ };
156
+ /** The run's computer is kept at its park (its KEPT_PREFIX row) pinned to a runner other than `claimer` that is still
157
+ * there under the incarnation the row names, at the deadlines' clock `n`: its runners row seen within RUNNER_STALE_MS,
158
+ * claiming (refused NULL); the keep neither ending nor ended, and its `until` ahead. That runner's Docker engine or
159
+ * attach hub holds the machine, so only it can take it back (workspace/computer-kept.ts pinnedOf); once any of these
160
+ * stops holding, any runner claims the run. Read in the claim's own statement, so no check-then-act gap. A row with no
161
+ * runner (a computer any runner reaches: an exec vendor's, a phone; or one an earlier build kept) pins nothing. */
162
+ const keptElsewhere = (d, n, claimer) => {
163
+ const value = readableJson(d, "kept.value");
164
+ const field = (name) => d.jsonText(value, [name]);
165
+ return {
166
+ sql: `EXISTS (SELECT 1 FROM settings kept JOIN runners pin ON pin.runner = ${field("runner")}
167
+ WHERE kept.key = '${KEPT_PREFIX}' || runs.id AND pin.runner <> ? AND pin.incarnation = ${field("incarnation")} AND pin.refused IS NULL
168
+ AND pin.seen_at >= ${n.sql} - ${d.bigintParam} AND ${field("ending")} IS NULL AND ${field("ended")} IS NULL
169
+ AND ${d.jsonNumber(value, ["until"])} > ${n.sql})`,
170
+ params: [claimer, ...n.params, RUNNER_STALE_MS, ...n.params],
171
+ };
172
+ };
146
173
  /** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
147
174
  * no backoff. Binds the runner, `n`'s parameters, then the lease. */
148
175
  const claimSet = (n) => `epoch = epoch + 1, runner = ?, claimed_until = ${n.sql} + ?, state = 'running', backoff_until = NULL`;
@@ -248,6 +275,7 @@ export const SQLITE_RUNNER_NEEDS = [
248
275
  { table: "settings", columns: ["connector_id"], why: "add native command ownership metadata" },
249
276
  { table: "runs", columns: ["cost_upper_bound"], why: "add the bound beside each run's cost" },
250
277
  { table: "runs", columns: ["labels"], why: "add each run's labels" },
278
+ { table: "run_launch", columns: ["census"], why: "add each run's census" },
251
279
  { table: "triggers", columns: ["template_id"], why: "add each trigger's package mark" },
252
280
  { table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
253
281
  { table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
@@ -426,6 +454,14 @@ export async function openSqliteStore(options) {
426
454
  throw new StoreAwaitsServer("add each run's labels");
427
455
  await connection.write([{ sql: RUNS_LABELS }], { full: true });
428
456
  }
457
+ // An earlier build of this version kept no census on a run's launch (schema.ts RUN_LAUNCH_CENSUS): the server adds the
458
+ // column, nullable, every run ended before reading as never handed a secret, and marks each launch that holds one now
459
+ // as pending (store.ts CENSUS_PENDING). A runner writes it at each end, so it waits for that server.
460
+ if (!(await connection.all("SELECT name FROM pragma_table_info('run_launch')")).some((column) => column.name === "census")) {
461
+ if (role === "runner")
462
+ throw new StoreAwaitsServer("add each run's census");
463
+ await connection.write([{ sql: RUN_LAUNCH_CENSUS }, { sql: RUN_LAUNCH_CENSUS_PENDING }], { full: true });
464
+ }
429
465
  // An earlier build of this version kept no package mark on a trigger (schema.ts TRIGGERS_TEMPLATE_ID): the server adds
430
466
  // the column, nullable, every trigger made before reading as no package's. A runner reads each trigger through it, so
431
467
  // it waits for that server.
@@ -680,6 +716,8 @@ class SqliteStore {
680
716
  where;
681
717
  /** The deadlines' clock now (fence.ts storeNow): the database's on Postgres, this store's clock bound on SQLite. */
682
718
  #clock;
719
+ /** Store.leaseClock: this store's clock when the deadlines are stamped on it (no database clock: SQLite, or a test's). */
720
+ leaseClock;
683
721
  /** Each claim's one journal, until it is closed. */
684
722
  #journals = new Map();
685
723
  /** Each run's claim this store released last (its epoch): journal() refuses that claim, or an older one, rather than
@@ -703,6 +741,8 @@ class SqliteStore {
703
741
  const d = db.dialect;
704
742
  const clock = () => storeNow(d, now);
705
743
  this.#clock = clock;
744
+ if (!d.nowSql)
745
+ this.leaseClock = now;
706
746
  const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
707
747
  /** Agent `agentId`'s row, held (a writer's row lock, as its purge takes it), or undefined when there is none; refused
708
748
  * (AgentPurged) once it is purged: a write that waited on the purge's lock reads its purge time, and one that took the
@@ -1060,6 +1100,8 @@ class SqliteStore {
1060
1100
  return undefined;
1061
1101
  if (change.startByWas !== undefined && !(was.status === "sent" && was.run_id === null && was.retry_at === change.startByWas))
1062
1102
  return undefined;
1103
+ if (change.noRun && was.run_id !== null)
1104
+ return undefined;
1063
1105
  const settled = change.status !== undefined && change.status !== "due";
1064
1106
  // Out of due, a firing keeps no retry, wait, payload or attrs (unless keepAttrs), nor the reason its last try gave
1065
1107
  // (unless it gives one). One exception: a sent firing keeps its startBy in retry_at (firingOf reads it back as
@@ -1225,8 +1267,21 @@ class SqliteStore {
1225
1267
  return runOf(row);
1226
1268
  })),
1227
1269
  };
1270
+ /** Firing `firing` started with run `runId`, in the run's own transaction, under its trigger's row lock (as settle
1271
+ * takes it): only while it has no run and is due, or sent with a start_by (its host took it); else FiringMoved,
1272
+ * which rolls the run back. Its trigger's last run and failure streak move as a started firing's do (settle). */
1273
+ const startFiring = async (tx, { triggerId, key }, runId, at) => {
1274
+ await d.lockRow(tx, "triggers", "id", triggerId);
1275
+ const moved = await tx.runCounted("UPDATE trigger_firings SET status = 'started', run_id = ?, retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, reason = NULL, attempts = 0 WHERE trigger_id = ? AND key = ? AND run_id IS NULL AND (status = 'due' OR (status = 'sent' AND retry_at IS NOT NULL))", runId, triggerId, key);
1276
+ if (moved === 0)
1277
+ throw new FiringMoved(triggerId, key);
1278
+ const trigger = await tx.get("SELECT last_run_id FROM triggers WHERE id = ?", triggerId);
1279
+ // Run ids are UUIDv7s, sorted by when the run started: an older run never takes a later one's place (settle).
1280
+ const last = trigger?.last_run_id && trigger.last_run_id > runId ? trigger.last_run_id : runId;
1281
+ await tx.run("UPDATE triggers SET last_run_id = ?, failures_in_a_row = 0, updated_at = ? WHERE id = ?", last, at, triggerId);
1282
+ };
1228
1283
  this.runs = {
1229
- create: async ({ id, agentId, revisionId, origin, labels, expectedCurrent, settingsGuards, startedAt }, launch) => {
1284
+ create: async ({ id, agentId, revisionId, origin, labels, expectedCurrent, settingsGuards, startedAt, firing }, launch) => {
1230
1285
  // sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
1231
1286
  const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
1232
1287
  const labelled = labelsColumn(labels);
@@ -1252,6 +1307,8 @@ class SqliteStore {
1252
1307
  await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
1253
1308
  if (launch)
1254
1309
  await writeLaunch(tx, id, launch, at);
1310
+ if (firing)
1311
+ await startFiring(tx, firing, id, at);
1255
1312
  return runOf(row);
1256
1313
  }));
1257
1314
  },
@@ -1532,8 +1589,9 @@ class SqliteStore {
1532
1589
  const [result] = await db.write([{ sql: `UPDATE runs SET wake_at = ${n.sql} WHERE id = ? AND state = 'parked' RETURNING id`, params: [...n.params, runId] }]);
1533
1590
  return (result?.rows.length ?? 0) > 0;
1534
1591
  },
1535
- claimable: async ({ limit } = {}) => {
1536
- const claimable = claimableIn(d, clock());
1592
+ claimable: async ({ limit, runner } = {}) => {
1593
+ // The claimer's name, where it is a claimer's read (a runner's memory path): a run pinned to another runner is not its.
1594
+ const claimable = claimableIn(d, clock(), runner);
1537
1595
  const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
1538
1596
  const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
1539
1597
  return rows.map((row) => row.id);
@@ -1588,7 +1646,7 @@ class SqliteStore {
1588
1646
  }
1589
1647
  }
1590
1648
  // An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
1591
- await refuseLeftovers(tx, claim.runId, patch.state, at, d, patch.keepsEnd === true);
1649
+ await refuseLeftovers(tx, claim.runId, patch.state, at, d, patch.keepsEnd === true, patch.census);
1592
1650
  // The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
1593
1651
  // SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
1594
1652
  // or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
@@ -2473,7 +2531,9 @@ class SqliteStore {
2473
2531
  // The clock is read once the transaction holds the writer lock: a claim that waited for another writer runs its
2474
2532
  // lease from now, never comes back already run out. The deadlines' clock (the database's on Postgres) both judges what
2475
2533
  // is claimable and stamps the lease, which comes back from the row.
2476
- const claimable = claimableIn(this.#db.dialect, this.#clock());
2534
+ // A run whose computer is kept for another runner still there is never picked: no claim, no epoch moved, nothing
2535
+ // given back (keptElsewhere).
2536
+ const claimable = claimableIn(this.#db.dialect, this.#clock(), runner);
2477
2537
  // With many claimers (Postgres), the rows picked are locked as they are read. A poll over many (claimMany) skips a
2478
2538
  // row another claimer holds (Dialect.claimLock): two claims never pick one run, and neither waits for the other. A
2479
2539
  // claim of one named run waits for a write in flight on its row (Dialect.claimOneLock), then reads it as it is: a