@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.46
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 +148 -5
- package/README.md +385 -305
- 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 +62 -19
- package/dist/composio-preset.js +69 -7
- package/dist/composio-triggers.d.ts +14 -0
- package/dist/composio-triggers.js +79 -15
- 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/computers.d.ts +21 -10
- package/dist/computers.js +39 -28
- package/dist/console/assets/index-C2MYaUBa.css +1 -0
- package/dist/console/assets/index-CZZeCReB.js +701 -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 +3 -1
- package/dist/errors.js +7 -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 +9 -1
- package/dist/harness-table.js +20 -3
- package/dist/harness.d.ts +1 -2
- package/dist/harness.js +3 -4
- package/dist/host.js +2 -1
- package/dist/import.d.ts +10 -0
- package/dist/import.js +28 -8
- 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 +23 -89
- package/dist/learn/check.js +57 -335
- 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 +89 -104
- package/dist/learn/corrections.d.ts +13 -0
- package/dist/learn/corrections.js +23 -0
- package/dist/learn/delete.d.ts +5 -5
- package/dist/learn/delete.js +8 -10
- 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 +23 -5
- package/dist/learn/promote.js +40 -2
- package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
- package/dist/learn/{skills.js → workflow-draft.js} +48 -58
- package/dist/learn/workflow-nodes.js +1 -1
- package/dist/learned-workflow.js +2 -2
- package/dist/learning-cost.d.ts +38 -24
- package/dist/learning-cost.js +41 -24
- package/dist/learning-routes.d.ts +91 -170
- package/dist/learning-routes.js +183 -421
- package/dist/learning-run.d.ts +19 -40
- package/dist/learning-run.js +23 -93
- package/dist/learning-setting.d.ts +21 -10
- package/dist/learning-setting.js +47 -11
- package/dist/learning-words.d.ts +28 -74
- package/dist/learning-words.js +64 -162
- package/dist/learning.d.ts +61 -392
- package/dist/learning.js +101 -651
- package/dist/live-reach.d.ts +25 -2
- package/dist/live-reach.js +46 -4
- package/dist/llms.txt +1 -1
- package/dist/local-models.d.ts +3 -11
- package/dist/local-models.js +5 -6
- package/dist/mcp-servers-store.d.ts +4 -4
- package/dist/model-form.js +6 -5
- package/dist/model.d.ts +4 -0
- package/dist/model.js +26 -9
- 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 +273 -319
- package/dist/paid-calls.d.ts +8 -0
- package/dist/paid-calls.js +20 -0
- package/dist/particle-provider.d.ts +11 -0
- package/dist/particle-provider.js +135 -0
- 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 +15 -1
- 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 +15 -89
- package/dist/run-listing.d.ts +34 -0
- package/dist/run-listing.js +128 -0
- package/dist/run-model-key.js +1 -1
- 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 +8 -6
- package/dist/runner/adapter-loop.js +16 -12
- package/dist/runner/adapter-run-spec.d.ts +16 -4
- package/dist/runner/adapter-run-spec.js +64 -58
- package/dist/runner/adapters/index.js +22 -0
- package/dist/runner/adapters/pi.d.ts +4 -12
- package/dist/runner/adapters/pi.js +2 -2
- package/dist/runner/audit.d.ts +1 -1
- package/dist/runner/audit.js +30 -13
- package/dist/runner/beside.d.ts +6 -2
- package/dist/runner/beside.js +38 -9
- package/dist/runner/claim-secrets.d.ts +18 -2
- package/dist/runner/claim-secrets.js +42 -18
- package/dist/runner/cli-run-spec.js +55 -51
- package/dist/runner/conformance/harness.d.ts +6 -0
- package/dist/runner/conformance/harness.js +35 -13
- package/dist/runner/conformance/subject.d.ts +6 -0
- 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 +2 -2
- package/dist/runner/feedback-round.js +7 -7
- package/dist/runner/github-app.js +3 -1
- package/dist/runner/harness-loops.d.ts +0 -8
- package/dist/runner/harness-loops.js +11 -59
- package/dist/runner/held.d.ts +170 -0
- package/dist/runner/held.js +57 -0
- package/dist/runner/journal-kinds.d.ts +2 -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 -69
- package/dist/runner/learning-end.js +250 -303
- package/dist/runner/learning-seed.d.ts +15 -33
- package/dist/runner/learning-seed.js +24 -45
- package/dist/runner/loop-contract.d.ts +2 -3
- package/dist/runner/main.d.ts +17 -9
- package/dist/runner/main.js +82 -20
- package/dist/runner/mcp-run.d.ts +11 -0
- package/dist/runner/mcp-run.js +67 -0
- package/dist/runner/memory-claim.d.ts +10 -5
- package/dist/runner/memory-claim.js +12 -6
- 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 +12 -8
- package/dist/runner/promotion.js +37 -28
- package/dist/runner/reflect-hook.d.ts +64 -95
- package/dist/runner/reflect-hook.js +112 -225
- 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 +1230 -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 +1 -5
- 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 +5 -1
- package/dist/runner/workflow-first.d.ts +5 -0
- package/dist/runner/workflow-first.js +4 -0
- package/dist/runner/workflow-spec.js +7 -2
- package/dist/runs-over-store.d.ts +16 -28
- package/dist/runs-over-store.js +31 -38
- package/dist/sdk/runs.d.ts +6 -11
- package/dist/sdk/runs.js +20 -41
- package/dist/sdk/schema.js +3 -4
- 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 +55 -33
- package/dist/server.js +689 -322
- 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 +2 -2
- package/dist/store/index.js +1 -1
- 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/sqlite/connection.d.ts +2 -0
- package/dist/store/sqlite/connection.js +3 -1
- package/dist/store/sqlite/run-patch.d.ts +0 -17
- package/dist/store/sqlite/run-patch.js +4 -33
- package/dist/store/sqlite/store.js +246 -63
- package/dist/store/sqlite/worker.js +25 -0
- package/dist/store/store.d.ts +193 -36
- package/dist/store/store.js +25 -3
- package/dist/store-reads/learning.d.ts +102 -204
- package/dist/store-reads/learning.js +159 -321
- package/dist/store-reads/loop.d.ts +0 -1
- package/dist/store-reads/loop.js +1 -1
- package/dist/store-view.d.ts +29 -1
- package/dist/store-view.js +97 -31
- package/dist/template-eval.d.ts +3 -6
- package/dist/template-eval.js +22 -36
- package/dist/templates.d.ts +8 -4
- package/dist/templates.js +44 -6
- 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/tools.d.ts +2 -2
- package/dist/tools.js +11 -4
- package/dist/triggers.d.ts +65 -6
- package/dist/triggers.js +125 -19
- package/dist/validate.js +1 -1
- package/dist/webhooks.d.ts +7 -2
- package/dist/webhooks.js +12 -5
- 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 +7 -3
- package/dist/workspace/computer-for-claim.js +119 -22
- 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 +33 -19
- 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 -10
- package/templates/README.md +8 -8
- package/templates/inbound-lead/agent.md +5 -4
- 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/kyb/agent.md +2 -1
- 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-BUktRvS-.css +0 -1
- package/dist/console/assets/index-nB9kTfIN.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 -35
- package/dist/learning-evals.js +0 -99
- 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
|
@@ -6,15 +6,9 @@
|
|
|
6
6
|
import { endedReason, FINAL_STATES, Fenced } from "../store.js";
|
|
7
7
|
import { settledBody, SQLITE } from "../dialect.js";
|
|
8
8
|
import { claimFence, storeNow } from "../fence.js";
|
|
9
|
-
import { writeLaunch } from "./run-launch.js";
|
|
10
9
|
/** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
|
|
11
10
|
* list of runs names. */
|
|
12
11
|
export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
|
|
13
|
-
/** A learning run's launch: harness "learning", its input the run that learned (and the round it grades, past the first),
|
|
14
|
-
* where it runs (on the runner, no box: its only writes are the learning folder's one script), `model`, the grade model
|
|
15
|
-
* when one is named (gradeModelOf; none: the agent's own grades it, as main's), and `max_cost_usd`, what the run's cap
|
|
16
|
-
* left for its grade (`capUsd`: a figure that is not one is no room, $0, never no cap; none for an uncapped run). */
|
|
17
|
-
export const learningLaunchOf = (runId, model, round = 1, capUsd) => ({ harness: "learning", input: { runId, ...(round > 1 ? { round } : {}) }, title: `Learning from ${runId}`, place: { mode: "runner" }, ...(model ? { model } : {}), ...(capUsd !== undefined ? { max_cost_usd: Number.isFinite(capUsd) && capUsd > 0 ? capUsd : 0 } : {}) });
|
|
18
12
|
/** The lock a write of a run's sign_in_handed and a sign-in's forget both take (Dialect.lockKey): the forget's check of
|
|
19
13
|
* the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
|
|
20
14
|
export const SIGN_IN_HANDED_LOCK = "sign_in_handed";
|
|
@@ -99,34 +93,11 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
|
|
|
99
93
|
case "channel_told":
|
|
100
94
|
await tx.run("INSERT INTO channel_told (channel, run_id, marker, at) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", each.row.channel, claim.runId, each.row.marker, now);
|
|
101
95
|
break;
|
|
102
|
-
// The run's kept learning of one round, of the run's own agent
|
|
103
|
-
//
|
|
104
|
-
case "learning_proposals":
|
|
105
|
-
|
|
106
|
-
await tx.run("INSERT INTO learning_proposals (run_id, round, agent_id, turn, proposal, learning_run_id, created_at) SELECT id, ?, agent_id, ?, ?, ?, ? FROM runs WHERE id = ? ON CONFLICT (run_id, round) DO NOTHING", each.row.round ?? 1, JSON.stringify(each.row.turn ?? null), JSON.stringify(each.row.proposal ?? null), queued?.row.id ?? null, now, claim.runId);
|
|
96
|
+
// The run's kept learning of one round, of the run's own agent; kept once a round (an end replayed after a crash
|
|
97
|
+
// keeps the first).
|
|
98
|
+
case "learning_proposals":
|
|
99
|
+
await tx.run("INSERT INTO learning_proposals (run_id, round, agent_id, turn, proposal, created_at) SELECT id, ?, agent_id, ?, ?, ? FROM runs WHERE id = ? ON CONFLICT (run_id, round) DO NOTHING", each.row.round ?? 1, JSON.stringify(each.row.turn ?? null), JSON.stringify(each.row.proposal ?? null), now, claim.runId);
|
|
107
100
|
break;
|
|
108
|
-
}
|
|
109
|
-
// The learning run is queued after every row of the end (below): only once its kept learning names it.
|
|
110
|
-
case "learning_run":
|
|
111
|
-
break;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
// The learning run: queued, of the run's agent and revision, started once (the same id again adds nothing), and only
|
|
115
|
-
// when the run's kept learning names it. A kept learning is kept once (above): a follow-up's end that keeps another
|
|
116
|
-
// beside one already kept that names no learning run (dropped: nothing to grade) queues none, so no learning run is
|
|
117
|
-
// ever left that no kept learning names. Such a run would be no run's grade: every list of runs would show it as the
|
|
118
|
-
// agent's own run (NOT_A_LEARNING_RUN reads the kept learning), and its spend would be booked on no run.
|
|
119
|
-
for (const each of also) {
|
|
120
|
-
if (each.table !== "learning_run")
|
|
121
|
-
continue;
|
|
122
|
-
const named = await tx.get("SELECT 1 AS found FROM learning_proposals WHERE run_id = ? AND learning_run_id = ?", claim.runId, each.row.id);
|
|
123
|
-
if (!named)
|
|
124
|
-
continue;
|
|
125
|
-
await tx.run("INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) SELECT ?, agent_id, revision_id, 'queued', 0, ? FROM runs WHERE id = ? ON CONFLICT (id) DO NOTHING", each.row.id, now, claim.runId);
|
|
126
|
-
// Its launch row, with it: harness "learning" (the runner's loop factory picks the learning loop by it), its input
|
|
127
|
-
// the run that learned. Written once, as the run is.
|
|
128
|
-
if (!(await tx.get("SELECT 1 AS found FROM run_launch WHERE run_id = ?", each.row.id))) {
|
|
129
|
-
await writeLaunch(tx, each.row.id, { body: learningLaunchOf(claim.runId, each.row.model, each.row.round, each.row.capUsd) }, now);
|
|
130
101
|
}
|
|
131
102
|
}
|
|
132
103
|
return runOf(row);
|
|
@@ -11,8 +11,8 @@ import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } fro
|
|
|
11
11
|
import { watchCommandsAt, wakeCommands } from "../command-wake.js";
|
|
12
12
|
import { claimFence, storeNow } from "../fence.js";
|
|
13
13
|
import { RunStorage } from "../journal/storage.js";
|
|
14
|
-
import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, 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, StoreBusy, 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))
|
|
@@ -21,7 +21,7 @@ const seqOf = (cursor) => {
|
|
|
21
21
|
};
|
|
22
22
|
import { cleanText, settledBody } from "../dialect.js";
|
|
23
23
|
import { inMemory } from "./memory.js";
|
|
24
|
-
import { Connection } from "./connection.js";
|
|
24
|
+
import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
|
|
25
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";
|
|
26
26
|
import { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
27
27
|
import { canonical } from "../agent-body.js";
|
|
@@ -30,6 +30,17 @@ import { aadOf, sealedAt } from "../seal.js";
|
|
|
30
30
|
export const DEFAULT_LEASE_MS = 30_000;
|
|
31
31
|
/** The store's file in its data directory: only the store names it. */
|
|
32
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
|
+
});
|
|
33
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";
|
|
34
45
|
const firingOf = (r) => ({
|
|
35
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,
|
|
@@ -48,6 +59,7 @@ const TRIGGER_PATCH = {
|
|
|
48
59
|
failuresInARow: (v) => ["failures_in_a_row", v ?? 0],
|
|
49
60
|
disabled: (v) => ["disabled", v === null ? null : json(v)],
|
|
50
61
|
maxActiveRuns: (v) => ["max_active_runs", v],
|
|
62
|
+
templateId: (v) => ["template_id", v],
|
|
51
63
|
};
|
|
52
64
|
/** `patch`'s columns, `updated_at` with them: the SET clause and its values. */
|
|
53
65
|
function triggerSet(patch, at) {
|
|
@@ -58,7 +70,7 @@ function triggerSet(patch, at) {
|
|
|
58
70
|
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
|
|
59
71
|
const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
|
|
60
72
|
const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
|
|
61
|
-
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";
|
|
62
74
|
const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
|
|
63
75
|
/** Taken (Dialect.lockKey) by every insert of a run's command row, before it: the run's rows commit in id order, as
|
|
64
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
|
|
@@ -105,7 +117,7 @@ const commandOf = (r) => ({ id: r.id, runId: r.run_id, kind: r.kind, body: JSON.
|
|
|
105
117
|
const triggerOf = (r) => ({
|
|
106
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,
|
|
107
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,
|
|
108
|
-
createdAt: r.created_at, updatedAt: r.updated_at,
|
|
120
|
+
createdAt: r.created_at, updatedAt: r.updated_at, templateId: r.template_id ?? null,
|
|
109
121
|
});
|
|
110
122
|
const json = (value) => JSON.stringify(value ?? null);
|
|
111
123
|
/** A UTF-16 surrogate standing alone (in `u` mode a whole pair is one code point, so only a lone half matches). */
|
|
@@ -145,7 +157,8 @@ const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r
|
|
|
145
157
|
const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
|
|
146
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 });
|
|
147
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 });
|
|
148
|
-
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) });
|
|
149
162
|
const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
|
|
150
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 });
|
|
151
164
|
const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
|
|
@@ -170,8 +183,9 @@ const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json
|
|
|
170
183
|
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
171
184
|
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
172
185
|
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
173
|
-
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made.
|
|
174
|
-
|
|
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) {
|
|
175
189
|
if (!existsSync(dataDir))
|
|
176
190
|
return [];
|
|
177
191
|
const found = [];
|
|
@@ -204,7 +218,7 @@ function earlierVersionIn(dataDir) {
|
|
|
204
218
|
}
|
|
205
219
|
};
|
|
206
220
|
const store = join(dataDir, STORE_FILE);
|
|
207
|
-
if (isFile(store) && !isThisVersionsStore(store))
|
|
221
|
+
if (isFile(store) && !isThisVersionsStore(store, busyTimeoutMs))
|
|
208
222
|
found.push(STORE_FILE);
|
|
209
223
|
for (const name of EARLIER_ROOT_FILES)
|
|
210
224
|
if (isFile(join(dataDir, name)))
|
|
@@ -232,9 +246,12 @@ function earlierVersionIn(dataDir) {
|
|
|
232
246
|
}
|
|
233
247
|
return found.sort();
|
|
234
248
|
}
|
|
235
|
-
/** Whether `file` is this version's store, or one with nothing in it yet: an earlier one has tables and no store_meta.
|
|
236
|
-
|
|
237
|
-
|
|
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 });
|
|
238
255
|
try {
|
|
239
256
|
const tables = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all();
|
|
240
257
|
if (tables.length === 0)
|
|
@@ -264,7 +281,7 @@ export async function openSqliteStore(options) {
|
|
|
264
281
|
// The server makes its data directory; a runner opens only one that is there. No migration: a directory an earlier
|
|
265
282
|
// version wrote is refused before anything in it is opened or made.
|
|
266
283
|
if (role === "server") {
|
|
267
|
-
const earlier = earlierVersionIn(options.dataDir);
|
|
284
|
+
const earlier = earlierVersionIn(options.dataDir, options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS);
|
|
268
285
|
if (earlier.length > 0)
|
|
269
286
|
throw new StoreFromEarlierVersion(options.dataDir, earlier);
|
|
270
287
|
mkdirSync(options.dataDir, { recursive: true });
|
|
@@ -283,7 +300,14 @@ export async function openSqliteStore(options) {
|
|
|
283
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 });
|
|
284
301
|
found = await versionOf(connection);
|
|
285
302
|
}
|
|
286
|
-
|
|
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)
|
|
287
311
|
throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
|
|
288
312
|
const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
|
|
289
313
|
if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
|
|
@@ -309,6 +333,14 @@ export async function openSqliteStore(options) {
|
|
|
309
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.");
|
|
310
334
|
await connection.write([{ sql: RUNS_LABELS }], { full: true });
|
|
311
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
|
+
}
|
|
312
344
|
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
313
345
|
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
314
346
|
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
@@ -335,6 +367,14 @@ export async function openSqliteStore(options) {
|
|
|
335
367
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
336
368
|
], { full: true });
|
|
337
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
|
+
}
|
|
338
378
|
}
|
|
339
379
|
}
|
|
340
380
|
catch (error) {
|
|
@@ -444,6 +484,7 @@ class SqliteStore {
|
|
|
444
484
|
computerLedger;
|
|
445
485
|
pairedComputers;
|
|
446
486
|
mintedTokens;
|
|
487
|
+
runnerRelays;
|
|
447
488
|
importedTemplates;
|
|
448
489
|
triggerSettings;
|
|
449
490
|
channels;
|
|
@@ -503,6 +544,16 @@ class SqliteStore {
|
|
|
503
544
|
if ((await tx.get("SELECT archived_at FROM agents WHERE id = ?", agentId))?.archived_at != null)
|
|
504
545
|
throw new AgentArchived(agentId);
|
|
505
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
|
+
};
|
|
506
557
|
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
507
558
|
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
508
559
|
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
@@ -586,6 +637,29 @@ class SqliteStore {
|
|
|
586
637
|
});
|
|
587
638
|
return row?.mcp_pin == null ? null : JSON.parse(row.mcp_pin);
|
|
588
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
|
+
},
|
|
589
663
|
};
|
|
590
664
|
this.templates = {
|
|
591
665
|
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
@@ -634,9 +708,12 @@ class SqliteStore {
|
|
|
634
708
|
// A trigger belongs to an agent the store holds: refused in words, never a bare foreign-key failure.
|
|
635
709
|
if (!(await tx.get("SELECT id FROM agents WHERE id = ?", t.agentId)))
|
|
636
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);
|
|
637
714
|
if (t.enabled)
|
|
638
715
|
await refuseArchived(tx, t.agentId);
|
|
639
|
-
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);
|
|
640
717
|
if (t.enabled)
|
|
641
718
|
await writeScopes(tx, t.id, scopes);
|
|
642
719
|
return made;
|
|
@@ -647,13 +724,18 @@ class SqliteStore {
|
|
|
647
724
|
const { set, params } = triggerSet(patch, now());
|
|
648
725
|
// A compare-and-set (options.ifUpdatedAt): no row is changed once the trigger was updated or deleted since that read.
|
|
649
726
|
// Its source too (options.ifSource, compared as the JSON text the store wrote): one millisecond's writes share an
|
|
650
|
-
// updated_at, never a source.
|
|
651
|
-
const unchanged = `${options?.ifUpdatedAt === undefined ? "" : " AND updated_at = ?"}${options?.ifSource === undefined ? "" : " AND source = ?"}`;
|
|
652
|
-
const since = [...(options?.ifUpdatedAt === undefined ? [] : [options.ifUpdatedAt]), ...(options?.ifSource === undefined ? [] : [json(options.ifSource)])];
|
|
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])];
|
|
653
730
|
const row = await db.transaction(async (tx) => {
|
|
654
731
|
// Moved to another agent (its target re-aimed): one the store holds, refused in words otherwise.
|
|
655
732
|
if (patch.agentId !== undefined && !(await tx.get("SELECT id FROM agents WHERE id = ?", patch.agentId)))
|
|
656
733
|
throw new StoreConstraint(`no agent ${patch.agentId}: a trigger belongs to an agent the store holds`);
|
|
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);
|
|
657
739
|
const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ?${unchanged} RETURNING ${TRIGGER_COLUMNS}`, ...params, id, ...since);
|
|
658
740
|
// Never left on for an archived agent (turned on, or moved there on): the whole update is undone.
|
|
659
741
|
if (changed?.enabled === 1)
|
|
@@ -666,8 +748,10 @@ class SqliteStore {
|
|
|
666
748
|
return row && triggerOf(row);
|
|
667
749
|
},
|
|
668
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),
|
|
669
|
-
remove: async (id) => {
|
|
670
|
-
|
|
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;
|
|
671
755
|
},
|
|
672
756
|
record: async (triggerId, firings, { patch, room } = {}) => db.transaction(async (tx) => {
|
|
673
757
|
const at = now();
|
|
@@ -857,21 +941,19 @@ class SqliteStore {
|
|
|
857
941
|
// sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
|
|
858
942
|
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
|
|
859
943
|
const labelled = labelsColumn(labels);
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
}
|
|
873
|
-
const [result] = await db.write([{ sql: insert, params: [id, agentId, revisionId, labelled, now()] }]);
|
|
874
|
-
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
|
+
}));
|
|
875
957
|
},
|
|
876
958
|
createInline: async ({ agent, revision, run, launch }) => {
|
|
877
959
|
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`;
|
|
@@ -882,6 +964,8 @@ class SqliteStore {
|
|
|
882
964
|
// The agent, one per external reference: written on its first run, read on every later one.
|
|
883
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);
|
|
884
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);
|
|
885
969
|
// The revision, one per version: a version already stored keeps its body (a different body is refused); a new
|
|
886
970
|
// version is written, made current, and brings the agent's name and description up to it (the source is the truth).
|
|
887
971
|
const existing = await tx.get("SELECT id, body FROM revisions WHERE agent_id = ? AND external_version = ?", mapped.id, revision.version);
|
|
@@ -933,6 +1017,75 @@ class SqliteStore {
|
|
|
933
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);
|
|
934
1018
|
return rows.map(runOf);
|
|
935
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
|
+
},
|
|
936
1089
|
// The run-change feed: the rows the runs_changed trigger wrote, each in its write's transaction, after the cursor's
|
|
937
1090
|
// seq. One writer numbers them in commit order, so the last one read is the watermark and the cursor is its seq. A
|
|
938
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
|
|
@@ -953,8 +1106,38 @@ class SqliteStore {
|
|
|
953
1106
|
// Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
|
|
954
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] }]);
|
|
955
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
|
+
},
|
|
956
1135
|
reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => {
|
|
957
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);
|
|
958
1141
|
// Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
|
|
959
1142
|
// spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
|
|
960
1143
|
const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}`, runId);
|
|
@@ -1223,7 +1406,6 @@ class SqliteStore {
|
|
|
1223
1406
|
return row ? proposalOf(row) : undefined;
|
|
1224
1407
|
},
|
|
1225
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),
|
|
1226
|
-
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),
|
|
1227
1409
|
kept: async (agentId) => {
|
|
1228
1410
|
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1229
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);
|
|
@@ -1246,29 +1428,6 @@ class SqliteStore {
|
|
|
1246
1428
|
return kept?.state === "proposed" ? [] : [{ agentId: row.agent_id, at: row.created_at, costUsd: 0 }];
|
|
1247
1429
|
});
|
|
1248
1430
|
},
|
|
1249
|
-
spentBeside: async (runId, { beforeRound } = {}) => {
|
|
1250
|
-
const rows = await db.all(`SELECT lr.state, ${EXACT_COST_USD("lr")} AS cost_usd, rl.body
|
|
1251
|
-
FROM learning_proposals lp
|
|
1252
|
-
LEFT JOIN runs lr ON lr.id = lp.learning_run_id
|
|
1253
|
-
LEFT JOIN run_launch rl ON rl.run_id = lp.learning_run_id
|
|
1254
|
-
WHERE lp.run_id = ? AND lp.learning_run_id IS NOT NULL${beforeRound === undefined ? "" : " AND lp.round < ?"}`, ...(beforeRound === undefined ? [runId] : [runId, beforeRound]));
|
|
1255
|
-
const figure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
|
|
1256
|
-
let spent = 0;
|
|
1257
|
-
for (const row of rows) {
|
|
1258
|
-
// A learning run named and never written spent nothing.
|
|
1259
|
-
if (row.state === null)
|
|
1260
|
-
continue;
|
|
1261
|
-
if (FINAL_STATES.includes(row.state) && figure(row.cost_usd)) {
|
|
1262
|
-
spent += row.cost_usd;
|
|
1263
|
-
continue;
|
|
1264
|
-
}
|
|
1265
|
-
const cap = row.body === null ? undefined : JSON.parse(row.body)?.max_cost_usd;
|
|
1266
|
-
if (!figure(cap))
|
|
1267
|
-
return null;
|
|
1268
|
-
spent += cap;
|
|
1269
|
-
}
|
|
1270
|
-
return spent;
|
|
1271
|
-
},
|
|
1272
1431
|
};
|
|
1273
1432
|
this.settings = {
|
|
1274
1433
|
get: async (key) => {
|
|
@@ -1447,16 +1606,16 @@ class SqliteStore {
|
|
|
1447
1606
|
return (result?.changes ?? 0) === 1;
|
|
1448
1607
|
},
|
|
1449
1608
|
};
|
|
1450
|
-
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";
|
|
1451
1610
|
this.mintedTokens = {
|
|
1452
1611
|
// A mint for a machine that has one replaces it: its older token dials no more.
|
|
1453
|
-
mint: async ({ machine, tokenSha256, kind, os, arch, expiresAt }) => {
|
|
1612
|
+
mint: async ({ machine, tokenSha256, kind, os, arch, expiresAt, runner, incarnation, run }) => {
|
|
1454
1613
|
const at = now();
|
|
1455
1614
|
await db.write([
|
|
1456
1615
|
{ sql: "DELETE FROM minted_tokens WHERE expires_at <= ?", params: [at] },
|
|
1457
1616
|
{
|
|
1458
|
-
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",
|
|
1459
|
-
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],
|
|
1460
1619
|
},
|
|
1461
1620
|
]);
|
|
1462
1621
|
},
|
|
@@ -1472,6 +1631,30 @@ class SqliteStore {
|
|
|
1472
1631
|
const [result] = await db.write([{ sql: "UPDATE minted_tokens SET revoked_at = ? WHERE machine = ? AND revoked_at IS NULL", params: [now(), machine] }]);
|
|
1473
1632
|
return (result?.changes ?? 0) === 1;
|
|
1474
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
|
+
},
|
|
1475
1658
|
};
|
|
1476
1659
|
this.importedTemplates = {
|
|
1477
1660
|
list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
// as stmt, or as step (one statement, its changes and rows, its `expect` checked)
|
|
20
20
|
// in between
|
|
21
21
|
// close
|
|
22
|
+
import { chmodSync, closeSync, openSync } from "node:fs";
|
|
22
23
|
import { parentPort } from "node:worker_threads";
|
|
23
24
|
import { DatabaseSync } from "node:sqlite";
|
|
24
25
|
import { inMemory } from "./memory.js";
|
|
@@ -171,15 +172,39 @@ function takeOwnerLock(file) {
|
|
|
171
172
|
}
|
|
172
173
|
owner = lock;
|
|
173
174
|
}
|
|
175
|
+
/** The store's files, the server's alone (0600) whatever the umask: a run's process, a user of its own that may cross the
|
|
176
|
+
* data directory to its folders, opens none of them. The file is made 0600 before SQLite opens it, and SQLite makes its
|
|
177
|
+
* WAL and shared-memory files with the database file's mode; each one already there is set again (a store an earlier
|
|
178
|
+
* start made 0644). A file this process does not own (a runner's on the server's store) is left as it is. */
|
|
179
|
+
function keepPrivate(file, made) {
|
|
180
|
+
if (inMemory(file))
|
|
181
|
+
return;
|
|
182
|
+
if (made) {
|
|
183
|
+
try {
|
|
184
|
+
closeSync(openSync(file, "a", 0o600));
|
|
185
|
+
}
|
|
186
|
+
catch { }
|
|
187
|
+
}
|
|
188
|
+
for (const each of [file, `${file}-wal`, `${file}-shm`, `${file}.owner`, `${file}.owner-journal`]) {
|
|
189
|
+
try {
|
|
190
|
+
chmodSync(each, 0o600);
|
|
191
|
+
}
|
|
192
|
+
catch { }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
174
195
|
function handle(request) {
|
|
175
196
|
switch (request.op) {
|
|
176
197
|
case "open": {
|
|
198
|
+
if (request.owner)
|
|
199
|
+
keepPrivate(request.file, true);
|
|
177
200
|
if (request.owner)
|
|
178
201
|
takeOwnerLock(request.file);
|
|
179
202
|
db = new DatabaseSync(request.file);
|
|
180
203
|
busyTimeout = Math.max(0, Math.floor(request.busyTimeoutMs));
|
|
181
204
|
db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
|
|
182
205
|
db.exec("PRAGMA journal_mode = WAL");
|
|
206
|
+
if (request.owner)
|
|
207
|
+
keepPrivate(request.file, false);
|
|
183
208
|
db.exec(NORMAL);
|
|
184
209
|
db.exec("PRAGMA foreign_keys = ON");
|
|
185
210
|
return null;
|