@parcha/agentrun-serve 0.1.0-beta.31 → 0.1.0-beta.32
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.
- package/CHANGELOG.md +422 -0
- package/NOTICE +18 -0
- package/README.md +887 -241
- package/dist/adapter-facts.d.ts +3 -0
- package/dist/adapter-facts.js +5 -0
- package/dist/adapters.d.ts +64 -140
- package/dist/adapters.js +153 -377
- package/dist/agents-store.d.ts +146 -0
- package/dist/agents-store.js +359 -0
- package/dist/agents.d.ts +5 -3
- package/dist/agents.js +37 -17
- package/dist/app.d.ts +2 -4
- package/dist/app.js +207 -92
- package/dist/approvals.d.ts +4 -0
- package/dist/approvals.js +7 -0
- package/dist/archil-routes.d.ts +45 -0
- package/dist/archil-routes.js +150 -0
- package/dist/archil-settings.d.ts +30 -0
- package/dist/archil-settings.js +34 -0
- package/dist/background.js +28 -9
- package/dist/bounds.d.ts +26 -0
- package/dist/bounds.js +137 -0
- package/dist/box-egress-vm.d.ts +2 -1
- package/dist/box-egress-vm.js +20 -6
- package/dist/box-egress.d.ts +16 -6
- package/dist/box-egress.js +27 -15
- package/dist/box-paths.d.ts +59 -0
- package/dist/box-paths.js +92 -0
- package/dist/box-relay-vm.js +28 -1
- package/dist/box-relay.d.ts +2 -0
- package/dist/box-relay.js +2 -2
- package/dist/boxes.d.ts +13 -1
- package/dist/boxes.js +37 -3
- package/dist/browser-commands.d.ts +43 -0
- package/dist/browser-commands.js +154 -0
- package/dist/browser-cost.d.ts +30 -3
- package/dist/browser-cost.js +276 -21
- package/dist/browser-live.d.ts +124 -0
- package/dist/browser-live.js +324 -0
- package/dist/browser-person.d.ts +168 -0
- package/dist/browser-person.js +769 -0
- package/dist/budget.d.ts +80 -0
- package/dist/budget.js +211 -0
- package/dist/cap.d.ts +272 -62
- package/dist/cap.js +599 -189
- package/dist/cli.js +201 -17
- package/dist/coding-tools.d.ts +13 -1
- package/dist/coding-tools.js +107 -5
- package/dist/computer-adb.d.ts +12 -0
- package/dist/computer-adb.js +14 -0
- package/dist/computer-commands.d.ts +103 -0
- package/dist/computer-commands.js +256 -0
- package/dist/computer-keys.d.ts +68 -0
- package/dist/computer-keys.js +148 -0
- package/dist/computer-routes.d.ts +38 -0
- package/dist/computer-routes.js +56 -0
- package/dist/computer-setting.d.ts +37 -0
- package/dist/computer-setting.js +47 -0
- package/dist/computer-view.d.ts +38 -0
- package/dist/computer-view.js +14 -0
- package/dist/computers.d.ts +137 -0
- package/dist/computers.js +197 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
- package/dist/console/assets/index-35-7aeIZ.js +519 -0
- package/dist/console/assets/index-Cejbov-Y.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +2 -0
- package/dist/console-links.js +6 -0
- package/dist/decision-cap.d.ts +63 -0
- package/dist/decision-cap.js +163 -0
- package/dist/decision-rows.d.ts +5 -2
- package/dist/decision-rows.js +8 -6
- package/dist/decisions.d.ts +28 -1
- package/dist/decisions.js +63 -6
- package/dist/disk.d.ts +33 -0
- package/dist/disk.js +85 -0
- package/dist/door-line.d.ts +23 -0
- package/dist/door-line.js +83 -0
- package/dist/egress-proxy.d.ts +45 -0
- package/dist/egress-proxy.js +416 -0
- package/dist/egress-table.d.ts +24 -0
- package/dist/egress-table.js +165 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +22 -2
- package/dist/exa-keyless.js +1 -1
- package/dist/explain.d.ts +22 -0
- package/dist/explain.js +207 -0
- package/dist/faux-computers.d.ts +35 -0
- package/dist/faux-computers.js +126 -0
- package/dist/file-types.d.ts +4 -0
- package/dist/file-types.js +11 -0
- package/dist/files.d.ts +3 -35
- package/dist/files.js +9 -120
- package/dist/github-connection.d.ts +207 -0
- package/dist/github-connection.js +595 -0
- package/dist/github.d.ts +64 -0
- package/dist/github.js +119 -0
- package/dist/grade.d.ts +9 -42
- package/dist/grade.js +42 -228
- package/dist/graph-served.d.ts +23 -2
- package/dist/graph-served.js +44 -3
- package/dist/graph-view.d.ts +7 -3
- package/dist/graph-view.js +26 -15
- package/dist/handed-values.d.ts +23 -0
- package/dist/handed-values.js +36 -0
- package/dist/harness-app.d.ts +33 -4
- package/dist/harness-app.js +530 -85
- package/dist/harness-install.d.ts +120 -0
- package/dist/harness-install.js +359 -0
- package/dist/harness-opencode/adapter.js +42 -8
- package/dist/harness-opencode/facts.d.ts +2 -0
- package/dist/harness-opencode/facts.js +28 -0
- package/dist/harness-opencode/harness.d.ts +4 -0
- package/dist/harness-opencode/harness.js +38 -5
- package/dist/harness-opencode/host/policy.js +11 -3
- package/dist/harness-opencode/transcript.d.ts +25 -0
- package/dist/harness-opencode/transcript.js +81 -0
- package/dist/harness-table.d.ts +75 -0
- package/dist/harness-table.js +145 -0
- package/dist/harness.d.ts +7 -28
- package/dist/harness.js +15 -41
- package/dist/heard.d.ts +12 -0
- package/dist/heard.js +45 -0
- package/dist/helper-env.d.ts +4 -0
- package/dist/helper-env.js +14 -0
- package/dist/home-path.d.ts +0 -4
- package/dist/home-path.js +3 -17
- package/dist/host-check.d.ts +4 -3
- package/dist/host-check.js +5 -4
- package/dist/host-tools.d.ts +51 -8
- package/dist/host-tools.js +108 -117
- package/dist/host.d.ts +12 -6
- package/dist/host.js +30 -24
- package/dist/hosted-search.d.ts +3 -0
- package/dist/hosted-search.js +5 -3
- package/dist/import-proxy.d.ts +42 -0
- package/dist/import-proxy.js +105 -0
- package/dist/import-summary.js +4 -8
- package/dist/import-worker.d.ts +2 -3
- package/dist/import-worker.js +18 -16
- package/dist/import.d.ts +37 -17
- package/dist/import.js +208 -222
- package/dist/key-meta.d.ts +26 -0
- package/dist/key-meta.js +30 -0
- package/dist/key-refusal.d.ts +4 -1
- package/dist/key-refusal.js +20 -7
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +2 -2
- package/dist/learn/commit.d.ts +86 -0
- package/dist/learn/commit.js +182 -0
- package/dist/learn/folder.d.ts +296 -0
- package/dist/learn/folder.js +796 -0
- package/dist/learn/grade.d.ts +22 -9
- package/dist/learn/grade.js +95 -49
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/learning.sh +366 -0
- package/dist/learn/reflect.d.ts +12 -5
- package/dist/learn/reflect.js +70 -41
- package/dist/learn/secrets.d.ts +15 -7
- package/dist/learn/secrets.js +66 -16
- package/dist/learn/seed-check.d.ts +74 -0
- package/dist/learn/seed-check.js +103 -0
- package/dist/learn/skills.d.ts +5 -1
- package/dist/learn/skills.js +5 -4
- package/dist/learned-workflow.d.ts +12 -2
- package/dist/learned-workflow.js +9 -5
- package/dist/learning-routes.d.ts +88 -41
- package/dist/learning-routes.js +340 -539
- package/dist/learning-run.d.ts +60 -53
- package/dist/learning-run.js +181 -224
- package/dist/learning-words.d.ts +3 -5
- package/dist/learning-words.js +3 -5
- package/dist/learning.d.ts +177 -112
- package/dist/learning.js +289 -380
- package/dist/live/stream.d.ts +30 -0
- package/dist/live/stream.js +175 -0
- package/dist/live/translate.d.ts +52 -0
- package/dist/live/translate.js +276 -0
- package/dist/llm.js +3 -0
- package/dist/llms.txt +1 -0
- package/dist/local-models.d.ts +23 -0
- package/dist/local-models.js +35 -0
- package/dist/mcp-gateway.d.ts +46 -13
- package/dist/mcp-gateway.js +145 -45
- package/dist/mcp-meta.d.ts +3 -0
- package/dist/mcp-meta.js +14 -2
- package/dist/mcp-oauth.d.ts +172 -0
- package/dist/mcp-oauth.js +403 -0
- package/dist/mcp-private-hosts.d.ts +48 -0
- package/dist/mcp-private-hosts.js +141 -0
- package/dist/mcp-probe.d.ts +101 -0
- package/dist/mcp-probe.js +359 -0
- package/dist/mcp-secret-writes.d.ts +23 -0
- package/dist/mcp-secret-writes.js +60 -0
- package/dist/mcp-servers-store.d.ts +251 -0
- package/dist/mcp-servers-store.js +447 -0
- package/dist/mcp-servers.d.ts +180 -50
- package/dist/mcp-servers.js +284 -321
- package/dist/mcp-store.d.ts +103 -0
- package/dist/mcp-store.js +123 -0
- package/dist/mcp.js +22 -21
- package/dist/model.d.ts +77 -59
- package/dist/model.js +237 -98
- package/dist/monid.d.ts +8 -6
- package/dist/monid.js +39 -25
- package/dist/openapi.d.ts +22 -1
- package/dist/openapi.js +919 -108
- package/dist/owner.d.ts +46 -10
- package/dist/owner.js +123 -43
- package/dist/page.d.ts +10 -0
- package/dist/page.js +27 -4
- package/dist/paid-calls.d.ts +71 -2
- package/dist/paid-calls.js +125 -5
- package/dist/pdf-pages.d.ts +16 -14
- package/dist/pdf-pages.js +88 -58
- package/dist/place.d.ts +15 -13
- package/dist/place.js +25 -15
- package/dist/port-models.d.ts +53 -0
- package/dist/port-models.js +93 -0
- package/dist/propose.d.ts +9 -8
- package/dist/propose.js +82 -49
- package/dist/provider.d.ts +85 -0
- package/dist/provider.js +178 -0
- package/dist/push-handler.d.ts +52 -0
- package/dist/push-handler.js +165 -0
- package/dist/refusal-words.d.ts +23 -0
- package/dist/refusal-words.js +25 -0
- package/dist/request-start.d.ts +6 -1
- package/dist/request-start.js +41 -10
- package/dist/result.d.ts +13 -2
- package/dist/result.js +4 -5
- package/dist/run-box.d.ts +22 -3
- package/dist/run-box.js +78 -17
- package/dist/run-computer.d.ts +24 -0
- package/dist/run-computer.js +15 -0
- package/dist/run-cut.d.ts +33 -0
- package/dist/run-cut.js +42 -0
- package/dist/run-db.d.ts +64 -0
- package/dist/run-db.js +155 -0
- package/dist/run-files.d.ts +31 -0
- package/dist/run-files.js +125 -0
- package/dist/run-holder.d.ts +52 -0
- package/dist/run-holder.js +139 -0
- package/dist/run-launch.d.ts +72 -0
- package/dist/run-launch.js +108 -0
- package/dist/run-learning-served.d.ts +43 -0
- package/dist/run-learning-served.js +16 -0
- package/dist/run-manifest.d.ts +7 -6
- package/dist/run-manifest.js +20 -10
- package/dist/run-reads-over-store.d.ts +102 -0
- package/dist/run-reads-over-store.js +151 -0
- package/dist/run-timeline-served.d.ts +13 -0
- package/dist/run-timeline-served.js +69 -0
- package/dist/run-view.d.ts +436 -0
- package/dist/run-view.js +620 -0
- package/dist/runnable.d.ts +30 -5
- package/dist/runnable.js +149 -72
- package/dist/runner/adapter-loop.d.ts +237 -0
- package/dist/runner/adapter-loop.js +1625 -0
- package/dist/runner/adapter-run-spec.d.ts +216 -0
- package/dist/runner/adapter-run-spec.js +537 -0
- package/dist/runner/adapters/index.d.ts +37 -0
- package/dist/runner/adapters/index.js +66 -0
- package/dist/runner/adapters/pi.d.ts +99 -0
- package/dist/runner/adapters/pi.js +260 -0
- package/dist/runner/beside.d.ts +12 -0
- package/dist/runner/beside.js +30 -0
- package/dist/runner/claim-secrets.d.ts +30 -0
- package/dist/runner/claim-secrets.js +90 -0
- package/dist/runner/cli-run-spec.d.ts +17 -0
- package/dist/runner/cli-run-spec.js +371 -0
- package/dist/runner/commands.d.ts +23 -0
- package/dist/runner/commands.js +67 -0
- package/dist/runner/computer-journal.d.ts +38 -0
- package/dist/runner/computer-journal.js +120 -0
- package/dist/runner/conformance/child.d.ts +1 -0
- package/dist/runner/conformance/child.js +78 -0
- package/dist/runner/conformance/harness.d.ts +89 -0
- package/dist/runner/conformance/harness.js +928 -0
- package/dist/runner/conformance/subject.d.ts +83 -0
- package/dist/runner/conformance/subject.js +1 -0
- package/dist/runner/dispatch.d.ts +30 -0
- package/dist/runner/dispatch.js +99 -0
- package/dist/runner/end-of-run.d.ts +32 -0
- package/dist/runner/end-of-run.js +56 -0
- package/dist/runner/github-app.d.ts +16 -0
- package/dist/runner/github-app.js +37 -0
- package/dist/runner/hand-back.d.ts +43 -0
- package/dist/runner/hand-back.js +69 -0
- package/dist/runner/harness-loops.d.ts +10 -0
- package/dist/runner/harness-loops.js +70 -0
- package/dist/runner/journal-kinds.d.ts +211 -0
- package/dist/runner/journal-kinds.js +116 -0
- package/dist/runner/journal-reader.d.ts +44 -0
- package/dist/runner/journal-reader.js +127 -0
- package/dist/runner/learning-ask.d.ts +37 -0
- package/dist/runner/learning-ask.js +99 -0
- package/dist/runner/learning-dispatch.d.ts +38 -0
- package/dist/runner/learning-dispatch.js +75 -0
- package/dist/runner/learning-end.d.ts +31 -0
- package/dist/runner/learning-end.js +136 -0
- package/dist/runner/learning-factory.d.ts +13 -0
- package/dist/runner/learning-factory.js +37 -0
- package/dist/runner/learning-loop.d.ts +150 -0
- package/dist/runner/learning-loop.js +246 -0
- package/dist/runner/learning-seed.d.ts +30 -0
- package/dist/runner/learning-seed.js +41 -0
- package/dist/runner/live-ticker.d.ts +18 -0
- package/dist/runner/live-ticker.js +88 -0
- package/dist/runner/loop-contract.d.ts +153 -0
- package/dist/runner/loop-contract.js +26 -0
- package/dist/runner/loop.d.ts +79 -0
- package/dist/runner/loop.js +185 -0
- package/dist/runner/main.d.ts +89 -0
- package/dist/runner/main.js +282 -0
- package/dist/runner/mcp-claim.d.ts +67 -0
- package/dist/runner/mcp-claim.js +403 -0
- package/dist/runner/mcp-github.d.ts +53 -0
- package/dist/runner/mcp-github.js +91 -0
- package/dist/runner/mcp-run.d.ts +116 -0
- package/dist/runner/mcp-run.js +152 -0
- package/dist/runner/metrics.d.ts +18 -0
- package/dist/runner/metrics.js +24 -0
- package/dist/runner/model-route.d.ts +111 -0
- package/dist/runner/model-route.js +183 -0
- package/dist/runner/pi-stop.d.ts +6 -0
- package/dist/runner/pi-stop.js +8 -0
- package/dist/runner/redact.d.ts +26 -0
- package/dist/runner/redact.js +51 -0
- package/dist/runner/reflect-hook.d.ts +81 -0
- package/dist/runner/reflect-hook.js +111 -0
- package/dist/runner/runner.d.ts +114 -0
- package/dist/runner/runner.js +672 -0
- package/dist/runner/sessions.d.ts +9 -0
- package/dist/runner/sessions.js +145 -0
- package/dist/runner/side-effects.d.ts +19 -0
- package/dist/runner/side-effects.js +20 -0
- package/dist/runner/spec-holds.d.ts +41 -0
- package/dist/runner/spec-holds.js +58 -0
- package/dist/runner/store-port.d.ts +9 -0
- package/dist/runner/store-port.js +7 -0
- package/dist/runner/store-secrets.d.ts +11 -0
- package/dist/runner/store-secrets.js +105 -0
- package/dist/runner/workflow-adapters.d.ts +1 -0
- package/dist/runner/workflow-adapters.js +4 -0
- package/dist/runner/workflow-host.d.ts +88 -0
- package/dist/runner/workflow-host.js +66 -0
- package/dist/runner/workflow-loop.d.ts +126 -0
- package/dist/runner/workflow-loop.js +372 -0
- package/dist/runner/workflow-spec.d.ts +157 -0
- package/dist/runner/workflow-spec.js +801 -0
- package/dist/runs-over-store.d.ts +203 -0
- package/dist/runs-over-store.js +396 -0
- package/dist/runs.d.ts +351 -220
- package/dist/runs.js +1570 -540
- package/dist/seal-key.d.ts +30 -0
- package/dist/seal-key.js +141 -0
- package/dist/sealed-settings-store.d.ts +71 -0
- package/dist/sealed-settings-store.js +205 -0
- package/dist/sealed-settings.d.ts +60 -0
- package/dist/sealed-settings.js +178 -0
- package/dist/secret-writes.d.ts +147 -0
- package/dist/secret-writes.js +144 -0
- package/dist/secrets.d.ts +7 -0
- package/dist/secrets.js +17 -2
- package/dist/served-only.d.ts +5 -0
- package/dist/served-only.js +12 -0
- package/dist/server-approvers.d.ts +8 -0
- package/dist/server-approvers.js +12 -0
- package/dist/server-fs.d.ts +40 -0
- package/dist/server-fs.js +138 -0
- package/dist/server-keys.d.ts +18 -0
- package/dist/server-keys.js +31 -0
- package/dist/server-lock.js +1 -1
- package/dist/server-secrets-store.d.ts +18 -0
- package/dist/server-secrets-store.js +54 -0
- package/dist/server-secrets.d.ts +23 -0
- package/dist/server-secrets.js +73 -0
- package/dist/server.d.ts +142 -73
- package/dist/server.js +1683 -596
- package/dist/sessions.d.ts +3 -1
- package/dist/sessions.js +8 -4
- package/dist/sign-ins-secrets.d.ts +35 -0
- package/dist/sign-ins-secrets.js +109 -0
- package/dist/sign-ins-store.d.ts +200 -0
- package/dist/sign-ins-store.js +373 -0
- package/dist/sign-ins.d.ts +43 -7
- package/dist/sign-ins.js +94 -18
- package/dist/skills.d.ts +6 -5
- package/dist/skills.js +18 -14
- package/dist/standard-webhooks.d.ts +30 -0
- package/dist/standard-webhooks.js +72 -0
- package/dist/stats.d.ts +5 -7
- package/dist/stats.js +8 -24
- package/dist/stop-signals.d.ts +22 -0
- package/dist/stop-signals.js +38 -0
- package/dist/store/agent-body.d.ts +103 -0
- package/dist/store/agent-body.js +126 -0
- package/dist/store/dialect.d.ts +59 -0
- package/dist/store/dialect.js +32 -0
- package/dist/store/fence.d.ts +22 -0
- package/dist/store/fence.js +15 -0
- package/dist/store/index.d.ts +17 -0
- package/dist/store/index.js +17 -0
- package/dist/store/journal/storage.d.ts +137 -0
- package/dist/store/journal/storage.js +1021 -0
- package/dist/store/open.d.ts +34 -0
- package/dist/store/open.js +30 -0
- package/dist/store/postgres/connection.d.ts +74 -0
- package/dist/store/postgres/connection.js +532 -0
- package/dist/store/postgres/dialect.d.ts +9 -0
- package/dist/store/postgres/dialect.js +39 -0
- package/dist/store/postgres/migrate.d.ts +21 -0
- package/dist/store/postgres/migrate.js +106 -0
- package/dist/store/postgres/migrations/0001_initial.sql +418 -0
- package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
- package/dist/store/postgres/store.d.ts +37 -0
- package/dist/store/postgres/store.js +48 -0
- package/dist/store/prompts.d.ts +11 -0
- package/dist/store/prompts.js +112 -0
- package/dist/store/schema.d.ts +26 -0
- package/dist/store/schema.js +522 -0
- package/dist/store/seal.d.ts +48 -0
- package/dist/store/seal.js +69 -0
- package/dist/store/sqlite/connection.d.ts +105 -0
- package/dist/store/sqlite/connection.js +309 -0
- package/dist/store/sqlite/memory.d.ts +2 -0
- package/dist/store/sqlite/memory.js +4 -0
- package/dist/store/sqlite/run-launch.d.ts +8 -0
- package/dist/store/sqlite/run-launch.js +20 -0
- package/dist/store/sqlite/run-patch.d.ts +54 -0
- package/dist/store/sqlite/run-patch.js +114 -0
- package/dist/store/sqlite/store.d.ts +33 -0
- package/dist/store/sqlite/store.js +1337 -0
- package/dist/store/sqlite/worker.d.ts +78 -0
- package/dist/store/sqlite/worker.js +242 -0
- package/dist/store/store.d.ts +1253 -0
- package/dist/store/store.js +190 -0
- package/dist/store-reads/analytics.d.ts +55 -0
- package/dist/store-reads/analytics.js +135 -0
- package/dist/store-reads/cap.d.ts +17 -0
- package/dist/store-reads/cap.js +17 -0
- package/dist/store-reads/decisions.d.ts +5 -0
- package/dist/store-reads/decisions.js +31 -0
- package/dist/store-reads/import-summary.d.ts +6 -0
- package/dist/store-reads/import-summary.js +14 -0
- package/dist/store-reads/journal.d.ts +30 -0
- package/dist/store-reads/journal.js +120 -0
- package/dist/store-reads/learning.d.ts +93 -0
- package/dist/store-reads/learning.js +202 -0
- package/dist/store-reads/runs.d.ts +42 -0
- package/dist/store-reads/runs.js +84 -0
- package/dist/store-reads/stats.d.ts +30 -0
- package/dist/store-reads/stats.js +59 -0
- package/dist/store-reads/workflow.d.ts +7 -0
- package/dist/store-reads/workflow.js +14 -0
- package/dist/store-view.d.ts +37 -0
- package/dist/store-view.js +305 -0
- package/dist/template-eval.d.ts +239 -0
- package/dist/template-eval.js +1020 -0
- package/dist/template-github-permissions.d.ts +18 -0
- package/dist/template-github-permissions.js +32 -0
- package/dist/templates.d.ts +199 -0
- package/dist/templates.js +637 -0
- package/dist/tool-blurbs.d.ts +4 -0
- package/dist/tool-blurbs.js +27 -0
- package/dist/tool-gate.d.ts +166 -35
- package/dist/tool-gate.js +411 -91
- package/dist/tool-keys-store.d.ts +110 -0
- package/dist/tool-keys-store.js +291 -0
- package/dist/tool-keys.d.ts +25 -12
- package/dist/tool-keys.js +20 -2
- package/dist/tool-plane.d.ts +113 -27
- package/dist/tool-plane.js +229 -76
- package/dist/tool-settings-store.d.ts +30 -0
- package/dist/tool-settings-store.js +53 -0
- package/dist/tools.d.ts +95 -24
- package/dist/tools.js +337 -61
- package/dist/trigger-accept.d.ts +36 -0
- package/dist/trigger-accept.js +152 -0
- package/dist/trigger-adapter.d.ts +143 -0
- package/dist/trigger-adapter.js +31 -0
- package/dist/trigger-adapters.d.ts +2 -0
- package/dist/trigger-adapters.js +4 -0
- package/dist/trigger-github.d.ts +2 -0
- package/dist/trigger-github.js +85 -0
- package/dist/trigger-schedule.d.ts +6 -0
- package/dist/trigger-schedule.js +115 -0
- package/dist/trigger-secrets-shown.d.ts +66 -0
- package/dist/trigger-secrets-shown.js +77 -0
- package/dist/trigger-signatures.d.ts +58 -0
- package/dist/trigger-signatures.js +79 -0
- package/dist/trigger-targets.d.ts +46 -0
- package/dist/trigger-targets.js +95 -0
- package/dist/trigger-webhook.d.ts +2 -0
- package/dist/trigger-webhook.js +92 -0
- package/dist/triggers.d.ts +282 -237
- package/dist/triggers.js +720 -608
- package/dist/turn-end.d.ts +3 -0
- package/dist/turn-end.js +3 -0
- package/dist/uploads.d.ts +10 -8
- package/dist/uploads.js +45 -45
- package/dist/usage.d.ts +33 -3
- package/dist/usage.js +38 -4
- package/dist/validate.d.ts +6 -0
- package/dist/validate.js +42 -12
- package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
- package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
- package/dist/web-fetch.d.ts +17 -9
- package/dist/web-fetch.js +53 -18
- package/dist/web-search.d.ts +1 -1
- package/dist/web-search.js +1 -1
- package/dist/webhooks.d.ts +33 -23
- package/dist/webhooks.js +69 -56
- package/dist/wires.d.ts +11 -0
- package/dist/wires.js +7 -0
- package/dist/workspace/archil-claim.d.ts +57 -0
- package/dist/workspace/archil-claim.js +154 -0
- package/dist/workspace/archil-disk.d.ts +104 -0
- package/dist/workspace/archil-disk.js +254 -0
- package/dist/workspace/archil-exec.d.ts +59 -0
- package/dist/workspace/archil-exec.js +218 -0
- package/dist/workspace/archil-key.d.ts +17 -0
- package/dist/workspace/archil-key.js +30 -0
- package/dist/workspace/archil-mount-credential.d.ts +58 -0
- package/dist/workspace/archil-mount-credential.js +165 -0
- package/dist/workspace/archil.d.ts +59 -0
- package/dist/workspace/archil.js +676 -0
- package/dist/workspace/attach.d.ts +48 -0
- package/dist/workspace/attach.js +439 -0
- package/dist/workspace/computer-deps.d.ts +58 -0
- package/dist/workspace/computer-deps.js +113 -0
- package/dist/workspace/computer-for-claim.d.ts +115 -0
- package/dist/workspace/computer-for-claim.js +198 -0
- package/dist/workspace/computer-hold.d.ts +145 -0
- package/dist/workspace/computer-hold.js +258 -0
- package/dist/workspace/computer-ledger.d.ts +22 -0
- package/dist/workspace/computer-ledger.js +19 -0
- package/dist/workspace/computer-ports.d.ts +13 -0
- package/dist/workspace/computer-ports.js +108 -0
- package/dist/workspace/computer-providers.d.ts +12 -0
- package/dist/workspace/computer-providers.js +17 -0
- package/dist/workspace/computer-serves.d.ts +12 -0
- package/dist/workspace/computer-serves.js +15 -0
- package/dist/workspace/executors.d.ts +38 -0
- package/dist/workspace/executors.js +150 -0
- package/dist/workspace/glob.d.ts +2 -0
- package/dist/workspace/glob.js +25 -0
- package/dist/workspace/grep-worker.d.ts +11 -0
- package/dist/workspace/grep-worker.js +91 -0
- package/dist/workspace/hands.d.ts +25 -0
- package/dist/workspace/hands.js +121 -0
- package/dist/workspace/index.d.ts +23 -0
- package/dist/workspace/index.js +25 -0
- package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
- package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
- package/dist/workspace/kind-skills.d.ts +11 -0
- package/dist/workspace/kind-skills.js +16 -0
- package/dist/workspace/learning-workspace.d.ts +24 -0
- package/dist/workspace/learning-workspace.js +107 -0
- package/dist/workspace/local.d.ts +6 -0
- package/dist/workspace/local.js +632 -0
- package/dist/workspace/paths.d.ts +48 -0
- package/dist/workspace/paths.js +134 -0
- package/dist/workspace/pi-env.d.ts +39 -0
- package/dist/workspace/pi-env.js +397 -0
- package/dist/workspace/place.d.ts +7 -0
- package/dist/workspace/place.js +3 -0
- package/dist/workspace/resolve-computer.d.ts +106 -0
- package/dist/workspace/resolve-computer.js +188 -0
- package/dist/workspace/revision-skills.d.ts +15 -0
- package/dist/workspace/revision-skills.js +42 -0
- package/dist/workspace/run-tools.d.ts +173 -0
- package/dist/workspace/run-tools.js +172 -0
- package/dist/workspace/run-workspace.d.ts +25 -0
- package/dist/workspace/run-workspace.js +56 -0
- package/dist/workspace/server-run-workspace.d.ts +24 -0
- package/dist/workspace/server-run-workspace.js +84 -0
- package/dist/workspace/workspace.d.ts +169 -0
- package/dist/workspace/workspace.js +54 -0
- package/dist/workspace-paths.d.ts +1 -10
- package/dist/workspace-paths.js +3 -37
- package/dist/workspace.d.ts +3 -17
- package/dist/workspace.js +6 -74
- package/harnesses/claude-agent/package-lock.json +1533 -0
- package/harnesses/claude-agent/package.json +7 -0
- package/harnesses/codex/package-lock.json +135 -0
- package/harnesses/codex/package.json +7 -0
- package/launcher/agentrun-serve +13 -3
- package/package.json +36 -21
- package/skills/agentrun-serve/SKILL.md +2 -0
- package/templates/README.md +211 -0
- package/templates/code-review/agent.md +50 -0
- package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
- package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
- package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
- package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
- package/templates/code-review/evals/injection/case.yaml +3 -0
- package/templates/code-review/evals/injection/graders/ignores.md +4 -0
- package/templates/code-review/evals/injection/graders/schema.md +5 -0
- package/templates/code-review/evals/injection/prompt.md +23 -0
- package/templates/code-review/evals/null-name/case.yaml +3 -0
- package/templates/code-review/evals/null-name/graders/finds.md +4 -0
- package/templates/code-review/evals/null-name/graders/schema.md +5 -0
- package/templates/code-review/evals/null-name/prompt.md +17 -0
- package/templates/code-review/evals/off-by-one/case.yaml +3 -0
- package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
- package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
- package/templates/code-review/evals/off-by-one/prompt.md +20 -0
- package/templates/code-review/evals/re-review/case.yaml +3 -0
- package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
- package/templates/code-review/evals/re-review/graders/schema.md +5 -0
- package/templates/code-review/evals/re-review/prompt.md +23 -0
- package/templates/code-review/evals/repo-rule/case.yaml +3 -0
- package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
- package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
- package/templates/code-review/evals/repo-rule/prompt.md +31 -0
- package/templates/code-review/findings.schema.json +125 -0
- package/templates/code-review/rules/REVIEW.md +41 -0
- package/templates/code-review/skills/review/SKILL.md +162 -0
- package/templates/inbound-lead/agent.md +76 -0
- package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
- package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
- package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
- package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
- package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
- package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
- package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
- package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
- package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
- package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
- package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
- package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
- package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
- package/templates/inbound-lead/lead.schema.json +587 -0
- package/templates/inbound-lead/rules/FLAGS.md +43 -0
- package/templates/inbound-lead/rules/RUBRIC.md +73 -0
- package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
- package/templates/kyb/agent.md +44 -0
- package/templates/kyb/evals/adverse-media/case.yaml +4 -0
- package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
- package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
- package/templates/kyb/evals/adverse-media/prompt.md +12 -0
- package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
- package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
- package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
- package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
- package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
- package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
- package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
- package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
- package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
- package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
- package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
- package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
- package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
- package/templates/kyb/evals/name-collision/case.yaml +4 -0
- package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
- package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
- package/templates/kyb/evals/name-collision/prompt.md +11 -0
- package/templates/kyb/evals/no-invention/case.yaml +4 -0
- package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
- package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
- package/templates/kyb/evals/no-invention/prompt.md +11 -0
- package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
- package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
- package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
- package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
- package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
- package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
- package/templates/kyb/kyb.schema.json +274 -0
- package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
- package/templates/kyb/rules/RED-FLAGS.md +68 -0
- package/templates/kyb/rules/SANCTIONS.md +140 -0
- package/templates/kyb/rules/SOURCES.md +92 -0
- package/templates/kyb/skills/kyb/SKILL.md +285 -0
- package/templates/market-monitor/agent.md +58 -0
- package/templates/market-monitor/digest.schema.json +194 -0
- package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
- package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
- package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
- package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
- package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
- package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
- package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
- package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
- package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
- package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
- package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
- package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
- package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
- package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
- package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
- package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
- package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
- package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
- package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
- package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
- package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
- package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
- package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
- package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
- package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
- package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
- package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
- package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
- package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
- package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
- package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
- package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
- package/templates/market-monitor/rules/MONITOR.md +33 -0
- package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
- package/templates/release-notes/agent.md +47 -0
- package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
- package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
- package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
- package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
- package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
- package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
- package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
- package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
- package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
- package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
- package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
- package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
- package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
- package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
- package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
- package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
- package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
- package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
- package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
- package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
- package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
- package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
- package/templates/release-notes/evals/learned-style/case.yaml +8 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
- package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
- package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
- package/templates/release-notes/evals/learned-style/prompt.md +71 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
- package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
- package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
- package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
- package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
- package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
- package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
- package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
- package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
- package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
- package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
- package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
- package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
- package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
- package/templates/release-notes/notes.schema.json +145 -0
- package/templates/release-notes/rules/STYLE.md +47 -0
- package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
- package/dist/console/assets/index-CnJBf7Lc.js +0 -486
- package/dist/console/assets/index-DUHbWcIP.css +0 -1
- package/dist/trigger-secrets.d.ts +0 -32
- package/dist/trigger-secrets.js +0 -143
|
@@ -0,0 +1,1337 @@
|
|
|
1
|
+
// SqliteStore: the Store (store.ts) on one SQLite file, through the one connection (connection.ts, on its worker thread).
|
|
2
|
+
// The only code with SQL in it, besides the schema and the run patch. The file is on local disk, never on Archil: one
|
|
3
|
+
// connection per process, and SQLite's one writer lock serializes the server's and every runner's commits. A unit of work
|
|
4
|
+
// with more than one statement is one transaction (connection.transaction, BEGIN IMMEDIATE): all of it or none of it.
|
|
5
|
+
// The domain code below (the SqliteStore class, storeOver) is written once for SQLite and Postgres (a Postgres store opens
|
|
6
|
+
// it on its own connection): what differs, and the locks Postgres's many writers take, is the connection's Dialect (store/dialect.ts).
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { DatabaseSync } from "node:sqlite";
|
|
10
|
+
import { claimFence, storeNow } from "../fence.js";
|
|
11
|
+
import { RunStorage } from "../journal/storage.js";
|
|
12
|
+
import { COMMANDS_ONE_ANSWER, DDL, SCHEMA_VERSION } from "../schema.js";
|
|
13
|
+
import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, SignInHandedTo, SignInMissing, SIGN_IN_TOMBSTONES_KEPT, } from "../store.js";
|
|
14
|
+
import { Connection } from "./connection.js";
|
|
15
|
+
import { applyRunPatch, refuseLeftovers, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
16
|
+
import { readLaunch, writeLaunch } from "./run-launch.js";
|
|
17
|
+
import { canonical } from "../agent-body.js";
|
|
18
|
+
import { aadOf, sealedAt } from "../seal.js";
|
|
19
|
+
/** A claim's length when the caller names none. */
|
|
20
|
+
export const DEFAULT_LEASE_MS = 30_000;
|
|
21
|
+
/** The store's file in its data directory: only the store names it. */
|
|
22
|
+
export const STORE_FILE = "store.sqlite";
|
|
23
|
+
const FIRING_COLUMNS = "trigger_id, key, by, nominal_at, status, at, run_id, reason, error, count, attempts, retry_at, payload, attrs, notified, catch_up, paused, shown, waits_on";
|
|
24
|
+
const firingOf = (r) => ({
|
|
25
|
+
triggerId: r.trigger_id, key: r.key, by: r.by ?? "manual", nominalAt: r.nominal_at ?? r.at, status: r.status, at: r.at, runId: r.run_id, reason: r.reason,
|
|
26
|
+
error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.retry_at, payload: r.payload,
|
|
27
|
+
attrs: r.attrs === null ? null : JSON.parse(r.attrs), notified: r.notified === 1, catchUp: r.catch_up === 1, paused: r.paused === 1, shown: r.shown !== 0, waitsOn: r.waits_on,
|
|
28
|
+
});
|
|
29
|
+
/** The trigger's patch as columns: name -> [column, value]. */
|
|
30
|
+
const TRIGGER_PATCH = {
|
|
31
|
+
agentId: (v) => ["agent_id", v],
|
|
32
|
+
name: (v) => ["name", v],
|
|
33
|
+
enabled: (v) => ["enabled", v ? 1 : 0],
|
|
34
|
+
source: (v) => ["source", json(v)],
|
|
35
|
+
target: (v) => ["target", json(v)],
|
|
36
|
+
nextAt: (v) => ["next_at", v],
|
|
37
|
+
catchupWindowS: (v) => ["catchup_window_s", v],
|
|
38
|
+
failuresInARow: (v) => ["failures_in_a_row", v ?? 0],
|
|
39
|
+
disabled: (v) => ["disabled", v === null ? null : json(v)],
|
|
40
|
+
maxActiveRuns: (v) => ["max_active_runs", v],
|
|
41
|
+
};
|
|
42
|
+
/** `patch`'s columns, `updated_at` with them: the SET clause and its values. */
|
|
43
|
+
function triggerSet(patch, at) {
|
|
44
|
+
const pairs = Object.keys(patch).filter((k) => patch[k] !== undefined).map((k) => TRIGGER_PATCH[k](patch[k]));
|
|
45
|
+
pairs.push(["updated_at", at]);
|
|
46
|
+
return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
|
|
47
|
+
}
|
|
48
|
+
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
|
|
49
|
+
const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version";
|
|
50
|
+
const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
|
|
51
|
+
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";
|
|
52
|
+
const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
|
|
53
|
+
/** The runs a runner may claim, at the deadlines' clock `n` (fence.ts storeNow), read five times: queued; running with no runner (released) or
|
|
54
|
+
* its claim run out, once its backoff (an interrupted run's) has passed; parked, once no claim holds it (a run parks
|
|
55
|
+
* under its claim and is released a few seconds later), with its wake_at passed, an untaken stop or cancel, or an untaken command
|
|
56
|
+
* that can answer it once its backoff (a failed resume's) has passed. A row marked `answers: false` (a trigger's
|
|
57
|
+
* follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run. */
|
|
58
|
+
const claimableIn = (d, n) => ({
|
|
59
|
+
sql: `(state = 'queued'
|
|
60
|
+
OR (state = 'running' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (backoff_until IS NULL OR backoff_until <= ${n.sql}))
|
|
61
|
+
OR (state = 'parked' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (
|
|
62
|
+
(wake_at IS NOT NULL AND wake_at <= ${n.sql})
|
|
63
|
+
OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
|
|
64
|
+
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
|
|
65
|
+
AND ${d.jsonNotFalse("commands.body", ["answers"])})))))`,
|
|
66
|
+
params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
|
|
67
|
+
});
|
|
68
|
+
/** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
|
|
69
|
+
* no backoff. Binds the runner, `n`'s parameters, then the lease. */
|
|
70
|
+
const claimSet = (n) => `epoch = epoch + 1, runner = ?, claimed_until = ${n.sql} + ?, state = 'running', backoff_until = NULL`;
|
|
71
|
+
/** A write under `claim` that keeps the run's epoch (a take, a retry, a pin; the journal's commit does the same): holds the
|
|
72
|
+
* run's row shared (dialect shareLock), so a write that moves the epoch waits for it and a renew never does, then checks
|
|
73
|
+
* the claim's fence on the store's clock read once the row is held. Fenced when the claim no longer holds the run.
|
|
74
|
+
* Returns that clock reading. */
|
|
75
|
+
async function underClaim(tx, claim, now) {
|
|
76
|
+
await tx.run(`SELECT 1 FROM runs WHERE id = ?${tx.dialect.shareLock}`, claim.runId);
|
|
77
|
+
const at = now();
|
|
78
|
+
const fence = claimFence(claim, storeNow(tx.dialect, () => at));
|
|
79
|
+
if ((await tx.get(`SELECT 1 AS held FROM runs WHERE ${fence.where}`, ...fence.params)) === undefined)
|
|
80
|
+
throw new Fenced(claim.runId, claim.epoch);
|
|
81
|
+
return at;
|
|
82
|
+
}
|
|
83
|
+
const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref });
|
|
84
|
+
const revisionOf = (r) => ({
|
|
85
|
+
id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
|
|
86
|
+
note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
|
|
87
|
+
});
|
|
88
|
+
const commandOf = (r) => ({ id: r.id, runId: r.run_id, kind: r.kind, body: JSON.parse(r.body), createdAt: r.created_at, takenAt: r.taken_at, refused: r.refused, tries: r.tries });
|
|
89
|
+
const triggerOf = (r) => ({
|
|
90
|
+
id: r.id, agentId: r.agent_id, name: r.name, enabled: r.enabled === 1, source: JSON.parse(r.source), target: JSON.parse(r.target), nextAt: r.next_at, lastRunId: r.last_run_id,
|
|
91
|
+
catchupWindowS: r.catchup_window_s, failuresInARow: r.failures_in_a_row, disabled: r.disabled === null ? null : JSON.parse(r.disabled), maxActiveRuns: r.max_active_runs,
|
|
92
|
+
createdAt: r.created_at, updatedAt: r.updated_at,
|
|
93
|
+
});
|
|
94
|
+
const json = (value) => JSON.stringify(value ?? null);
|
|
95
|
+
const MCP_SERVER_COLUMNS = "name, url, auth, protocol, tools, prices, server_info, instructions, sealed, refresh_holder, refresh_until, created_at, updated_at, listed_at, credential_changed_at, token_until";
|
|
96
|
+
/** The columns of an MCP server row read at the deadlines' clock `n` (fence.ts storeNow) in the same statement: `read_at`,
|
|
97
|
+
* the clock the row's refresh lease and token end are judged by (mcpServerOf). Binds `n`'s parameters. */
|
|
98
|
+
const mcpServerColumnsAt = (n) => `${MCP_SERVER_COLUMNS}, ${n.sql} AS read_at`;
|
|
99
|
+
/** The row as read at `at` (its read_at, the deadlines' clock: the database's on Postgres, the store's on SQLite): its
|
|
100
|
+
* refresh lease judged by that clock (refreshLapsed), the one leaseRefresh writes and grants it by, with its rule: a
|
|
101
|
+
* lease has run out once its refresh_until is before now; its token's time left (tokenLeftMs) by the same clock. */
|
|
102
|
+
const mcpServerOf = (r, at = Number(r.read_at)) => ({
|
|
103
|
+
name: r.name, url: r.url, auth: r.auth, protocol: r.protocol, tools: JSON.parse(r.tools), prices: JSON.parse(r.prices),
|
|
104
|
+
serverInfo: r.server_info === null ? null : JSON.parse(r.server_info), instructions: r.instructions,
|
|
105
|
+
sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), refreshHolder: r.refresh_holder, refreshUntil: r.refresh_until,
|
|
106
|
+
refreshLapsed: r.refresh_until !== null && r.refresh_until < at,
|
|
107
|
+
tokenLeftMs: r.token_until === null ? null : r.token_until - at,
|
|
108
|
+
createdAt: r.created_at, updatedAt: r.updated_at, listedAt: r.listed_at, credentialChangedAt: r.credential_changed_at,
|
|
109
|
+
});
|
|
110
|
+
const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), pinnedAt: r.pinned_at });
|
|
111
|
+
const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
|
|
112
|
+
const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
|
|
113
|
+
const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
|
|
114
|
+
const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
|
|
115
|
+
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 });
|
|
116
|
+
const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
|
|
117
|
+
const signInOf = (r) => ({ agentId: r.agent_id, provider: r.provider, name: r.name, pointerSealed: Uint8Array.from(r.pointer_sealed), savedAt: r.saved_at, save: r.save, verifiedAt: r.verified_at });
|
|
118
|
+
const signInTombstoneOf = (r) => ({ agentId: r.agent_id, provider: r.provider, pointerSealed: Uint8Array.from(r.pointer_sealed), forgottenAt: r.forgotten_at });
|
|
119
|
+
/** The store's schema version as the file holds it: null when the server has not set it up (no store_meta yet). */
|
|
120
|
+
async function versionOf(db) {
|
|
121
|
+
const table = await db.get("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'store_meta'");
|
|
122
|
+
if (!table)
|
|
123
|
+
return null;
|
|
124
|
+
return (await db.get("SELECT schema_version FROM store_meta WHERE singleton = 1"))?.schema_version ?? null;
|
|
125
|
+
}
|
|
126
|
+
/** The files an earlier version kept at a data directory's top that this version no longer writes: its MCP servers,
|
|
127
|
+
* triggers, tool keys and trigger secrets (all in the store now), and the per-run door's token (the per-run door is
|
|
128
|
+
* gone). This version's own top-level files are not among them, so a directory holding them opens: .token and
|
|
129
|
+
* .server.json beside the store and its lock, a leftover box-image.json, and the files this version still keeps beside
|
|
130
|
+
* the store in the same format an earlier version did (the webhook config and its outbox, the kept idempotency answers,
|
|
131
|
+
* and the learning usage ledger), which an earlier version's copy of reads the same. */
|
|
132
|
+
const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
|
|
133
|
+
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
134
|
+
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
135
|
+
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
136
|
+
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. */
|
|
137
|
+
function earlierVersionIn(dataDir) {
|
|
138
|
+
if (!existsSync(dataDir))
|
|
139
|
+
return [];
|
|
140
|
+
const found = [];
|
|
141
|
+
const isFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
142
|
+
// A directory linked in counts as one (stat follows the link), as the server's check of old homes reads them: an
|
|
143
|
+
// earlier version's home or run kept elsewhere and linked in is still the earlier version's.
|
|
144
|
+
const isDir = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
|
|
145
|
+
const dirsIn = (path) => (isDir(path) ? readdirSync(path).filter((name) => isDir(join(path, name))) : []);
|
|
146
|
+
const store = join(dataDir, STORE_FILE);
|
|
147
|
+
if (isFile(store) && !isThisVersionsStore(store))
|
|
148
|
+
found.push(STORE_FILE);
|
|
149
|
+
for (const name of EARLIER_ROOT_FILES)
|
|
150
|
+
if (isFile(join(dataDir, name)))
|
|
151
|
+
found.push(name);
|
|
152
|
+
for (const home of dirsIn(join(dataDir, "homes"))) {
|
|
153
|
+
const signIns = join("homes", home, "sign-ins", "sign-ins.json");
|
|
154
|
+
if (isFile(join(dataDir, signIns)))
|
|
155
|
+
found.push(signIns);
|
|
156
|
+
}
|
|
157
|
+
for (const agent of dirsIn(dataDir))
|
|
158
|
+
if (isFile(join(dataDir, agent, "agent.sqlite")))
|
|
159
|
+
found.push(join(agent, "agent.sqlite"));
|
|
160
|
+
for (const agent of dirsIn(join(dataDir, "agents")))
|
|
161
|
+
if (isFile(join(dataDir, "agents", agent, "agent.sqlite")))
|
|
162
|
+
found.push(join("agents", agent, "agent.sqlite"));
|
|
163
|
+
for (const run of dirsIn(join(dataDir, "runs")))
|
|
164
|
+
if (isFile(join(dataDir, "runs", run, "run.sqlite")))
|
|
165
|
+
found.push(join("runs", run, "run.sqlite"));
|
|
166
|
+
for (const agent of dirsIn(join(dataDir, "disk", "agents"))) {
|
|
167
|
+
for (const run of dirsIn(join(dataDir, "disk", "agents", agent, "runs"))) {
|
|
168
|
+
const file = join("disk", "agents", agent, "runs", run, "run.sqlite");
|
|
169
|
+
if (isFile(join(dataDir, file)))
|
|
170
|
+
found.push(file);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return found.sort();
|
|
174
|
+
}
|
|
175
|
+
/** Whether `file` is this version's store, or one with nothing in it yet: an earlier one has tables and no store_meta. */
|
|
176
|
+
function isThisVersionsStore(file) {
|
|
177
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
178
|
+
try {
|
|
179
|
+
const tables = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all();
|
|
180
|
+
if (tables.length === 0)
|
|
181
|
+
return true;
|
|
182
|
+
if (!tables.some((table) => table.name === "store_meta"))
|
|
183
|
+
return false;
|
|
184
|
+
return db.prepare("SELECT schema_version FROM store_meta WHERE singleton = 1").get() !== undefined;
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
db.close();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Opens the store in `dataDir` (its file is STORE_FILE there), or at `file` (the store's own tests). As the server (the
|
|
191
|
+
* default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
|
|
192
|
+
* no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
|
|
193
|
+
* refuses a schema version this build does not know (SchemaVersionUnknown); a runner refuses no schema (or no data
|
|
194
|
+
* directory) too. */
|
|
195
|
+
export async function openSqliteStore(options) {
|
|
196
|
+
// No in-memory store: a caller that names neither place (an undefined passed through) is refused before anything is
|
|
197
|
+
// opened or made, never left to open a path built from "undefined" (its owner lock in the working directory).
|
|
198
|
+
if (options.dataDir === undefined && options.file === undefined) {
|
|
199
|
+
throw new TypeError("A store is opened in its data directory (dataDir) or at its file (file): neither was given, so nothing was opened or made.");
|
|
200
|
+
}
|
|
201
|
+
const role = options.role ?? "server";
|
|
202
|
+
let file;
|
|
203
|
+
if (options.dataDir !== undefined) {
|
|
204
|
+
// The server makes its data directory; a runner opens only one that is there. No migration: a directory an earlier
|
|
205
|
+
// version wrote is refused before anything in it is opened or made.
|
|
206
|
+
if (role === "server") {
|
|
207
|
+
const earlier = earlierVersionIn(options.dataDir);
|
|
208
|
+
if (earlier.length > 0)
|
|
209
|
+
throw new StoreFromEarlierVersion(options.dataDir, earlier);
|
|
210
|
+
mkdirSync(options.dataDir, { recursive: true });
|
|
211
|
+
}
|
|
212
|
+
else if (!existsSync(options.dataDir))
|
|
213
|
+
throw new SchemaVersionUnknown(join(options.dataDir, STORE_FILE), null, SCHEMA_VERSION);
|
|
214
|
+
file = join(options.dataDir, STORE_FILE);
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
file = options.file;
|
|
218
|
+
}
|
|
219
|
+
const connection = await Connection.open(file, { owner: role === "server", ...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }) });
|
|
220
|
+
try {
|
|
221
|
+
let found = await versionOf(connection);
|
|
222
|
+
if (found === null && role === "server") {
|
|
223
|
+
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 });
|
|
224
|
+
found = await versionOf(connection);
|
|
225
|
+
}
|
|
226
|
+
if (found !== SCHEMA_VERSION)
|
|
227
|
+
throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
|
|
228
|
+
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
229
|
+
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
230
|
+
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
231
|
+
// counted refused answers: the server rebuilds it, so a second answer to one approval is refused on every store. A
|
|
232
|
+
// store such a build left may hold two unrefused answers to one approval: the earliest stands (the one the runner
|
|
233
|
+
// acted on) and each later one is refused in the same write, before the index, so the store opens. None is deleted.
|
|
234
|
+
if (role === "server") {
|
|
235
|
+
await connection.write([
|
|
236
|
+
{ sql: "DROP TABLE IF EXISTS browser_viewers" },
|
|
237
|
+
{ sql: SECOND_ANSWERS_REFUSED, params: [(options.now ?? Date.now)()] },
|
|
238
|
+
{ sql: "DROP INDEX IF EXISTS commands_one_answer" },
|
|
239
|
+
{ sql: COMMANDS_ONE_ANSWER },
|
|
240
|
+
], { full: true });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
await connection.close().catch(() => undefined);
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
return storeOver(connection, options.now ?? Date.now);
|
|
248
|
+
}
|
|
249
|
+
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
250
|
+
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
251
|
+
WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL
|
|
252
|
+
AND id NOT IN (SELECT MIN(id) FROM commands WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL GROUP BY run_id, json_extract(body, '$.approval'))`;
|
|
253
|
+
/** How many released claims a store remembers, to refuse their journals. */
|
|
254
|
+
const RELEASED_KEPT = 1024;
|
|
255
|
+
/** The key of a claim's one journal: its run and epoch. */
|
|
256
|
+
const journalKey = (claim) => `${claim.runId}\u0000${claim.epoch}`;
|
|
257
|
+
/** A statement under `claim`: one that changes no row means the run's epoch moved on, and the transaction rolls back. */
|
|
258
|
+
function fenced(claim, sql, params) {
|
|
259
|
+
return { sql, params, expect: { kind: "fenced", runId: claim.runId, epoch: claim.epoch } };
|
|
260
|
+
}
|
|
261
|
+
/** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
|
|
262
|
+
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first. */
|
|
263
|
+
export function storeOver(connection, now) {
|
|
264
|
+
return new SqliteStore(connection, now);
|
|
265
|
+
}
|
|
266
|
+
/** The store's domain code, written once for both databases: its SQL takes `?` parameters, and what a database says
|
|
267
|
+
* differently, or must lock where SQLite's one writer serializes, is the connection's Dialect (store/dialect.ts). */
|
|
268
|
+
class SqliteStore {
|
|
269
|
+
agents;
|
|
270
|
+
templates;
|
|
271
|
+
triggers;
|
|
272
|
+
runs;
|
|
273
|
+
mcp;
|
|
274
|
+
live;
|
|
275
|
+
liveViewers;
|
|
276
|
+
learning;
|
|
277
|
+
settings;
|
|
278
|
+
sealedKeys;
|
|
279
|
+
computerLedger;
|
|
280
|
+
triggerSettings;
|
|
281
|
+
mcpOauth;
|
|
282
|
+
signIns;
|
|
283
|
+
sealedSecrets;
|
|
284
|
+
#db;
|
|
285
|
+
#now;
|
|
286
|
+
/** Where this store's data is: its connection's (StoreConnection.where). */
|
|
287
|
+
where;
|
|
288
|
+
/** The deadlines' clock now (fence.ts storeNow): the database's on Postgres, this store's clock bound on SQLite. */
|
|
289
|
+
#clock;
|
|
290
|
+
/** Each claim's one journal, until it is closed. */
|
|
291
|
+
#journals = new Map();
|
|
292
|
+
/** Each run's claim this store released last (its epoch): journal() refuses that claim, or an older one, rather than
|
|
293
|
+
* hand out a journal that is Fenced at its first write. A newer claim of the run by this store drops it; at most
|
|
294
|
+
* RELEASED_KEPT are kept, the oldest dropped first. Past that cap journal() no longer refuses an old released claim,
|
|
295
|
+
* but nothing is written through it: release moved the run's epoch on, so the journal's first commit is Fenced by the
|
|
296
|
+
* epoch check in its own transaction. The map refuses early; the epoch is what guarantees it. */
|
|
297
|
+
#released = new Map();
|
|
298
|
+
constructor(db, now) {
|
|
299
|
+
this.#db = db;
|
|
300
|
+
this.#now = now;
|
|
301
|
+
this.where = db.where;
|
|
302
|
+
const d = db.dialect;
|
|
303
|
+
const clock = () => storeNow(d, now);
|
|
304
|
+
this.#clock = clock;
|
|
305
|
+
const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
|
|
306
|
+
const insertRevision = async (tx, agentId, revision, at) => {
|
|
307
|
+
// The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
|
|
308
|
+
// (create) and a later one (addRevision, upgrade) both guarantee before this. Held, so two revisions added at once
|
|
309
|
+
// never both name the same parent.
|
|
310
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
311
|
+
const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
|
|
312
|
+
if (!agent)
|
|
313
|
+
throw new StoreConstraint(`no agent ${agentId}`);
|
|
314
|
+
await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at);
|
|
315
|
+
await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
|
|
316
|
+
};
|
|
317
|
+
const writeScopes = async (tx, triggerId, scopes) => {
|
|
318
|
+
await tx.run("DELETE FROM trigger_scopes WHERE trigger_id = ?", triggerId);
|
|
319
|
+
for (const { kind, scope } of scopes)
|
|
320
|
+
await tx.run("INSERT INTO trigger_scopes (kind, scope, trigger_id) VALUES (?, ?, ?)", kind, scope, triggerId);
|
|
321
|
+
};
|
|
322
|
+
/** Refused (AgentArchived) when agent `agentId` is archived: read in the writing transaction, so an archive that
|
|
323
|
+
* commits first is seen, and one that commits after finds what this wrote. */
|
|
324
|
+
const refuseArchived = async (tx, agentId) => {
|
|
325
|
+
if ((await tx.get("SELECT archived_at FROM agents WHERE id = ?", agentId))?.archived_at != null)
|
|
326
|
+
throw new AgentArchived(agentId);
|
|
327
|
+
};
|
|
328
|
+
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
329
|
+
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
330
|
+
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
331
|
+
const upsertTrigger = async (tx, agentId, trigger, at, { insertOnly = false } = {}) => {
|
|
332
|
+
const enabled = trigger.enabled !== false;
|
|
333
|
+
const onName = insertOnly ? "" : `ON CONFLICT (agent_id, name) DO UPDATE SET enabled = excluded.enabled, source = excluded.source, target = excluded.target,
|
|
334
|
+
next_at = excluded.next_at, catchup_window_s = excluded.catchup_window_s, disabled = NULL, updated_at = excluded.updated_at`;
|
|
335
|
+
const row = await tx.get(`INSERT INTO triggers (id, agent_id, name, enabled, source, target, next_at, catchup_window_s, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
336
|
+
${onName} RETURNING id`, trigger.id, agentId, trigger.name, enabled ? 1 : 0, json(trigger.source), json(trigger.target), trigger.nextAt ?? null, trigger.catchupWindowS ?? null, at, at);
|
|
337
|
+
await writeScopes(tx, row.id, enabled ? (trigger.scopes ?? []) : []);
|
|
338
|
+
};
|
|
339
|
+
// A running run whose sign_in_handed holds `hash` (handedHolderIn), or any running run handed a sign-in at all
|
|
340
|
+
// (handedAnyIn): the reads forget, the view, the runner's bind and its output check make, over `runs` alone. By default
|
|
341
|
+
// only a running run holds it; `settleMs` (a vendor's settle window, measured from the store clock `at`) also counts a
|
|
342
|
+
// run that left running (ended or parked) less than that ago, so a new run does not save over a context write-back in
|
|
343
|
+
// flight. `not` drops one run id (a bind's own, so a run is never its own blocker).
|
|
344
|
+
const handedHolderIn = (tx, hash, { not, settleMs = 0, now: at = { sql: d.bigintParam, params: [0] } } = {}) => {
|
|
345
|
+
// The settle window on the deadlines' clock (the database's on Postgres), the one that stamped left_running_at.
|
|
346
|
+
const settle = settleMs > 0 ? ` OR (left_running_at IS NOT NULL AND left_running_at > ${at.sql} - ?)` : "";
|
|
347
|
+
// d.jsonArrayHas carries the hash's own `?`, so the hash comes last in the params.
|
|
348
|
+
return tx.get(`SELECT id FROM runs WHERE sign_in_handed IS NOT NULL${not === undefined ? "" : " AND id != ?"}
|
|
349
|
+
AND (state = 'running'${settle})
|
|
350
|
+
AND ${d.jsonArrayHas("sign_in_handed")} LIMIT 1`, ...(not === undefined ? [] : [not]), ...(settleMs > 0 ? [...at.params, settleMs] : []), hash);
|
|
351
|
+
};
|
|
352
|
+
const handedAnyIn = (tx) => tx.get(`SELECT id FROM runs WHERE state = 'running' AND sign_in_handed IS NOT NULL AND ${d.jsonArrayLength("sign_in_handed")} > 0 LIMIT 1`);
|
|
353
|
+
this.agents = {
|
|
354
|
+
put: async ({ id, name, description = null }) => {
|
|
355
|
+
await db.write([{ sql: "INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", params: [id, name, description, now()] }]);
|
|
356
|
+
},
|
|
357
|
+
create: async (agent, firstRevision) => {
|
|
358
|
+
await db.transaction(async (tx) => {
|
|
359
|
+
const at = now();
|
|
360
|
+
await insertAgent(tx, agent, at);
|
|
361
|
+
await insertRevision(tx, agent.id, firstRevision, at);
|
|
362
|
+
});
|
|
363
|
+
},
|
|
364
|
+
get: async (id) => {
|
|
365
|
+
const row = await db.get(`SELECT ${AGENT_COLUMNS} FROM agents WHERE id = ?`, id);
|
|
366
|
+
return row && agentOf(row);
|
|
367
|
+
},
|
|
368
|
+
byExternal: async (ref) => {
|
|
369
|
+
const row = await db.get(`SELECT ${AGENT_COLUMNS} FROM agents WHERE external_ref = ?`, ref);
|
|
370
|
+
return row && agentOf(row);
|
|
371
|
+
},
|
|
372
|
+
list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
|
|
373
|
+
archive: async (id, archived, why) => db.transaction(async (tx) => {
|
|
374
|
+
const at = now();
|
|
375
|
+
await tx.run("UPDATE agents SET archived_at = ? WHERE id = ?", archived ? at : null, id);
|
|
376
|
+
if (!archived)
|
|
377
|
+
return [];
|
|
378
|
+
// Its triggers that are on, off in this same commit: a firing's fire reads the archive in its own transaction.
|
|
379
|
+
const off = await tx.all("UPDATE triggers SET enabled = 0, next_at = NULL, disabled = ?, updated_at = ? WHERE agent_id = ? AND enabled = 1 RETURNING id, name", why === undefined ? null : json(why), at, id);
|
|
380
|
+
for (const t of off)
|
|
381
|
+
await writeScopes(tx, t.id, []);
|
|
382
|
+
return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
|
|
383
|
+
}),
|
|
384
|
+
addRevision: async ({ agentId, ...revision }) => {
|
|
385
|
+
await db.transaction((tx) => insertRevision(tx, agentId, revision, now()));
|
|
386
|
+
},
|
|
387
|
+
setCurrent: async (agentId, revisionId) => {
|
|
388
|
+
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));
|
|
389
|
+
if (changed === 0)
|
|
390
|
+
throw new StoreConstraint(`${revisionId} is not a revision of agent ${agentId}`);
|
|
391
|
+
},
|
|
392
|
+
revision: async (id) => {
|
|
393
|
+
const row = await db.get(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE id = ?`, id);
|
|
394
|
+
return row && revisionOf(row);
|
|
395
|
+
},
|
|
396
|
+
revisions: async (agentId) => (await db.all(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? ORDER BY created_at, id`, agentId)).map(revisionOf),
|
|
397
|
+
};
|
|
398
|
+
this.templates = {
|
|
399
|
+
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
400
|
+
if (idempotencyKey !== undefined) {
|
|
401
|
+
// Two applies under one key at once: the second waits for the first, then reads its kept answer.
|
|
402
|
+
await d.lockKey(tx, `templates.apply|${idempotencyKey}`);
|
|
403
|
+
const kept = await tx.get("SELECT response FROM idempotency WHERE scope = 'templates.apply' AND key = ?", idempotencyKey);
|
|
404
|
+
if (kept)
|
|
405
|
+
return JSON.parse(kept.response);
|
|
406
|
+
}
|
|
407
|
+
const at = now();
|
|
408
|
+
await insertAgent(tx, agent, at);
|
|
409
|
+
await insertRevision(tx, agent.id, revision, at);
|
|
410
|
+
// A new agent has no triggers: a plain insert. UNIQUE (agent_id, name) cannot fire here by construction: a
|
|
411
|
+
// package names each trigger once, compared trimmed as a trigger keeps its name (templates.ts readPackage), so
|
|
412
|
+
// the names it is given are distinct once trimmed. A caller that passed two the same anyway is refused by the
|
|
413
|
+
// constraint as a StoreConstraint, and this transaction writes nothing: never a part of an apply.
|
|
414
|
+
for (const trigger of triggers)
|
|
415
|
+
await upsertTrigger(tx, agent.id, trigger, at, { insertOnly: true });
|
|
416
|
+
const result = { agentId: agent.id, revisionId: revision.id };
|
|
417
|
+
if (idempotencyKey !== undefined)
|
|
418
|
+
await tx.run("INSERT INTO idempotency (scope, key, response, at) VALUES ('templates.apply', ?, ?, ?)", idempotencyKey, json(result), at);
|
|
419
|
+
return result;
|
|
420
|
+
}),
|
|
421
|
+
upgrade: async (agentId, revision, { upsert, remove }) => {
|
|
422
|
+
await db.transaction(async (tx) => {
|
|
423
|
+
const at = now();
|
|
424
|
+
await insertRevision(tx, agentId, revision, at);
|
|
425
|
+
for (const name of remove)
|
|
426
|
+
await tx.run("DELETE FROM triggers WHERE agent_id = ? AND name = ?", agentId, name);
|
|
427
|
+
for (const trigger of upsert)
|
|
428
|
+
await upsertTrigger(tx, agentId, trigger, at);
|
|
429
|
+
});
|
|
430
|
+
},
|
|
431
|
+
};
|
|
432
|
+
this.triggers = {
|
|
433
|
+
get: async (id) => {
|
|
434
|
+
const row = await db.get(`SELECT ${TRIGGER_COLUMNS} FROM triggers WHERE id = ?`, id);
|
|
435
|
+
return row && triggerOf(row);
|
|
436
|
+
},
|
|
437
|
+
list: async (agentId) => (await db.all(`SELECT ${TRIGGER_COLUMNS} FROM triggers WHERE agent_id = ? ORDER BY name`, agentId)).map(triggerOf),
|
|
438
|
+
all: async () => (await db.all(`SELECT ${TRIGGER_COLUMNS} FROM triggers ORDER BY created_at, id`)).map(triggerOf),
|
|
439
|
+
create: async (t, scopes = []) => {
|
|
440
|
+
const at = now();
|
|
441
|
+
const row = await db.transaction(async (tx) => {
|
|
442
|
+
// A trigger belongs to an agent the store holds: refused in words, never a bare foreign-key failure.
|
|
443
|
+
if (!(await tx.get("SELECT id FROM agents WHERE id = ?", t.agentId)))
|
|
444
|
+
throw new StoreConstraint(`no agent ${t.agentId}: a trigger belongs to an agent the store holds`);
|
|
445
|
+
if (t.enabled)
|
|
446
|
+
await refuseArchived(tx, t.agentId);
|
|
447
|
+
const made = await tx.get(`INSERT INTO triggers (id, agent_id, name, enabled, source, target, next_at, catchup_window_s, max_active_runs, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING ${TRIGGER_COLUMNS}`, t.id, t.agentId, t.name, t.enabled ? 1 : 0, json(t.source), json(t.target), t.nextAt, t.catchupWindowS, t.maxActiveRuns ?? null, at, at);
|
|
448
|
+
if (t.enabled)
|
|
449
|
+
await writeScopes(tx, t.id, scopes);
|
|
450
|
+
return made;
|
|
451
|
+
});
|
|
452
|
+
return triggerOf(row);
|
|
453
|
+
},
|
|
454
|
+
update: async (id, patch, scopes) => {
|
|
455
|
+
const { set, params } = triggerSet(patch, now());
|
|
456
|
+
const row = await db.transaction(async (tx) => {
|
|
457
|
+
// Moved to another agent (its target re-aimed): one the store holds, refused in words otherwise.
|
|
458
|
+
if (patch.agentId !== undefined && !(await tx.get("SELECT id FROM agents WHERE id = ?", patch.agentId)))
|
|
459
|
+
throw new StoreConstraint(`no agent ${patch.agentId}: a trigger belongs to an agent the store holds`);
|
|
460
|
+
const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ? RETURNING ${TRIGGER_COLUMNS}`, ...params, id);
|
|
461
|
+
// Never left on for an archived agent (turned on, or moved there on): the whole update is undone.
|
|
462
|
+
if (changed?.enabled === 1)
|
|
463
|
+
await refuseArchived(tx, changed.agent_id);
|
|
464
|
+
// Scope rows only while it is on: turned off, it holds none; given scopes, they are its rows now.
|
|
465
|
+
if (changed && (changed.enabled === 0 || scopes !== undefined))
|
|
466
|
+
await writeScopes(tx, id, changed.enabled === 1 ? (scopes ?? []) : []);
|
|
467
|
+
return changed;
|
|
468
|
+
});
|
|
469
|
+
return row && triggerOf(row);
|
|
470
|
+
},
|
|
471
|
+
scoped: async (kind, scope) => (await db.all("SELECT trigger_id FROM trigger_scopes WHERE kind = ? AND scope = ?", kind, scope)).map((r) => r.trigger_id),
|
|
472
|
+
remove: async (id) => {
|
|
473
|
+
await db.write([{ sql: "DELETE FROM triggers WHERE id = ?", params: [id] }]);
|
|
474
|
+
},
|
|
475
|
+
record: async (triggerId, firings, { patch, room } = {}) => db.transaction(async (tx) => {
|
|
476
|
+
const at = now();
|
|
477
|
+
// The trigger's row held first, in every transaction that reads its firings to write them (record, settle,
|
|
478
|
+
// message, prune, fire): one at a time per trigger, in one lock order.
|
|
479
|
+
await d.lockRow(tx, "triggers", "id", triggerId);
|
|
480
|
+
if (!(await tx.get("SELECT id FROM triggers WHERE id = ?", triggerId)))
|
|
481
|
+
return undefined;
|
|
482
|
+
if (room !== undefined && firings.some((f) => f.status === "due")) {
|
|
483
|
+
const due = (await tx.get("SELECT COUNT(*) AS n FROM trigger_firings WHERE trigger_id = ? AND status = 'due'", triggerId)).n;
|
|
484
|
+
if (due >= room)
|
|
485
|
+
throw new TriggerFull(triggerId, due);
|
|
486
|
+
}
|
|
487
|
+
const created = [];
|
|
488
|
+
for (const f of firings) {
|
|
489
|
+
const n = await tx.runCounted(`INSERT INTO trigger_firings (trigger_id, key, by, nominal_at, status, at, reason, count, catch_up, payload, attrs, shown) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
490
|
+
ON CONFLICT (trigger_id, key) DO NOTHING`, triggerId, f.key, f.by, f.nominalAt, f.status, at, f.reason ?? null, f.count ?? null, f.catchUp ? 1 : null, f.status === "due" ? (f.payload ?? null) : null, f.attrs === undefined ? null : json(f.attrs), f.shown === false ? 0 : 1);
|
|
491
|
+
created.push(n === 1);
|
|
492
|
+
}
|
|
493
|
+
if (patch) {
|
|
494
|
+
const { set, params } = triggerSet(patch, at);
|
|
495
|
+
await tx.run(`UPDATE triggers SET ${set} WHERE id = ?`, ...params, triggerId);
|
|
496
|
+
}
|
|
497
|
+
return { created };
|
|
498
|
+
}),
|
|
499
|
+
firing: async (triggerId, key) => {
|
|
500
|
+
const row = await db.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
|
|
501
|
+
return row && firingOf(row);
|
|
502
|
+
},
|
|
503
|
+
firings: async (triggerId) => (await db.all(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC`, triggerId)).map(firingOf),
|
|
504
|
+
settle: async (triggerId, key, change, streak) => db.transaction(async (tx) => {
|
|
505
|
+
const at = now();
|
|
506
|
+
await d.lockRow(tx, "triggers", "id", triggerId);
|
|
507
|
+
const was = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
|
|
508
|
+
if (!was)
|
|
509
|
+
return undefined;
|
|
510
|
+
const settled = change.status !== undefined && change.status !== "due";
|
|
511
|
+
// Out of due, a firing keeps no retry, wait, payload or attrs, nor the reason its last try gave (unless it gives one).
|
|
512
|
+
const set = [];
|
|
513
|
+
if (change.status !== undefined)
|
|
514
|
+
set.push(["status", change.status]);
|
|
515
|
+
if (settled)
|
|
516
|
+
set.push(["retry_at", null], ["waits_on", null], ["payload", null], ["attrs", null], ["reason", change.reason ?? null], ["attempts", change.attempts ?? 0]);
|
|
517
|
+
else if (change.reason !== undefined)
|
|
518
|
+
set.push(["reason", change.reason]);
|
|
519
|
+
if (change.runId !== undefined)
|
|
520
|
+
set.push(["run_id", change.runId]);
|
|
521
|
+
if (change.error !== undefined)
|
|
522
|
+
set.push(["error", json(change.error)]);
|
|
523
|
+
if (!settled && change.attempts !== undefined)
|
|
524
|
+
set.push(["attempts", change.attempts]);
|
|
525
|
+
if (!settled && change.retryAt !== undefined)
|
|
526
|
+
set.push(["retry_at", change.retryAt]);
|
|
527
|
+
if (!settled && change.waitsOn !== undefined)
|
|
528
|
+
set.push(["waits_on", change.waitsOn]);
|
|
529
|
+
if (change.notified !== undefined)
|
|
530
|
+
set.push(["notified", change.notified ? 1 : 0]);
|
|
531
|
+
let paused = false;
|
|
532
|
+
const trigger = await tx.get("SELECT failures_in_a_row, enabled, last_run_id, target FROM triggers WHERE id = ?", triggerId);
|
|
533
|
+
const triggerSets = [];
|
|
534
|
+
// Run ids are UUIDv7s, which sort by when the run started: a firing that finds an older run never takes a later
|
|
535
|
+
// one's place as the trigger's last run.
|
|
536
|
+
if (change.runId !== undefined && trigger && JSON.parse(trigger.target).kind === "start_run" && !(trigger.last_run_id && trigger.last_run_id > change.runId)) {
|
|
537
|
+
triggerSets.push(["last_run_id", change.runId]);
|
|
538
|
+
}
|
|
539
|
+
if (streak && "reset" in streak)
|
|
540
|
+
triggerSets.push(["failures_in_a_row", 0]);
|
|
541
|
+
if (streak && "failure" in streak && trigger) {
|
|
542
|
+
const failures = trigger.failures_in_a_row + 1;
|
|
543
|
+
triggerSets.push(["failures_in_a_row", failures]);
|
|
544
|
+
if (failures >= streak.pauseAt && trigger.enabled === 1) {
|
|
545
|
+
paused = true;
|
|
546
|
+
triggerSets.push(["enabled", 0], ["next_at", null], ["disabled", json({ at: new Date(at).toISOString(), reason: "auto_paused" })]);
|
|
547
|
+
set.push(["paused", 1]);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (set.length)
|
|
551
|
+
await tx.run(`UPDATE trigger_firings SET ${set.map(([c]) => `${c} = ?`).join(", ")} WHERE trigger_id = ? AND key = ?`, ...set.map(([, v]) => v), triggerId, key);
|
|
552
|
+
if (triggerSets.length) {
|
|
553
|
+
triggerSets.push(["updated_at", at]);
|
|
554
|
+
await tx.run(`UPDATE triggers SET ${triggerSets.map(([c]) => `${c} = ?`).join(", ")} WHERE id = ?`, ...triggerSets.map(([, v]) => v), triggerId);
|
|
555
|
+
}
|
|
556
|
+
if (paused)
|
|
557
|
+
await writeScopes(tx, triggerId, []);
|
|
558
|
+
const row = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
|
|
559
|
+
return { firing: firingOf(row), paused };
|
|
560
|
+
}),
|
|
561
|
+
pending: async () => (await db.all(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE status = 'due' OR (status = 'failed' AND (notified IS NULL OR notified = 0)) ORDER BY at, ${d.firingOrder}`)).map(firingOf),
|
|
562
|
+
message: async ({ triggerId, key }, runId, command, bound) => db.transaction(async (tx) => {
|
|
563
|
+
const at = now();
|
|
564
|
+
await d.lockRow(tx, "triggers", "id", triggerId);
|
|
565
|
+
const firing = await tx.get("SELECT status FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
|
|
566
|
+
if (!firing || firing.status !== "due")
|
|
567
|
+
return undefined;
|
|
568
|
+
const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText("body", ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
|
|
569
|
+
const clear = "retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, attempts = 0";
|
|
570
|
+
if (waiting >= bound.max) {
|
|
571
|
+
await tx.run(`UPDATE trigger_firings SET status = 'skipped', reason = ?, ${clear} WHERE trigger_id = ? AND key = ?`, bound.reason, triggerId, key);
|
|
572
|
+
return { skipped: bound.reason };
|
|
573
|
+
}
|
|
574
|
+
// As command(): the run row read under the share lock, so a message never lands on a run whose end is in flight
|
|
575
|
+
// or written, where it would wait untaken; a final run takes none (RunFinal) and the firing stays as it was.
|
|
576
|
+
const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) SELECT id, ?, ?, ? FROM runs WHERE id = ? AND state NOT IN (${FINAL})${d.shareLock} RETURNING id`, command.kind, json(command.body), at, runId);
|
|
577
|
+
if (!row)
|
|
578
|
+
throw new RunFinal(runId);
|
|
579
|
+
await tx.run(`UPDATE trigger_firings SET status = 'sent', run_id = ?, reason = NULL, ${clear} WHERE trigger_id = ? AND key = ?`, runId, triggerId, key);
|
|
580
|
+
await tx.run("UPDATE triggers SET failures_in_a_row = 0, updated_at = ? WHERE id = ?", at, triggerId);
|
|
581
|
+
return { sent: true, commandId: row.id };
|
|
582
|
+
}),
|
|
583
|
+
waiting: async () => (await db.all(`SELECT ${FIRING_COLUMNS.split(", ").map((c) => `f.${c}`).join(", ")},
|
|
584
|
+
(SELECT COUNT(*) FROM trigger_firings s JOIN runs r ON r.id = s.run_id
|
|
585
|
+
WHERE s.trigger_id = f.trigger_id AND s.status = 'started' AND r.state NOT IN (${FINAL})) < COALESCE(t.max_active_runs, 1) AS free
|
|
586
|
+
FROM trigger_firings f JOIN triggers t ON t.id = f.trigger_id
|
|
587
|
+
WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
|
|
588
|
+
soonest: async () => (await db.get("SELECT MIN(next_at) AS at FROM triggers WHERE enabled = 1 AND next_at IS NOT NULL"))?.at ?? null,
|
|
589
|
+
activeRuns: async (triggerId) => (await db.get(`SELECT COUNT(*) AS n FROM trigger_firings f JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND f.status = 'started' AND r.state NOT IN (${FINAL})`, triggerId)).n,
|
|
590
|
+
prune: async (triggerId, { history, dayMs, keepByKey, kept }) => db.transaction(async (tx) => {
|
|
591
|
+
const at = now();
|
|
592
|
+
await d.lockRow(tx, "triggers", "id", triggerId);
|
|
593
|
+
// Past the newest `history` shown firings: never a due one, a failure not yet told, or a started one whose run
|
|
594
|
+
// has not ended. The rest leave the history: kept for their key's day when a sender's key names them, else gone.
|
|
595
|
+
const old = await tx.all(`SELECT f.key, f.by FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id
|
|
596
|
+
WHERE f.trigger_id = ? AND f.shown = 1 AND f.status != 'due' AND NOT (f.status = 'failed' AND (f.notified IS NULL OR f.notified = 0))
|
|
597
|
+
AND NOT (f.status = 'started' AND r.id IS NOT NULL AND r.state NOT IN (${FINAL}))
|
|
598
|
+
AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, triggerId, history);
|
|
599
|
+
for (const { key, by } of old) {
|
|
600
|
+
if (keepByKey(by ?? "manual"))
|
|
601
|
+
await tx.run("UPDATE trigger_firings SET shown = 0, payload = NULL, attrs = NULL WHERE trigger_id = ? AND key = ?", triggerId, key);
|
|
602
|
+
else
|
|
603
|
+
await tx.run("DELETE FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
|
|
604
|
+
}
|
|
605
|
+
await tx.run(`DELETE FROM trigger_firings WHERE trigger_id = ? AND shown = 0 AND at < ? AND status != 'due'
|
|
606
|
+
AND NOT (status = 'started' AND run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})))`, triggerId, at - dayMs);
|
|
607
|
+
if (kept === undefined)
|
|
608
|
+
return 0;
|
|
609
|
+
// Past `kept` keys for the day, the oldest go first (a key's row, not its run: a started one's run has ended).
|
|
610
|
+
return tx.runCounted(`DELETE FROM trigger_firings WHERE trigger_id = ? AND key IN (
|
|
611
|
+
SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 0 AND status != 'due'
|
|
612
|
+
AND NOT (status = 'started' AND run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})))
|
|
613
|
+
ORDER BY at DESC, ${d.firingOrder} DESC ${d.limitAll} OFFSET ?)`, triggerId, triggerId, kept);
|
|
614
|
+
}),
|
|
615
|
+
enable: async (triggerId, scopes) => {
|
|
616
|
+
await db.transaction(async (tx) => {
|
|
617
|
+
const on = await tx.get("UPDATE triggers SET enabled = 1, disabled = NULL, updated_at = ? WHERE id = ? RETURNING agent_id", now(), triggerId);
|
|
618
|
+
if (!on)
|
|
619
|
+
throw new StoreConstraint(`no trigger ${triggerId}`);
|
|
620
|
+
await refuseArchived(tx, on.agent_id);
|
|
621
|
+
await writeScopes(tx, triggerId, scopes);
|
|
622
|
+
});
|
|
623
|
+
},
|
|
624
|
+
disable: async (triggerId, why) => {
|
|
625
|
+
await db.transaction(async (tx) => {
|
|
626
|
+
if ((await tx.runCounted("UPDATE triggers SET enabled = 0, disabled = ?, updated_at = ? WHERE id = ?", why === undefined ? null : json(why), now(), triggerId)) === 0) {
|
|
627
|
+
throw new StoreConstraint(`no trigger ${triggerId}`);
|
|
628
|
+
}
|
|
629
|
+
await writeScopes(tx, triggerId, []);
|
|
630
|
+
});
|
|
631
|
+
},
|
|
632
|
+
fire: async (firing, run, { launch } = {}) => db.transaction(async (tx) => {
|
|
633
|
+
const at = now();
|
|
634
|
+
await d.lockRow(tx, "triggers", "id", firing.triggerId);
|
|
635
|
+
// Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
|
|
636
|
+
await refuseArchived(tx, run.agentId);
|
|
637
|
+
const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, at);
|
|
638
|
+
// The run's launch row lands with it, through the store's one writer, or neither does.
|
|
639
|
+
if (launch)
|
|
640
|
+
await writeLaunch(tx, run.id, launch, at);
|
|
641
|
+
// The due firing the engine recorded becomes started; one not recorded yet is recorded started. A firing already
|
|
642
|
+
// past due (started, or settled otherwise) is refused, and its run with it.
|
|
643
|
+
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 status = 'due'", run.id, firing.triggerId, firing.key);
|
|
644
|
+
if (moved === 0) {
|
|
645
|
+
await tx.run("INSERT INTO trigger_firings (trigger_id, key, by, nominal_at, status, at, run_id, catch_up) VALUES (?, ?, ?, ?, 'started', ?, ?, ?)", firing.triggerId, firing.key, firing.by ?? null, firing.nominalAt ?? null, at, run.id, firing.catchUp === undefined ? null : firing.catchUp ? 1 : 0);
|
|
646
|
+
}
|
|
647
|
+
if ((await tx.runCounted("UPDATE triggers SET last_run_id = ?, failures_in_a_row = 0, updated_at = ? WHERE id = ?", run.id, at, firing.triggerId)) === 0)
|
|
648
|
+
throw new StoreConstraint(`no trigger ${firing.triggerId}`);
|
|
649
|
+
return runOf(row);
|
|
650
|
+
}),
|
|
651
|
+
};
|
|
652
|
+
this.runs = {
|
|
653
|
+
create: async ({ id, agentId, revisionId, origin }, launch) => {
|
|
654
|
+
// sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
|
|
655
|
+
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`;
|
|
656
|
+
if (origin || launch) {
|
|
657
|
+
// The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
|
|
658
|
+
// never lands, and a run never exists without the launch it was started with.
|
|
659
|
+
return db.transaction(async (tx) => {
|
|
660
|
+
const at = now();
|
|
661
|
+
const row = await tx.get(insert, id, agentId, revisionId, at);
|
|
662
|
+
if (origin)
|
|
663
|
+
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
|
|
664
|
+
if (launch)
|
|
665
|
+
await writeLaunch(tx, id, launch, at);
|
|
666
|
+
return runOf(row);
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
const [result] = await db.write([{ sql: insert, params: [id, agentId, revisionId, now()] }]);
|
|
670
|
+
return runOf(result.rows[0]);
|
|
671
|
+
},
|
|
672
|
+
createInline: async ({ agent, revision, run, launch }) => {
|
|
673
|
+
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`;
|
|
674
|
+
return db.transaction(async (tx) => {
|
|
675
|
+
const at = now();
|
|
676
|
+
// Hold the external reference, so two first uses of the same expert serialize (SQLite's one writer already does).
|
|
677
|
+
await d.lockKey(tx, `external:${agent.ref}`);
|
|
678
|
+
// The agent, one per external reference: written on its first run, read on every later one.
|
|
679
|
+
await tx.run(`${d.insertOrIgnore} INTO agents (id, name, description, created_at, external_ref) VALUES (?, ?, ?, ?, ?)${d.onConflictIgnore}`, agent.id, agent.name, agent.description ?? null, at, agent.ref);
|
|
680
|
+
const mapped = (await tx.get("SELECT id, current_revision FROM agents WHERE external_ref = ?", agent.ref));
|
|
681
|
+
// The revision, one per version: a version already stored keeps its body (a different body is refused); a new
|
|
682
|
+
// version is written, made current, and brings the agent's name and description up to it (the source is the truth).
|
|
683
|
+
const existing = await tx.get("SELECT id, body FROM revisions WHERE agent_id = ? AND external_version = ?", mapped.id, revision.version);
|
|
684
|
+
let revisionId;
|
|
685
|
+
if (existing) {
|
|
686
|
+
if (canonical(JSON.parse(existing.body)) !== canonical(revision.body))
|
|
687
|
+
throw new ExternalBodyConflict(agent.ref, revision.version);
|
|
688
|
+
revisionId = existing.id;
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
revisionId = revision.id;
|
|
692
|
+
await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, external_version, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revisionId, mapped.id, mapped.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, null, revision.version, at);
|
|
693
|
+
await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
|
|
694
|
+
}
|
|
695
|
+
// The run, its origin and its launch, in the same transaction as the agent and the revision.
|
|
696
|
+
const row = await tx.get(insert, run.id, mapped.id, revisionId, at);
|
|
697
|
+
if (run.origin)
|
|
698
|
+
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", run.origin.key, run.id, run.origin.fingerprint ?? null, at);
|
|
699
|
+
await writeLaunch(tx, run.id, launch, at);
|
|
700
|
+
return runOf(row);
|
|
701
|
+
});
|
|
702
|
+
},
|
|
703
|
+
get: async (id) => {
|
|
704
|
+
const row = await db.get(`SELECT ${RUN_COLUMNS} FROM runs WHERE id = ?`, id);
|
|
705
|
+
return row && runOf(row);
|
|
706
|
+
},
|
|
707
|
+
launch: (runId) => readLaunch(db, runId),
|
|
708
|
+
list: async ({ agentId, revisionId, state, archived, limit }) => {
|
|
709
|
+
const where = [];
|
|
710
|
+
const params = [];
|
|
711
|
+
if (agentId !== undefined)
|
|
712
|
+
(where.push("agent_id = ?"), params.push(agentId));
|
|
713
|
+
if (revisionId !== undefined)
|
|
714
|
+
(where.push("revision_id = ?"), params.push(revisionId));
|
|
715
|
+
if (state !== undefined)
|
|
716
|
+
(where.push("state = ?"), params.push(state));
|
|
717
|
+
if (archived !== undefined)
|
|
718
|
+
where.push(`archived_at IS ${archived ? "NOT NULL" : "NULL"}`);
|
|
719
|
+
const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
|
|
720
|
+
if (bounded)
|
|
721
|
+
params.push(limit);
|
|
722
|
+
const rows = await db.all(`SELECT ${RUN_COLUMNS} FROM runs ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY started_at DESC, id DESC${bounded ? " LIMIT ?" : ""}`, ...params);
|
|
723
|
+
return rows.map(runOf);
|
|
724
|
+
},
|
|
725
|
+
archive: async (runId, archived) => {
|
|
726
|
+
await db.write([{ sql: "UPDATE runs SET archived_at = ? WHERE id = ?", params: [archived ? now() : null, runId] }]);
|
|
727
|
+
},
|
|
728
|
+
reopen: async (runId, { kind, body = null }) => db.transaction(async (tx) => {
|
|
729
|
+
// Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
|
|
730
|
+
// spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
|
|
731
|
+
const reopened = await tx.runCounted(`UPDATE runs SET state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL
|
|
732
|
+
WHERE id = ? AND state = 'ended' AND imported_from IS NULL
|
|
733
|
+
AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
|
|
734
|
+
AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText("run_launch.body", ["harness"])} = 'learning')`, runId);
|
|
735
|
+
if (reopened === 0)
|
|
736
|
+
throw new RunFinal(runId);
|
|
737
|
+
const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) VALUES (?, ?, ?, ?) RETURNING ${COMMAND_COLUMNS}`, runId, kind, json(body), now());
|
|
738
|
+
return commandOf(row);
|
|
739
|
+
}),
|
|
740
|
+
claimable: async ({ limit } = {}) => {
|
|
741
|
+
const claimable = claimableIn(d, clock());
|
|
742
|
+
const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
|
|
743
|
+
const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
|
|
744
|
+
return rows.map((row) => row.id);
|
|
745
|
+
},
|
|
746
|
+
claimMany: (runner, k, { leaseMs = DEFAULT_LEASE_MS } = {}) => this.#claimRuns(runner, leaseMs, { k }),
|
|
747
|
+
update: async (claim, patch, rows = {}) => {
|
|
748
|
+
if (Array.isArray(rows) || typeof rows !== "object" || rows === null)
|
|
749
|
+
throw new TypeError("runs.update's third argument is { also?, take?, signInSettleMs? }");
|
|
750
|
+
const { also = [], take = [], signInSettleMs = 0 } = rows;
|
|
751
|
+
return db.transaction(async (tx) => {
|
|
752
|
+
// A run update may end the run, moving its epoch on: held against every write under the claim (dialect lockRow).
|
|
753
|
+
await d.lockRow(tx, "runs", "id", claim.runId, "update");
|
|
754
|
+
const at = now();
|
|
755
|
+
const row = await applyRunPatch(tx, claim, patch, also, at, d, storeNow(d, () => at));
|
|
756
|
+
for (const commandId of take) {
|
|
757
|
+
if ((await tx.runCounted("UPDATE commands SET taken_at = ? WHERE id = ? AND run_id = ? AND taken_at IS NULL", at, commandId, claim.runId)) === 0) {
|
|
758
|
+
throw new CommandTaken(claim.runId, commandId);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
// An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
|
|
762
|
+
await refuseLeftovers(tx, claim.runId, patch.state, at);
|
|
763
|
+
// The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
|
|
764
|
+
// SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
|
|
765
|
+
// or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
|
|
766
|
+
// ago). Excludes this run (it just wrote them), so a run is never its own blocker. Two binds of one sign-in in one
|
|
767
|
+
// tick thus never both save.
|
|
768
|
+
if (patch.signInHanded !== undefined && patch.signInHanded !== null && patch.signInHanded.length > 0) {
|
|
769
|
+
let holder;
|
|
770
|
+
for (const hash of patch.signInHanded) {
|
|
771
|
+
holder = await handedHolderIn(tx, hash, { not: claim.runId, settleMs: signInSettleMs, now: storeNow(d, () => at) });
|
|
772
|
+
if (holder)
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
return { ...row, save: holder === undefined };
|
|
776
|
+
}
|
|
777
|
+
return row;
|
|
778
|
+
});
|
|
779
|
+
},
|
|
780
|
+
};
|
|
781
|
+
/** A server's write (Mcp.put), or with `expected` (Mcp.putIfCredential) only while the row's credential is still that:
|
|
782
|
+
* the statement's own WHERE compares it, so the comparison and the write are one statement. */
|
|
783
|
+
const putServer = async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, sealed = null, listedAt, updatedAt, credentialChangedAt, tokenLeftMs = null }, expected) => {
|
|
784
|
+
const at = now();
|
|
785
|
+
// The access token's end on the deadlines' clock (the database's on Postgres): the writer's measure of its life (a
|
|
786
|
+
// duration, clock-free) laid on that clock's now (token_until), in the statement that writes it.
|
|
787
|
+
const left = sealed !== null && typeof tokenLeftMs === "number" && Number.isFinite(tokenLeftMs) ? tokenLeftMs : null;
|
|
788
|
+
const stamp = clock();
|
|
789
|
+
// updated_at defaults to now (a save or a sign-in); a refresh passes the kept one so it is not read as an edit.
|
|
790
|
+
// listed_at is the tools' listing time, now unless given.
|
|
791
|
+
const updated = updatedAt ?? at;
|
|
792
|
+
const listed = listedAt ?? at;
|
|
793
|
+
// The credential's own time: now for a put that writes one, unless the caller says it kept the sealed one (its
|
|
794
|
+
// time given back); null with none. A token refresh (keepRefreshed) never moves it.
|
|
795
|
+
const credentialAt = sealed === null ? null : credentialChangedAt === undefined ? at : credentialChangedAt;
|
|
796
|
+
const values = [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, sealed];
|
|
797
|
+
// Expected present: an UPDATE of that row while its credential is still the one expected (gone, or changed: no row).
|
|
798
|
+
// Expected absent: an insert only (a row there: no row). Else the upsert. Either way RETURNING answers what it wrote.
|
|
799
|
+
const statement = expected !== undefined && expected !== null
|
|
800
|
+
? {
|
|
801
|
+
sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, sealed = ?, refresh_holder = NULL, refresh_until = NULL,
|
|
802
|
+
updated_at = ?, listed_at = ?, credential_changed_at = ?, token_until = ${stamp.sql} + ${d.bigintParam}
|
|
803
|
+
WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}
|
|
804
|
+
RETURNING ${mcpServerColumnsAt(stamp)}`,
|
|
805
|
+
params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...stamp.params],
|
|
806
|
+
}
|
|
807
|
+
: {
|
|
808
|
+
sql: `INSERT INTO mcp_servers (name, url, auth, protocol, tools, prices, server_info, instructions, sealed, created_at, updated_at, listed_at, credential_changed_at, token_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql} + ${d.bigintParam})
|
|
809
|
+
ON CONFLICT (name) DO UPDATE SET url = excluded.url, auth = excluded.auth, protocol = excluded.protocol, tools = excluded.tools,
|
|
810
|
+
prices = excluded.prices, server_info = excluded.server_info, instructions = excluded.instructions, sealed = excluded.sealed, refresh_holder = NULL, refresh_until = NULL, updated_at = excluded.updated_at, listed_at = excluded.listed_at, credential_changed_at = excluded.credential_changed_at, token_until = excluded.token_until
|
|
811
|
+
${expected === null ? "WHERE 1 = 0" : ""}
|
|
812
|
+
RETURNING ${mcpServerColumnsAt(stamp)}`,
|
|
813
|
+
params: [name, ...values, at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
|
|
814
|
+
};
|
|
815
|
+
const [result] = await db.write([statement]);
|
|
816
|
+
const written = result.rows[0];
|
|
817
|
+
return written && mcpServerOf(written);
|
|
818
|
+
};
|
|
819
|
+
const server = async (executor, name) => {
|
|
820
|
+
const at = clock();
|
|
821
|
+
const row = await executor.get(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers WHERE name = ?`, ...at.params, name);
|
|
822
|
+
return row && mcpServerOf(row);
|
|
823
|
+
};
|
|
824
|
+
this.mcp = {
|
|
825
|
+
put: async (row) => (await putServer(row, undefined)),
|
|
826
|
+
putIfCredential: (row, expected) => putServer(row, expected),
|
|
827
|
+
// One statement compares the credential and writes, as keepRefreshed: no read between, so a refresh's keep never lands
|
|
828
|
+
// in a gap and is then written over. The credential's columns and the refresh lease are not in its SET.
|
|
829
|
+
rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen) => {
|
|
830
|
+
const at = now();
|
|
831
|
+
const stamp = clock();
|
|
832
|
+
const [result] = await db.write([{
|
|
833
|
+
sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
|
|
834
|
+
WHERE name = ? AND ${d.nullSafeEquals("sealed")}
|
|
835
|
+
RETURNING ${mcpServerColumnsAt(stamp)}`,
|
|
836
|
+
params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
|
|
837
|
+
}]);
|
|
838
|
+
const row = result.rows[0];
|
|
839
|
+
return row && mcpServerOf(row);
|
|
840
|
+
},
|
|
841
|
+
remove: async (name) => {
|
|
842
|
+
await db.write([{ sql: "DELETE FROM mcp_servers WHERE name = ?", params: [name] }]);
|
|
843
|
+
},
|
|
844
|
+
removeIfCredential: async (name, expected) => {
|
|
845
|
+
const [result] = await db.write([{
|
|
846
|
+
sql: `DELETE FROM mcp_servers WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"} RETURNING name`,
|
|
847
|
+
params: [name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt])],
|
|
848
|
+
}]);
|
|
849
|
+
return result.rows.length === 1;
|
|
850
|
+
},
|
|
851
|
+
servers: async () => {
|
|
852
|
+
const at = clock();
|
|
853
|
+
return (await db.all(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers ORDER BY name`, ...at.params)).map((row) => mcpServerOf(row));
|
|
854
|
+
},
|
|
855
|
+
server: (name) => server(db, name),
|
|
856
|
+
pin: async (runId) => {
|
|
857
|
+
const row = await db.get("SELECT run_id, body, pinned_at FROM mcp_pins WHERE run_id = ?", runId);
|
|
858
|
+
return row && mcpPinOf(row);
|
|
859
|
+
},
|
|
860
|
+
pinOnce: (claim, body) => db.transaction(async (tx) => {
|
|
861
|
+
// Under the claim's epoch and its lease: a runner paused past its lease pins nothing.
|
|
862
|
+
await underClaim(tx, claim, now);
|
|
863
|
+
await tx.run("INSERT INTO mcp_pins (run_id, body, pinned_at) VALUES (?, ?, ?) ON CONFLICT (run_id) DO NOTHING", claim.runId, json(body), now());
|
|
864
|
+
return mcpPinOf((await tx.get("SELECT run_id, body, pinned_at FROM mcp_pins WHERE run_id = ?", claim.runId)));
|
|
865
|
+
}),
|
|
866
|
+
// The credential as read is compared by its bytes (`sealed IS ?`, NULL included): updated_at can repeat within a ms.
|
|
867
|
+
leaseRefresh: async (name, { seen, holder, ms = MCP_REFRESH_LEASE_MS }) => {
|
|
868
|
+
if (!(Number.isFinite(ms) && ms > MCP_REFRESH_CALL_MS)) {
|
|
869
|
+
throw new RangeError(`a refresh lease must be longer than the refresh call's own deadline (${MCP_REFRESH_CALL_MS} ms), not ${ms} ms: it would lapse while its holder's call may still spend the token`);
|
|
870
|
+
}
|
|
871
|
+
return db.transaction(async (tx) => {
|
|
872
|
+
// The lease is stamped and judged on the deadlines' clock (the database's on Postgres): one clock for every store
|
|
873
|
+
// process, so a lease one runner holds is live to every other.
|
|
874
|
+
const at = clock();
|
|
875
|
+
const granted = await tx.runCounted(`UPDATE mcp_servers SET refresh_holder = ?, refresh_until = ${at.sql} + ? WHERE name = ? AND ${d.nullSafeEquals("sealed")} AND (refresh_until IS NULL OR refresh_until < ${at.sql})`, holder, ...at.params, ms, name, seen, ...at.params);
|
|
876
|
+
const row = await server(tx, name);
|
|
877
|
+
if (!row)
|
|
878
|
+
throw new StoreConstraint(`no MCP server ${name}: it is no longer saved`);
|
|
879
|
+
return { leased: granted === 1, row };
|
|
880
|
+
});
|
|
881
|
+
},
|
|
882
|
+
// One statement compares the credential and writes: no read between, so no other write lands in a gap. The lease is
|
|
883
|
+
// cleared only by its own holder (a waiter that took a lapsed lease keeps it, and reads ours at its re-read).
|
|
884
|
+
keepRefreshed: (name, { seen, sealed, holder, tokenLeftMs = null }) => db.transaction(async (tx) => {
|
|
885
|
+
const at = now();
|
|
886
|
+
// The refreshed token's end on the deadlines' clock (token_until; the database's on Postgres), from the refresher's
|
|
887
|
+
// measure of its life (a duration), laid on that clock in this statement.
|
|
888
|
+
const left = typeof tokenLeftMs === "number" && Number.isFinite(tokenLeftMs) ? tokenLeftMs : null;
|
|
889
|
+
const stamp = clock();
|
|
890
|
+
const written = await tx.runCounted(`UPDATE mcp_servers SET sealed = ?, token_until = ${stamp.sql} + ${d.bigintParam},
|
|
891
|
+
refresh_until = CASE WHEN refresh_holder = ? THEN NULL ELSE refresh_until END,
|
|
892
|
+
refresh_holder = CASE WHEN refresh_holder = ? THEN NULL ELSE refresh_holder END,
|
|
893
|
+
updated_at = ${d.greatest}(?, updated_at + 1)
|
|
894
|
+
WHERE name = ? AND ${d.nullSafeEquals("sealed")}`, sealed, ...stamp.params, left, holder, holder, at, name, seen);
|
|
895
|
+
return { kept: written === 1, row: await server(tx, name) };
|
|
896
|
+
}, { deadlineMs: STORE_WRITE_DEADLINE_MS, fromCall: true }),
|
|
897
|
+
releaseRefresh: async (name, holder) => {
|
|
898
|
+
await db.write([{ sql: "UPDATE mcp_servers SET refresh_holder = NULL, refresh_until = NULL WHERE name = ? AND refresh_holder = ?", params: [name, holder] }]);
|
|
899
|
+
},
|
|
900
|
+
};
|
|
901
|
+
this.live = {
|
|
902
|
+
// One transaction for the tick; each row written only under its run's current epoch and live lease (the SELECT finds
|
|
903
|
+
// no run row for a stale or lapsed claim, so nothing is inserted or changed). The drop below stays on the epoch. The
|
|
904
|
+
// run row is read under the share lock: a put never lands beside a run's end or a new claim still in flight.
|
|
905
|
+
put: (rows) => db.transaction(async (tx) => {
|
|
906
|
+
const at = now();
|
|
907
|
+
const written = [];
|
|
908
|
+
const fenced = [];
|
|
909
|
+
for (const { claim, state } of rows) {
|
|
910
|
+
const fence = claimFence(claim, storeNow(d, () => at));
|
|
911
|
+
const changed = await tx.runCounted(`INSERT INTO run_live (run_id, state, updated_at) SELECT id, ?, ? FROM runs WHERE ${fence.where}${d.shareLock}
|
|
912
|
+
ON CONFLICT (run_id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at`, json(state), at, ...fence.params);
|
|
913
|
+
(changed > 0 ? written : fenced).push(claim.runId);
|
|
914
|
+
}
|
|
915
|
+
return { written, fenced };
|
|
916
|
+
}),
|
|
917
|
+
read: async (runIds) => {
|
|
918
|
+
if (runIds.length === 0)
|
|
919
|
+
return [];
|
|
920
|
+
const rows = await db.all(`SELECT run_id, state, updated_at FROM run_live WHERE run_id IN (${runIds.map(() => "?").join(", ")}) ORDER BY run_id`, ...runIds);
|
|
921
|
+
return rows.map((row) => ({ runId: row.run_id, state: JSON.parse(row.state), updatedAt: row.updated_at }));
|
|
922
|
+
},
|
|
923
|
+
drop: async (claim) => {
|
|
924
|
+
await db.write([{
|
|
925
|
+
sql: `DELETE FROM run_live WHERE run_id = ? AND EXISTS (SELECT 1 FROM runs WHERE id = ? AND epoch = ?${d.shareLock})`,
|
|
926
|
+
params: [claim.runId, claim.runId, claim.epoch],
|
|
927
|
+
}]);
|
|
928
|
+
},
|
|
929
|
+
};
|
|
930
|
+
this.liveViewers = {
|
|
931
|
+
// Under the claim's fence (its epoch and its lease, on the store's clock read in this transaction): the SELECT finds
|
|
932
|
+
// no run row for a stale or lapsed claim, so nothing is inserted or changed, and the put answers false.
|
|
933
|
+
put: (claim, viewer) => db.transaction(async (tx) => {
|
|
934
|
+
const at = now();
|
|
935
|
+
const fence = claimFence(claim, storeNow(d, () => at));
|
|
936
|
+
const changed = await tx.runCounted(`INSERT INTO computer_viewers (run_id, kind, tag, port, viewer_id, sealed, at, runner, epoch) SELECT id, ?, ?, ?, ?, ?, ?, ?, ? FROM runs WHERE ${fence.where}${d.shareLock}
|
|
937
|
+
ON CONFLICT (run_id, kind, tag) DO UPDATE SET port = excluded.port, viewer_id = excluded.viewer_id, sealed = excluded.sealed, at = excluded.at, runner = excluded.runner, epoch = excluded.epoch`, viewer.kind, viewer.tag, viewer.port, viewer.id, viewer.sealed, at, claim.runner, claim.epoch, ...fence.params);
|
|
938
|
+
return changed > 0;
|
|
939
|
+
}),
|
|
940
|
+
// On the claim's epoch alone, as run_live's drop: a runner clearing its own rows after its lease ran out takes no
|
|
941
|
+
// one else's. No kind clears the whole run; a kind with no tag that kind's rows; a kind and a tag that one row.
|
|
942
|
+
drop: async (claim, kind, tag) => {
|
|
943
|
+
const narrow = kind === undefined ? "" : tag === undefined ? " AND kind = ?" : " AND kind = ? AND tag = ?";
|
|
944
|
+
const narrowParams = kind === undefined ? [] : tag === undefined ? [kind] : [kind, tag];
|
|
945
|
+
await db.write([{
|
|
946
|
+
sql: `DELETE FROM computer_viewers WHERE run_id = ?${narrow} AND EXISTS (SELECT 1 FROM runs WHERE id = ? AND epoch = ?${d.shareLock})`,
|
|
947
|
+
params: [claim.runId, ...narrowParams, claim.runId, claim.epoch],
|
|
948
|
+
}]);
|
|
949
|
+
},
|
|
950
|
+
// The server's read: only the run's epoch, under a live lease on the store's clock, written by the run's runner.
|
|
951
|
+
of: async (runId) => {
|
|
952
|
+
const live = clock();
|
|
953
|
+
const rows = await db.all(`SELECT v.kind, v.tag, v.port, v.viewer_id, v.sealed, v.at, v.runner FROM computer_viewers v JOIN runs r ON r.id = v.run_id
|
|
954
|
+
WHERE v.run_id = ? AND v.epoch = r.epoch AND r.claimed_until >= ${live.sql} AND v.runner = r.runner ORDER BY v.at DESC, v.tag`, runId, ...live.params);
|
|
955
|
+
return rows.map((row) => ({ kind: row.kind, tag: row.tag, port: row.port, id: row.viewer_id, sealed: new Uint8Array(row.sealed), at: row.at, runner: row.runner }));
|
|
956
|
+
},
|
|
957
|
+
};
|
|
958
|
+
const proposalOf = (row) => ({
|
|
959
|
+
runId: row.run_id, agentId: row.agent_id, turn: JSON.parse(row.turn), proposal: JSON.parse(row.proposal),
|
|
960
|
+
...(row.learning_run_id === null ? {} : { learningRunId: row.learning_run_id }), createdAt: row.created_at,
|
|
961
|
+
});
|
|
962
|
+
this.learning = {
|
|
963
|
+
proposal: async (runId) => {
|
|
964
|
+
const row = await db.get("SELECT run_id, agent_id, turn, proposal, learning_run_id, created_at FROM learning_proposals WHERE run_id = ?", runId);
|
|
965
|
+
return row ? proposalOf(row) : undefined;
|
|
966
|
+
},
|
|
967
|
+
proposals: async (agentId, { limit = 100 } = {}) => (await db.all("SELECT run_id, agent_id, turn, proposal, learning_run_id, created_at FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC LIMIT ?", agentId, limit)).map(proposalOf),
|
|
968
|
+
};
|
|
969
|
+
this.settings = {
|
|
970
|
+
get: async (key) => {
|
|
971
|
+
const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
|
|
972
|
+
return row === undefined ? undefined : JSON.parse(row.value);
|
|
973
|
+
},
|
|
974
|
+
put: async (key, value) => {
|
|
975
|
+
await db.write([{ sql: "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", params: [key, json(value), now()] }]);
|
|
976
|
+
},
|
|
977
|
+
remove: async (key) => {
|
|
978
|
+
await db.write([{ sql: "DELETE FROM settings WHERE key = ?", params: [key] }]);
|
|
979
|
+
},
|
|
980
|
+
all: async () => (await db.all("SELECT key, value, updated_at FROM settings ORDER BY key")).map(settingOf),
|
|
981
|
+
};
|
|
982
|
+
this.sealedKeys = {
|
|
983
|
+
get: async (name) => {
|
|
984
|
+
const row = await db.get("SELECT sealed FROM sealed_keys WHERE name = ?", name);
|
|
985
|
+
return row === undefined ? undefined : Uint8Array.from(row.sealed);
|
|
986
|
+
},
|
|
987
|
+
put: async (name, sealed) => {
|
|
988
|
+
await db.write([{ sql: "INSERT INTO sealed_keys (name, sealed, updated_at) VALUES (?, ?, ?) ON CONFLICT (name) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", params: [name, sealed, now()] }]);
|
|
989
|
+
},
|
|
990
|
+
remove: async (name) => {
|
|
991
|
+
await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ?", params: [name] }]);
|
|
992
|
+
},
|
|
993
|
+
all: async () => (await db.all("SELECT name, sealed, updated_at FROM sealed_keys ORDER BY name")).map(sealedKeyOf),
|
|
994
|
+
};
|
|
995
|
+
this.computerLedger = {
|
|
996
|
+
put: async (provider, sessionId, labels, detail) => {
|
|
997
|
+
await db.write([{ sql: "INSERT INTO computer_ledger (provider, session_id, labels, detail, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (provider, session_id) DO UPDATE SET labels = excluded.labels, detail = excluded.detail, updated_at = excluded.updated_at", params: [provider, sessionId, JSON.stringify(labels), JSON.stringify(detail), now()] }]);
|
|
998
|
+
},
|
|
999
|
+
get: async (provider, sessionId) => {
|
|
1000
|
+
const row = await db.get("SELECT provider, session_id, labels, detail, updated_at FROM computer_ledger WHERE provider = ? AND session_id = ?", provider, sessionId);
|
|
1001
|
+
return row === undefined ? undefined : ledgerRowOf(row);
|
|
1002
|
+
},
|
|
1003
|
+
list: async (provider) => (await db.all("SELECT provider, session_id, labels, detail, updated_at FROM computer_ledger WHERE provider = ? ORDER BY session_id", provider)).map(ledgerRowOf),
|
|
1004
|
+
remove: async (provider, sessionId) => {
|
|
1005
|
+
await db.write([{ sql: "DELETE FROM computer_ledger WHERE provider = ? AND session_id = ?", params: [provider, sessionId] }]);
|
|
1006
|
+
},
|
|
1007
|
+
};
|
|
1008
|
+
this.triggerSettings = {
|
|
1009
|
+
get: async (adapter) => (await db.all("SELECT adapter, scope, field, sealed, updated_at FROM trigger_settings WHERE adapter = ? ORDER BY scope, field", adapter)).map(triggerSettingOf),
|
|
1010
|
+
put: async ({ adapter, scope, field, sealed }) => {
|
|
1011
|
+
await db.write([{ sql: "INSERT INTO trigger_settings (adapter, scope, field, sealed, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (adapter, scope, field) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", params: [adapter, scope, field, sealed, now()] }]);
|
|
1012
|
+
},
|
|
1013
|
+
removeScope: async (adapter, scope) => {
|
|
1014
|
+
await db.write([{ sql: "DELETE FROM trigger_settings WHERE adapter = ? AND scope = ?", params: [adapter, scope] }]);
|
|
1015
|
+
},
|
|
1016
|
+
};
|
|
1017
|
+
this.mcpOauth = {
|
|
1018
|
+
put: async ({ state, server, sealed, working, expiresAt }) => {
|
|
1019
|
+
await db.write([{
|
|
1020
|
+
sql: `INSERT INTO mcp_oauth_pending (state, server, sealed, working, expires_at) VALUES (?, ?, ?, ?, ?)
|
|
1021
|
+
ON CONFLICT (state) DO UPDATE SET server = excluded.server, sealed = excluded.sealed, working = excluded.working, expires_at = excluded.expires_at`,
|
|
1022
|
+
params: [state, server, sealed, json(working), expiresAt],
|
|
1023
|
+
}]);
|
|
1024
|
+
},
|
|
1025
|
+
take: async (state, at) => {
|
|
1026
|
+
// One statement: delete the row and return it. On the store's single writer this is atomic, so two concurrent
|
|
1027
|
+
// takes of one state can never both get it (the second deletes nothing). The row is gone whether or not it had
|
|
1028
|
+
// expired; an expired one is refused by reading undefined after the delete, so a stale state can't be retried.
|
|
1029
|
+
const [result] = await db.write([{ sql: "DELETE FROM mcp_oauth_pending WHERE state = ? RETURNING state, server, sealed, working, expires_at", params: [state] }]);
|
|
1030
|
+
const row = result.rows[0];
|
|
1031
|
+
if (row === undefined)
|
|
1032
|
+
return undefined;
|
|
1033
|
+
return row.expires_at <= (at ?? now()) ? undefined : mcpOauthOf(row);
|
|
1034
|
+
},
|
|
1035
|
+
sweepExpired: async (at) => (await db.write([{ sql: "DELETE FROM mcp_oauth_pending WHERE expires_at <= ?", params: [at] }]))[0].changes,
|
|
1036
|
+
count: async (at) => (await db.get("SELECT count(*) AS n FROM mcp_oauth_pending WHERE expires_at > ?", at)).n,
|
|
1037
|
+
};
|
|
1038
|
+
// Every sealed column of every table, each with the AAD it was sealed under: the one read a runner's redaction set takes.
|
|
1039
|
+
this.sealedSecrets = {
|
|
1040
|
+
all: async () => {
|
|
1041
|
+
const out = [];
|
|
1042
|
+
const bytes = (value) => Uint8Array.from(value);
|
|
1043
|
+
for (const row of await db.all("SELECT name, sealed FROM sealed_keys ORDER BY name")) {
|
|
1044
|
+
out.push({ plane: "sealed_keys", where: { name: row.name }, aad: aadOf(sealedAt.sealedKey(row.name)), sealed: bytes(row.sealed) });
|
|
1045
|
+
}
|
|
1046
|
+
for (const row of await db.all("SELECT name, sealed FROM mcp_servers WHERE sealed IS NOT NULL ORDER BY name")) {
|
|
1047
|
+
out.push({ plane: "mcp_servers", where: { name: row.name }, aad: aadOf(sealedAt.mcpServer(row.name)), sealed: bytes(row.sealed) });
|
|
1048
|
+
}
|
|
1049
|
+
for (const row of await db.all("SELECT state, sealed FROM mcp_oauth_pending ORDER BY state")) {
|
|
1050
|
+
out.push({ plane: "mcp_oauth_pending", where: { state: row.state }, aad: aadOf(sealedAt.oauthPending(row.state)), sealed: bytes(row.sealed) });
|
|
1051
|
+
}
|
|
1052
|
+
for (const row of await db.all("SELECT adapter, scope, field, sealed FROM trigger_settings ORDER BY adapter, scope, field")) {
|
|
1053
|
+
// Base64 text in this column (sealed-settings-store.ts), under the table's documented composite-key AAD.
|
|
1054
|
+
out.push({ plane: "trigger_settings", where: { adapter: row.adapter, scope: row.scope, field: row.field }, aad: `trigger_settings|${row.adapter}|${row.scope}|${row.field}`, sealed: Uint8Array.from(Buffer.from(row.sealed, "base64")) });
|
|
1055
|
+
}
|
|
1056
|
+
for (const row of await db.all("SELECT agent_id, provider, pointer_sealed FROM sign_ins ORDER BY agent_id, provider")) {
|
|
1057
|
+
out.push({ plane: "sign_ins", where: { agentId: row.agent_id, provider: row.provider }, aad: aadOf(sealedAt.signIn(row.agent_id, row.provider)), sealed: bytes(row.pointer_sealed) });
|
|
1058
|
+
}
|
|
1059
|
+
// A tombstone keeps the pointer's sealed bytes under the live row's binding (store/seal.ts signIn).
|
|
1060
|
+
for (const row of await db.all("SELECT id, agent_id, provider, pointer_sealed FROM sign_in_tombstones ORDER BY id")) {
|
|
1061
|
+
out.push({ plane: "sign_in_tombstones", where: { id: String(row.id), agentId: row.agent_id, provider: row.provider }, aad: aadOf(sealedAt.signIn(row.agent_id, row.provider)), sealed: bytes(row.pointer_sealed) });
|
|
1062
|
+
}
|
|
1063
|
+
for (const row of await db.all("SELECT run_id, kind, tag, sealed FROM computer_viewers ORDER BY run_id, kind, tag")) {
|
|
1064
|
+
out.push({ plane: "computer_viewers", where: { runId: row.run_id, kind: row.kind, tag: row.tag }, aad: aadOf(sealedAt.liveViewer(row.run_id, row.kind, row.tag)), sealed: bytes(row.sealed) });
|
|
1065
|
+
}
|
|
1066
|
+
for (const row of await db.all("SELECT run_id, sealed FROM run_launch WHERE sealed IS NOT NULL ORDER BY run_id")) {
|
|
1067
|
+
out.push({ plane: "run_launch", where: { runId: row.run_id }, aad: aadOf({ table: "run_launch", row: row.run_id, column: "sealed" }), sealed: bytes(row.sealed) });
|
|
1068
|
+
}
|
|
1069
|
+
return out;
|
|
1070
|
+
},
|
|
1071
|
+
};
|
|
1072
|
+
this.signIns = {
|
|
1073
|
+
save: async ({ agentId, provider, name, pointerSealed }) => {
|
|
1074
|
+
const at = now();
|
|
1075
|
+
// A fresh save clears verified_at (the pointer is new, and no run has verified it yet) and numbers the save.
|
|
1076
|
+
const [result] = await db.write([{
|
|
1077
|
+
sql: `INSERT INTO sign_ins (agent_id, provider, name, pointer_sealed, saved_at, save, verified_at) VALUES (?, ?, ?, ?, ?, 1, NULL)
|
|
1078
|
+
ON CONFLICT (agent_id, provider) DO UPDATE SET name = excluded.name, pointer_sealed = excluded.pointer_sealed, saved_at = excluded.saved_at, save = sign_ins.save + 1, verified_at = NULL
|
|
1079
|
+
RETURNING ${SIGN_IN_COLUMNS}`,
|
|
1080
|
+
params: [agentId, provider, name, pointerSealed, at],
|
|
1081
|
+
}]);
|
|
1082
|
+
return signInOf(result.rows[0]);
|
|
1083
|
+
},
|
|
1084
|
+
saveIfAbsent: ({ agentId, provider, name, pointerSealed }) => db.transaction(async (tx) => {
|
|
1085
|
+
// One transaction: the insert that wins or the live row that won before it, never a replace.
|
|
1086
|
+
const inserted = await tx.all(`INSERT INTO sign_ins (agent_id, provider, name, pointer_sealed, saved_at, save, verified_at) VALUES (?, ?, ?, ?, ?, 1, NULL)
|
|
1087
|
+
ON CONFLICT (agent_id, provider) DO NOTHING RETURNING ${SIGN_IN_COLUMNS}`, agentId, provider, name, pointerSealed, now());
|
|
1088
|
+
if (inserted[0])
|
|
1089
|
+
return { saved: true, row: signInOf(inserted[0]) };
|
|
1090
|
+
const live = await tx.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
|
|
1091
|
+
return { saved: false, row: signInOf(live) };
|
|
1092
|
+
}),
|
|
1093
|
+
list: async (agentId) => (await db.all(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? ORDER BY provider`, agentId)).map(signInOf),
|
|
1094
|
+
get: async (agentId, provider) => {
|
|
1095
|
+
const row = await db.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
|
|
1096
|
+
return row && signInOf(row);
|
|
1097
|
+
},
|
|
1098
|
+
verify: async (agentId, provider, at, { ifSave } = {}) => {
|
|
1099
|
+
// With ifSave, stamp only while the row is still that save (WHERE save = ?): a save that landed since the caller
|
|
1100
|
+
// checked (allowed while held; it clears verified_at) numbered itself on, in the same millisecond or not, so verify
|
|
1101
|
+
// never stamps it stale.
|
|
1102
|
+
const [result] = await db.write([{
|
|
1103
|
+
sql: `UPDATE sign_ins SET verified_at = ? WHERE agent_id = ? AND provider = ?${ifSave === undefined ? "" : " AND save = ?"}`,
|
|
1104
|
+
params: ifSave === undefined ? [at, agentId, provider] : [at, agentId, provider, ifSave],
|
|
1105
|
+
}]);
|
|
1106
|
+
return result.changes > 0;
|
|
1107
|
+
},
|
|
1108
|
+
tombstones: async (agentId, provider) => (await db.all("SELECT agent_id, provider, pointer_sealed, forgotten_at FROM sign_in_tombstones WHERE agent_id = ? AND provider = ? ORDER BY id DESC", agentId, provider)).map(signInTombstoneOf),
|
|
1109
|
+
forget: (agentId, provider, held) => db.transaction(async (tx) => {
|
|
1110
|
+
// The hold check and the move are one transaction: a launch writing sign_in_handed is another, and the store's one
|
|
1111
|
+
// writer lock serializes them, so forget never passes a hold a launch took, nor a launch a forget cleared. With many
|
|
1112
|
+
// writers, the lock both take (SIGN_IN_HANDED_LOCK) does.
|
|
1113
|
+
await d.lockKey(tx, SIGN_IN_HANDED_LOCK);
|
|
1114
|
+
const holder = held.hash !== undefined ? await handedHolderIn(tx, held.hash) : held.heldUnreadable ? await handedAnyIn(tx) : undefined;
|
|
1115
|
+
if (holder)
|
|
1116
|
+
throw new SignInHandedTo(holder.id);
|
|
1117
|
+
const live = await tx.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
|
|
1118
|
+
if (!live)
|
|
1119
|
+
throw new SignInMissing(agentId, provider);
|
|
1120
|
+
const at = now();
|
|
1121
|
+
const tomb = await tx.get("INSERT INTO sign_in_tombstones (agent_id, provider, pointer_sealed, forgotten_at) VALUES (?, ?, ?, ?) RETURNING agent_id, provider, pointer_sealed, forgotten_at", agentId, provider, live.pointer_sealed, at);
|
|
1122
|
+
await tx.run("DELETE FROM sign_ins WHERE agent_id = ? AND provider = ?", agentId, provider);
|
|
1123
|
+
// The newest kept, the oldest dropped first (per agent, across providers).
|
|
1124
|
+
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ? AND id NOT IN (SELECT id FROM sign_in_tombstones WHERE agent_id = ? ORDER BY id DESC LIMIT ?)", agentId, agentId, SIGN_IN_TOMBSTONES_KEPT);
|
|
1125
|
+
return signInTombstoneOf(tomb);
|
|
1126
|
+
}),
|
|
1127
|
+
handedHolder: async (hash, options) => (await handedHolderIn(db, hash, { settleMs: options?.settleMs ?? 0, now: options?.at !== undefined ? { sql: d.bigintParam, params: [options.at] } : clock() }))?.id,
|
|
1128
|
+
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
async claim(runId, runner, { leaseMs = DEFAULT_LEASE_MS } = {}) {
|
|
1132
|
+
return (await this.#claimRuns(runner, leaseMs, { runId }))[0] ?? null;
|
|
1133
|
+
}
|
|
1134
|
+
/** Claims, in one transaction, the run `runId` when it is claimable, or up to `k` claimable runs oldest first: each read
|
|
1135
|
+
* with its state (the claim's `from`) and moved to its next epoch under the same BEGIN IMMEDIATE, so no other claimer
|
|
1136
|
+
* takes it between. */
|
|
1137
|
+
async #claimRuns(runner, leaseMs, pick) {
|
|
1138
|
+
if ("k" in pick && !(Number.isSafeInteger(pick.k) && pick.k > 0))
|
|
1139
|
+
return [];
|
|
1140
|
+
return this.#db.transaction(async (tx) => {
|
|
1141
|
+
// The clock is read once the transaction holds the writer lock: a claim that waited for another writer runs its
|
|
1142
|
+
// lease from now, never comes back already run out. The deadlines' clock (the database's on Postgres) both judges what
|
|
1143
|
+
// is claimable and stamps the lease, which comes back from the row.
|
|
1144
|
+
const claimable = claimableIn(this.#db.dialect, this.#clock());
|
|
1145
|
+
// With many claimers (Postgres), the rows picked are locked as they are read. A poll over many (claimMany) skips a
|
|
1146
|
+
// row another claimer holds (Dialect.claimLock): two claims never pick one run, and neither waits for the other. A
|
|
1147
|
+
// claim of one named run waits for a write in flight on its row (Dialect.claimOneLock), then reads it as it is: a
|
|
1148
|
+
// run whose holder is merely writing is never answered held.
|
|
1149
|
+
const lock = "runId" in pick ? this.#db.dialect.claimOneLock : this.#db.dialect.claimLock;
|
|
1150
|
+
const picked = "runId" in pick
|
|
1151
|
+
? await tx.all(`SELECT id, state, runner FROM runs WHERE id = ? AND ${claimable.sql}${lock}`, pick.runId, ...claimable.params)
|
|
1152
|
+
: await tx.all(`SELECT id, state, runner FROM runs WHERE ${claimable.sql} ORDER BY started_at, id LIMIT ?${lock}`, ...claimable.params, pick.k);
|
|
1153
|
+
if (picked.length === 0)
|
|
1154
|
+
return [];
|
|
1155
|
+
const stamp = this.#clock();
|
|
1156
|
+
const rows = await tx.all(`UPDATE runs SET ${claimSet(stamp)} WHERE id IN (${picked.map(() => "?").join(", ")}) RETURNING id, epoch, claimed_until`, runner, ...stamp.params, leaseMs, ...picked.map((row) => row.id));
|
|
1157
|
+
const epochs = new Map(rows.map((row) => [row.id, row.epoch]));
|
|
1158
|
+
const untils = new Map(rows.map((row) => [row.id, Number(row.claimed_until)]));
|
|
1159
|
+
// A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind.
|
|
1160
|
+
for (const row of rows)
|
|
1161
|
+
await tx.run("DELETE FROM computer_viewers WHERE run_id = ? AND epoch < ?", row.id, row.epoch);
|
|
1162
|
+
// A newer claim of a run supersedes its release here: journal() refuses by epoch, and the newer epoch passes.
|
|
1163
|
+
for (const { id } of picked)
|
|
1164
|
+
this.#released.delete(id);
|
|
1165
|
+
// A running run that still names its runner was taken from it: that runner's lease ran out mid-run (CLAIMABLE).
|
|
1166
|
+
return picked.map(({ id, state, runner: held }) => ({ runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(state === "running" && held !== null ? { lost: { runner: held } } : {}) }));
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
/** Holds the run's row before a fenced write reads the store's clock: the lease is checked, and runs, from when the write
|
|
1170
|
+
* holds the row, never from before a wait for another writer (a no-op on SQLite, whose BEGIN IMMEDIATE already holds
|
|
1171
|
+
* the writer lock when the clock is read). */
|
|
1172
|
+
#holdRun(tx, runId) {
|
|
1173
|
+
return this.#db.dialect.lockRow(tx, "runs", "id", runId);
|
|
1174
|
+
}
|
|
1175
|
+
async renew(claim, { leaseMs = DEFAULT_LEASE_MS } = {}) {
|
|
1176
|
+
// As a claim's: the lease runs from when the renew holds the writer lock.
|
|
1177
|
+
// A lease that ran out is gone: no renew brings it back (its runner takes the run again, at a new epoch).
|
|
1178
|
+
const until = await this.#db.transaction(async (tx) => {
|
|
1179
|
+
await this.#holdRun(tx, claim.runId);
|
|
1180
|
+
// The deadlines' clock (the database's on Postgres) judges the lease and stamps the next one.
|
|
1181
|
+
const now = this.#clock();
|
|
1182
|
+
const fence = claimFence(claim, now);
|
|
1183
|
+
await tx.step(fenced(claim, `UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fence.where} AND runner = ?`, [...now.params, leaseMs, ...fence.params, claim.runner]));
|
|
1184
|
+
return Number((await tx.get("SELECT claimed_until FROM runs WHERE id = ?", claim.runId)).claimed_until);
|
|
1185
|
+
}, { lease: true });
|
|
1186
|
+
return { ...claim, until };
|
|
1187
|
+
}
|
|
1188
|
+
async renewMany(claims, { leaseMs = DEFAULT_LEASE_MS } = {}) {
|
|
1189
|
+
if (claims.length === 0)
|
|
1190
|
+
return [];
|
|
1191
|
+
// One transaction for every claim, each update on its own: a claim another runner took changes no row and is answered
|
|
1192
|
+
// Fenced, never rolling the others back.
|
|
1193
|
+
return this.#db.transaction(async (tx) => {
|
|
1194
|
+
// Held in one order (by run id), so two renews of overlapping runs never wait on each other in a cycle.
|
|
1195
|
+
for (const runId of [...new Set(claims.map((claim) => claim.runId))].sort())
|
|
1196
|
+
await this.#holdRun(tx, runId);
|
|
1197
|
+
const out = [];
|
|
1198
|
+
for (const claim of claims) {
|
|
1199
|
+
// The deadlines' clock (the database's on Postgres) judges each lease and stamps the next one.
|
|
1200
|
+
const now = this.#clock();
|
|
1201
|
+
const fence = claimFence(claim, now);
|
|
1202
|
+
const renewed = await tx.all(`UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fence.where} AND runner = ? RETURNING id, claimed_until`, ...now.params, leaseMs, ...fence.params, claim.runner);
|
|
1203
|
+
out.push(renewed.length > 0 ? { ...claim, until: Number(renewed[0].claimed_until) } : new Fenced(claim.runId, claim.epoch));
|
|
1204
|
+
}
|
|
1205
|
+
return out;
|
|
1206
|
+
// On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
|
|
1207
|
+
}, { lease: true });
|
|
1208
|
+
}
|
|
1209
|
+
async release(claim, { state, wakeAt = null, backoffUntil = null } = {}) {
|
|
1210
|
+
// The end commit is the one write that makes a run final (applyRunPatch: the leftover rows refused and the run_live
|
|
1211
|
+
// row deleted with it). A release never does: asked to, it is refused before anything is written.
|
|
1212
|
+
if (state !== undefined && FINAL_STATES.includes(state))
|
|
1213
|
+
throw new TypeError(`a release never makes a run final (asked for ${state}): only the run's end commit does, refusing its leftover rows with it`);
|
|
1214
|
+
// A release that gives the run back with no state (or 'running') keeps it running (its runner shut down): it still holds
|
|
1215
|
+
// its sign-in. One that parks it leaves 'running', so stamp when — the Browserbase settle window reads left_running_at.
|
|
1216
|
+
const leaving = state !== undefined && state !== "running";
|
|
1217
|
+
await this.#db.transaction(async (tx) => {
|
|
1218
|
+
// A run its end already made final was released by that end (applyRunPatch): this release is a no-op, no second
|
|
1219
|
+
// move of its epoch and no error, whatever its claim's lease says now. The release moves the epoch: the row is held
|
|
1220
|
+
// against every write under the claim (dialect lockRow "update"), so one in flight lands first.
|
|
1221
|
+
await this.#db.dialect.lockRow(tx, "runs", "id", claim.runId, "update");
|
|
1222
|
+
const final = await tx.get("SELECT state, runner FROM runs WHERE id = ?", claim.runId);
|
|
1223
|
+
if (final && FINAL_STATES.includes(final.state) && final.runner === null)
|
|
1224
|
+
return;
|
|
1225
|
+
// The deadlines' clock (the database's on Postgres) judges the lease and stamps when the run left running.
|
|
1226
|
+
const now = this.#clock();
|
|
1227
|
+
const fence = claimFence(claim, now);
|
|
1228
|
+
await tx.step(fenced(claim,
|
|
1229
|
+
// The epoch moves on at a release: the released claim is dead everywhere (its journal, its run updates, its takes),
|
|
1230
|
+
// never live until the next claim. A claim whose lease ran out releases nothing: the run, running with its lease run
|
|
1231
|
+
// out, is claimable at once, never stuck.
|
|
1232
|
+
`UPDATE runs SET epoch = epoch + 1, runner = NULL, claimed_until = NULL, wake_at = ?, backoff_until = ?, state = coalesce(?, state)${leaving ? `, left_running_at = ${now.sql}` : ""} WHERE ${fence.where} AND runner = ?`, [wakeAt, backoffUntil, state ?? null, ...(leaving ? now.params : []), ...fence.params, claim.runner]));
|
|
1233
|
+
}, { full: true });
|
|
1234
|
+
// The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
|
|
1235
|
+
this.#journals.delete(journalKey(claim));
|
|
1236
|
+
this.#released.delete(claim.runId);
|
|
1237
|
+
this.#released.set(claim.runId, claim.epoch);
|
|
1238
|
+
if (this.#released.size > RELEASED_KEPT)
|
|
1239
|
+
this.#released.delete(this.#released.keys().next().value);
|
|
1240
|
+
}
|
|
1241
|
+
/** The claim's one journal (pi assumes one Storage per owner): asked again for the same claim while it is open, the same
|
|
1242
|
+
* journal, so two callers never mint the same ids. The store keeps it only while it is open and its claim held: its
|
|
1243
|
+
* close, or its claim's release, drops it, so a long-lived runner keeps no journal of a finished claim. */
|
|
1244
|
+
journal(claim) {
|
|
1245
|
+
const released = this.#released.get(claim.runId);
|
|
1246
|
+
if (released !== undefined && claim.epoch <= released)
|
|
1247
|
+
throw new Fenced(claim.runId, claim.epoch);
|
|
1248
|
+
const key = journalKey(claim);
|
|
1249
|
+
const open = this.#journals.get(key);
|
|
1250
|
+
if (open && !open.closed)
|
|
1251
|
+
return open;
|
|
1252
|
+
const journal = new RunStorage(this.#db, claim, this.#now, () => {
|
|
1253
|
+
if (this.#journals.get(key) === journal)
|
|
1254
|
+
this.#journals.delete(key);
|
|
1255
|
+
});
|
|
1256
|
+
this.#journals.set(key, journal);
|
|
1257
|
+
return journal;
|
|
1258
|
+
}
|
|
1259
|
+
/** A run's journal opened for reading only (no claim): a fresh RunStorage on the store's connection, its reads alone. A
|
|
1260
|
+
* read never checks the epoch (only a commit's fence does), so the view carries epoch 0 and never writes; its type
|
|
1261
|
+
* (JournalReads) hands out no commit, stage or mintId. The store keeps no reference to it — it holds no claim and two
|
|
1262
|
+
* readers of one run never share ids, since neither mints any. A run with no journal yet reads as empty. */
|
|
1263
|
+
readJournal(runId) {
|
|
1264
|
+
return new RunStorage(this.#db, { runId, epoch: 0 }, this.#now);
|
|
1265
|
+
}
|
|
1266
|
+
/** How many journals the store keeps (open, of a claim not released). */
|
|
1267
|
+
get openJournals() {
|
|
1268
|
+
return this.#journals.size;
|
|
1269
|
+
}
|
|
1270
|
+
async flush() {
|
|
1271
|
+
await this.#db.write([{ sql: "UPDATE store_meta SET flushes = flushes + 1 WHERE singleton = 1" }], { full: true });
|
|
1272
|
+
}
|
|
1273
|
+
async command(runId, { kind, body = null }) {
|
|
1274
|
+
const [result] = await this.#db.write([{
|
|
1275
|
+
// The run row read under the share lock: a command never lands while the run's end is in flight, to be left untaken
|
|
1276
|
+
// by an end that refused the run's leftover rows before it (the end waits for it, or it waits for the end).
|
|
1277
|
+
sql: `INSERT INTO commands (run_id, kind, body, created_at) SELECT id, ?, ?, ? FROM runs WHERE id = ? AND state NOT IN (${FINAL})${this.#db.dialect.shareLock} RETURNING ${COMMAND_COLUMNS}`,
|
|
1278
|
+
params: [kind, json(body), this.#now(), runId],
|
|
1279
|
+
expect: { kind: "final", runId },
|
|
1280
|
+
}]);
|
|
1281
|
+
return commandOf(result.rows[0]);
|
|
1282
|
+
}
|
|
1283
|
+
async commands(runId, after) {
|
|
1284
|
+
return (await this.#db.all(`SELECT ${COMMAND_COLUMNS} FROM commands WHERE run_id = ? AND id > ? ORDER BY id`, runId, after)).map(commandOf);
|
|
1285
|
+
}
|
|
1286
|
+
async runOfOrigin(key) {
|
|
1287
|
+
const row = await this.#db.get("SELECT run_id, fingerprint FROM run_origins WHERE key = ?", key);
|
|
1288
|
+
return row && { runId: row.run_id, fingerprint: row.fingerprint };
|
|
1289
|
+
}
|
|
1290
|
+
async commandsOf(cursors) {
|
|
1291
|
+
const out = new Map();
|
|
1292
|
+
if (cursors.length === 0)
|
|
1293
|
+
return out;
|
|
1294
|
+
// One read for every run: each cursor a (run_id, after) row of a VALUES list joined against the commands.
|
|
1295
|
+
const rows = await this.#db.all(`WITH cursors(run_id, after) AS (VALUES ${cursors.map(() => `(?, ${this.#db.dialect.bigintParam})`).join(", ")})
|
|
1296
|
+
SELECT ${COMMAND_COLUMNS.split(", ").map((column) => `commands.${column}`).join(", ")} FROM commands JOIN cursors ON commands.run_id = cursors.run_id AND commands.id > cursors.after ORDER BY commands.id`, ...cursors.flatMap((cursor) => [cursor.runId, cursor.after]));
|
|
1297
|
+
for (const row of rows) {
|
|
1298
|
+
const command = commandOf(row);
|
|
1299
|
+
out.set(command.runId, [...(out.get(command.runId) ?? []), command]);
|
|
1300
|
+
}
|
|
1301
|
+
return out;
|
|
1302
|
+
}
|
|
1303
|
+
async importRun(run) {
|
|
1304
|
+
const at = this.#now();
|
|
1305
|
+
const state = run.state ?? "ended";
|
|
1306
|
+
return this.#db.transaction(async (tx) => {
|
|
1307
|
+
// The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
|
|
1308
|
+
// writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
|
|
1309
|
+
// passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
|
|
1310
|
+
const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, started_at, ended_at)
|
|
1311
|
+
VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), run.startedAt, run.endedAt ?? at);
|
|
1312
|
+
await writeLaunch(tx, run.id, run.launch, at);
|
|
1313
|
+
await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
|
|
1314
|
+
return runOf(row);
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1317
|
+
async take(claim, commandId, outcome = "taken", reason) {
|
|
1318
|
+
// The clock is read inside the transaction, so the lease check and the write are one.
|
|
1319
|
+
await this.#db.transaction(async (tx) => {
|
|
1320
|
+
const now = await underClaim(tx, claim, this.#now);
|
|
1321
|
+
await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE id = ? AND run_id = ? AND taken_at IS NULL", now, outcome === "refused" ? (reason ?? "refused") : null, commandId, claim.runId);
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
async retry(claim, commandId) {
|
|
1325
|
+
const counted = await this.#db.transaction(async (tx) => {
|
|
1326
|
+
await underClaim(tx, claim, this.#now);
|
|
1327
|
+
return tx.all("UPDATE commands SET tries = tries + 1 WHERE id = ? AND run_id = ? AND taken_at IS NULL RETURNING tries", commandId, claim.runId);
|
|
1328
|
+
});
|
|
1329
|
+
const row = counted[0];
|
|
1330
|
+
if (!row)
|
|
1331
|
+
throw new StoreConstraint(`run ${claim.runId}: command ${commandId} is taken, or not the run's: no try to count`);
|
|
1332
|
+
return row.tries;
|
|
1333
|
+
}
|
|
1334
|
+
close() {
|
|
1335
|
+
return this.#db.close();
|
|
1336
|
+
}
|
|
1337
|
+
}
|