@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -1,6 +1,6 @@
1
- export { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
- export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRelayRow, RunnerRelays, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, 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, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
- export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type RunMcpAuth, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
1
+ export { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, 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, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
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";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
6
6
  export { DDL, PI_DDL, PI_TABLE, PI_TABLES, SCHEMA_VERSION, STORE_DDL } from "./schema.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 { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } from "./store.js";
2
+ export { AgentArchived, AgentDeleting, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft } 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";
@@ -0,0 +1,18 @@
1
+ -- The store's schema on Postgres, version 20: each runner's word that it is there (runner/presence.ts) and its relay
2
+ -- (dial-relay.ts) in one table, as store/schema.ts keeps it on SQLite (RUNNERS). Applied once, after 0019, inside the
3
+ -- transaction migrate.ts opens. Never edit this file once applied: a change is a new file.
4
+ --
5
+ -- runners (runner_relays until now): one row per runner, beside a server or in a process of its own: its name, its
6
+ -- incarnation (its process since its start, the one its relay's minted tokens and proofs name), why it refused to claim
7
+ -- any run (`refused`, its words; null for a runner that claims), where its relay's attach listener answers (`host` and
8
+ -- `port`; null for a runner with no relay) and when it last said it was there. The server reads them for whether any
9
+ -- runner here can take a run, and where to relay a dial. In place: every relay's row is kept, refusing nothing, and
10
+ -- reads as gone 30 s after its last renewal, as any runner's row does.
11
+
12
+ ALTER TABLE runner_relays RENAME TO runners;
13
+ ALTER TABLE runners RENAME CONSTRAINT runner_relays_pkey TO runners_pkey;
14
+ ALTER TABLE runners ALTER COLUMN host DROP NOT NULL;
15
+ ALTER TABLE runners ALTER COLUMN port DROP NOT NULL;
16
+ ALTER TABLE runners ADD COLUMN refused TEXT;
17
+
18
+ UPDATE store_meta SET schema_version = 20 WHERE singleton = 1;
@@ -44,5 +44,5 @@ export interface PostgresStoreOptions {
44
44
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
45
45
  * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
46
46
  * clock is far from the database's. Either refuses a schema version this build does not know (SchemaVersionUnknown), a
47
- * runner also a schema not set up yet. */
47
+ * runner also a schema not set up yet, and one this build's server has yet to migrate (StoreAwaitsServer). */
48
48
  export declare function openPostgresStore(options: PostgresStoreOptions): Promise<Store>;
@@ -1,7 +1,7 @@
1
1
  // The Store on Postgres: the same domain code as SQLite's (sqlite/store.ts storeOver) over a Postgres connection
2
2
  // (connection.ts) in the store's own schema (default "agentrun"). The server sets the schema up (migrate.ts) and holds the
3
3
  // owner lock, one server per schema; runners are many, set nothing up, and refuse a schema version they do not know.
4
- import { SchemaVersionUnknown } from "../store.js";
4
+ import { SchemaVersionUnknown, StoreAwaitsServer } from "../store.js";
5
5
  import { backfillNativeCommandOwners } from '../native-command-owner.js';
6
6
  import { storeOver } from "../sqlite/store.js";
7
7
  import { PgConnection, SCHEMA_NAME } from "./connection.js";
@@ -15,7 +15,7 @@ export { postgresWhere } from "./connection.js";
15
15
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
16
16
  * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
17
17
  * clock is far from the database's. Either refuses a schema version this build does not know (SchemaVersionUnknown), a
18
- * runner also a schema not set up yet. */
18
+ * runner also a schema not set up yet, and one this build's server has yet to migrate (StoreAwaitsServer). */
19
19
  export async function openPostgresStore(options) {
20
20
  const schema = options.schema ?? DEFAULT_SCHEMA;
21
21
  if (!SCHEMA_NAME.test(schema))
@@ -42,6 +42,8 @@ export async function openPostgresStore(options) {
42
42
  });
43
43
  try {
44
44
  const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
45
+ if (role === "runner" && found !== null && found < known)
46
+ throw new StoreAwaitsServer(`bring this store from version ${found} to ${known}`);
45
47
  if (found !== known)
46
48
  throw new SchemaVersionUnknown(placeOf(schema), found, known);
47
49
  if (role === "server")
@@ -40,12 +40,20 @@ export declare const IMPORTED_TEMPLATES: string;
40
40
  * end its wait; null while none was, and again at a mint. In STORE_DDL, and added at a server open to a store an earlier
41
41
  * build of this version made. */
42
42
  export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (\n machine TEXT PRIMARY KEY,\n token_sha256 TEXT NOT NULL UNIQUE,\n kind TEXT NOT NULL,\n os TEXT NOT NULL,\n arch TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL,\n runner TEXT,\n incarnation TEXT,\n run TEXT,\n refused TEXT\n ) STRICT";
43
- /** Where each runner in a process of its own takes the dials the server relays to it (version 13, dial-relay.ts): its
44
- * attach listener's host and port under its name, with its incarnation and when it last said it was there. */
45
- export declare const RUNNER_RELAYS = "CREATE TABLE IF NOT EXISTS runner_relays (\n runner TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n host TEXT NOT NULL,\n port INTEGER NOT NULL,\n seen_at INTEGER NOT NULL\n ) STRICT";
43
+ /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
44
+ * its name, its incarnation (its process since its start, the one its relay's minted tokens and proofs name), why it
45
+ * refused to claim any run (`refused`, its words; null for one that claims), where its relay's attach listener takes the
46
+ * dials the server relays to it (`host` and `port`, dial-relay.ts; null for a runner with no relay) and when it last said
47
+ * it was there. The server reads them for whether any runner here can take a run (a launch's 503 runner_refused,
48
+ * capabilities' runner_refused, health's runner check) and where to relay a dial (computer-attach.ts liveRelays). In
49
+ * STORE_DDL. A store an earlier build of version 13 made kept the relays in a table of their own (runner_relays): the
50
+ * server's open drops it and makes this one (sqlite/store.ts), as it drops browser_viewers, with no version: the rows
51
+ * are heartbeats renewed every 10 s, so none is copied, and a runner waits for that server (StoreAwaitsServer). */
52
+ export declare const RUNNERS = "CREATE TABLE IF NOT EXISTS runners (\n runner TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n refused TEXT,\n host TEXT,\n port INTEGER,\n seen_at INTEGER NOT NULL\n ) STRICT";
46
53
  /** Version 12 → 13 on SQLite (the server's open, sqlite/store.ts), given minted_tokens' columns now: the minting runner,
47
54
  * its incarnation, the machine's run and a refused relay's words on each token's row (none of the rows there has one: the
48
- * server's own process minted them, naming no run), the runners' relays, and the version, in one durable write. */
55
+ * server's own process minted them, naming no run), the runners (where their relays answer), and the version, in one
56
+ * durable write. */
49
57
  export declare function relayUpgrade(mintedColumns: ReadonlySet<string>): readonly string[];
50
58
  /** A run's listing on its row (version 12): what a runs list shows of the run, so a list reads rows alone and never builds
51
59
  * a run's view. `list_mark` moves (+1) in the transaction of every write that can change what the run's view shows: its
@@ -56,7 +64,7 @@ export declare function relayUpgrade(mintedColumns: ReadonlySet<string>): readon
56
64
  * that lands meanwhile keeps the row as it left it (its list_status too), behind (listing_mark < list_mark), and it is
57
65
  * built again: a crash between a write and its listing leaves a row that says
58
66
  * it is behind, never one that says it is current. `listing` is the list item without the parts read when it is listed
59
- * (console_url, archived_at); `list_status` its status, which a status filter reads in SQL; `listing_live` whether a runner
67
+ * (console_url, archived_at), with the secrets it was cut of (a list builds one cut of other secrets again: store-view.ts builtOfNow); `list_status` its status, which a status filter reads in SQL; `listing_live` whether a runner
60
68
  * held the run when it was built (its status reads otherwise once that claim runs out); `listing_until` when it goes stale
61
69
  * by the clock alone (an ask that expires, or the retry of a build that withheld the run for a sign-in it could not read
62
70
  * back); `listing_flags` what outside the run it read (LISTING_HELD: learning held for
@@ -18,7 +18,7 @@
18
18
  // The template packages imported from GitHub (imported_templates) are a table of their own that nothing
19
19
  // else reads, so it needs no version: the server adds it at its open to a store an earlier build of this version made
20
20
  // (IMPORTED_TEMPLATES), as it does the one-answer index. A hosted machine's minted token (minted_tokens, MINTED_TOKENS) is
21
- // added the same way.
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
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
23
23
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
24
24
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -32,7 +32,7 @@
32
32
  // Version 12 keeps each run's listing on its row (RUN_LISTING_COLUMNS): what a runs list shows of it, so a list reads rows
33
33
  // alone. Version 13 names the runner in a process of its own that minted a hosted machine's token (minted_tokens.runner,
34
34
  // .incarnation), the run the machine works for (.run), why the server refused to relay its dial (.refused), and where each
35
- // such runner takes the dials the server relays to it (runner_relays, dial-relay.ts). The server upgrades these two in place at its open (listingUpgrade from 11, then relayUpgrade from 12); a runner waits for it.
35
+ // such runner takes the dials the server relays to it (runners.host and .port, dial-relay.ts). The server upgrades these two in place at its open (listingUpgrade from 11, then relayUpgrade from 12); a runner waits for it.
36
36
  export const SCHEMA_VERSION = 13;
37
37
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
38
38
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
@@ -100,22 +100,31 @@ export const MINTED_TOKENS = `CREATE TABLE IF NOT EXISTS minted_tokens (
100
100
  run TEXT,
101
101
  refused TEXT
102
102
  ) STRICT`;
103
- /** Where each runner in a process of its own takes the dials the server relays to it (version 13, dial-relay.ts): its
104
- * attach listener's host and port under its name, with its incarnation and when it last said it was there. */
105
- export const RUNNER_RELAYS = `CREATE TABLE IF NOT EXISTS runner_relays (
103
+ /** Each runner's word that it is there (runner/presence.ts), every runner's, beside a server or in a process of its own:
104
+ * its name, its incarnation (its process since its start, the one its relay's minted tokens and proofs name), why it
105
+ * refused to claim any run (`refused`, its words; null for one that claims), where its relay's attach listener takes the
106
+ * dials the server relays to it (`host` and `port`, dial-relay.ts; null for a runner with no relay) and when it last said
107
+ * it was there. The server reads them for whether any runner here can take a run (a launch's 503 runner_refused,
108
+ * capabilities' runner_refused, health's runner check) and where to relay a dial (computer-attach.ts liveRelays). In
109
+ * STORE_DDL. A store an earlier build of version 13 made kept the relays in a table of their own (runner_relays): the
110
+ * server's open drops it and makes this one (sqlite/store.ts), as it drops browser_viewers, with no version: the rows
111
+ * are heartbeats renewed every 10 s, so none is copied, and a runner waits for that server (StoreAwaitsServer). */
112
+ export const RUNNERS = `CREATE TABLE IF NOT EXISTS runners (
106
113
  runner TEXT PRIMARY KEY,
107
114
  incarnation TEXT NOT NULL,
108
- host TEXT NOT NULL,
109
- port INTEGER NOT NULL,
115
+ refused TEXT,
116
+ host TEXT,
117
+ port INTEGER,
110
118
  seen_at INTEGER NOT NULL
111
119
  ) STRICT`;
112
120
  /** Version 12 → 13 on SQLite (the server's open, sqlite/store.ts), given minted_tokens' columns now: the minting runner,
113
121
  * its incarnation, the machine's run and a refused relay's words on each token's row (none of the rows there has one: the
114
- * server's own process minted them, naming no run), the runners' relays, and the version, in one durable write. */
122
+ * server's own process minted them, naming no run), the runners (where their relays answer), and the version, in one
123
+ * durable write. */
115
124
  export function relayUpgrade(mintedColumns) {
116
125
  return [
117
126
  ...["runner", "incarnation", "run", "refused"].filter((column) => !mintedColumns.has(column)).map((column) => `ALTER TABLE minted_tokens ADD COLUMN ${column} TEXT`),
118
- RUNNER_RELAYS,
127
+ RUNNERS,
119
128
  "UPDATE store_meta SET schema_version = 13 WHERE singleton = 1",
120
129
  ];
121
130
  }
@@ -128,7 +137,7 @@ export function relayUpgrade(mintedColumns) {
128
137
  * that lands meanwhile keeps the row as it left it (its list_status too), behind (listing_mark < list_mark), and it is
129
138
  * built again: a crash between a write and its listing leaves a row that says
130
139
  * it is behind, never one that says it is current. `listing` is the list item without the parts read when it is listed
131
- * (console_url, archived_at); `list_status` its status, which a status filter reads in SQL; `listing_live` whether a runner
140
+ * (console_url, archived_at), with the secrets it was cut of (a list builds one cut of other secrets again: store-view.ts builtOfNow); `list_status` its status, which a status filter reads in SQL; `listing_live` whether a runner
132
141
  * held the run when it was built (its status reads otherwise once that claim runs out); `listing_until` when it goes stale
133
142
  * by the clock alone (an ask that expires, or the retry of a build that withheld the run for a sign-in it could not read
134
143
  * back); `listing_flags` what outside the run it read (LISTING_HELD: learning held for
@@ -538,7 +547,7 @@ export const STORE_DDL = [
538
547
  ) STRICT`,
539
548
  IMPORTED_TEMPLATES,
540
549
  MINTED_TOKENS,
541
- RUNNER_RELAYS,
550
+ RUNNERS,
542
551
  // An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
543
552
  // pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
544
553
  // sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
@@ -49,12 +49,24 @@ export declare function openMcpCredential(key: Buffer, row: {
49
49
  readonly url: string;
50
50
  readonly sealed: Uint8Array | null;
51
51
  }): OpenedMcpCredential;
52
- /** The MCP credentials a run's caller handed it (`mcp_auth` at its start or with a message), by server name: each one's
53
- * headers and the origin of the server's url when it was handed, so a server moved since never receives them. */
54
- export type RunMcpAuth = Readonly<Record<string, {
52
+ /** A run's binding of a per-run Composio server: the Composio user its calls run as, and the connected account when the
53
+ * caller names one. Never kept on the server's row: sealed in the run's launch alone. */
54
+ export type ComposioBinding = {
55
+ readonly user_id: string;
56
+ readonly connected_account_id?: string;
57
+ };
58
+ /** What a run's caller handed one MCP server (`mcp_auth.<server>`): a per_run server's headers, or a per-run Composio
59
+ * server's binding (its key stays the server's own); each with the origin of the server's url when it was handed, so a
60
+ * server moved since never receives them. */
61
+ export type RunMcpEntry = ({
55
62
  readonly headers: Readonly<Record<string, string>>;
63
+ } | {
64
+ readonly composio: ComposioBinding;
65
+ }) & {
56
66
  readonly origin: string;
57
- }>>;
67
+ };
68
+ /** The MCP credentials a run's caller handed it (`mcp_auth` at its start or with a message), by server name. */
69
+ export type RunMcpAuth = Readonly<Record<string, RunMcpEntry>>;
58
70
  /** A run's own model key (`model_key` at its start or with a message): the key its model requests carry, and the origin
59
71
  * of the gateway it was handed for (AGENT_MODEL_BASE_URL's then), so a gateway moved since never receives it. */
60
72
  export type RunModelKey = {
@@ -26,7 +26,7 @@ export type SqliteStoreOptions = (
26
26
  * default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
27
27
  * no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
28
28
  * refuses a schema version this build does not know (SchemaVersionUnknown); a runner refuses no schema (or no data
29
- * directory) too. */
29
+ * directory) too, and a store this build's server has yet to upgrade (StoreAwaitsServer). */
30
30
  export declare function openSqliteStore(options: SqliteStoreOptions): Promise<Store>;
31
31
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
32
32
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
@@ -11,8 +11,9 @@ import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } fro
11
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { RunStorage } from "../journal/storage.js";
14
- import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
15
- import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
14
+ import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
+ import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
+ import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, } from "../store.js";
16
17
  /** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
17
18
  const seqOf = (cursor) => {
18
19
  if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
@@ -72,6 +73,9 @@ const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, pac
72
73
  const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
73
74
  const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
74
75
  const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
76
+ /** An ended run, not imported, whose stored cost is unknown: null with no bound beside it (cost_upper_bound 0, never NULL).
77
+ * What Runs.healCost writes over and Runs.costUnknown lists. */
78
+ const COST_UNKNOWN = `cost_usd IS NULL AND cost_upper_bound = 0 AND state IN (${FINAL}) AND imported_from IS NULL AND ended_at IS NOT NULL`;
75
79
  /** Taken (Dialect.lockKey) by every insert of a run's command row, before it: the run's rows commit in id order, as
76
80
  * SQLite's one writer commits them. On Postgres an id is taken at the insert and the row is seen at its commit, so two
77
81
  * inserts at once could commit out of order, and a reader of the rows past the last id it handed on (the runner) would
@@ -158,7 +162,7 @@ const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), u
158
162
  const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
159
163
  const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
160
164
  const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at, runner: r.runner, incarnation: r.incarnation, run: r.run, refused: r.refused });
161
- const relayOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, host: r.host, port: Number(r.port), seenAt: Number(r.seen_at) });
165
+ const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at) });
162
166
  const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
163
167
  const mcpOauthOf = (r) => ({ state: r.state, server: r.server, sealed: Uint8Array.from(r.sealed), working: r.working === null ? null : JSON.parse(r.working), expiresAt: r.expires_at });
164
168
  const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
@@ -268,7 +272,7 @@ function isThisVersionsStore(file, busyTimeoutMs) {
268
272
  * default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
269
273
  * no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
270
274
  * refuses a schema version this build does not know (SchemaVersionUnknown); a runner refuses no schema (or no data
271
- * directory) too. */
275
+ * directory) too, and a store this build's server has yet to upgrade (StoreAwaitsServer). */
272
276
  export async function openSqliteStore(options) {
273
277
  // No in-memory store: a caller that names neither place (an undefined passed through) is refused before anything is
274
278
  // opened or made, never left to open a path built from "undefined" (its owner lock in the working directory).
@@ -300,22 +304,22 @@ export async function openSqliteStore(options) {
300
304
  await connection.write([...DDL.map((sql) => ({ sql })), { sql: "INSERT INTO store_meta (singleton, schema_version) VALUES (1, ?) ON CONFLICT (singleton) DO NOTHING", params: [SCHEMA_VERSION] }], { full: true });
301
305
  found = await versionOf(connection);
302
306
  }
303
- // Version 11 (0.1.0-beta.43 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
307
+ // Version 11 (0.1.0-beta.44 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
304
308
  // in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
305
309
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
306
310
  // (schema.ts relayUpgrade). A runner refuses 11 and 12 until that server has.
307
311
  const upgrading = found === SCHEMA_VERSION - 2 || found === SCHEMA_VERSION - 1;
308
312
  if (upgrading && role === "runner")
309
- throw new Error(`Start the AgentRun server to bring this store from version ${found} to ${SCHEMA_VERSION} before opening a runner. The runner does not upgrade this store.`);
313
+ throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
310
314
  if (found !== SCHEMA_VERSION && !upgrading)
311
315
  throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
312
316
  const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
313
317
  if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
314
- throw new Error("Start the AgentRun server to install MCP and Monid revision metadata before opening a runner. The runner does not upgrade this store.");
318
+ throw new StoreAwaitsServer("install MCP and Monid revision metadata");
315
319
  const nativeOwners = (await connection.all("PRAGMA table_info(settings)")).some(column => column.name === 'connector_id');
316
320
  if (!nativeOwners) {
317
321
  if (role === 'runner')
318
- throw new Error('Native command ownership metadata is not prepared. Start this build’s server before its runners.');
322
+ throw new StoreAwaitsServer('add native command ownership metadata');
319
323
  await connection.write([{ sql: 'ALTER TABLE settings ADD COLUMN connector_id TEXT' }], { full: true });
320
324
  }
321
325
  // An earlier build of this version kept no bound beside a run's cost (schema.ts RUNS_COST_UPPER_BOUND): the server adds
@@ -323,14 +327,14 @@ export async function openSqliteStore(options) {
323
327
  const runColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
324
328
  if (!runColumns.has("cost_upper_bound")) {
325
329
  if (role === "runner")
326
- throw new Error("Start the AgentRun server to add the bound beside each run's cost before opening a runner. The runner does not upgrade this store.");
330
+ throw new StoreAwaitsServer("add the bound beside each run's cost");
327
331
  await connection.write([{ sql: RUNS_COST_UPPER_BOUND }], { full: true });
328
332
  }
329
333
  // An earlier build of this version kept no labels on a run (schema.ts RUNS_LABELS): the server adds the column, nullable,
330
334
  // every run it started reading as given none. A runner reads each run through it, so it waits for that server.
331
335
  if (!runColumns.has("labels")) {
332
336
  if (role === "runner")
333
- throw new Error("Start the AgentRun server to add each run's labels before opening a runner. The runner does not upgrade this store.");
337
+ throw new StoreAwaitsServer("add each run's labels");
334
338
  await connection.write([{ sql: RUNS_LABELS }], { full: true });
335
339
  }
336
340
  // An earlier build of this version kept no package mark on a trigger (schema.ts TRIGGERS_TEMPLATE_ID): the server adds
@@ -338,9 +342,15 @@ export async function openSqliteStore(options) {
338
342
  // it waits for that server.
339
343
  if (!(await connection.all("SELECT name FROM pragma_table_info('triggers')")).some((column) => column.name === "template_id")) {
340
344
  if (role === "runner")
341
- throw new Error("Start the AgentRun server to add each trigger's package mark before opening a runner. The runner does not upgrade this store.");
345
+ throw new StoreAwaitsServer("add each trigger's package mark");
342
346
  await connection.write([{ sql: TRIGGERS_TEMPLATE_ID }], { full: true });
343
347
  }
348
+ // An earlier build of version 13 kept each runner's relay in a table of its own (runner_relays), which the server's
349
+ // open below drops for runners (schema.ts RUNNERS). A runner says it is there, and where its relay answers, through
350
+ // runners alone, so it waits for that server.
351
+ if (role === "runner" && !(await connection.all("SELECT name FROM pragma_table_info('runners')")).some((column) => column.name === "host")) {
352
+ throw new StoreAwaitsServer("keep each runner's word that it is there and its relay in one table (runners)");
353
+ }
344
354
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
345
355
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
346
356
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -364,6 +374,10 @@ export async function openSqliteStore(options) {
364
374
  { sql: IMPORTED_TEMPLATES },
365
375
  // Nor any hosted machine's minted token (schema.ts MINTED_TOKENS).
366
376
  { sql: MINTED_TOKENS },
377
+ // Nor any runner's word that it is there (schema.ts RUNNERS), and it kept each runner's relay in runner_relays:
378
+ // dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
379
+ { sql: "DROP TABLE IF EXISTS runner_relays" },
380
+ { sql: RUNNERS },
367
381
  { sql: NATIVE_COMMANDS_INDEX },
368
382
  ], { full: true });
369
383
  await backfillNativeCommandOwners(connection);
@@ -484,7 +498,7 @@ class SqliteStore {
484
498
  computerLedger;
485
499
  pairedComputers;
486
500
  mintedTokens;
487
- runnerRelays;
501
+ runners;
488
502
  importedTemplates;
489
503
  triggerSettings;
490
504
  channels;
@@ -615,8 +629,13 @@ class SqliteStore {
615
629
  await writeScopes(tx, t.id, []);
616
630
  return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
617
631
  }),
618
- addRevision: async ({ agentId, ifCurrent, ...revision }) => {
619
- await db.transaction((tx) => insertRevision(tx, agentId, revision, now(), ifCurrent));
632
+ addRevision: async ({ agentId, ifCurrent, description, ...revision }) => {
633
+ await db.transaction(async (tx) => {
634
+ await insertRevision(tx, agentId, revision, now(), ifCurrent);
635
+ // Under the row lock insertRevision took, after its ifCurrent passed: the revision and the description, or neither.
636
+ if (description !== undefined)
637
+ await tx.run("UPDATE agents SET description = ? WHERE id = ?", description, agentId);
638
+ });
620
639
  },
621
640
  setCurrent: async (agentId, revisionId) => {
622
641
  const changed = await db.transaction((tx) => tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId));
@@ -1079,6 +1098,36 @@ class SqliteStore {
1079
1098
  const row = await db.get("SELECT list_mark FROM runs WHERE id = ?", runId);
1080
1099
  return row === undefined ? undefined : Number(row.list_mark);
1081
1100
  },
1101
+ // A heal of an ended run's unknown cost from its priced booking, as its end writes one (the bound beside the figure
1102
+ // with it, applyRunPatch): one conditional UPDATE, only over a null with no bound beside it (cost_upper_bound 0, the
1103
+ // column's no-bound value: it is never NULL), only at the end it was read at (a reopen or a later end moves ended_at
1104
+ // or the epoch), so it never overwrites a figure or a bound, whatever its caller read.
1105
+ healCost: async (runId, { epoch, endedAt }, { costUsd, costUpperBound }) => {
1106
+ if (!Number.isFinite(costUsd) || costUsd < 0)
1107
+ throw new TypeError(`a healed cost is a figure of $0 or more (got ${costUsd})`);
1108
+ const [result] = await db.write([{
1109
+ sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING id`,
1110
+ params: [costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt],
1111
+ }]);
1112
+ return (result?.rows.length ?? 0) > 0;
1113
+ },
1114
+ // The runs healCost may write that the heal's rule (store-view.ts bookedCostOf, healOf) does not refuse by its
1115
+ // columns alone, so the start sweep never reads one that cannot heal again at each start: left out are a person's
1116
+ // stop of an agentic run (it reads running, stoppedByPerson), an agentic run whose launch names a native connection
1117
+ // (its end reads its own cost; a launch whose `native` is no connection is one no runner could read, so it booked
1118
+ // nothing either), and a run whose journal holds no runner.turn (no request booked with an answer: no figure to heal
1119
+ // to). Kept, and read at each start while their cost stays null: runs with a booked request whose booking still
1120
+ // gives no figure (a charge of no known cost, every request given back). Telling them apart is the booking rule
1121
+ // itself (turnCostOf over each turn's data), which no column holds.
1122
+ costUnknown: async ({ limit, after }) => {
1123
+ const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
1124
+ const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
1125
+ AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
1126
+ AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${db.dialect.jsonText("run_launch.body", ["native"])} IS NOT NULL))
1127
+ AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${db.dialect.jsonText("entry.record", ["kind"])} = ?)
1128
+ ${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
1129
+ return rows.map((row) => row.id);
1130
+ },
1082
1131
  relist: async ({ flags, agentId }) => {
1083
1132
  const [result] = await db.write([{
1084
1133
  sql: `UPDATE runs SET list_mark = list_mark + 1 WHERE listing_flags <> 0 AND (listing_flags & ?) <> 0${agentId === undefined ? "" : " AND agent_id = ?"} RETURNING id`,
@@ -1165,6 +1214,30 @@ class SqliteStore {
1165
1214
  const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
1166
1215
  return rows.map((row) => row.id);
1167
1216
  },
1217
+ failUnclaimed: async (summary) => {
1218
+ // Queued is only ever written at a run's insert (epoch 0); a claim moves it to running and its epoch on. Each run
1219
+ // in a transaction of its own, fenced on that, so a claim that takes one meanwhile leaves it to its runner.
1220
+ const queued = await db.all("SELECT id FROM runs WHERE state = 'queued' AND epoch = 0 AND runner IS NULL ORDER BY started_at, id");
1221
+ const failed = [];
1222
+ for (const { id } of queued) {
1223
+ const ended = await db.transaction(async (tx) => {
1224
+ await d.lockRow(tx, "runs", "id", id, "update");
1225
+ const at = now();
1226
+ const n = storeNow(d, () => at);
1227
+ const row = await tx.get(`UPDATE runs SET state = 'failed', summary = ?, ended_at = ?, left_running_at = ${n.sql}, epoch = epoch + 1 WHERE id = ? AND state = 'queued' AND epoch = 0 AND runner IS NULL RETURNING id`, summary, at, ...n.params, id);
1228
+ if (!row)
1229
+ return false;
1230
+ // As an end does: its untaken commands refused, its launch's secrets erased, in this same commit.
1231
+ await refuseLeftovers(tx, id, "failed", at, d);
1232
+ return true;
1233
+ });
1234
+ if (!ended)
1235
+ continue;
1236
+ failed.push(id);
1237
+ wakeCommands(this.where, { runId: id, what: "answered" });
1238
+ }
1239
+ return failed;
1240
+ },
1168
1241
  heldAt: async (runId) => {
1169
1242
  const n = clock();
1170
1243
  const row = await db.get(`SELECT epoch FROM runs WHERE id = ? AND runner IS NOT NULL AND claimed_until >= ${n.sql}`, runId, ...n.params);
@@ -1635,25 +1708,36 @@ class SqliteStore {
1635
1708
  await db.write([{ sql: "UPDATE minted_tokens SET refused = ? WHERE token_sha256 = ?", params: [words, tokenSha256] }]);
1636
1709
  },
1637
1710
  };
1638
- const RELAYS = "SELECT runner, incarnation, host, port, seen_at FROM runner_relays";
1639
- this.runnerRelays = {
1640
- put: async ({ runner, incarnation, host, port }) => {
1641
- await db.write([{
1642
- sql: "INSERT INTO runner_relays (runner, incarnation, host, port, seen_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at",
1643
- params: [runner, incarnation, host, port, now()],
1644
- }]);
1711
+ // Stamped and judged on the deadlines' clock (fence.ts storeNow: the database's on Postgres), the one a claim's lease
1712
+ // runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
1713
+ const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
1714
+ this.runners = {
1715
+ put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
1716
+ const n = clock();
1717
+ // With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
1718
+ // statement: no read between, so a later process's put can never land between a look and this write.
1719
+ const unlessLive = unlessLiveMs === undefined ? "" : ` WHERE runners.incarnation = excluded.incarnation OR runners.seen_at < excluded.seen_at - ${d.bigintParam}`;
1720
+ const [, result] = await db.write([
1721
+ { sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
1722
+ {
1723
+ sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at${unlessLive}`,
1724
+ params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
1725
+ },
1726
+ ]);
1727
+ return (result?.changes ?? 0) === 1;
1645
1728
  },
1646
- seen: async (runner, incarnation) => {
1647
- const [result] = await db.write([{ sql: "UPDATE runner_relays SET seen_at = ? WHERE runner = ? AND incarnation = ?", params: [now(), runner, incarnation] }]);
1729
+ renew: async (runner, incarnation, at) => {
1730
+ const n = clock();
1731
+ const [result] = await db.write([{ sql: `UPDATE runners SET host = ?, port = ?, seen_at = ${n.sql} WHERE runner = ? AND incarnation = ?`, params: [at?.host ?? null, at?.port ?? null, ...n.params, runner, incarnation] }]);
1648
1732
  return (result?.changes ?? 0) === 1;
1649
1733
  },
1650
- get: async (runner) => {
1651
- const row = await db.get(`${RELAYS} WHERE runner = ?`, runner);
1652
- return row === undefined ? undefined : relayOf(row);
1734
+ list: async () => (await db.all(`${RUNNERS_SELECT} ORDER BY runner`)).map(runnerOf),
1735
+ live: async (staleMs) => {
1736
+ const n = clock();
1737
+ return (await db.all(`${RUNNERS_SELECT} WHERE seen_at >= ${n.sql} - ${d.bigintParam} ORDER BY runner`, ...n.params, staleMs)).map(runnerOf);
1653
1738
  },
1654
- list: async () => (await db.all(`${RELAYS} ORDER BY runner`)).map(relayOf),
1655
1739
  remove: async (runner, incarnation) => {
1656
- await db.write([{ sql: "DELETE FROM runner_relays WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
1740
+ await db.write([{ sql: "DELETE FROM runners WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
1657
1741
  },
1658
1742
  };
1659
1743
  this.importedTemplates = {