@parcha/agentrun-serve 0.1.0-beta.52 → 0.1.0-beta.53
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 +122 -1
- package/README.md +213 -24
- package/dist/agent-delete.d.ts +5 -6
- package/dist/agent-delete.js +30 -67
- package/dist/agent-package.d.ts +71 -0
- package/dist/agent-package.js +345 -0
- package/dist/agents-store.d.ts +26 -20
- package/dist/agents-store.js +41 -33
- package/dist/api-only.d.ts +26 -6
- package/dist/api-only.js +35 -13
- package/dist/claude-login.d.ts +1 -0
- package/dist/claude-login.js +1 -1
- package/dist/cli-learning/cli.d.ts +3 -0
- package/dist/cli-learning/cli.js +17 -3
- package/dist/cli-learning/connections.js +3 -2
- package/dist/cli-learning/schema.js +2 -1
- package/dist/cli.js +70 -7
- package/dist/composio-preset.d.ts +2 -1
- package/dist/composio-preset.js +4 -3
- package/dist/composio-triggers.d.ts +4 -0
- package/dist/composio-triggers.js +4 -1
- package/dist/computer-needs.d.ts +32 -0
- package/dist/computer-needs.js +80 -0
- package/dist/computer-setting.d.ts +1 -0
- package/dist/computer-setting.js +8 -1
- package/dist/console/assets/index-BFgyZzF_.js +734 -0
- package/dist/console/assets/index-DbilxljH.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +1 -0
- package/dist/console-links.js +2 -0
- package/dist/env-switch.d.ts +14 -0
- package/dist/env-switch.js +23 -0
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +3 -0
- package/dist/eval-previous.js +4 -3
- package/dist/fal-price.js +10 -13
- package/dist/handed-secret.d.ts +4 -0
- package/dist/handed-secret.js +10 -0
- package/dist/harness-archive.d.ts +15 -5
- package/dist/harness-archive.js +71 -34
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +36 -95
- package/dist/harness-egress.d.ts +23 -0
- package/dist/harness-egress.js +69 -0
- package/dist/harness-recipe-entry.d.ts +71 -0
- package/dist/harness-recipe-entry.js +184 -0
- package/dist/harness-recipe.d.ts +73 -6
- package/dist/harness-recipe.js +185 -31
- package/dist/harness-sign-in.d.ts +29 -0
- package/dist/harness-sign-in.js +122 -0
- package/dist/harness-table.d.ts +21 -0
- package/dist/harness-table.js +58 -3
- package/dist/harness-zip.d.ts +6 -0
- package/dist/harness-zip.js +203 -0
- package/dist/ids.d.ts +11 -0
- package/dist/ids.js +36 -0
- package/dist/learn/commit.d.ts +14 -1
- package/dist/learn/commit.js +156 -1
- package/dist/learn/compile.js +22 -8
- package/dist/learn/folder.d.ts +5 -0
- package/dist/learn/folder.js +10 -1
- package/dist/learn/learning.sh +15 -3
- package/dist/learn/promote.d.ts +2 -2
- package/dist/learn/secrets.js +30 -7
- package/dist/learning-routes.d.ts +23 -11
- package/dist/learning-routes.js +110 -20
- package/dist/learning.d.ts +9 -6
- package/dist/learning.js +9 -4
- package/dist/mcp-gateway.js +15 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +7 -2
- package/dist/mcp-resources.d.ts +44 -0
- package/dist/mcp-resources.js +100 -0
- package/dist/mcp-servers-store.d.ts +16 -12
- package/dist/model.d.ts +4 -4
- package/dist/model.js +6 -6
- package/dist/native/cli.js +9 -2
- package/dist/native/connection.d.ts +2 -2
- package/dist/native/connection.js +5 -2
- package/dist/native/discovery.d.ts +2 -0
- package/dist/native/discovery.js +10 -6
- package/dist/native/remote-worker-bridge.js +36 -4
- package/dist/native/remote.d.ts +18 -1
- package/dist/native/remote.js +126 -37
- package/dist/native/schema.d.ts +6 -0
- package/dist/native/schema.js +31 -6
- package/dist/native/source-account.d.ts +13 -0
- package/dist/native/source-account.js +114 -0
- package/dist/native/source-capture-hooks.d.ts +5 -0
- package/dist/native/source-capture-hooks.js +102 -0
- package/dist/native/source-mcp-selection.d.ts +13 -0
- package/dist/native/source-mcp-selection.js +72 -0
- package/dist/native/source-runtime-tools.d.ts +19 -0
- package/dist/native/source-runtime-tools.js +103 -0
- package/dist/native/source-snapshot-types.d.ts +138 -0
- package/dist/native/source-snapshot-types.js +12 -0
- package/dist/native/source-snapshot.d.ts +8 -0
- package/dist/native/source-snapshot.js +1201 -0
- package/dist/observation/learning.js +3 -2
- package/dist/openapi.js +167 -36
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +12 -0
- package/dist/purged-workflow.js +43 -0
- package/dist/run-keys.d.ts +46 -0
- package/dist/run-keys.js +109 -0
- package/dist/run-launch.d.ts +16 -1
- package/dist/run-launch.js +30 -1
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +2 -2
- package/dist/run-model-key.js +5 -5
- package/dist/run-secrets.d.ts +2 -0
- package/dist/run-secrets.js +7 -4
- package/dist/run-view.d.ts +17 -0
- package/dist/run-view.js +25 -1
- package/dist/runner/adapter-loop.d.ts +11 -3
- package/dist/runner/adapter-loop.js +138 -22
- package/dist/runner/adapter-run-spec.js +25 -12
- package/dist/runner/audit.d.ts +2 -0
- package/dist/runner/audit.js +9 -1
- package/dist/runner/beside.js +2 -1
- package/dist/runner/claim-secrets.d.ts +29 -3
- package/dist/runner/claim-secrets.js +38 -4
- package/dist/runner/cli-run-spec.js +23 -12
- package/dist/runner/harness-loops.d.ts +6 -0
- package/dist/runner/harness-loops.js +11 -1
- package/dist/runner/held.d.ts +4 -0
- package/dist/runner/journal-kinds.d.ts +2 -0
- package/dist/runner/learned-first.d.ts +2 -0
- package/dist/runner/learned-first.js +1 -1
- package/dist/runner/learning-end.d.ts +7 -2
- package/dist/runner/learning-end.js +22 -10
- package/dist/runner/learning-seed.d.ts +9 -3
- package/dist/runner/learning-seed.js +2 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +20 -13
- package/dist/runner/mcp-claim.js +6 -1
- package/dist/runner/mcp-run.d.ts +10 -7
- package/dist/runner/mcp-run.js +3 -5
- package/dist/runner/monid-run.js +9 -11
- package/dist/runner/project-checkpoint.d.ts +35 -0
- package/dist/runner/project-checkpoint.js +116 -0
- package/dist/runner/project-drain.d.ts +8 -0
- package/dist/runner/project-drain.js +25 -0
- package/dist/runner/project-host.d.ts +10 -0
- package/dist/runner/project-host.js +52 -0
- package/dist/runner/promotion.d.ts +14 -6
- package/dist/runner/promotion.js +98 -41
- package/dist/runner/redact.d.ts +13 -0
- package/dist/runner/redact.js +67 -1
- package/dist/runner/run-channel.d.ts +9 -0
- package/dist/runner/run-channel.js +15 -2
- package/dist/runner/run-child-host.d.ts +8 -4
- package/dist/runner/run-child-host.js +171 -41
- package/dist/runner/run-errors.js +2 -2
- package/dist/runner/runner-check.js +5 -2
- package/dist/runner/runner.js +26 -9
- package/dist/runner/store-secrets.js +7 -3
- package/dist/runner/workflow-first.d.ts +4 -0
- package/dist/runner/workflow-first.js +13 -0
- package/dist/runner/workflow-loop.d.ts +2 -1
- package/dist/runner/workflow-loop.js +2 -1
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/runs-over-store.d.ts +34 -6
- package/dist/runs-over-store.js +133 -25
- package/dist/sdk/runs.d.ts +11 -1
- package/dist/sdk/runs.js +117 -26
- package/dist/sdk/schema.js +12 -2
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +68 -32
- package/dist/server.js +600 -110
- package/dist/skills/agentrun-serve/SKILL.md +2 -1
- package/dist/source-sync/adoption.d.ts +15 -0
- package/dist/source-sync/adoption.js +36 -0
- package/dist/source-sync/auxiliary.d.ts +23 -0
- package/dist/source-sync/auxiliary.js +64 -0
- package/dist/source-sync/capture-git.d.ts +5 -0
- package/dist/source-sync/capture-git.js +272 -0
- package/dist/source-sync/capture-project.d.ts +53 -0
- package/dist/source-sync/capture-project.js +206 -0
- package/dist/source-sync/capture-refusal.d.ts +7 -0
- package/dist/source-sync/capture-refusal.js +16 -0
- package/dist/source-sync/capture.d.ts +11 -0
- package/dist/source-sync/capture.js +22 -0
- package/dist/source-sync/checkpoint-gate.d.ts +21 -0
- package/dist/source-sync/checkpoint-gate.js +52 -0
- package/dist/source-sync/checkpoints.d.ts +66 -0
- package/dist/source-sync/checkpoints.js +168 -0
- package/dist/source-sync/claim.d.ts +11 -0
- package/dist/source-sync/claim.js +48 -0
- package/dist/source-sync/destination.d.ts +47 -0
- package/dist/source-sync/destination.js +239 -0
- package/dist/source-sync/io.d.ts +15 -0
- package/dist/source-sync/io.js +52 -0
- package/dist/source-sync/local.d.ts +43 -0
- package/dist/source-sync/local.js +229 -0
- package/dist/source-sync/prepare.d.ts +59 -0
- package/dist/source-sync/prepare.js +93 -0
- package/dist/source-sync/projects.d.ts +61 -0
- package/dist/source-sync/projects.js +130 -0
- package/dist/source-sync/registry.d.ts +95 -0
- package/dist/source-sync/registry.js +226 -0
- package/dist/source-sync/service.d.ts +33 -0
- package/dist/source-sync/service.js +118 -0
- package/dist/source-sync/skill-edits.d.ts +12 -0
- package/dist/source-sync/skill-edits.js +122 -0
- package/dist/source-sync/snapshots.d.ts +48 -0
- package/dist/source-sync/snapshots.js +448 -0
- package/dist/source-sync/types.d.ts +9 -0
- package/dist/source-sync/types.js +14 -0
- package/dist/source-sync/workspace.d.ts +66 -0
- package/dist/source-sync/workspace.js +273 -0
- package/dist/store/agent-body.d.ts +4 -0
- package/dist/store/agent-body.js +16 -5
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/schema.d.ts +2 -1
- package/dist/store/schema.js +2 -1
- package/dist/store/seal.d.ts +5 -1
- package/dist/store/seal.js +12 -3
- package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
- package/dist/store/sqlite/project-checkpoints.js +70 -0
- package/dist/store/sqlite/run-launch.d.ts +4 -12
- package/dist/store/sqlite/run-launch.js +5 -19
- package/dist/store/sqlite/store.js +224 -170
- package/dist/store/store.d.ts +116 -39
- package/dist/store/store.js +14 -1
- package/dist/store-reads/learning.d.ts +2 -2
- package/dist/store-view.d.ts +3 -1
- package/dist/store-view.js +17 -5
- package/dist/template-import.d.ts +10 -2
- package/dist/template-import.js +116 -13
- package/dist/templates.d.ts +26 -5
- package/dist/templates.js +62 -10
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -0
- package/dist/timeline/timeline.js +8 -0
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +8 -8
- package/dist/trigger-launch-hook.d.ts +47 -0
- package/dist/trigger-launch-hook.js +90 -0
- package/dist/trigger-targets.d.ts +14 -1
- package/dist/trigger-targets.js +20 -0
- package/dist/triggers.d.ts +54 -5
- package/dist/triggers.js +143 -8
- package/dist/uploads-archil.js +1 -1
- package/dist/uploads.js +1 -1
- package/dist/validate.js +1 -2
- package/dist/workspace/computer-for-claim.d.ts +2 -0
- package/dist/workspace/computer-for-claim.js +43 -0
- package/dist/workspace/paths.d.ts +6 -0
- package/dist/workspace/paths.js +6 -0
- package/dist/workspace/resolve-computer.d.ts +1 -0
- package/dist/workspace/run-tools.d.ts +2 -0
- package/dist/workspace/run-tools.js +8 -0
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +2 -1
- package/templates/README.md +5 -2
- package/dist/console/assets/index-B-D0EM3j.js +0 -733
- package/dist/console/assets/index-DlQepP2J.css +0 -1
|
@@ -13,7 +13,7 @@ import { claimFence, storeNow } from "../fence.js";
|
|
|
13
13
|
import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
|
|
14
14
|
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
15
15
|
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
|
-
import { AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
|
|
16
|
+
import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, RUNNER_ROWS_KEPT_MS, tombstoneMetrics, } from "../store.js";
|
|
17
17
|
/** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
|
|
18
18
|
const madeOf = (body) => {
|
|
19
19
|
for (const link of ["replay", "audit"]) {
|
|
@@ -33,9 +33,38 @@ import { cleanText, settledBody } from "../dialect.js";
|
|
|
33
33
|
import { inMemory } from "./memory.js";
|
|
34
34
|
import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
|
|
35
35
|
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
36
|
-
import { launchDiskOf,
|
|
36
|
+
import { launchDiskOf, readableJson, readLaunch, readLearningStarts, readSeededBefore, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
37
37
|
import { canonical } from "../agent-body.js";
|
|
38
|
+
import { readProjectCheckpoints } from "./project-checkpoints.js";
|
|
38
39
|
import { aadOf, sealedAt } from "../seal.js";
|
|
40
|
+
/** Registry writers UPDATE/DELETE this same row, so a prepared cutover and a credential/catalog edit serialize. */
|
|
41
|
+
async function checkMcpGuards(tx, d, guards = []) {
|
|
42
|
+
const names = [...new Set(guards.map(guard => guard.name))].sort();
|
|
43
|
+
for (const name of names)
|
|
44
|
+
await d.lockRow(tx, "mcp_servers", "name", name);
|
|
45
|
+
for (const guard of guards) {
|
|
46
|
+
const row = await tx.get("SELECT url, auth, credential_changed_at, tools, sealed FROM mcp_servers WHERE name = ?", guard.name);
|
|
47
|
+
const sameSealed = row !== undefined && (row.sealed === null || guard.sealed === null
|
|
48
|
+
? row.sealed === guard.sealed : Buffer.from(row.sealed).equals(Buffer.from(guard.sealed)));
|
|
49
|
+
if (!row || row.url !== guard.url || row.auth !== guard.auth || row.credential_changed_at !== guard.credentialChangedAt
|
|
50
|
+
|| canonical(JSON.parse(row.tools)) !== canonical(guard.tools) || !sameSealed)
|
|
51
|
+
throw new StoreConstraint("An MCP server changed before the revision was saved. Prepare its tools and credentials again.");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Source authorization and admission share one transaction. Keep the settings locks before any agent/trigger/run
|
|
55
|
+
* lock, in stable key order, so revocation either commits first and refuses admission or follows its completed write. */
|
|
56
|
+
async function checkSettingsGuards(tx, guards = [], message = "The source grant changed before the write committed.", alsoLock = []) {
|
|
57
|
+
const byKey = new Map();
|
|
58
|
+
for (const guard of guards)
|
|
59
|
+
byKey.set(guard.key, [...(byKey.get(guard.key) ?? []), guard]);
|
|
60
|
+
for (const key of [...new Set([...byKey.keys(), ...alsoLock])].sort((a, b) => a.localeCompare(b))) {
|
|
61
|
+
const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", key);
|
|
62
|
+
const value = setting === undefined ? undefined : JSON.parse(setting.value);
|
|
63
|
+
if ((byKey.get(key) ?? []).some(guard => !value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected)))) {
|
|
64
|
+
throw new StoreConstraint(message);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
39
68
|
/** A claim's length when the caller names none. */
|
|
40
69
|
export const DEFAULT_LEASE_MS = 30_000;
|
|
41
70
|
/** The store's file in its data directory: only the store names it. */
|
|
@@ -52,9 +81,11 @@ const listingBehind = (now) => ({
|
|
|
52
81
|
params: (at) => [...at, ...at],
|
|
53
82
|
});
|
|
54
83
|
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";
|
|
84
|
+
/** A sent firing's retry_at is its startBy (settle's one exception), never a retry. */
|
|
55
85
|
const firingOf = (r) => ({
|
|
56
86
|
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,
|
|
57
|
-
error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.
|
|
87
|
+
error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.status === "sent" ? null : r.retry_at,
|
|
88
|
+
startBy: r.status === "sent" ? r.retry_at : null, payload: r.payload,
|
|
58
89
|
attrs: r.attrs === null ? null : JSON.parse(r.attrs), notified: r.notified === 1, catchUp: r.catch_up === 1, paused: r.paused === 1, shown: r.shown !== 0, waitsOn: r.waits_on,
|
|
59
90
|
});
|
|
60
91
|
/** The trigger's patch as columns: name -> [column, value]. */
|
|
@@ -585,14 +616,13 @@ async function dropAgentPrivate(tx, agentId) {
|
|
|
585
616
|
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
586
617
|
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
587
618
|
}
|
|
588
|
-
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge
|
|
589
|
-
*
|
|
590
|
-
*
|
|
619
|
+
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite (and a purge before its
|
|
620
|
+
* transaction) and removes once no file of the store keeps the bytes they replaced: a start that finds it finishes the
|
|
621
|
+
* scrub. */
|
|
591
622
|
const SCRUB_SUFFIX = ".scrub";
|
|
592
623
|
/** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
|
|
593
624
|
const VACUUM_RETRY_MS = 400;
|
|
594
|
-
/** The marker at `path`, written and synced (its directory too): before the rewrite it marks changes a byte
|
|
595
|
-
* purge's checkpoint left the log. */
|
|
625
|
+
/** The marker at `path`, written and synced (its directory too): before the rewrite or purge it marks changes a byte. */
|
|
596
626
|
function markScrub(path) {
|
|
597
627
|
const fd = openSync(path, "w", 0o600);
|
|
598
628
|
try {
|
|
@@ -653,10 +683,10 @@ class SqliteStore {
|
|
|
653
683
|
#released = new Map();
|
|
654
684
|
/** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
|
|
655
685
|
#scrubMarker;
|
|
656
|
-
/** How many times a purge
|
|
657
|
-
*
|
|
658
|
-
*
|
|
659
|
-
#
|
|
686
|
+
/** How many times a purge (#purging) or a rewrite (secureRewrite) wrote the marker. The marker has many writers: each
|
|
687
|
+
* removes it only when no other wrote it since the step that covers that writer's log (its own start, or the checkpoint
|
|
688
|
+
* it asked), so a marker is never removed without a checkpoint that truncated every writer's frames. */
|
|
689
|
+
#scrubMarks = 0;
|
|
660
690
|
constructor(db, now, origin, scrubMarker) {
|
|
661
691
|
this.#db = db;
|
|
662
692
|
this.#scrubMarker = scrubMarker;
|
|
@@ -677,18 +707,24 @@ class SqliteStore {
|
|
|
677
707
|
throw new AgentPurged(agentId, agent.archived_at, agent.purged_at);
|
|
678
708
|
return agent;
|
|
679
709
|
};
|
|
680
|
-
const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
|
|
710
|
+
const insertRevision = async (tx, agentId, revision, at, { ifCurrent, ifNoActiveRuns, advance } = {}) => {
|
|
681
711
|
// The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
|
|
682
712
|
// (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
|
|
683
|
-
// revisions
|
|
713
|
+
// revisions advanced at once, by this server or another on the same store, never both name the same parent, and
|
|
684
714
|
// `ifCurrent` is compared with what no other writer can move until this commits. Never one of a purged agent.
|
|
685
715
|
const agent = await heldAgent(tx, agentId);
|
|
686
716
|
if (!agent)
|
|
687
717
|
throw new StoreConstraint(`no agent ${agentId}`);
|
|
688
718
|
if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
|
|
689
719
|
throw new RevisionMoved(agentId, agent.current_revision);
|
|
720
|
+
if (ifNoActiveRuns) {
|
|
721
|
+
const active = await tx.all("SELECT id FROM runs WHERE agent_id = ? AND state IN ('queued', 'running', 'parked') ORDER BY id", agentId);
|
|
722
|
+
if (active.length > 0)
|
|
723
|
+
throw new ActiveRuns(agentId, active.map(({ id }) => id));
|
|
724
|
+
}
|
|
690
725
|
await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at, mcp_pin, monid_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at, pinText(revision.mcpPin), pinText(revision.monidPin));
|
|
691
|
-
|
|
726
|
+
if (advance !== false)
|
|
727
|
+
await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
|
|
692
728
|
};
|
|
693
729
|
const writeScopes = async (tx, triggerId, scopes) => {
|
|
694
730
|
await tx.run("DELETE FROM trigger_scopes WHERE trigger_id = ?", triggerId);
|
|
@@ -706,15 +742,20 @@ class SqliteStore {
|
|
|
706
742
|
* takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
|
|
707
743
|
* this run to be in the store, where the delete's listing of the agent's runs finds it. A purged agent is refused too
|
|
708
744
|
* (AgentPurged): it takes no run and no trigger. */
|
|
709
|
-
const refuseDeleting = async (tx, agentId) => {
|
|
745
|
+
const refuseDeleting = async (tx, agentId, expectedCurrent) => {
|
|
710
746
|
const agent = await heldAgent(tx, agentId);
|
|
711
747
|
if (agent?.archived_at != null && agent.external_ref != null)
|
|
712
748
|
throw new AgentDeleting(agentId);
|
|
749
|
+
if (expectedCurrent !== undefined) {
|
|
750
|
+
if (!agent)
|
|
751
|
+
throw new StoreConstraint(`no agent ${agentId}`);
|
|
752
|
+
if (agent.current_revision !== expectedCurrent)
|
|
753
|
+
throw new RevisionMoved(agentId, agent.current_revision);
|
|
754
|
+
}
|
|
713
755
|
};
|
|
714
756
|
/** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
|
|
715
|
-
* launch is read (no index names its source): a purge's read, never a hot path.
|
|
716
|
-
|
|
717
|
-
const launchedFrom = async (ex, runId, body = "body") => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText(body, ["replay", "of"])} = ? OR ${d.jsonText(body, ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
|
|
757
|
+
* launch is read (no index names its source): a purge's read, never a hot path. */
|
|
758
|
+
const launchedFrom = async (ex, runId) => (await ex.all(`SELECT run_id AS id FROM run_launch WHERE (${d.jsonText(readableJson(d, "body"), ["replay", "of"])} = ? OR ${d.jsonText(readableJson(d, "body"), ["audit", "of"])} = ?) AND run_id <> ? ORDER BY run_id`, runId, runId, runId)).map((row) => row.id);
|
|
718
759
|
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
719
760
|
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
720
761
|
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
@@ -782,9 +823,11 @@ class SqliteStore {
|
|
|
782
823
|
await writeScopes(tx, t.id, []);
|
|
783
824
|
return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
|
|
784
825
|
}),
|
|
785
|
-
addRevision: async ({ agentId, ifCurrent, description, ...revision }) => {
|
|
826
|
+
addRevision: async ({ agentId, ifCurrent, description, ifNoActiveRuns, settingsGuards, mcpGuards, advance, ...revision }) => {
|
|
786
827
|
await db.transaction(async (tx) => {
|
|
787
|
-
await
|
|
828
|
+
await checkSettingsGuards(tx, settingsGuards);
|
|
829
|
+
await checkMcpGuards(tx, d, mcpGuards);
|
|
830
|
+
await insertRevision(tx, agentId, revision, now(), { ifCurrent, ifNoActiveRuns, advance });
|
|
788
831
|
// Under the row lock insertRevision took, after its ifCurrent passed: the revision and the description, or neither.
|
|
789
832
|
if (description !== undefined)
|
|
790
833
|
await tx.run("UPDATE agents SET description = ? WHERE id = ?", description, agentId);
|
|
@@ -841,31 +884,42 @@ class SqliteStore {
|
|
|
841
884
|
await tx.run("DELETE FROM agents WHERE id = ?", agentId);
|
|
842
885
|
});
|
|
843
886
|
},
|
|
844
|
-
purge: async (
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
887
|
+
purge: (agentId) => this.#purging(() => db.transaction(async (tx) => {
|
|
888
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
889
|
+
const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
|
|
890
|
+
if (!agent || agent.purged_at !== null)
|
|
891
|
+
return false;
|
|
892
|
+
// Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
|
|
893
|
+
const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
|
|
894
|
+
if (left)
|
|
895
|
+
throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
|
|
896
|
+
const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
|
|
897
|
+
if (triggersLeft.length)
|
|
898
|
+
throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
|
|
899
|
+
await dropAgentPrivate(tx, agentId);
|
|
900
|
+
// The answer a template apply kept under its key, which holds the agent as it was made.
|
|
901
|
+
await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
|
|
902
|
+
// The uploads it was applied from, each gone unless another agent not purged was applied from it too: nothing
|
|
903
|
+
// else owns one, and a server that serves no template route (API-only) could never remove it. Each is held by its
|
|
904
|
+
// id, in order, before it is read: two purges of agents applied from one upload read it in turn, so the later
|
|
905
|
+
// reads the earlier's purge (committed) and removes the upload.
|
|
906
|
+
const packageId = (alias) => d.jsonText(`${alias}.package`, ["id"]);
|
|
907
|
+
const applied = (await tx.all(`SELECT DISTINCT ${packageId("r")} AS id FROM revisions r WHERE r.agent_id = ? AND r.package IS NOT NULL`, agentId))
|
|
908
|
+
.map((row) => row.id)
|
|
909
|
+
.filter((id) => id !== null && id.startsWith(UPLOAD_PREFIX))
|
|
910
|
+
.sort();
|
|
911
|
+
for (const id of applied) {
|
|
912
|
+
await d.lockKey(tx, `imported_templates:${id}`);
|
|
913
|
+
const kept = await tx.get(`SELECT r.id FROM revisions r JOIN agents a ON a.id = r.agent_id WHERE r.agent_id <> ? AND a.purged_at IS NULL AND ${packageId("r")} = ? LIMIT 1`, agentId, id);
|
|
914
|
+
if (!kept)
|
|
915
|
+
await tx.run("DELETE FROM imported_templates WHERE id = ?", id);
|
|
916
|
+
}
|
|
917
|
+
// Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
|
|
918
|
+
await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
|
|
919
|
+
// Its purge time last, in the same write as its name and description.
|
|
920
|
+
await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
|
|
921
|
+
return true;
|
|
922
|
+
})),
|
|
869
923
|
};
|
|
870
924
|
this.templates = {
|
|
871
925
|
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
@@ -995,13 +1049,18 @@ class SqliteStore {
|
|
|
995
1049
|
if (!was)
|
|
996
1050
|
return undefined;
|
|
997
1051
|
const settled = change.status !== undefined && change.status !== "due";
|
|
998
|
-
// Out of due, a firing keeps no retry, wait, payload or attrs, nor the reason its last try gave
|
|
1052
|
+
// Out of due, a firing keeps no retry, wait, payload or attrs (unless keepAttrs), nor the reason its last try gave
|
|
1053
|
+
// (unless it gives one). One exception: a sent firing keeps its startBy in retry_at (firingOf reads it back as
|
|
1054
|
+
// startBy, never as a retry), so no migration adds a column for it. Each column is set once: Postgres refuses an
|
|
1055
|
+
// update that names one twice.
|
|
999
1056
|
const set = [];
|
|
1000
1057
|
if (change.status !== undefined)
|
|
1001
1058
|
set.push(["status", change.status]);
|
|
1002
1059
|
if (settled)
|
|
1003
|
-
set.push(["retry_at",
|
|
1004
|
-
|
|
1060
|
+
set.push(["retry_at", change.status === "sent" ? change.startBy ?? null : null], ["waits_on", null], ["payload", null], ["reason", change.reason ?? null], ["attempts", change.attempts ?? 0]);
|
|
1061
|
+
if (settled && !change.keepAttrs)
|
|
1062
|
+
set.push(["attrs", null]);
|
|
1063
|
+
if (!settled && change.reason !== undefined)
|
|
1005
1064
|
set.push(["reason", change.reason]);
|
|
1006
1065
|
if (change.runId !== undefined)
|
|
1007
1066
|
set.push(["run_id", change.runId]);
|
|
@@ -1080,15 +1139,17 @@ class SqliteStore {
|
|
|
1080
1139
|
WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
|
|
1081
1140
|
soonest: async () => (await db.get("SELECT MIN(next_at) AS at FROM triggers WHERE enabled = 1 AND next_at IS NOT NULL"))?.at ?? null,
|
|
1082
1141
|
activeRuns: async (triggerId) => (await db.get(`SELECT COUNT(*) AS n FROM trigger_firings f JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND f.status = 'started' AND r.state NOT IN (${FINAL})`, triggerId)).n,
|
|
1083
|
-
prune: async (triggerId, { history, dayMs, keepByKey, kept }) => db.transaction(async (tx) => {
|
|
1142
|
+
prune: async (triggerId, { history, dayMs, keepByKey, kept, now: clockNow }) => db.transaction(async (tx) => {
|
|
1084
1143
|
const at = now();
|
|
1085
1144
|
await d.lockRow(tx, "triggers", "id", triggerId);
|
|
1086
|
-
// Past the newest `history` shown firings: never a due one, a failure not yet told,
|
|
1087
|
-
//
|
|
1145
|
+
// Past the newest `history` shown firings: never a due one, a failure not yet told, a started one whose run has
|
|
1146
|
+
// not ended, or a sent one its host may still start (its startBy, in retry_at, not passed on the triggers'
|
|
1147
|
+
// clock). The rest leave the history: kept for their key's day when a sender's key names them, else gone.
|
|
1088
1148
|
const old = await tx.all(`SELECT f.key, f.by FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id
|
|
1089
1149
|
WHERE f.trigger_id = ? AND f.shown = 1 AND f.status != 'due' AND NOT (f.status = 'failed' AND (f.notified IS NULL OR f.notified = 0))
|
|
1090
1150
|
AND NOT (f.status = 'started' AND r.id IS NOT NULL AND r.state NOT IN (${FINAL}))
|
|
1091
|
-
AND
|
|
1151
|
+
AND NOT (f.status = 'sent' AND f.retry_at IS NOT NULL AND f.retry_at >= ?)
|
|
1152
|
+
AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, clockNow, triggerId, history);
|
|
1092
1153
|
for (const { key, by } of old) {
|
|
1093
1154
|
if (keepByKey(by ?? "manual"))
|
|
1094
1155
|
await tx.run("UPDATE trigger_firings SET shown = 0, payload = NULL, attrs = NULL WHERE trigger_id = ? AND key = ?", triggerId, key);
|
|
@@ -1124,7 +1185,16 @@ class SqliteStore {
|
|
|
1124
1185
|
},
|
|
1125
1186
|
fire: async (firing, run, { launch } = {}) => this.#queued(await db.transaction(async (tx) => {
|
|
1126
1187
|
const at = now();
|
|
1188
|
+
await checkSettingsGuards(tx, run.settingsGuards);
|
|
1189
|
+
// Match archive's agent -> trigger order. Preparation may have raced a trigger move; never start a run for
|
|
1190
|
+
// its former agent merely because that agent's admission guards still pass.
|
|
1191
|
+
await refuseDeleting(tx, run.agentId, run.expectedCurrent);
|
|
1127
1192
|
await d.lockRow(tx, "triggers", "id", firing.triggerId);
|
|
1193
|
+
const trigger = await tx.get("SELECT agent_id FROM triggers WHERE id = ?", firing.triggerId);
|
|
1194
|
+
if (!trigger)
|
|
1195
|
+
throw new StoreConstraint(`no trigger ${firing.triggerId}`);
|
|
1196
|
+
if (trigger.agent_id !== run.agentId)
|
|
1197
|
+
throw new StoreConstraint(`trigger ${firing.triggerId} no longer belongs to agent ${run.agentId}`);
|
|
1128
1198
|
// Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
|
|
1129
1199
|
await refuseArchived(tx, run.agentId);
|
|
1130
1200
|
const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, launchDiskOf(launch), at);
|
|
@@ -1143,7 +1213,7 @@ class SqliteStore {
|
|
|
1143
1213
|
})),
|
|
1144
1214
|
};
|
|
1145
1215
|
this.runs = {
|
|
1146
|
-
create: async ({ id, agentId, revisionId, origin, labels }, launch) => {
|
|
1216
|
+
create: async ({ id, agentId, revisionId, origin, labels, expectedCurrent, settingsGuards, startedAt }, launch) => {
|
|
1147
1217
|
// sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
|
|
1148
1218
|
const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, labels, disk, started_at) VALUES (?, ?, ?, 'queued', 0, ?, ?, ?) RETURNING ${RUN_COLUMNS}`;
|
|
1149
1219
|
const labelled = labelsColumn(labels);
|
|
@@ -1152,7 +1222,8 @@ class SqliteStore {
|
|
|
1152
1222
|
// deleted: its mark is read here, in the transaction that would start the run.
|
|
1153
1223
|
return this.#queued(await db.transaction(async (tx) => {
|
|
1154
1224
|
const at = now();
|
|
1155
|
-
await
|
|
1225
|
+
await checkSettingsGuards(tx, settingsGuards);
|
|
1226
|
+
await refuseDeleting(tx, agentId, expectedCurrent);
|
|
1156
1227
|
// A run made from another (a replay of its input, an audit's shadow) never of a purged one: its source's row
|
|
1157
1228
|
// held as its purge holds it, so either this commits first and the purge finds it (RunsMadeFromLeft), or the
|
|
1158
1229
|
// purge does and this reads its purge time.
|
|
@@ -1163,7 +1234,7 @@ class SqliteStore {
|
|
|
1163
1234
|
if (source && source.purged_at !== null)
|
|
1164
1235
|
throw new RunPurged(of, id);
|
|
1165
1236
|
}
|
|
1166
|
-
const row = await tx.get(insert, id, agentId, revisionId, labelled, launchDiskOf(launch), at);
|
|
1237
|
+
const row = await tx.get(insert, id, agentId, revisionId, labelled, launchDiskOf(launch), startedAt ?? at);
|
|
1167
1238
|
if (origin)
|
|
1168
1239
|
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
|
|
1169
1240
|
if (launch)
|
|
@@ -1211,6 +1282,7 @@ class SqliteStore {
|
|
|
1211
1282
|
},
|
|
1212
1283
|
launch: (runId) => readLaunch(db, runId),
|
|
1213
1284
|
usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
|
|
1285
|
+
projectCheckpoints: (filter) => readProjectCheckpoints(db, filter),
|
|
1214
1286
|
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
1215
1287
|
seededBefore: (agentId, at) => readSeededBefore(db, agentId, at),
|
|
1216
1288
|
list: async ({ agentId, revisionId, state, archived, labels, disk, limit, purged = false }) => {
|
|
@@ -1324,22 +1396,11 @@ class SqliteStore {
|
|
|
1324
1396
|
// itself (turnCostOf over each turn's data), which no column holds.
|
|
1325
1397
|
costUnknown: async ({ limit, after }) => {
|
|
1326
1398
|
const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
|
|
1327
|
-
const
|
|
1399
|
+
const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
|
|
1328
1400
|
AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
|
|
1329
|
-
AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText(
|
|
1330
|
-
AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${d.jsonText(
|
|
1401
|
+
AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText(readableJson(d, "run_launch.body"), ["native"])} IS NOT NULL))
|
|
1402
|
+
AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${d.jsonText(readableJson(d, "entry.record"), ["kind"])} = ?)
|
|
1331
1403
|
${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
|
|
1332
|
-
let rows;
|
|
1333
|
-
try {
|
|
1334
|
-
rows = await read((column) => column);
|
|
1335
|
-
}
|
|
1336
|
-
catch (error) {
|
|
1337
|
-
// A run's input or journal holding an escaped NUL or a lone surrogate makes Postgres refuse the read: read again
|
|
1338
|
-
// from copies with those escapes blanked (whether `native` is there, a record's kind), never a run's text.
|
|
1339
|
-
if (d.name !== "postgres" || !postgresUnicodeRefusal(error))
|
|
1340
|
-
throw error;
|
|
1341
|
-
rows = await read(postgresReadableJson);
|
|
1342
|
-
}
|
|
1343
1404
|
return rows.map((row) => row.id);
|
|
1344
1405
|
},
|
|
1345
1406
|
relist: async ({ flags, agentId }) => {
|
|
@@ -1373,62 +1434,47 @@ class SqliteStore {
|
|
|
1373
1434
|
.map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null, disk: row.disk ?? null })),
|
|
1374
1435
|
madeFrom: async (runId) => {
|
|
1375
1436
|
const learning = (await db.all("SELECT DISTINCT learning_run_id AS id FROM learning_proposals WHERE run_id = ? AND learning_run_id IS NOT NULL AND learning_run_id <> ?", runId, runId)).map((row) => row.id);
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1437
|
+
return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
|
|
1438
|
+
},
|
|
1439
|
+
purge: (runId, kept) => this.#purging(() => db.transaction(async (tx) => {
|
|
1440
|
+
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
|
|
1441
|
+
await d.lockRow(tx, "runs", "id", runId, "update");
|
|
1442
|
+
const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
|
|
1443
|
+
if (!run || run.purged_at !== null)
|
|
1444
|
+
return false;
|
|
1445
|
+
if (!FINAL_STATES.includes(run.state) || run.runner !== null)
|
|
1446
|
+
throw new StoreConstraint(`run ${runId} is ${run.state}${run.runner === null ? "" : ` under ${run.runner}'s claim`}: only a final run no runner holds is purged`);
|
|
1447
|
+
// A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
|
|
1448
|
+
// its input: each is purged first.
|
|
1449
|
+
const left = [];
|
|
1450
|
+
for (const id of await launchedFrom(tx, runId)) {
|
|
1451
|
+
if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
|
|
1452
|
+
left.push(id);
|
|
1379
1453
|
}
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1454
|
+
if (left.length)
|
|
1455
|
+
throw new RunsMadeFromLeft(runId, left);
|
|
1456
|
+
await dropRunContent(tx, runId);
|
|
1457
|
+
// What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
|
|
1458
|
+
// fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
|
|
1459
|
+
// trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
|
|
1460
|
+
await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
|
|
1461
|
+
await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
|
|
1462
|
+
await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
|
|
1463
|
+
await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
|
|
1464
|
+
// Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
|
|
1465
|
+
// state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
|
|
1466
|
+
for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
|
|
1467
|
+
const state = JSON.parse(row.proposal)?.state;
|
|
1468
|
+
await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
|
|
1386
1469
|
}
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
return false;
|
|
1396
|
-
if (!FINAL_STATES.includes(run.state) || run.runner !== null)
|
|
1397
|
-
throw new StoreConstraint(`run ${runId} is ${run.state}${run.runner === null ? "" : ` under ${run.runner}'s claim`}: only a final run no runner holds is purged`);
|
|
1398
|
-
// A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
|
|
1399
|
-
// its input: each is purged first.
|
|
1400
|
-
const left = [];
|
|
1401
|
-
for (const id of await launchedFrom(tx, runId, readableJson(d, "body"))) {
|
|
1402
|
-
if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
|
|
1403
|
-
left.push(id);
|
|
1404
|
-
}
|
|
1405
|
-
if (left.length)
|
|
1406
|
-
throw new RunsMadeFromLeft(runId, left);
|
|
1407
|
-
await dropRunContent(tx, runId);
|
|
1408
|
-
// What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
|
|
1409
|
-
// fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
|
|
1410
|
-
// trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
|
|
1411
|
-
await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
|
|
1412
|
-
await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
|
|
1413
|
-
await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
|
|
1414
|
-
await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
|
|
1415
|
-
// Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
|
|
1416
|
-
// state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
|
|
1417
|
-
for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
|
|
1418
|
-
const state = JSON.parse(row.proposal)?.state;
|
|
1419
|
-
await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
|
|
1420
|
-
}
|
|
1421
|
-
// Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
|
|
1422
|
-
// read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
|
|
1423
|
-
const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
|
|
1424
|
-
await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
|
|
1425
|
-
// Its listing, and its purge time last: no list shows it, and no lister builds it again.
|
|
1426
|
-
await tx.run("UPDATE runs SET listing = NULL, list_status = NULL, listing_mark = list_mark, listing_live = 0, listing_until = NULL, listing_flags = 0, purged_at = ? WHERE id = ?", now(), runId);
|
|
1427
|
-
return true;
|
|
1428
|
-
});
|
|
1429
|
-
if (purged)
|
|
1430
|
-
await this.#purged();
|
|
1431
|
-
},
|
|
1470
|
+
// Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
|
|
1471
|
+
// read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
|
|
1472
|
+
const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
|
|
1473
|
+
await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
|
|
1474
|
+
// Its listing, and its purge time last: no list shows it, and no lister builds it again.
|
|
1475
|
+
await tx.run("UPDATE runs SET listing = NULL, list_status = NULL, listing_mark = list_mark, listing_live = 0, listing_until = NULL, listing_flags = 0, purged_at = ? WHERE id = ?", now(), runId);
|
|
1476
|
+
return true;
|
|
1477
|
+
})),
|
|
1432
1478
|
remove: async (runId) => {
|
|
1433
1479
|
await db.transaction(async (tx) => {
|
|
1434
1480
|
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
|
|
@@ -1813,11 +1859,15 @@ class SqliteStore {
|
|
|
1813
1859
|
return row === undefined ? undefined : JSON.parse(row.value);
|
|
1814
1860
|
},
|
|
1815
1861
|
// `was` is compared as the JSON text put wrote: a row read and parsed gives the same text back, its keys in order.
|
|
1816
|
-
replaceIf: async (key, was, value, claim) => {
|
|
1862
|
+
replaceIf: async (key, was, value, claim, guards) => {
|
|
1817
1863
|
const encoded = json(value);
|
|
1818
|
-
if (claim)
|
|
1864
|
+
if (claim || guards !== undefined)
|
|
1819
1865
|
return db.transaction(async (tx) => {
|
|
1820
|
-
|
|
1866
|
+
// Include the destination in the same sorted lock set. Source revocation and a publication's pointer move
|
|
1867
|
+
// are ordered in one transaction; when also claimed, settings precede the run's claim lock.
|
|
1868
|
+
if (guards !== undefined)
|
|
1869
|
+
await checkSettingsGuards(tx, guards, undefined, [key]);
|
|
1870
|
+
const at = claim ? await underClaim(tx, claim, now) : now();
|
|
1821
1871
|
return await tx.runCounted("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", encoded, nativeCommandOwner(key, encoded), at, key, json(was)) === 1;
|
|
1822
1872
|
});
|
|
1823
1873
|
const [result] = await db.write([{ sql: "UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", params: [encoded, nativeCommandOwner(key, encoded), now(), key, json(was)] }]);
|
|
@@ -2060,6 +2110,7 @@ class SqliteStore {
|
|
|
2060
2110
|
list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
|
|
2061
2111
|
id: row.id, source: row.source, sha: row.sha, publisher: row.publisher, files: JSON.parse(row.files), importedAt: row.imported_at,
|
|
2062
2112
|
})),
|
|
2113
|
+
ids: async () => (await db.all("SELECT id FROM imported_templates ORDER BY id")).map((row) => row.id),
|
|
2063
2114
|
put: async ({ id, source, sha, publisher, files }) => {
|
|
2064
2115
|
await db.write([{
|
|
2065
2116
|
sql: "INSERT INTO imported_templates (id, source, sha, publisher, files, imported_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET source = excluded.source, sha = excluded.sha, publisher = excluded.publisher, files = excluded.files, imported_at = excluded.imported_at",
|
|
@@ -2260,41 +2311,52 @@ class SqliteStore {
|
|
|
2260
2311
|
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
2261
2312
|
};
|
|
2262
2313
|
}
|
|
2263
|
-
/**
|
|
2264
|
-
*
|
|
2265
|
-
* in the
|
|
2266
|
-
*
|
|
2267
|
-
* the log
|
|
2268
|
-
*
|
|
2269
|
-
*
|
|
2270
|
-
*
|
|
2271
|
-
*
|
|
2272
|
-
*
|
|
2273
|
-
|
|
2314
|
+
/** A purge (runs.purge, agents.purge, `work` its transaction, true when it purged), on a SQLite store with a file:
|
|
2315
|
+
* secureRewrite's marker first, then the purge, then a WAL checkpoint (TRUNCATE). secure_delete (worker.ts open) zeroes
|
|
2316
|
+
* the purged bytes in the pages the purge writes, but those pages are new frames in the WAL: the file keeps its earlier
|
|
2317
|
+
* images of them, and the WAL its earlier frames, until a checkpoint copies the zeroed pages into the file and truncates
|
|
2318
|
+
* the log. The marker is written before any byte changes, as secureRewrite's is: one that cannot be written (a full
|
|
2319
|
+
* disk) throws with nothing purged, so the client's retry purges whole; a server that dies past it leaves it, and its
|
|
2320
|
+
* next start's scrub truncates the log. A reader in another connection (a runner's read, a backup) may hold the log
|
|
2321
|
+
* back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy wait, since every request of
|
|
2322
|
+
* the store's one connection queues behind it. One it held back (or that failed) keeps the marker for the next start.
|
|
2323
|
+
* The marker goes once no file keeps what the purge changed (the log truncated, or nothing committed: a purge refused or
|
|
2324
|
+
* failed rolled back), under secureRewrite's own rule: only one that was not there before this purge wrote it (a
|
|
2325
|
+
* rewrite's or an earlier start's needs that start's VACUUM), and that no other writer wrote since (#scrubMarks). */
|
|
2326
|
+
async #purging(work) {
|
|
2274
2327
|
const marker = this.#scrubMarker;
|
|
2275
2328
|
const db = this.#db;
|
|
2276
2329
|
if (marker === undefined || !(db instanceof Connection))
|
|
2277
|
-
return;
|
|
2278
|
-
const
|
|
2279
|
-
|
|
2280
|
-
return;
|
|
2281
|
-
this.#purgeMarks++;
|
|
2330
|
+
return void (await work());
|
|
2331
|
+
const pending = existsSync(marker);
|
|
2332
|
+
const mine = ++this.#scrubMarks;
|
|
2282
2333
|
try {
|
|
2283
2334
|
markScrub(marker);
|
|
2284
2335
|
}
|
|
2285
2336
|
catch (error) {
|
|
2286
|
-
throw new Error(`The purge
|
|
2337
|
+
throw new Error(`The purge's scrub marker could not be written (${error.message}): nothing was purged.`, { cause: error });
|
|
2287
2338
|
}
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2339
|
+
const done = () => {
|
|
2340
|
+
if (pending || this.#scrubMarks !== mine)
|
|
2341
|
+
return;
|
|
2342
|
+
try {
|
|
2343
|
+
rmSync(marker, { force: true });
|
|
2344
|
+
}
|
|
2345
|
+
catch {
|
|
2346
|
+
// Left for the next start's scrub, which costs it a VACUUM: never a failure of a purge that committed.
|
|
2347
|
+
}
|
|
2348
|
+
};
|
|
2349
|
+
let purged;
|
|
2350
|
+
try {
|
|
2351
|
+
purged = await work();
|
|
2352
|
+
}
|
|
2353
|
+
catch (error) {
|
|
2354
|
+
done();
|
|
2355
|
+
throw error;
|
|
2356
|
+
}
|
|
2357
|
+
if (purged && (await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS).catch(() => undefined))?.busy !== 0)
|
|
2292
2358
|
return;
|
|
2293
|
-
|
|
2294
|
-
// unless a checkpoint asked after this truncates the log.
|
|
2295
|
-
if (existsSync(marker))
|
|
2296
|
-
return void this.#purgeMarks++;
|
|
2297
|
-
await this.#purged();
|
|
2359
|
+
done();
|
|
2298
2360
|
}
|
|
2299
2361
|
async secureRewrite(work, options = {}) {
|
|
2300
2362
|
const marker = this.#scrubMarker;
|
|
@@ -2304,13 +2366,13 @@ class SqliteStore {
|
|
|
2304
2366
|
// Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
|
|
2305
2367
|
// leaves it, and its next start scrubs though no row is left in the clear.
|
|
2306
2368
|
const pending = existsSync(marker);
|
|
2307
|
-
const
|
|
2369
|
+
const mine = ++this.#scrubMarks;
|
|
2308
2370
|
markScrub(marker);
|
|
2309
2371
|
// secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
|
|
2310
2372
|
const rewritten = await work();
|
|
2311
|
-
// Nothing rewritten, and the marker is this call's alone: no purge
|
|
2312
|
-
// did needs the checkpoint below, or the next start's scrub.
|
|
2313
|
-
if (rewritten === 0 && !pending && this.#
|
|
2373
|
+
// Nothing rewritten, and the marker is this call's alone: no purge or other rewrite wrote it while the work ran
|
|
2374
|
+
// (#scrubMarks). One that did needs the checkpoint below, or the next start's scrub.
|
|
2375
|
+
if (rewritten === 0 && !pending && this.#scrubMarks === mine) {
|
|
2314
2376
|
rmSync(marker, { force: true });
|
|
2315
2377
|
return { rewritten };
|
|
2316
2378
|
}
|
|
@@ -2328,12 +2390,12 @@ class SqliteStore {
|
|
|
2328
2390
|
await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
|
|
2329
2391
|
await this.#db.all("VACUUM");
|
|
2330
2392
|
});
|
|
2331
|
-
const
|
|
2393
|
+
const marksBefore = this.#scrubMarks;
|
|
2332
2394
|
const checkpoint = await db.checkpoint();
|
|
2333
2395
|
// A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
|
|
2334
|
-
// checkpoint is done, so the marker stays. So does one a purge
|
|
2335
|
-
// be past it.
|
|
2336
|
-
if (checkpoint?.busy !== 0 || this.#
|
|
2396
|
+
// checkpoint is done, so the marker stays. So does one a purge or another rewrite wrote after this checkpoint was
|
|
2397
|
+
// asked: its frames may be past it.
|
|
2398
|
+
if (checkpoint?.busy !== 0 || this.#scrubMarks !== marksBefore)
|
|
2337
2399
|
return { rewritten, left: "busy" };
|
|
2338
2400
|
}
|
|
2339
2401
|
catch (error) {
|
|
@@ -2604,15 +2666,7 @@ class SqliteStore {
|
|
|
2604
2666
|
const at = this.#now();
|
|
2605
2667
|
const state = run.state ?? "ended";
|
|
2606
2668
|
return this.#db.transaction(async (tx) => {
|
|
2607
|
-
|
|
2608
|
-
// A no-op update takes the row's write lock on both SQLite and Postgres until the import commits. A source
|
|
2609
|
-
// revoke/disconnect either commits first and refuses this write, or waits for this already-started import.
|
|
2610
|
-
const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", guard.key);
|
|
2611
|
-
const value = setting === undefined ? undefined : JSON.parse(setting.value);
|
|
2612
|
-
if (!value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected))) {
|
|
2613
|
-
throw new StoreConstraint("The source import grant changed before the history write committed.");
|
|
2614
|
-
}
|
|
2615
|
-
}
|
|
2669
|
+
await checkSettingsGuards(tx, run.settingsGuards, "The source import grant changed before the history write committed.");
|
|
2616
2670
|
if (run.requireActiveAgent) {
|
|
2617
2671
|
// Archive updates this same row. It either commits first and refuses this import, or waits for this
|
|
2618
2672
|
// already-admitted history transaction; a read outside the transaction cannot establish that order.
|