@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45
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 +231 -0
- package/README.md +580 -320
- package/dist/acp-package.d.ts +28 -0
- package/dist/acp-package.js +23 -0
- package/dist/adapter-facts.d.ts +8 -1
- package/dist/adapter-facts.js +9 -1
- package/dist/adapters.d.ts +5 -0
- package/dist/adapters.js +36 -3
- package/dist/agent-delete.d.ts +50 -0
- package/dist/agent-delete.js +125 -0
- package/dist/agents-store.d.ts +9 -3
- package/dist/agents-store.js +22 -8
- package/dist/agents.d.ts +5 -1
- package/dist/agents.js +8 -4
- package/dist/api-only.d.ts +8 -3
- package/dist/api-only.js +10 -4
- package/dist/archil-routes.d.ts +5 -1
- package/dist/archil-routes.js +57 -2
- package/dist/browser-wait-ended.d.ts +2 -0
- package/dist/browser-wait-ended.js +2 -0
- package/dist/calendar/ics-faux.d.ts +3 -1
- package/dist/calendar/ics-faux.js +12 -2
- package/dist/calendar/tools.js +5 -2
- package/dist/chatgpt-plan.js +3 -1
- package/dist/claude-login.d.ts +135 -0
- package/dist/claude-login.js +244 -0
- package/dist/cli.js +92 -22
- package/dist/composio-preset.d.ts +4 -3
- package/dist/composio-preset.js +81 -11
- package/dist/composio-triggers.d.ts +34 -2
- package/dist/composio-triggers.js +261 -31
- package/dist/computer-attach.d.ts +40 -5
- package/dist/computer-attach.js +130 -15
- package/dist/computer-keys.d.ts +3 -0
- package/dist/computer-keys.js +7 -1
- package/dist/computer-live.js +3 -2
- package/dist/computer-lost.d.ts +11 -0
- package/dist/computer-lost.js +19 -0
- package/dist/computer-record.d.ts +10 -2
- package/dist/computer-record.js +50 -18
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +2 -2
- package/dist/computers.d.ts +21 -10
- package/dist/computers.js +39 -28
- package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
- package/dist/console/assets/index-DaFsZuzQ.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.d.ts +1 -1
- package/dist/dial-relay.d.ts +29 -0
- package/dist/dial-relay.js +94 -0
- package/dist/email/tools.js +10 -5
- package/dist/env-proxy.d.ts +2 -0
- package/dist/env-proxy.js +35 -0
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +10 -4
- package/dist/faux-computers.d.ts +8 -2
- package/dist/faux-computers.js +83 -6
- package/dist/harness-archive.d.ts +67 -0
- package/dist/harness-archive.js +177 -0
- package/dist/harness-goose.d.ts +34 -0
- package/dist/harness-goose.js +87 -0
- package/dist/harness-install.d.ts +21 -0
- package/dist/harness-install.js +24 -11
- package/dist/harness-opencode/adapter.js +1 -1
- package/dist/harness-table.d.ts +59 -3
- package/dist/harness-table.js +119 -14
- package/dist/harness.d.ts +17 -1
- package/dist/harness.js +22 -11
- package/dist/host.d.ts +12 -10
- package/dist/host.js +19 -16
- package/dist/import-worker.d.ts +3 -0
- package/dist/import-worker.js +7 -5
- package/dist/import.d.ts +22 -1
- package/dist/import.js +141 -28
- package/dist/key-check.js +3 -0
- package/dist/learn/audit.d.ts +6 -6
- package/dist/learn/audit.js +3 -7
- package/dist/learn/check.d.ts +26 -89
- package/dist/learn/check.js +58 -336
- package/dist/learn/commit.d.ts +63 -90
- package/dist/learn/commit.js +124 -316
- package/dist/learn/compile.d.ts +53 -50
- package/dist/learn/compile.js +88 -103
- package/dist/learn/corrections.d.ts +13 -0
- package/dist/learn/corrections.js +23 -0
- package/dist/learn/delete.d.ts +17 -0
- package/dist/learn/delete.js +42 -0
- package/dist/learn/folder.d.ts +35 -47
- package/dist/learn/folder.js +118 -134
- package/dist/learn/index.d.ts +3 -5
- package/dist/learn/index.js +6 -9
- package/dist/learn/learning.sh +45 -15
- package/dist/learn/promote.d.ts +20 -2
- package/dist/learn/promote.js +17 -4
- package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
- package/dist/learn/{skills.js → workflow-draft.js} +65 -59
- package/dist/learn/workflow-nodes.d.ts +22 -1
- package/dist/learn/workflow-nodes.js +29 -10
- package/dist/learned-workflow.js +2 -2
- package/dist/learning-cost.d.ts +127 -13
- package/dist/learning-cost.js +142 -10
- package/dist/learning-routes.d.ts +99 -170
- package/dist/learning-routes.js +199 -420
- package/dist/learning-run.d.ts +19 -40
- package/dist/learning-run.js +23 -93
- package/dist/learning-setting.d.ts +4 -4
- package/dist/learning-setting.js +6 -6
- package/dist/learning-words.d.ts +28 -74
- package/dist/learning-words.js +64 -162
- package/dist/learning.d.ts +62 -393
- package/dist/learning.js +101 -651
- package/dist/listen-first.d.ts +30 -0
- package/dist/listen-first.js +115 -0
- package/dist/live-reach.d.ts +25 -2
- package/dist/live-reach.js +46 -4
- package/dist/llms.txt +2 -1
- package/dist/local-models.d.ts +3 -11
- package/dist/local-models.js +5 -6
- package/dist/mcp-servers-store.d.ts +16 -16
- package/dist/model-form.js +6 -5
- package/dist/model.d.ts +12 -4
- package/dist/model.js +41 -16
- package/dist/native/binding.js +1 -1
- package/dist/native/connection.js +1 -1
- package/dist/native/discovery.js +1 -1
- package/dist/native/instructions.d.ts +3 -0
- package/dist/native/instructions.js +5 -3
- package/dist/native/remote-worker-bridge.js +9 -43
- package/dist/native/remote.d.ts +8 -15
- package/dist/native/remote.js +3 -3
- package/dist/native/schema.js +1 -1
- package/dist/native/types.d.ts +2 -2
- package/dist/openapi.js +375 -347
- package/dist/owner.d.ts +8 -0
- package/dist/owner.js +11 -0
- package/dist/paid-calls.d.ts +14 -0
- package/dist/paid-calls.js +31 -1
- package/dist/particle-provider.d.ts +11 -0
- package/dist/particle-provider.js +135 -0
- package/dist/place.d.ts +8 -3
- package/dist/place.js +13 -9
- package/dist/port-models.d.ts +12 -4
- package/dist/port-models.js +28 -11
- package/dist/print.d.ts +27 -0
- package/dist/print.js +21 -0
- package/dist/provider.d.ts +7 -0
- package/dist/provider.js +30 -2
- package/dist/reflect-range.js +2 -3
- package/dist/run-launch.d.ts +14 -28
- package/dist/run-launch.js +9 -12
- package/dist/run-learning-served.d.ts +16 -90
- package/dist/run-listing.d.ts +34 -0
- package/dist/run-listing.js +128 -0
- package/dist/run-model-key.d.ts +64 -0
- package/dist/run-model-key.js +147 -0
- package/dist/run-timeline-served.js +5 -3
- package/dist/run-trace.d.ts +97 -0
- package/dist/run-trace.js +253 -0
- package/dist/run-view.d.ts +15 -0
- package/dist/run-view.js +9 -0
- package/dist/runnable.js +2 -1
- package/dist/runner/adapter-loop.d.ts +14 -6
- package/dist/runner/adapter-loop.js +25 -14
- package/dist/runner/adapter-run-spec.d.ts +22 -7
- package/dist/runner/adapter-run-spec.js +130 -77
- package/dist/runner/adapters/index.d.ts +4 -2
- package/dist/runner/adapters/index.js +35 -4
- package/dist/runner/adapters/pi.d.ts +4 -12
- package/dist/runner/adapters/pi.js +2 -2
- package/dist/runner/audit.d.ts +5 -1
- package/dist/runner/audit.js +31 -12
- package/dist/runner/beside.d.ts +7 -2
- package/dist/runner/beside.js +41 -9
- package/dist/runner/claim-secrets.d.ts +66 -1
- package/dist/runner/claim-secrets.js +136 -3
- package/dist/runner/cli-run-spec.d.ts +2 -1
- package/dist/runner/cli-run-spec.js +82 -59
- package/dist/runner/commands.d.ts +3 -6
- package/dist/runner/conformance/harness.d.ts +6 -0
- package/dist/runner/conformance/harness.js +16 -5
- package/dist/runner/dispatch.d.ts +2 -2
- package/dist/runner/end-of-run.d.ts +6 -14
- package/dist/runner/end-of-run.js +8 -33
- package/dist/runner/feedback-round.d.ts +5 -4
- package/dist/runner/feedback-round.js +14 -10
- package/dist/runner/github-app.js +3 -1
- package/dist/runner/harness-loops.d.ts +0 -8
- package/dist/runner/harness-loops.js +30 -56
- package/dist/runner/held.d.ts +170 -0
- package/dist/runner/held.js +57 -0
- package/dist/runner/journal-kinds.d.ts +7 -3
- package/dist/runner/journal-kinds.js +2 -3
- package/dist/runner/learned-first.d.ts +40 -0
- package/dist/runner/learned-first.js +32 -0
- package/dist/runner/learning-end.d.ts +77 -66
- package/dist/runner/learning-end.js +250 -299
- package/dist/runner/learning-seed.d.ts +15 -33
- package/dist/runner/learning-seed.js +24 -45
- package/dist/runner/loop-contract.d.ts +8 -3
- package/dist/runner/loop-contract.js +4 -0
- package/dist/runner/loop.js +6 -2
- package/dist/runner/main.d.ts +18 -9
- package/dist/runner/main.js +82 -22
- package/dist/runner/mcp-run.d.ts +11 -0
- package/dist/runner/mcp-run.js +67 -0
- package/dist/runner/memory-claim.d.ts +14 -6
- package/dist/runner/memory-claim.js +18 -9
- package/dist/runner/model-route.d.ts +7 -4
- package/dist/runner/model-route.js +22 -10
- package/dist/runner/native-loop.d.ts +0 -7
- package/dist/runner/native-loop.js +9 -101
- package/dist/runner/promotion.d.ts +13 -6
- package/dist/runner/promotion.js +63 -17
- package/dist/runner/reflect-hook.d.ts +64 -91
- package/dist/runner/reflect-hook.js +112 -206
- package/dist/runner/run-channel.d.ts +43 -0
- package/dist/runner/run-channel.js +467 -0
- package/dist/runner/run-child-host.d.ts +169 -0
- package/dist/runner/run-child-host.js +1222 -0
- package/dist/runner/run-child.d.ts +1 -0
- package/dist/runner/run-child.js +254 -0
- package/dist/runner/run-errors.d.ts +2 -0
- package/dist/runner/run-errors.js +20 -0
- package/dist/runner/runner.js +58 -9
- package/dist/runner/sdk-ask.d.ts +78 -0
- package/dist/runner/sdk-ask.js +158 -0
- package/dist/runner/sdk-loop.d.ts +2 -4
- package/dist/runner/sdk-loop.js +29 -49
- package/dist/runner/store-secrets.d.ts +5 -3
- package/dist/runner/store-secrets.js +14 -6
- package/dist/runner/workflow-first.d.ts +5 -0
- package/dist/runner/workflow-first.js +4 -0
- package/dist/runner/workflow-spec.js +17 -4
- package/dist/runs-over-store.d.ts +21 -32
- package/dist/runs-over-store.js +44 -41
- package/dist/sdk/runs.d.ts +6 -11
- package/dist/sdk/runs.js +20 -41
- package/dist/sdk/schema.js +3 -4
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/seal-key.d.ts +5 -0
- package/dist/seal-key.js +7 -0
- package/dist/secrets.d.ts +3 -0
- package/dist/secrets.js +16 -3
- package/dist/server.d.ts +119 -83
- package/dist/server.js +1121 -419
- package/dist/sign-ins-store.d.ts +8 -0
- package/dist/sign-ins-store.js +36 -1
- package/dist/skills.js +1 -1
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/journal/storage.js +3 -0
- package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
- package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
- package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
- package/dist/store/schema.d.ts +53 -4
- package/dist/store/schema.js +137 -6
- package/dist/store/seal.d.ts +20 -2
- package/dist/store/seal.js +24 -8
- package/dist/store/sqlite/connection.d.ts +2 -0
- package/dist/store/sqlite/connection.js +3 -1
- package/dist/store/sqlite/run-launch.d.ts +4 -1
- package/dist/store/sqlite/run-launch.js +12 -0
- package/dist/store/sqlite/run-patch.d.ts +0 -17
- package/dist/store/sqlite/run-patch.js +4 -33
- package/dist/store/sqlite/store.d.ts +3 -2
- package/dist/store/sqlite/store.js +360 -75
- package/dist/store/sqlite/worker.js +25 -0
- package/dist/store/store.d.ts +231 -39
- package/dist/store/store.js +25 -3
- package/dist/store-reads/analytics.js +11 -1
- package/dist/store-reads/learning.d.ts +131 -194
- package/dist/store-reads/learning.js +292 -301
- package/dist/store-reads/loop.d.ts +0 -1
- package/dist/store-reads/loop.js +1 -1
- package/dist/store-reads/stats.js +13 -3
- package/dist/store-view.d.ts +34 -2
- package/dist/store-view.js +108 -41
- package/dist/telemetry.d.ts +59 -0
- package/dist/telemetry.js +153 -0
- package/dist/template-eval.d.ts +3 -6
- package/dist/template-eval.js +22 -36
- package/dist/templates.d.ts +2 -1
- package/dist/templates.js +6 -3
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -1
- package/dist/timeline/timeline.js +16 -0
- package/dist/tool-gate.d.ts +0 -7
- package/dist/tool-gate.js +1 -15
- package/dist/tool-keys-store.d.ts +1 -1
- package/dist/tool-keys.d.ts +6 -4
- package/dist/tool-keys.js +12 -6
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +13 -13
- package/dist/tools.js +29 -9
- package/dist/trigger-adapter.d.ts +3 -0
- package/dist/trigger-adapters.d.ts +4 -0
- package/dist/trigger-adapters.js +13 -0
- package/dist/trigger-composio.d.ts +58 -1
- package/dist/trigger-composio.js +160 -6
- package/dist/triggers.d.ts +64 -5
- package/dist/triggers.js +141 -17
- package/dist/validate.d.ts +11 -7
- package/dist/validate.js +9 -8
- package/dist/webhooks.d.ts +4 -1
- package/dist/webhooks.js +11 -4
- package/dist/workspace/agent-computer.d.ts +2 -0
- package/dist/workspace/agent-computer.js +2 -0
- package/dist/workspace/archil-claim.d.ts +7 -0
- package/dist/workspace/archil-claim.js +29 -0
- package/dist/workspace/archil.d.ts +9 -1
- package/dist/workspace/archil.js +165 -3
- package/dist/workspace/attach.d.ts +3 -1
- package/dist/workspace/attach.js +2 -0
- package/dist/workspace/attached-computers.d.ts +16 -5
- package/dist/workspace/attached-computers.js +25 -9
- package/dist/workspace/computer-deps.js +1 -1
- package/dist/workspace/computer-for-claim.d.ts +22 -8
- package/dist/workspace/computer-for-claim.js +339 -46
- package/dist/workspace/computer-hold.js +2 -1
- package/dist/workspace/computer-kept.d.ts +11 -1
- package/dist/workspace/computer-kept.js +24 -3
- package/dist/workspace/resolve-computer.d.ts +41 -21
- package/dist/workspace/resolve-computer.js +172 -64
- package/dist/workspace/revision-skills.d.ts +1 -2
- package/dist/workspace/revision-skills.js +3 -4
- package/dist/workspace/run-workspace.d.ts +1 -1
- package/dist/workspace/run-workspace.js +5 -0
- package/dist/workspace/synced-folder.d.ts +85 -0
- package/dist/workspace/synced-folder.js +230 -0
- package/dist/workspace/workspace.d.ts +4 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -9
- package/templates/README.md +7 -7
- package/templates/inbound-lead/agent.md +3 -3
- package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
- package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
- package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
- package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
- package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
- package/templates/inbound-lead/lead.schema.json +6 -5
- package/templates/inbound-lead/rules/RUBRIC.md +4 -4
- package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
- package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
- package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
- package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
- package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
- package/templates/release-notes/evals/learned-style/case.yaml +4 -4
- package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
- package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
- package/templates/release-notes/evals/learned-style/prompt.md +1 -1
- package/dist/console/assets/index-BrcDSBD8.css +0 -1
- package/dist/console/assets/index-Bz6IWncl.js +0 -711
- package/dist/learn/grade.d.ts +0 -138
- package/dist/learn/grade.js +0 -682
- package/dist/learn/notes.d.ts +0 -81
- package/dist/learn/notes.js +0 -178
- package/dist/learn/reflect.d.ts +0 -77
- package/dist/learn/reflect.js +0 -228
- package/dist/learn/relevance.d.ts +0 -24
- package/dist/learn/relevance.js +0 -91
- package/dist/learn/seed-check.d.ts +0 -74
- package/dist/learn/seed-check.js +0 -103
- package/dist/learning-batch.d.ts +0 -291
- package/dist/learning-batch.js +0 -600
- package/dist/learning-evals.d.ts +0 -33
- package/dist/learning-evals.js +0 -98
- package/dist/native/context.d.ts +0 -6
- package/dist/native/context.js +0 -22
- package/dist/propose.d.ts +0 -52
- package/dist/propose.js +0 -224
- package/dist/runner/learning-ask.d.ts +0 -47
- package/dist/runner/learning-ask.js +0 -128
- package/dist/runner/learning-dispatch.d.ts +0 -45
- package/dist/runner/learning-dispatch.js +0 -99
- package/dist/runner/learning-factory.d.ts +0 -16
- package/dist/runner/learning-factory.js +0 -50
- package/dist/runner/learning-loop.d.ts +0 -273
- package/dist/runner/learning-loop.js +0 -521
- package/dist/usage.d.ts +0 -11
- package/dist/usage.js +0 -11
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
- package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
- package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
- package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
- package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
- package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
|
@@ -4,15 +4,15 @@
|
|
|
4
4
|
// with more than one statement is one transaction (connection.transaction, BEGIN IMMEDIATE): all of it or none of it.
|
|
5
5
|
// The domain code below (the SqliteStore class, storeOver) is written once for SQLite and Postgres (a Postgres store opens
|
|
6
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";
|
|
7
|
+
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, rmSync, statSync, writeSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
9
|
import { DatabaseSync } from "node:sqlite";
|
|
10
10
|
import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } from '../native-command-owner.js';
|
|
11
11
|
import { watchCommandsAt, wakeCommands } from "../command-wake.js";
|
|
12
12
|
import { claimFence, storeNow } from "../fence.js";
|
|
13
13
|
import { RunStorage } from "../journal/storage.js";
|
|
14
|
-
import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, MINTED_TOKENS, NATIVE_COMMANDS_INDEX, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION } from "../schema.js";
|
|
15
|
-
import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
|
|
14
|
+
import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
15
|
+
import { AgentArchived, AgentDeleting, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
|
|
16
16
|
/** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
|
|
17
17
|
const seqOf = (cursor) => {
|
|
18
18
|
if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
|
|
@@ -20,15 +20,27 @@ const seqOf = (cursor) => {
|
|
|
20
20
|
return Number(cursor);
|
|
21
21
|
};
|
|
22
22
|
import { cleanText, settledBody } from "../dialect.js";
|
|
23
|
-
import {
|
|
23
|
+
import { inMemory } from "./memory.js";
|
|
24
|
+
import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
|
|
24
25
|
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
25
|
-
import { readLaunch, readLearningStarts, writeLaunch } from "./run-launch.js";
|
|
26
|
+
import { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
26
27
|
import { canonical } from "../agent-body.js";
|
|
27
28
|
import { aadOf, sealedAt } from "../seal.js";
|
|
28
29
|
/** A claim's length when the caller names none. */
|
|
29
30
|
export const DEFAULT_LEASE_MS = 30_000;
|
|
30
31
|
/** The store's file in its data directory: only the store names it. */
|
|
31
32
|
export const STORE_FILE = "store.sqlite";
|
|
33
|
+
/** No audit's shadow run (learn/audit.ts SHADOW_PREFIX "audit."): the prefix compared as it is, which LIKE does not on
|
|
34
|
+
* SQLite (it folds case). */
|
|
35
|
+
const NOT_A_SHADOW_RUN = "substr(runs.id, 1, 6) <> 'audit.'";
|
|
36
|
+
/** A runner holds the run's claim at `now` (SQL), and the run is not over. */
|
|
37
|
+
const heldAt = (now) => `(runs.runner IS NOT NULL AND runs.claimed_until >= ${now} AND runs.state NOT IN ('ended', 'stopped', 'failed'))`;
|
|
38
|
+
/** The run's listing is behind at `now` (SQL; its parameters twice, `params`): built before the latest write that moved
|
|
39
|
+
* what its view shows, or while a runner held it and that claim has run out, or past the time an ask it waits on expires. */
|
|
40
|
+
const listingBehind = (now) => ({
|
|
41
|
+
sql: `(runs.listing_mark < runs.list_mark OR (runs.listing_live = 1 AND NOT ${heldAt(now)}) OR (runs.listing_until IS NOT NULL AND runs.listing_until <= ${now}))`,
|
|
42
|
+
params: (at) => [...at, ...at],
|
|
43
|
+
});
|
|
32
44
|
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";
|
|
33
45
|
const firingOf = (r) => ({
|
|
34
46
|
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,
|
|
@@ -47,6 +59,7 @@ const TRIGGER_PATCH = {
|
|
|
47
59
|
failuresInARow: (v) => ["failures_in_a_row", v ?? 0],
|
|
48
60
|
disabled: (v) => ["disabled", v === null ? null : json(v)],
|
|
49
61
|
maxActiveRuns: (v) => ["max_active_runs", v],
|
|
62
|
+
templateId: (v) => ["template_id", v],
|
|
50
63
|
};
|
|
51
64
|
/** `patch`'s columns, `updated_at` with them: the SET clause and its values. */
|
|
52
65
|
function triggerSet(patch, at) {
|
|
@@ -57,7 +70,7 @@ function triggerSet(patch, at) {
|
|
|
57
70
|
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
|
|
58
71
|
const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
|
|
59
72
|
const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
|
|
60
|
-
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";
|
|
73
|
+
const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
|
|
61
74
|
const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
|
|
62
75
|
/** Taken (Dialect.lockKey) by every insert of a run's command row, before it: the run's rows commit in id order, as
|
|
63
76
|
* SQLite's one writer commits them. On Postgres an id is taken at the insert and the row is seen at its commit, so two
|
|
@@ -104,7 +117,7 @@ const commandOf = (r) => ({ id: r.id, runId: r.run_id, kind: r.kind, body: JSON.
|
|
|
104
117
|
const triggerOf = (r) => ({
|
|
105
118
|
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,
|
|
106
119
|
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,
|
|
107
|
-
createdAt: r.created_at, updatedAt: r.updated_at,
|
|
120
|
+
createdAt: r.created_at, updatedAt: r.updated_at, templateId: r.template_id ?? null,
|
|
108
121
|
});
|
|
109
122
|
const json = (value) => JSON.stringify(value ?? null);
|
|
110
123
|
/** A UTF-16 surrogate standing alone (in `u` mode a whole pair is one code point, so only a lone half matches). */
|
|
@@ -144,7 +157,8 @@ const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r
|
|
|
144
157
|
const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
|
|
145
158
|
const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
|
|
146
159
|
const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
|
|
147
|
-
const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at });
|
|
160
|
+
const mintedOf = (r) => ({ machine: r.machine, kind: r.kind, os: r.os, arch: r.arch, expiresAt: r.expires_at, revokedAt: r.revoked_at, createdAt: r.created_at, runner: r.runner, incarnation: r.incarnation, run: r.run, refused: r.refused });
|
|
161
|
+
const relayOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, host: r.host, port: Number(r.port), seenAt: Number(r.seen_at) });
|
|
148
162
|
const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
|
|
149
163
|
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 });
|
|
150
164
|
const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
|
|
@@ -169,18 +183,42 @@ const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json
|
|
|
169
183
|
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
170
184
|
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
171
185
|
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
172
|
-
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made.
|
|
173
|
-
|
|
186
|
+
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
|
|
187
|
+
* this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
|
|
188
|
+
function earlierVersionIn(dataDir, busyTimeoutMs) {
|
|
174
189
|
if (!existsSync(dataDir))
|
|
175
190
|
return [];
|
|
176
191
|
const found = [];
|
|
177
|
-
|
|
192
|
+
// A path the server may not look into is not an earlier version's: that version wrote its files as the server's own
|
|
193
|
+
// user. A disk mounted as the data directory has one such, lost+found (root's, mode 700).
|
|
194
|
+
const stat = (path) => {
|
|
195
|
+
try {
|
|
196
|
+
return statSync(path, { throwIfNoEntry: false });
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (error.code === "EACCES")
|
|
200
|
+
return undefined;
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
const isFile = (path) => stat(path)?.isFile() === true;
|
|
178
205
|
// A directory linked in counts as one (stat follows the link), as the server's check of old homes reads them: an
|
|
179
206
|
// earlier version's home or run kept elsewhere and linked in is still the earlier version's.
|
|
180
|
-
const isDir = (path) =>
|
|
181
|
-
const dirsIn = (path) =>
|
|
207
|
+
const isDir = (path) => stat(path)?.isDirectory() === true;
|
|
208
|
+
const dirsIn = (path) => {
|
|
209
|
+
if (!isDir(path))
|
|
210
|
+
return [];
|
|
211
|
+
try {
|
|
212
|
+
return readdirSync(path).filter((name) => isDir(join(path, name)));
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error.code === "EACCES")
|
|
216
|
+
return [];
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
182
220
|
const store = join(dataDir, STORE_FILE);
|
|
183
|
-
if (isFile(store) && !isThisVersionsStore(store))
|
|
221
|
+
if (isFile(store) && !isThisVersionsStore(store, busyTimeoutMs))
|
|
184
222
|
found.push(STORE_FILE);
|
|
185
223
|
for (const name of EARLIER_ROOT_FILES)
|
|
186
224
|
if (isFile(join(dataDir, name)))
|
|
@@ -208,9 +246,12 @@ function earlierVersionIn(dataDir) {
|
|
|
208
246
|
}
|
|
209
247
|
return found.sort();
|
|
210
248
|
}
|
|
211
|
-
/** Whether `file` is this version's store, or one with nothing in it yet: an earlier one has tables and no store_meta.
|
|
212
|
-
|
|
213
|
-
|
|
249
|
+
/** Whether `file` is this version's store, or one with nothing in it yet: an earlier one has tables and no store_meta.
|
|
250
|
+
* Read before the owner lock is taken, so the server this one replaces may still have the file open: its close (the last
|
|
251
|
+
* connection's checkpoint) holds the file locked for a moment, and a read with no busy wait is refused "database is
|
|
252
|
+
* locked", which no replaced-server wait retries. It waits `busyTimeoutMs` for that lock, as the store's connection does. */
|
|
253
|
+
function isThisVersionsStore(file, busyTimeoutMs) {
|
|
254
|
+
const db = new DatabaseSync(file, { readOnly: true, timeout: busyTimeoutMs });
|
|
214
255
|
try {
|
|
215
256
|
const tables = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all();
|
|
216
257
|
if (tables.length === 0)
|
|
@@ -240,7 +281,7 @@ export async function openSqliteStore(options) {
|
|
|
240
281
|
// The server makes its data directory; a runner opens only one that is there. No migration: a directory an earlier
|
|
241
282
|
// version wrote is refused before anything in it is opened or made.
|
|
242
283
|
if (role === "server") {
|
|
243
|
-
const earlier = earlierVersionIn(options.dataDir);
|
|
284
|
+
const earlier = earlierVersionIn(options.dataDir, options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS);
|
|
244
285
|
if (earlier.length > 0)
|
|
245
286
|
throw new StoreFromEarlierVersion(options.dataDir, earlier);
|
|
246
287
|
mkdirSync(options.dataDir, { recursive: true });
|
|
@@ -259,7 +300,14 @@ export async function openSqliteStore(options) {
|
|
|
259
300
|
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 });
|
|
260
301
|
found = await versionOf(connection);
|
|
261
302
|
}
|
|
262
|
-
|
|
303
|
+
// Version 11 (0.1.0-beta.43 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
|
|
304
|
+
// in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
|
|
305
|
+
// it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
|
|
306
|
+
// (schema.ts relayUpgrade). A runner refuses 11 and 12 until that server has.
|
|
307
|
+
const upgrading = found === SCHEMA_VERSION - 2 || found === SCHEMA_VERSION - 1;
|
|
308
|
+
if (upgrading && role === "runner")
|
|
309
|
+
throw new Error(`Start the AgentRun server to bring this store from version ${found} to ${SCHEMA_VERSION} before opening a runner. The runner does not upgrade this store.`);
|
|
310
|
+
if (found !== SCHEMA_VERSION && !upgrading)
|
|
263
311
|
throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
|
|
264
312
|
const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
|
|
265
313
|
if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
|
|
@@ -285,6 +333,14 @@ export async function openSqliteStore(options) {
|
|
|
285
333
|
throw new Error("Start the AgentRun server to add each run's labels before opening a runner. The runner does not upgrade this store.");
|
|
286
334
|
await connection.write([{ sql: RUNS_LABELS }], { full: true });
|
|
287
335
|
}
|
|
336
|
+
// An earlier build of this version kept no package mark on a trigger (schema.ts TRIGGERS_TEMPLATE_ID): the server adds
|
|
337
|
+
// the column, nullable, every trigger made before reading as no package's. A runner reads each trigger through it, so
|
|
338
|
+
// it waits for that server.
|
|
339
|
+
if (!(await connection.all("SELECT name FROM pragma_table_info('triggers')")).some((column) => column.name === "template_id")) {
|
|
340
|
+
if (role === "runner")
|
|
341
|
+
throw new Error("Start the AgentRun server to add each trigger's package mark before opening a runner. The runner does not upgrade this store.");
|
|
342
|
+
await connection.write([{ sql: TRIGGERS_TEMPLATE_ID }], { full: true });
|
|
343
|
+
}
|
|
288
344
|
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
289
345
|
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
290
346
|
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
@@ -311,13 +367,21 @@ export async function openSqliteStore(options) {
|
|
|
311
367
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
312
368
|
], { full: true });
|
|
313
369
|
await backfillNativeCommandOwners(connection);
|
|
370
|
+
if (found === SCHEMA_VERSION - 2) {
|
|
371
|
+
const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
|
|
372
|
+
await connection.write(listingUpgrade(present).map((sql) => ({ sql })), { full: true });
|
|
373
|
+
}
|
|
374
|
+
if (upgrading) {
|
|
375
|
+
const minted = new Set((await connection.all("SELECT name FROM pragma_table_info('minted_tokens')")).map((column) => column.name));
|
|
376
|
+
await connection.write(relayUpgrade(minted).map((sql) => ({ sql })), { full: true });
|
|
377
|
+
}
|
|
314
378
|
}
|
|
315
379
|
}
|
|
316
380
|
catch (error) {
|
|
317
381
|
await connection.close().catch(() => undefined);
|
|
318
382
|
throw error;
|
|
319
383
|
}
|
|
320
|
-
return storeOver(connection, options.now ?? Date.now);
|
|
384
|
+
return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
|
|
321
385
|
}
|
|
322
386
|
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
323
387
|
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
@@ -376,9 +440,33 @@ function readOnly(tx) {
|
|
|
376
440
|
};
|
|
377
441
|
}
|
|
378
442
|
/** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
|
|
379
|
-
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
|
|
380
|
-
|
|
381
|
-
|
|
443
|
+
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
|
|
444
|
+
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX). */
|
|
445
|
+
export function storeOver(connection, now, file) {
|
|
446
|
+
return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`);
|
|
447
|
+
}
|
|
448
|
+
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
|
|
449
|
+
* file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
|
|
450
|
+
const SCRUB_SUFFIX = ".scrub";
|
|
451
|
+
/** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
|
|
452
|
+
const VACUUM_RETRY_MS = 400;
|
|
453
|
+
/** The marker at `path`, written and synced (its directory too) before the rewrite it marks changes a byte. */
|
|
454
|
+
function markScrub(path) {
|
|
455
|
+
const fd = openSync(path, "w", 0o600);
|
|
456
|
+
try {
|
|
457
|
+
writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear may have left its old bytes in the store's free pages; the next start scrubs them and removes this file.\n");
|
|
458
|
+
fsyncSync(fd);
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
closeSync(fd);
|
|
462
|
+
}
|
|
463
|
+
const dir = openSync(dirname(path), "r");
|
|
464
|
+
try {
|
|
465
|
+
fsyncSync(dir);
|
|
466
|
+
}
|
|
467
|
+
finally {
|
|
468
|
+
closeSync(dir);
|
|
469
|
+
}
|
|
382
470
|
}
|
|
383
471
|
/** The store's domain code, written once for both databases: its SQL takes `?` parameters, and what a database says
|
|
384
472
|
* differently, or must lock where SQLite's one writer serializes, is the connection's Dialect (store/dialect.ts). */
|
|
@@ -396,6 +484,7 @@ class SqliteStore {
|
|
|
396
484
|
computerLedger;
|
|
397
485
|
pairedComputers;
|
|
398
486
|
mintedTokens;
|
|
487
|
+
runnerRelays;
|
|
399
488
|
importedTemplates;
|
|
400
489
|
triggerSettings;
|
|
401
490
|
channels;
|
|
@@ -418,8 +507,11 @@ class SqliteStore {
|
|
|
418
507
|
* but nothing is written through it: release moved the run's epoch on, so the journal's first commit is Fenced by the
|
|
419
508
|
* epoch check in its own transaction. The map refuses early; the epoch is what guarantees it. */
|
|
420
509
|
#released = new Map();
|
|
421
|
-
|
|
510
|
+
/** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
|
|
511
|
+
#scrubMarker;
|
|
512
|
+
constructor(db, now, origin, scrubMarker) {
|
|
422
513
|
this.#db = db;
|
|
514
|
+
this.#scrubMarker = scrubMarker;
|
|
423
515
|
this.#now = now;
|
|
424
516
|
this.origin = origin ?? this;
|
|
425
517
|
this.where = db.where;
|
|
@@ -452,6 +544,16 @@ class SqliteStore {
|
|
|
452
544
|
if ((await tx.get("SELECT archived_at FROM agents WHERE id = ?", agentId))?.archived_at != null)
|
|
453
545
|
throw new AgentArchived(agentId);
|
|
454
546
|
};
|
|
547
|
+
/** Refused (AgentDeleting) when agent `agentId` is being deleted: another system's agent with an archive time, which
|
|
548
|
+
* only its delete writes (AgentDeleting). The agent's row is held first (a writer's row lock, as the archive's UPDATE
|
|
549
|
+
* takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
|
|
550
|
+
* this run to be in the store, where the delete's listing of the agent's runs finds it. */
|
|
551
|
+
const refuseDeleting = async (tx, agentId) => {
|
|
552
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
553
|
+
const agent = await tx.get("SELECT archived_at, external_ref FROM agents WHERE id = ?", agentId);
|
|
554
|
+
if (agent?.archived_at != null && agent.external_ref != null)
|
|
555
|
+
throw new AgentDeleting(agentId);
|
|
556
|
+
};
|
|
455
557
|
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
456
558
|
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
457
559
|
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
@@ -535,6 +637,29 @@ class SqliteStore {
|
|
|
535
637
|
});
|
|
536
638
|
return row?.mcp_pin == null ? null : JSON.parse(row.mcp_pin);
|
|
537
639
|
},
|
|
640
|
+
remove: async (agentId) => {
|
|
641
|
+
await db.transaction(async (tx) => {
|
|
642
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
643
|
+
if (await tx.get("SELECT id FROM runs WHERE agent_id = ? LIMIT 1", agentId))
|
|
644
|
+
throw new StoreConstraint(`agent ${agentId} still has runs: each is removed first (runs.remove)`);
|
|
645
|
+
// A trigger is never removed with the agent: what it keeps outside its row (a registration upstream, its adapter
|
|
646
|
+
// settings) goes only through the trigger engine. One made past the delete's listing (it is refused once the
|
|
647
|
+
// agent is marked, triggers.create; this is read under the agent row's lock, which that refusal takes too)
|
|
648
|
+
// keeps the agent for the next delete to remove whole.
|
|
649
|
+
const left = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
|
|
650
|
+
if (left.length)
|
|
651
|
+
throw new TriggersLeft(agentId, left.map((one) => one.id));
|
|
652
|
+
await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
|
|
653
|
+
await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
|
|
654
|
+
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
655
|
+
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
656
|
+
// Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
|
|
657
|
+
// agent's pointer at its current one cleared first.
|
|
658
|
+
await tx.run("UPDATE agents SET current_revision = NULL WHERE id = ?", agentId);
|
|
659
|
+
await tx.run("DELETE FROM revisions WHERE agent_id = ?", agentId);
|
|
660
|
+
await tx.run("DELETE FROM agents WHERE id = ?", agentId);
|
|
661
|
+
});
|
|
662
|
+
},
|
|
538
663
|
};
|
|
539
664
|
this.templates = {
|
|
540
665
|
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
@@ -583,22 +708,35 @@ class SqliteStore {
|
|
|
583
708
|
// A trigger belongs to an agent the store holds: refused in words, never a bare foreign-key failure.
|
|
584
709
|
if (!(await tx.get("SELECT id FROM agents WHERE id = ?", t.agentId)))
|
|
585
710
|
throw new StoreConstraint(`no agent ${t.agentId}: a trigger belongs to an agent the store holds`);
|
|
711
|
+
// None for an agent being deleted, off too: an off trigger may hold a registration upstream (Composio's) that
|
|
712
|
+
// the delete, having listed the agent's triggers already, would never remove.
|
|
713
|
+
await refuseDeleting(tx, t.agentId);
|
|
586
714
|
if (t.enabled)
|
|
587
715
|
await refuseArchived(tx, t.agentId);
|
|
588
|
-
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);
|
|
716
|
+
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, template_id) 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, t.templateId ?? null);
|
|
589
717
|
if (t.enabled)
|
|
590
718
|
await writeScopes(tx, t.id, scopes);
|
|
591
719
|
return made;
|
|
592
720
|
});
|
|
593
721
|
return triggerOf(row);
|
|
594
722
|
},
|
|
595
|
-
update: async (id, patch, scopes) => {
|
|
723
|
+
update: async (id, patch, scopes, options) => {
|
|
596
724
|
const { set, params } = triggerSet(patch, now());
|
|
725
|
+
// A compare-and-set (options.ifUpdatedAt): no row is changed once the trigger was updated or deleted since that read.
|
|
726
|
+
// Its source too (options.ifSource, compared as the JSON text the store wrote): one millisecond's writes share an
|
|
727
|
+
// updated_at, never a source. Its agent too (options.ifAgent): none is changed once the trigger was moved to another.
|
|
728
|
+
const unchanged = `${options?.ifUpdatedAt === undefined ? "" : " AND updated_at = ?"}${options?.ifSource === undefined ? "" : " AND source = ?"}${options?.ifAgent === undefined ? "" : " AND agent_id = ?"}`;
|
|
729
|
+
const since = [...(options?.ifUpdatedAt === undefined ? [] : [options.ifUpdatedAt]), ...(options?.ifSource === undefined ? [] : [json(options.ifSource)]), ...(options?.ifAgent === undefined ? [] : [options.ifAgent])];
|
|
597
730
|
const row = await db.transaction(async (tx) => {
|
|
598
731
|
// Moved to another agent (its target re-aimed): one the store holds, refused in words otherwise.
|
|
599
732
|
if (patch.agentId !== undefined && !(await tx.get("SELECT id FROM agents WHERE id = ?", patch.agentId)))
|
|
600
733
|
throw new StoreConstraint(`no agent ${patch.agentId}: a trigger belongs to an agent the store holds`);
|
|
601
|
-
|
|
734
|
+
// Never moved to an agent being deleted, off too, nor turned on for one: read (and its row held) before the
|
|
735
|
+
// trigger's row is written, in the agent-then-trigger order its archive and its removal take.
|
|
736
|
+
const to = patch.agentId ?? (await tx.get("SELECT agent_id FROM triggers WHERE id = ?", id))?.agent_id;
|
|
737
|
+
if (to !== undefined && (patch.agentId !== undefined || patch.enabled === true))
|
|
738
|
+
await refuseDeleting(tx, to);
|
|
739
|
+
const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ?${unchanged} RETURNING ${TRIGGER_COLUMNS}`, ...params, id, ...since);
|
|
602
740
|
// Never left on for an archived agent (turned on, or moved there on): the whole update is undone.
|
|
603
741
|
if (changed?.enabled === 1)
|
|
604
742
|
await refuseArchived(tx, changed.agent_id);
|
|
@@ -610,8 +748,10 @@ class SqliteStore {
|
|
|
610
748
|
return row && triggerOf(row);
|
|
611
749
|
},
|
|
612
750
|
scoped: async (kind, scope) => (await db.all("SELECT trigger_id FROM trigger_scopes WHERE kind = ? AND scope = ?", kind, scope)).map((r) => r.trigger_id),
|
|
613
|
-
remove: async (id) => {
|
|
614
|
-
|
|
751
|
+
remove: async (id, options) => {
|
|
752
|
+
// On its agent's condition (options.ifAgent), compared in the same statement: one moved to another is left.
|
|
753
|
+
const [done] = await db.write([options?.ifAgent === undefined ? { sql: "DELETE FROM triggers WHERE id = ?", params: [id] } : { sql: "DELETE FROM triggers WHERE id = ? AND agent_id = ?", params: [id, options.ifAgent] }]);
|
|
754
|
+
return done.changes > 0;
|
|
615
755
|
},
|
|
616
756
|
record: async (triggerId, firings, { patch, room } = {}) => db.transaction(async (tx) => {
|
|
617
757
|
const at = now();
|
|
@@ -801,21 +941,19 @@ class SqliteStore {
|
|
|
801
941
|
// sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
|
|
802
942
|
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
|
|
803
943
|
const labelled = labelsColumn(labels);
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
}
|
|
817
|
-
const [result] = await db.write([{ sql: insert, params: [id, agentId, revisionId, labelled, now()] }]);
|
|
818
|
-
return this.#queued(runOf(result.rows[0]));
|
|
944
|
+
// The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
|
|
945
|
+
// never lands, and a run never exists without the launch it was started with. Never a run of an agent being
|
|
946
|
+
// deleted: its mark is read here, in the transaction that would start the run.
|
|
947
|
+
return this.#queued(await db.transaction(async (tx) => {
|
|
948
|
+
const at = now();
|
|
949
|
+
await refuseDeleting(tx, agentId);
|
|
950
|
+
const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
|
|
951
|
+
if (origin)
|
|
952
|
+
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
|
|
953
|
+
if (launch)
|
|
954
|
+
await writeLaunch(tx, id, launch, at);
|
|
955
|
+
return runOf(row);
|
|
956
|
+
}));
|
|
819
957
|
},
|
|
820
958
|
createInline: async ({ agent, revision, run, launch }) => {
|
|
821
959
|
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
|
|
@@ -826,6 +964,8 @@ class SqliteStore {
|
|
|
826
964
|
// The agent, one per external reference: written on its first run, read on every later one.
|
|
827
965
|
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);
|
|
828
966
|
const mapped = (await tx.get("SELECT id, current_revision FROM agents WHERE external_ref = ?", agent.ref));
|
|
967
|
+
// An agent being deleted takes no run, nor a revision: the reference names it until its delete commits.
|
|
968
|
+
await refuseDeleting(tx, mapped.id);
|
|
829
969
|
// The revision, one per version: a version already stored keeps its body (a different body is refused); a new
|
|
830
970
|
// version is written, made current, and brings the agent's name and description up to it (the source is the truth).
|
|
831
971
|
const existing = await tx.get("SELECT id, body FROM revisions WHERE agent_id = ? AND external_version = ?", mapped.id, revision.version);
|
|
@@ -877,6 +1017,75 @@ class SqliteStore {
|
|
|
877
1017
|
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);
|
|
878
1018
|
return rows.map(runOf);
|
|
879
1019
|
},
|
|
1020
|
+
// A list's page from the rows alone: filtered, ordered and cut to the page in the query, one read whatever the number
|
|
1021
|
+
// of runs, each row with its listing (schema.ts RUN_LISTING_COLUMNS) and its agent's archive time.
|
|
1022
|
+
listed: async ({ agentId, revisionId, labels, archived, status, going, after, limit, offset = 0 }) => {
|
|
1023
|
+
const n = clock();
|
|
1024
|
+
const behind = listingBehind(n.sql);
|
|
1025
|
+
// Neither a built-in learning run nor an audit's shadow run (learn/audit.ts SHADOW_PREFIX, matched as it is, case and all).
|
|
1026
|
+
const where = [`runs.${NOT_A_LEARNING_RUN}`, NOT_A_SHADOW_RUN];
|
|
1027
|
+
const params = [];
|
|
1028
|
+
if (agentId !== undefined)
|
|
1029
|
+
(where.push("runs.agent_id = ?"), params.push(agentId));
|
|
1030
|
+
if (revisionId !== undefined)
|
|
1031
|
+
(where.push("runs.revision_id = ?"), params.push(revisionId));
|
|
1032
|
+
for (const [key, value] of Object.entries(labels ?? {}))
|
|
1033
|
+
(where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
|
|
1034
|
+
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`);
|
|
1035
|
+
if (status !== undefined)
|
|
1036
|
+
(where.push("runs.list_status = ?"), params.push(status));
|
|
1037
|
+
// A run still going (no settled status on its row) whose listing is behind: its list_status may say what it was.
|
|
1038
|
+
if (going)
|
|
1039
|
+
(where.push(`(${SETTLED_LIST_STATUS}) IS NULL`, behind.sql), params.push(...behind.params(n.params)));
|
|
1040
|
+
if (after)
|
|
1041
|
+
(where.push("(runs.started_at < ? OR (runs.started_at = ? AND runs.id < ?))"), params.push(after.startedAt, after.startedAt, after.id));
|
|
1042
|
+
const rows = await db.all(`SELECT ${RUN_COLUMNS.split(", ").map((column) => `runs.${column}`).join(", ")}, agents.archived_at AS agent_archived_at, runs.listing, runs.list_status, runs.list_mark,
|
|
1043
|
+
${behind.sql} AS behind
|
|
1044
|
+
FROM runs JOIN agents ON agents.id = runs.agent_id WHERE ${where.join(" AND ")} ORDER BY runs.started_at DESC, runs.id DESC LIMIT ? OFFSET ?`, ...behind.params(n.params), ...params, limit + 1, offset);
|
|
1045
|
+
return {
|
|
1046
|
+
rows: rows.slice(0, limit).map((row) => ({
|
|
1047
|
+
row: runOf(row), agentArchivedAt: row.agent_archived_at, listStatus: row.list_status, listMark: Number(row.list_mark), behind: Boolean(Number(row.behind)),
|
|
1048
|
+
listing: row.listing === null ? null : JSON.parse(row.listing),
|
|
1049
|
+
})),
|
|
1050
|
+
more: rows.length > limit,
|
|
1051
|
+
};
|
|
1052
|
+
},
|
|
1053
|
+
counts: async (agentId) => {
|
|
1054
|
+
const [row] = await db.all(`SELECT COUNT(*) AS count, SUM(CASE WHEN runs.state IN ('queued', 'running', 'parked')
|
|
1055
|
+
OR (runs.state = 'stopped' AND runs.outcome = 'stopped' AND runs.imported_from IS NULL AND revisions.kind = 'agentic') THEN 1 ELSE 0 END) AS live
|
|
1056
|
+
FROM runs JOIN revisions ON revisions.id = runs.revision_id
|
|
1057
|
+
WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN}`, agentId);
|
|
1058
|
+
return { count: Number(row?.count ?? 0), live: Number(row?.live ?? 0) };
|
|
1059
|
+
},
|
|
1060
|
+
// The rows whose listing is behind, by the three ways one falls behind, each over its own partial index.
|
|
1061
|
+
behind: async ({ limit, offset = 0 }) => {
|
|
1062
|
+
const n = clock();
|
|
1063
|
+
const held = heldAt(n.sql);
|
|
1064
|
+
const rows = await db.all(`SELECT id, list_mark AS mark, held FROM (
|
|
1065
|
+
SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark
|
|
1066
|
+
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_live = 1 AND NOT ${held}
|
|
1067
|
+
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_until IS NOT NULL AND listing_until <= ${n.sql}
|
|
1068
|
+
) AS behind ORDER BY held, started_at DESC, id DESC LIMIT ? OFFSET ?`, ...n.params, ...n.params, ...n.params, ...n.params, ...n.params, limit, offset);
|
|
1069
|
+
return rows.map((row) => ({ id: row.id, mark: Number(row.mark), held: Boolean(Number(row.held)) }));
|
|
1070
|
+
},
|
|
1071
|
+
putListing: async (runId, mark, { item, cut, status, live, until, flags }) => {
|
|
1072
|
+
const [result] = await db.write([{
|
|
1073
|
+
sql: "UPDATE runs SET listing = ?, list_status = ?, listing_mark = ?, listing_live = ?, listing_until = ?, listing_flags = ? WHERE id = ? AND list_mark = ? RETURNING id",
|
|
1074
|
+
params: [json({ item, cut }), status, mark, live ? 1 : 0, until, flags, runId, mark],
|
|
1075
|
+
}]);
|
|
1076
|
+
return (result?.rows.length ?? 0) > 0;
|
|
1077
|
+
},
|
|
1078
|
+
listMark: async (runId) => {
|
|
1079
|
+
const row = await db.get("SELECT list_mark FROM runs WHERE id = ?", runId);
|
|
1080
|
+
return row === undefined ? undefined : Number(row.list_mark);
|
|
1081
|
+
},
|
|
1082
|
+
relist: async ({ flags, agentId }) => {
|
|
1083
|
+
const [result] = await db.write([{
|
|
1084
|
+
sql: `UPDATE runs SET list_mark = list_mark + 1 WHERE listing_flags <> 0 AND (listing_flags & ?) <> 0${agentId === undefined ? "" : " AND agent_id = ?"} RETURNING id`,
|
|
1085
|
+
params: [flags, ...(agentId === undefined ? [] : [agentId])],
|
|
1086
|
+
}]);
|
|
1087
|
+
return result?.rows.length ?? 0;
|
|
1088
|
+
},
|
|
880
1089
|
// The run-change feed: the rows the runs_changed trigger wrote, each in its write's transaction, after the cursor's
|
|
881
1090
|
// seq. One writer numbers them in commit order, so the last one read is the watermark and the cursor is its seq. A
|
|
882
1091
|
// built-in learning run's changes are left out, as the run list leaves it out (NOT_A_LEARNING_RUN): its end is the
|
|
@@ -897,8 +1106,38 @@ class SqliteStore {
|
|
|
897
1106
|
// Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
|
|
898
1107
|
await db.write([archived ? { sql: "UPDATE runs SET archived_at = COALESCE(archived_at, ?) WHERE id = ?", params: [now(), runId] } : { sql: "UPDATE runs SET archived_at = NULL WHERE id = ?", params: [runId] }]);
|
|
899
1108
|
},
|
|
1109
|
+
every: async (agentId) => db.all("SELECT id, state FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId),
|
|
1110
|
+
remove: async (runId) => {
|
|
1111
|
+
await db.transaction(async (tx) => {
|
|
1112
|
+
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
|
|
1113
|
+
await d.lockRow(tx, "runs", "id", runId, "update");
|
|
1114
|
+
const run = await tx.get("SELECT state FROM runs WHERE id = ?", runId);
|
|
1115
|
+
if (!run)
|
|
1116
|
+
return;
|
|
1117
|
+
if (!FINAL_STATES.includes(run.state))
|
|
1118
|
+
throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
|
|
1119
|
+
for (const table of PI_TABLES)
|
|
1120
|
+
await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
|
|
1121
|
+
await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
|
|
1122
|
+
await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
|
|
1123
|
+
await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
|
|
1124
|
+
await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
|
|
1125
|
+
await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
|
|
1126
|
+
await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
|
|
1127
|
+
await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
|
|
1128
|
+
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
1129
|
+
await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
|
|
1130
|
+
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
1131
|
+
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1132
|
+
await tx.run("DELETE FROM runs WHERE id = ?", runId);
|
|
1133
|
+
});
|
|
1134
|
+
},
|
|
900
1135
|
reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => {
|
|
901
1136
|
const command = await db.transaction(async (tx) => {
|
|
1137
|
+
// Never a run of an agent being deleted opened again (its mark, read in this transaction).
|
|
1138
|
+
const of = await tx.get("SELECT agent_id FROM runs WHERE id = ?", runId);
|
|
1139
|
+
if (of)
|
|
1140
|
+
await refuseDeleting(tx, of.agent_id);
|
|
902
1141
|
// Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
|
|
903
1142
|
// spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
|
|
904
1143
|
const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}`, runId);
|
|
@@ -906,7 +1145,7 @@ class SqliteStore {
|
|
|
906
1145
|
throw new RunFinal(runId);
|
|
907
1146
|
// The message's launch secrets, with it: the claim that runs its turn reads them.
|
|
908
1147
|
if (launchSealed)
|
|
909
|
-
await tx
|
|
1148
|
+
await writeLaunchSealed(tx, runId, launchSealed);
|
|
910
1149
|
await lockCommandsOf(tx, runId);
|
|
911
1150
|
const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) VALUES (?, ?, ?, ?) RETURNING ${COMMAND_COLUMNS}`, runId, kind, json(body), now());
|
|
912
1151
|
return commandOf(row);
|
|
@@ -1167,7 +1406,6 @@ class SqliteStore {
|
|
|
1167
1406
|
return row ? proposalOf(row) : undefined;
|
|
1168
1407
|
},
|
|
1169
1408
|
proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
|
|
1170
|
-
grading: async (agentId) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND learning_run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})) ORDER BY created_at DESC, run_id DESC, round DESC`, agentId)).map(proposalOf),
|
|
1171
1409
|
kept: async (agentId) => {
|
|
1172
1410
|
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1173
1411
|
const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
|
|
@@ -1190,29 +1428,6 @@ class SqliteStore {
|
|
|
1190
1428
|
return kept?.state === "proposed" ? [] : [{ agentId: row.agent_id, at: row.created_at, costUsd: 0 }];
|
|
1191
1429
|
});
|
|
1192
1430
|
},
|
|
1193
|
-
spentBeside: async (runId, { beforeRound } = {}) => {
|
|
1194
|
-
const rows = await db.all(`SELECT lr.state, ${EXACT_COST_USD("lr")} AS cost_usd, rl.body
|
|
1195
|
-
FROM learning_proposals lp
|
|
1196
|
-
LEFT JOIN runs lr ON lr.id = lp.learning_run_id
|
|
1197
|
-
LEFT JOIN run_launch rl ON rl.run_id = lp.learning_run_id
|
|
1198
|
-
WHERE lp.run_id = ? AND lp.learning_run_id IS NOT NULL${beforeRound === undefined ? "" : " AND lp.round < ?"}`, ...(beforeRound === undefined ? [runId] : [runId, beforeRound]));
|
|
1199
|
-
const figure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
|
|
1200
|
-
let spent = 0;
|
|
1201
|
-
for (const row of rows) {
|
|
1202
|
-
// A learning run named and never written spent nothing.
|
|
1203
|
-
if (row.state === null)
|
|
1204
|
-
continue;
|
|
1205
|
-
if (FINAL_STATES.includes(row.state) && figure(row.cost_usd)) {
|
|
1206
|
-
spent += row.cost_usd;
|
|
1207
|
-
continue;
|
|
1208
|
-
}
|
|
1209
|
-
const cap = row.body === null ? undefined : JSON.parse(row.body)?.max_cost_usd;
|
|
1210
|
-
if (!figure(cap))
|
|
1211
|
-
return null;
|
|
1212
|
-
spent += cap;
|
|
1213
|
-
}
|
|
1214
|
-
return spent;
|
|
1215
|
-
},
|
|
1216
1431
|
};
|
|
1217
1432
|
this.settings = {
|
|
1218
1433
|
get: async (key) => {
|
|
@@ -1391,16 +1606,16 @@ class SqliteStore {
|
|
|
1391
1606
|
return (result?.changes ?? 0) === 1;
|
|
1392
1607
|
},
|
|
1393
1608
|
};
|
|
1394
|
-
const MINTED = "SELECT machine, kind, os, arch, expires_at, revoked_at, created_at FROM minted_tokens";
|
|
1609
|
+
const MINTED = "SELECT machine, kind, os, arch, expires_at, revoked_at, created_at, runner, incarnation, run, refused FROM minted_tokens";
|
|
1395
1610
|
this.mintedTokens = {
|
|
1396
1611
|
// A mint for a machine that has one replaces it: its older token dials no more.
|
|
1397
|
-
mint: async ({ machine, tokenSha256, kind, os, arch, expiresAt }) => {
|
|
1612
|
+
mint: async ({ machine, tokenSha256, kind, os, arch, expiresAt, runner, incarnation, run }) => {
|
|
1398
1613
|
const at = now();
|
|
1399
1614
|
await db.write([
|
|
1400
1615
|
{ sql: "DELETE FROM minted_tokens WHERE expires_at <= ?", params: [at] },
|
|
1401
1616
|
{
|
|
1402
|
-
sql: "INSERT INTO minted_tokens (machine, token_sha256, kind, os, arch, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (machine) DO UPDATE SET token_sha256 = excluded.token_sha256, kind = excluded.kind, os = excluded.os, arch = excluded.arch, expires_at = excluded.expires_at, revoked_at = NULL, created_at = excluded.created_at",
|
|
1403
|
-
params: [machine, tokenSha256, kind, os, arch, expiresAt, at],
|
|
1617
|
+
sql: "INSERT INTO minted_tokens (machine, token_sha256, kind, os, arch, expires_at, created_at, runner, incarnation, run) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (machine) DO UPDATE SET token_sha256 = excluded.token_sha256, kind = excluded.kind, os = excluded.os, arch = excluded.arch, expires_at = excluded.expires_at, revoked_at = NULL, created_at = excluded.created_at, runner = excluded.runner, incarnation = excluded.incarnation, run = excluded.run, refused = NULL",
|
|
1618
|
+
params: [machine, tokenSha256, kind, os, arch, expiresAt, at, runner ?? null, incarnation ?? null, run ?? null],
|
|
1404
1619
|
},
|
|
1405
1620
|
]);
|
|
1406
1621
|
},
|
|
@@ -1416,6 +1631,30 @@ class SqliteStore {
|
|
|
1416
1631
|
const [result] = await db.write([{ sql: "UPDATE minted_tokens SET revoked_at = ? WHERE machine = ? AND revoked_at IS NULL", params: [now(), machine] }]);
|
|
1417
1632
|
return (result?.changes ?? 0) === 1;
|
|
1418
1633
|
},
|
|
1634
|
+
refuse: async (tokenSha256, words) => {
|
|
1635
|
+
await db.write([{ sql: "UPDATE minted_tokens SET refused = ? WHERE token_sha256 = ?", params: [words, tokenSha256] }]);
|
|
1636
|
+
},
|
|
1637
|
+
};
|
|
1638
|
+
const RELAYS = "SELECT runner, incarnation, host, port, seen_at FROM runner_relays";
|
|
1639
|
+
this.runnerRelays = {
|
|
1640
|
+
put: async ({ runner, incarnation, host, port }) => {
|
|
1641
|
+
await db.write([{
|
|
1642
|
+
sql: "INSERT INTO runner_relays (runner, incarnation, host, port, seen_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at",
|
|
1643
|
+
params: [runner, incarnation, host, port, now()],
|
|
1644
|
+
}]);
|
|
1645
|
+
},
|
|
1646
|
+
seen: async (runner, incarnation) => {
|
|
1647
|
+
const [result] = await db.write([{ sql: "UPDATE runner_relays SET seen_at = ? WHERE runner = ? AND incarnation = ?", params: [now(), runner, incarnation] }]);
|
|
1648
|
+
return (result?.changes ?? 0) === 1;
|
|
1649
|
+
},
|
|
1650
|
+
get: async (runner) => {
|
|
1651
|
+
const row = await db.get(`${RELAYS} WHERE runner = ?`, runner);
|
|
1652
|
+
return row === undefined ? undefined : relayOf(row);
|
|
1653
|
+
},
|
|
1654
|
+
list: async () => (await db.all(`${RELAYS} ORDER BY runner`)).map(relayOf),
|
|
1655
|
+
remove: async (runner, incarnation) => {
|
|
1656
|
+
await db.write([{ sql: "DELETE FROM runner_relays WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
|
|
1657
|
+
},
|
|
1419
1658
|
};
|
|
1420
1659
|
this.importedTemplates = {
|
|
1421
1660
|
list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
|
|
@@ -1621,6 +1860,52 @@ class SqliteStore {
|
|
|
1621
1860
|
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
1622
1861
|
};
|
|
1623
1862
|
}
|
|
1863
|
+
async secureRewrite(work, options = {}) {
|
|
1864
|
+
const marker = this.#scrubMarker;
|
|
1865
|
+
if (this.#db.dialect.name !== "sqlite" || marker === undefined)
|
|
1866
|
+
return { rewritten: await work() };
|
|
1867
|
+
// Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
|
|
1868
|
+
// leaves it, and its next start scrubs though no row is left in the clear.
|
|
1869
|
+
const pending = existsSync(marker);
|
|
1870
|
+
markScrub(marker);
|
|
1871
|
+
let rewritten;
|
|
1872
|
+
await this.#db.all("PRAGMA secure_delete = ON");
|
|
1873
|
+
try {
|
|
1874
|
+
rewritten = await work();
|
|
1875
|
+
}
|
|
1876
|
+
finally {
|
|
1877
|
+
await this.#db.all("PRAGMA secure_delete = OFF");
|
|
1878
|
+
}
|
|
1879
|
+
if (rewritten === 0 && !pending) {
|
|
1880
|
+
rmSync(marker, { force: true });
|
|
1881
|
+
return { rewritten };
|
|
1882
|
+
}
|
|
1883
|
+
// Asked with no VACUUM (a server already serving): the marker stays, and the next start's scrub runs it before it serves.
|
|
1884
|
+
if (options.vacuum === false)
|
|
1885
|
+
return { rewritten, left: "deferred" };
|
|
1886
|
+
// secure_delete zeroes only the bytes `work` freed: a copy an earlier, ordinary update of the row left (a pause, a
|
|
1887
|
+
// rename, a firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
|
|
1888
|
+
// checkpoint copies it into the file and truncates the log. Run outside any transaction.
|
|
1889
|
+
try {
|
|
1890
|
+
// Another connection's write (a runner's) may hold the lock past the busy wait: one retry after a short pause.
|
|
1891
|
+
await this.#db.all("VACUUM").catch(async (error) => {
|
|
1892
|
+
if (!(error instanceof StoreBusy))
|
|
1893
|
+
throw error;
|
|
1894
|
+
await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
|
|
1895
|
+
await this.#db.all("VACUUM");
|
|
1896
|
+
});
|
|
1897
|
+
const [checkpoint] = await this.#db.all("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
1898
|
+
// A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
|
|
1899
|
+
// checkpoint is done, so the marker stays.
|
|
1900
|
+
if (checkpoint?.busy !== 0)
|
|
1901
|
+
return { rewritten, left: "busy" };
|
|
1902
|
+
}
|
|
1903
|
+
catch (error) {
|
|
1904
|
+
return { rewritten, left: error instanceof StoreBusy ? "busy" : "failed" };
|
|
1905
|
+
}
|
|
1906
|
+
rmSync(marker, { force: true });
|
|
1907
|
+
return { rewritten };
|
|
1908
|
+
}
|
|
1624
1909
|
async claim(runId, runner, { leaseMs = DEFAULT_LEASE_MS } = {}) {
|
|
1625
1910
|
return (await this.#claimRuns(runner, leaseMs, { runId }))[0] ?? null;
|
|
1626
1911
|
}
|
|
@@ -1786,7 +2071,7 @@ class SqliteStore {
|
|
|
1786
2071
|
});
|
|
1787
2072
|
// The message's launch secrets, in the command's own write: written only when the command is (a final run refuses both).
|
|
1788
2073
|
if (launchSealed)
|
|
1789
|
-
await tx
|
|
2074
|
+
await writeLaunchSealed(tx, runId, launchSealed);
|
|
1790
2075
|
return inserted;
|
|
1791
2076
|
});
|
|
1792
2077
|
wakeCommands(this.where, { runId, what: "written" });
|