@parcha/agentrun-serve 0.1.0-beta.47 → 0.1.0-beta.49
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 +68 -1
- package/README.md +218 -20
- package/dist/acp-package.d.ts +24 -6
- package/dist/adapter-facts.d.ts +0 -4
- package/dist/adapter-facts.js +1 -4
- package/dist/adapters.d.ts +3 -12
- package/dist/adapters.js +1 -70
- package/dist/agent-delete.d.ts +33 -10
- package/dist/agent-delete.js +184 -26
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +18 -5
- package/dist/agents.d.ts +8 -1
- package/dist/agents.js +14 -4
- package/dist/answer-json.d.ts +10 -0
- package/dist/answer-json.js +23 -0
- package/dist/api-only.d.ts +5 -2
- package/dist/api-only.js +10 -2
- package/dist/archil-routes.d.ts +1 -1
- package/dist/archil-routes.js +4 -3
- package/dist/browser-live.d.ts +9 -4
- package/dist/browser-live.js +18 -5
- package/dist/browser-sessions.d.ts +56 -0
- package/dist/browser-sessions.js +117 -0
- package/dist/cap.js +7 -9
- package/dist/cli.js +6 -6
- package/dist/computer-routes.d.ts +6 -14
- package/dist/computer-routes.js +8 -10
- package/dist/computers.d.ts +6 -2
- package/dist/computers.js +4 -2
- package/dist/conformance.d.ts +4 -0
- package/dist/conformance.js +6 -0
- package/dist/console/assets/index-Bzn4eUYF.js +715 -0
- package/dist/console/assets/index-CR2ZGei1.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +15 -5
- package/dist/harness-check.d.ts +3 -1
- package/dist/harness-check.js +99 -70
- package/dist/harness-cursor.d.ts +10 -27
- package/dist/harness-cursor.js +5 -84
- package/dist/harness-goose.d.ts +4 -29
- package/dist/harness-goose.js +6 -86
- package/dist/harness-module.d.ts +4 -0
- package/dist/harness-module.js +1 -0
- package/dist/harness-owned.d.ts +52 -0
- package/dist/harness-owned.js +92 -0
- package/dist/harness-recipe.js +2 -24
- package/dist/harness-table.d.ts +109 -6
- package/dist/harness-table.js +242 -28
- package/dist/harness.js +2 -2
- package/dist/import.js +4 -3
- package/dist/key-refusal.d.ts +2 -1
- package/dist/key-refusal.js +18 -2
- package/dist/learn/check.d.ts +11 -2
- package/dist/learn/check.js +12 -9
- package/dist/learn/promote.d.ts +18 -1
- package/dist/learn/promote.js +47 -0
- package/dist/learn/repick.d.ts +34 -0
- package/dist/learn/repick.js +201 -0
- package/dist/learn/secrets.d.ts +4 -0
- package/dist/learn/secrets.js +23 -0
- package/dist/learned-workflow.d.ts +2 -0
- package/dist/learned-workflow.js +18 -1
- package/dist/learning-model.d.ts +18 -0
- package/dist/learning-model.js +77 -0
- package/dist/learning-setting.d.ts +13 -0
- package/dist/learning-setting.js +23 -1
- package/dist/llms.txt +1 -0
- package/dist/model-form.js +12 -12
- package/dist/model.d.ts +5 -4
- package/dist/model.js +19 -13
- package/dist/openapi.js +203 -15
- package/dist/page.d.ts +1 -0
- package/dist/page.js +1 -1
- package/dist/paid-calls.d.ts +4 -1
- package/dist/paid-calls.js +1 -1
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-secrets.d.ts +2 -2
- package/dist/run-secrets.js +6 -5
- package/dist/run-trace.js +6 -3
- package/dist/run-usage.d.ts +110 -0
- package/dist/run-usage.js +312 -0
- package/dist/runner/adapter-loop.d.ts +4 -1
- package/dist/runner/adapter-loop.js +52 -22
- package/dist/runner/adapter-run-spec.d.ts +3 -2
- package/dist/runner/adapter-run-spec.js +8 -4
- package/dist/runner/adapters/index.d.ts +4 -2
- package/dist/runner/adapters/index.js +6 -42
- package/dist/runner/cli-run-spec.js +10 -6
- package/dist/runner/conformance/harness.d.ts +2 -0
- package/dist/runner/conformance/harness.js +18 -4
- package/dist/runner/conformance/host-tools.d.ts +4 -0
- package/dist/runner/conformance/host-tools.js +14 -0
- package/dist/runner/feedback-round.d.ts +29 -1
- package/dist/runner/feedback-round.js +54 -3
- package/dist/runner/journal-kinds.d.ts +3 -1
- package/dist/runner/learning-end.js +49 -18
- package/dist/runner/loop-contract.d.ts +3 -0
- package/dist/runner/meta-tools.js +4 -2
- package/dist/runner/monid-run.js +2 -2
- package/dist/runner/presence.d.ts +3 -0
- package/dist/runner/presence.js +19 -12
- package/dist/runner/promotion.d.ts +62 -4
- package/dist/runner/promotion.js +154 -17
- package/dist/runner/reflect-hook.js +3 -2
- package/dist/runner/sdk-loop.js +25 -1
- package/dist/runner/workflow-spec.js +3 -2
- package/dist/runs-over-store.d.ts +5 -3
- package/dist/runs-over-store.js +11 -11
- package/dist/sdk/check.d.ts +31 -0
- package/dist/sdk/check.js +58 -0
- package/dist/sdk/runs.d.ts +10 -2
- package/dist/sdk/runs.js +87 -17
- package/dist/sdk/schema.js +11 -3
- package/dist/server.d.ts +6 -3
- package/dist/server.js +297 -98
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/open.d.ts +1 -1
- package/dist/store/open.js +1 -1
- package/dist/store/postgres/migrations/0021_purged.sql +13 -0
- package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
- package/dist/store/schema.d.ts +15 -1
- package/dist/store/schema.js +50 -5
- package/dist/store/sqlite/connection.d.ts +4 -1
- package/dist/store/sqlite/connection.js +5 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -3
- package/dist/store/sqlite/run-patch.js +15 -7
- package/dist/store/sqlite/store.d.ts +5 -2
- package/dist/store/sqlite/store.js +283 -77
- package/dist/store/sqlite/worker.d.ts +9 -0
- package/dist/store/sqlite/worker.js +18 -1
- package/dist/store/store.d.ts +162 -27
- package/dist/store/store.js +63 -0
- package/dist/store-reads/analytics.js +2 -1
- package/dist/store-reads/cap.d.ts +8 -2
- package/dist/store-reads/cap.js +27 -3
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/learning.js +5 -2
- package/dist/store-reads/runs.js +2 -0
- package/dist/store-reads/stats.js +4 -2
- package/dist/store-view.d.ts +12 -3
- package/dist/store-view.js +70 -27
- package/dist/template-eval.js +5 -2
- package/dist/template-github-permissions.d.ts +5 -1
- package/dist/template-github-permissions.js +7 -3
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +8 -0
- package/dist/timeline/timeline.js +18 -6
- package/dist/tool-gate.d.ts +8 -4
- package/dist/tool-gate.js +6 -7
- package/dist/tool-plane.d.ts +4 -0
- package/dist/tool-plane.js +10 -10
- package/dist/tools.js +9 -0
- package/dist/trigger-targets.d.ts +14 -2
- package/dist/trigger-targets.js +73 -4
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +5 -2
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +18 -4
- package/dist/viewer-credential.d.ts +24 -0
- package/dist/viewer-credential.js +53 -0
- package/dist/workspace/computer-for-claim.d.ts +5 -1
- package/dist/workspace/computer-for-claim.js +47 -18
- package/dist/workspace/computer-intervals.d.ts +20 -0
- package/dist/workspace/computer-intervals.js +49 -0
- package/dist/workspace/computer-janitor.d.ts +7 -3
- package/dist/workspace/computer-janitor.js +14 -6
- package/dist/workspace/computer-kept.d.ts +7 -2
- package/dist/workspace/computer-kept.js +9 -2
- package/dist/workspace/resolve-computer.d.ts +9 -1
- package/dist/workspace/resolve-computer.js +29 -22
- package/dist/workspace/run-end-computers.d.ts +1 -0
- package/dist/workspace/run-end-computers.js +4 -1
- package/package.json +18 -10
- package/templates/code-review/agent.md +2 -3
- package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
- package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
- package/templates/code-review/evals/other-repo/case.yaml +0 -1
- package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
- package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
- package/dist/console/assets/index-BBFzAxLB.js +0 -715
- package/dist/console/assets/index-BRi-Rgq6.css +0 -1
|
@@ -11,8 +11,18 @@ 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 {
|
|
15
|
-
import {
|
|
14
|
+
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
15
|
+
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_RUN, DDL, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNNERS, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
|
+
import { AgentArchived, AgentDeleting, 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";
|
|
17
|
+
/** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
|
|
18
|
+
const madeOf = (body) => {
|
|
19
|
+
for (const link of ["replay", "audit"]) {
|
|
20
|
+
const of = body?.[link]?.of;
|
|
21
|
+
if (typeof of === "string")
|
|
22
|
+
return of;
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
};
|
|
16
26
|
/** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
|
|
17
27
|
const seqOf = (cursor) => {
|
|
18
28
|
if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
|
|
@@ -67,11 +77,14 @@ function triggerSet(patch, at) {
|
|
|
67
77
|
pairs.push(["updated_at", at]);
|
|
68
78
|
return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
|
|
69
79
|
}
|
|
70
|
-
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
|
|
80
|
+
const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref, purged_at";
|
|
71
81
|
const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
|
|
72
82
|
const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
|
|
73
83
|
const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at, template_id";
|
|
74
84
|
const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
|
|
85
|
+
/** An ended run, not imported, whose stored cost is unknown: null with no bound beside it (cost_upper_bound 0, never NULL).
|
|
86
|
+
* What Runs.healCost writes over and Runs.costUnknown lists. */
|
|
87
|
+
const COST_UNKNOWN = `cost_usd IS NULL AND cost_upper_bound = 0 AND state IN (${FINAL}) AND imported_from IS NULL AND ended_at IS NOT NULL`;
|
|
75
88
|
/** Taken (Dialect.lockKey) by every insert of a run's command row, before it: the run's rows commit in id order, as
|
|
76
89
|
* SQLite's one writer commits them. On Postgres an id is taken at the insert and the row is seen at its commit, so two
|
|
77
90
|
* inserts at once could commit out of order, and a reader of the rows past the last id it handed on (the runner) would
|
|
@@ -107,7 +120,7 @@ async function underClaim(tx, claim, now) {
|
|
|
107
120
|
throw new Fenced(claim.runId, claim.epoch);
|
|
108
121
|
return at;
|
|
109
122
|
}
|
|
110
|
-
const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref });
|
|
123
|
+
const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref, purgedAt: r.purged_at ?? null });
|
|
111
124
|
const revisionOf = (r) => ({
|
|
112
125
|
id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
|
|
113
126
|
note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
|
|
@@ -155,6 +168,11 @@ const mcpServerOf = (r, at = Number(r.read_at)) => ({
|
|
|
155
168
|
const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.mcp_pin), pinnedAt: Number(r.created_at) });
|
|
156
169
|
const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
|
|
157
170
|
const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
|
|
171
|
+
const orNull = (value) => (value === null ? null : Number(value));
|
|
172
|
+
const intervalOf = (r) => ({
|
|
173
|
+
runId: r.run_id, provider: r.provider, providerId: r.provider_id, kind: r.kind, gpuType: r.gpu_type, gpuCount: orNull(r.gpu_count), cpus: orNull(r.cpus),
|
|
174
|
+
memoryMb: orNull(r.memory_mb), startedAt: Number(r.started_at), kept: Number(r.kept) === 1, endedAt: orNull(r.ended_at),
|
|
175
|
+
});
|
|
158
176
|
const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
|
|
159
177
|
const pairedOf = (r) => ({ id: r.id, name: r.name, hello: JSON.parse(r.hello), driver: r.driver, labels: JSON.parse(r.labels), pairingId: r.pairing_id, createdAt: r.created_at, seenAt: r.seen_at, revokedAt: r.revoked_at });
|
|
160
178
|
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 });
|
|
@@ -303,8 +321,9 @@ export async function openSqliteStore(options) {
|
|
|
303
321
|
// Version 11 (0.1.0-beta.44 and before) keeps no listing on a run's row: the server adds it (schema.ts listingUpgrade)
|
|
304
322
|
// in one durable write once the columns an earlier build of 11 lacked are in, every run behind until its lister builds
|
|
305
323
|
// 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).
|
|
307
|
-
|
|
324
|
+
// (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
|
|
325
|
+
// purgeUpgrade). A runner refuses 11, 12 and 13 until that server has.
|
|
326
|
+
const upgrading = found === 11 || found === 12 || found === 13;
|
|
308
327
|
if (upgrading && role === "runner")
|
|
309
328
|
throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
|
|
310
329
|
if (found !== SCHEMA_VERSION && !upgrading)
|
|
@@ -374,24 +393,31 @@ export async function openSqliteStore(options) {
|
|
|
374
393
|
// dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
|
|
375
394
|
{ sql: "DROP TABLE IF EXISTS runner_relays" },
|
|
376
395
|
{ sql: RUNNERS },
|
|
396
|
+
// Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
|
|
397
|
+
{ sql: COMPUTER_INTERVALS },
|
|
398
|
+
{ sql: COMPUTER_INTERVALS_RUN },
|
|
377
399
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
378
400
|
], { full: true });
|
|
379
401
|
await backfillNativeCommandOwners(connection);
|
|
380
|
-
if (found ===
|
|
402
|
+
if (found === 11) {
|
|
381
403
|
const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
|
|
382
404
|
await connection.write(listingUpgrade(present).map((sql) => ({ sql })), { full: true });
|
|
383
405
|
}
|
|
384
|
-
if (
|
|
406
|
+
if (found === 11 || found === 12) {
|
|
385
407
|
const minted = new Set((await connection.all("SELECT name FROM pragma_table_info('minted_tokens')")).map((column) => column.name));
|
|
386
408
|
await connection.write(relayUpgrade(minted).map((sql) => ({ sql })), { full: true });
|
|
387
409
|
}
|
|
410
|
+
if (upgrading) {
|
|
411
|
+
const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
|
|
412
|
+
await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
|
|
413
|
+
}
|
|
388
414
|
}
|
|
389
415
|
}
|
|
390
416
|
catch (error) {
|
|
391
417
|
await connection.close().catch(() => undefined);
|
|
392
418
|
throw error;
|
|
393
419
|
}
|
|
394
|
-
return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
|
|
420
|
+
return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file, options.warn);
|
|
395
421
|
}
|
|
396
422
|
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
397
423
|
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
@@ -451,10 +477,18 @@ function readOnly(tx) {
|
|
|
451
477
|
}
|
|
452
478
|
/** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
|
|
453
479
|
* clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
|
|
454
|
-
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX)
|
|
455
|
-
|
|
456
|
-
|
|
480
|
+
* `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX), and whose WAL a
|
|
481
|
+
* purge checkpoints. `warn`: told when that checkpoint could not empty the WAL (stderr by default). */
|
|
482
|
+
export function storeOver(connection, now, file, warn = stderrWarn) {
|
|
483
|
+
return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`, warn);
|
|
457
484
|
}
|
|
485
|
+
const stderrWarn = (message) => void process.stderr.write(`agentrun-serve: ${message}\n`);
|
|
486
|
+
/** How long a purge's checkpoint waits, once SQLite's busy wait ran out on another connection's reader or writer, before
|
|
487
|
+
* its one retry. */
|
|
488
|
+
const PURGE_CHECKPOINT_RETRY_MS = 200;
|
|
489
|
+
/** How long a purge's checkpoint waits for another connection's reader or writer before it gives up (and is retried):
|
|
490
|
+
* short, since every other request of the store's connection queues behind it. */
|
|
491
|
+
const PURGE_CHECKPOINT_BUSY_MS = 20;
|
|
458
492
|
/** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
|
|
459
493
|
* file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
|
|
460
494
|
const SCRUB_SUFFIX = ".scrub";
|
|
@@ -492,6 +526,7 @@ class SqliteStore {
|
|
|
492
526
|
settings;
|
|
493
527
|
sealedKeys;
|
|
494
528
|
computerLedger;
|
|
529
|
+
computerIntervals;
|
|
495
530
|
pairedComputers;
|
|
496
531
|
mintedTokens;
|
|
497
532
|
runners;
|
|
@@ -519,9 +554,12 @@ class SqliteStore {
|
|
|
519
554
|
#released = new Map();
|
|
520
555
|
/** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
|
|
521
556
|
#scrubMarker;
|
|
522
|
-
|
|
557
|
+
/** Told what a person should know that no caller is answered (a purge's checkpoint that left the WAL as it was). */
|
|
558
|
+
#warn;
|
|
559
|
+
constructor(db, now, origin, scrubMarker, warn = stderrWarn) {
|
|
523
560
|
this.#db = db;
|
|
524
561
|
this.#scrubMarker = scrubMarker;
|
|
562
|
+
this.#warn = warn;
|
|
525
563
|
this.#now = now;
|
|
526
564
|
this.origin = origin ?? this;
|
|
527
565
|
this.where = db.where;
|
|
@@ -529,13 +567,22 @@ class SqliteStore {
|
|
|
529
567
|
const clock = () => storeNow(d, now);
|
|
530
568
|
this.#clock = clock;
|
|
531
569
|
const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
|
|
570
|
+
/** Agent `agentId`'s row, held (a writer's row lock, as its purge takes it), or undefined when there is none; refused
|
|
571
|
+
* (AgentPurged) once it is purged: a write that waited on the purge's lock reads its purge time, and one that took the
|
|
572
|
+
* lock first commits before the purge reads anything. */
|
|
573
|
+
const heldAgent = async (tx, agentId) => {
|
|
574
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
575
|
+
const agent = await tx.get("SELECT current_revision, archived_at, external_ref, purged_at FROM agents WHERE id = ?", agentId);
|
|
576
|
+
if (agent && agent.purged_at != null)
|
|
577
|
+
throw new AgentPurged(agentId, agent.archived_at, agent.purged_at);
|
|
578
|
+
return agent;
|
|
579
|
+
};
|
|
532
580
|
const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
|
|
533
581
|
// The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
|
|
534
582
|
// (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
|
|
535
583
|
// revisions added at once, by this server or another on the same store, never both name the same parent, and
|
|
536
|
-
// `ifCurrent` is compared with what no other writer can move until this commits.
|
|
537
|
-
await
|
|
538
|
-
const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
|
|
584
|
+
// `ifCurrent` is compared with what no other writer can move until this commits. Never one of a purged agent.
|
|
585
|
+
const agent = await heldAgent(tx, agentId);
|
|
539
586
|
if (!agent)
|
|
540
587
|
throw new StoreConstraint(`no agent ${agentId}`);
|
|
541
588
|
if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
|
|
@@ -557,13 +604,16 @@ class SqliteStore {
|
|
|
557
604
|
/** Refused (AgentDeleting) when agent `agentId` is being deleted: another system's agent with an archive time, which
|
|
558
605
|
* only its delete writes (AgentDeleting). The agent's row is held first (a writer's row lock, as the archive's UPDATE
|
|
559
606
|
* takes it), so on Postgres a delete's archive that commits first is read here, and one that commits after waits for
|
|
560
|
-
* this run to be in the store, where the delete's listing of the agent's runs finds it.
|
|
607
|
+
* 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
|
|
608
|
+
* (AgentPurged): it takes no run and no trigger. */
|
|
561
609
|
const refuseDeleting = async (tx, agentId) => {
|
|
562
|
-
await
|
|
563
|
-
const agent = await tx.get("SELECT archived_at, external_ref FROM agents WHERE id = ?", agentId);
|
|
610
|
+
const agent = await heldAgent(tx, agentId);
|
|
564
611
|
if (agent?.archived_at != null && agent.external_ref != null)
|
|
565
612
|
throw new AgentDeleting(agentId);
|
|
566
613
|
};
|
|
614
|
+
/** The runs whose launch is made from run `runId` (madeOf: a replay of its input, an audit's shadow), by id. Every
|
|
615
|
+
* launch is read (no index names its source): a purge's read, never a hot path. */
|
|
616
|
+
const launchedFrom = async (ex, runId) => (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);
|
|
567
617
|
/** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
|
|
568
618
|
* while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
|
|
569
619
|
* distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
|
|
@@ -591,7 +641,11 @@ class SqliteStore {
|
|
|
591
641
|
const handedAnyIn = (tx) => tx.get(`SELECT id FROM runs WHERE state = 'running' AND sign_in_handed IS NOT NULL AND ${d.jsonArrayLength("sign_in_handed")} > 0 LIMIT 1`);
|
|
592
642
|
this.agents = {
|
|
593
643
|
put: async ({ id, name, description = null }) => {
|
|
594
|
-
await db.
|
|
644
|
+
await db.transaction(async (tx) => {
|
|
645
|
+
// Never a purged agent's name or description written back.
|
|
646
|
+
await heldAgent(tx, id);
|
|
647
|
+
await tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", id, name, description, now());
|
|
648
|
+
});
|
|
595
649
|
},
|
|
596
650
|
create: async (agent, firstRevision) => {
|
|
597
651
|
await db.transaction(async (tx) => {
|
|
@@ -613,9 +667,11 @@ class SqliteStore {
|
|
|
613
667
|
const row = await db.get(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? AND external_version = ?`, agentId, version);
|
|
614
668
|
return row && revisionOf(row);
|
|
615
669
|
},
|
|
616
|
-
list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
|
|
670
|
+
list: async ({ archived = false, purged = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"}${purged ? "" : " AND purged_at IS NULL"} ORDER BY created_at, id`)).map(agentOf),
|
|
617
671
|
archive: async (id, archived, why) => db.transaction(async (tx) => {
|
|
618
672
|
const at = now();
|
|
673
|
+
// A purged agent stays as its purge left it: archived, never unarchived.
|
|
674
|
+
await heldAgent(tx, id);
|
|
619
675
|
await tx.run("UPDATE agents SET archived_at = ? WHERE id = ?", archived ? at : null, id);
|
|
620
676
|
if (!archived)
|
|
621
677
|
return [];
|
|
@@ -634,7 +690,11 @@ class SqliteStore {
|
|
|
634
690
|
});
|
|
635
691
|
},
|
|
636
692
|
setCurrent: async (agentId, revisionId) => {
|
|
637
|
-
const changed = await db.transaction((tx) =>
|
|
693
|
+
const changed = await db.transaction(async (tx) => {
|
|
694
|
+
// Never a purged agent's: its current revision stays the one its runs' tombstones read.
|
|
695
|
+
await heldAgent(tx, agentId);
|
|
696
|
+
return tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId);
|
|
697
|
+
});
|
|
638
698
|
if (changed === 0)
|
|
639
699
|
throw new StoreConstraint(`${revisionId} is not a revision of agent ${agentId}`);
|
|
640
700
|
},
|
|
@@ -644,9 +704,16 @@ class SqliteStore {
|
|
|
644
704
|
},
|
|
645
705
|
revisions: async (agentId) => (await db.all(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? ORDER BY created_at, id`, agentId)).map(revisionOf),
|
|
646
706
|
// Written only while the revision has none (the one place a revision changes after its save), then read back in the
|
|
647
|
-
// same transaction: the pin that stood, this one or another first run's.
|
|
707
|
+
// same transaction: the pin that stood, this one or another first run's. Never on a purged agent's revision (its purge
|
|
708
|
+
// cleared every pin): its agent's row held first, as the purge holds it, and none written once it is purged.
|
|
648
709
|
pinOnce: async (revisionId, pin) => {
|
|
649
710
|
const row = await db.transaction(async (tx) => {
|
|
711
|
+
const of = await tx.get("SELECT agent_id FROM revisions WHERE id = ?", revisionId);
|
|
712
|
+
if (!of)
|
|
713
|
+
return undefined;
|
|
714
|
+
await d.lockRow(tx, "agents", "id", of.agent_id);
|
|
715
|
+
if ((await tx.get("SELECT purged_at FROM agents WHERE id = ?", of.agent_id))?.purged_at != null)
|
|
716
|
+
return undefined;
|
|
650
717
|
await tx.run("UPDATE revisions SET mcp_pin = ? WHERE id = ? AND mcp_pin IS NULL", pinText(pin), revisionId);
|
|
651
718
|
return tx.get("SELECT mcp_pin FROM revisions WHERE id = ?", revisionId);
|
|
652
719
|
});
|
|
@@ -675,6 +742,33 @@ class SqliteStore {
|
|
|
675
742
|
await tx.run("DELETE FROM agents WHERE id = ?", agentId);
|
|
676
743
|
});
|
|
677
744
|
},
|
|
745
|
+
purge: async (agentId) => {
|
|
746
|
+
const purged = await db.transaction(async (tx) => {
|
|
747
|
+
await d.lockRow(tx, "agents", "id", agentId);
|
|
748
|
+
const agent = await tx.get("SELECT purged_at FROM agents WHERE id = ?", agentId);
|
|
749
|
+
if (!agent || agent.purged_at !== null)
|
|
750
|
+
return false;
|
|
751
|
+
// Each run a tombstone first (Runs.purge): a run started past the delete's listing keeps the agent for the next one.
|
|
752
|
+
const left = await tx.get("SELECT id FROM runs WHERE agent_id = ? AND purged_at IS NULL LIMIT 1", agentId);
|
|
753
|
+
if (left)
|
|
754
|
+
throw new StoreConstraint(`agent ${agentId} still has run ${left.id} not purged: each is purged first (runs.purge)`);
|
|
755
|
+
const triggersLeft = await tx.all("SELECT id FROM triggers WHERE agent_id = ? ORDER BY id", agentId);
|
|
756
|
+
if (triggersLeft.length)
|
|
757
|
+
throw new TriggersLeft(agentId, triggersLeft.map((one) => one.id));
|
|
758
|
+
await tx.run("DELETE FROM learning WHERE agent_id = ?", agentId);
|
|
759
|
+
await tx.run("DELETE FROM sign_ins WHERE agent_id = ?", agentId);
|
|
760
|
+
await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ?", agentId);
|
|
761
|
+
// The answer a template apply kept under its key, which holds the agent as it was made.
|
|
762
|
+
await tx.run(`DELETE FROM idempotency WHERE scope = 'templates.apply' AND ${d.jsonText("response", ["agentId"])} = ?`, agentId);
|
|
763
|
+
// Each revision's content; its id, kind, parent and time stay, which its runs' tombstones name.
|
|
764
|
+
await tx.run("UPDATE revisions SET body = '{}', skills = NULL, package = NULL, note = NULL, mcp_pin = NULL, monid_pin = NULL WHERE agent_id = ?", agentId);
|
|
765
|
+
// Its purge time last, in the same write as its name and description.
|
|
766
|
+
await tx.run("UPDATE agents SET name = '', description = NULL, purged_at = ? WHERE id = ?", now(), agentId);
|
|
767
|
+
return true;
|
|
768
|
+
});
|
|
769
|
+
if (purged)
|
|
770
|
+
await this.#purged(`agent ${agentId}`);
|
|
771
|
+
},
|
|
678
772
|
};
|
|
679
773
|
this.templates = {
|
|
680
774
|
apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
|
|
@@ -962,6 +1056,16 @@ class SqliteStore {
|
|
|
962
1056
|
return this.#queued(await db.transaction(async (tx) => {
|
|
963
1057
|
const at = now();
|
|
964
1058
|
await refuseDeleting(tx, agentId);
|
|
1059
|
+
// A run made from another (a replay of its input, an audit's shadow) never of a purged one: its source's row
|
|
1060
|
+
// held as its purge holds it, so either this commits first and the purge finds it (RunsMadeFromLeft), or the
|
|
1061
|
+
// purge does and this reads its purge time.
|
|
1062
|
+
const of = launch ? madeOf(launch.body) : undefined;
|
|
1063
|
+
if (of !== undefined) {
|
|
1064
|
+
await d.lockRow(tx, "runs", "id", of);
|
|
1065
|
+
const source = await tx.get("SELECT purged_at FROM runs WHERE id = ?", of);
|
|
1066
|
+
if (source && source.purged_at !== null)
|
|
1067
|
+
throw new RunPurged(of, id);
|
|
1068
|
+
}
|
|
965
1069
|
const row = await tx.get(insert, id, agentId, revisionId, labelled, at);
|
|
966
1070
|
if (origin)
|
|
967
1071
|
await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
|
|
@@ -1010,10 +1114,10 @@ class SqliteStore {
|
|
|
1010
1114
|
},
|
|
1011
1115
|
launch: (runId) => readLaunch(db, runId),
|
|
1012
1116
|
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
1013
|
-
list: async ({ agentId, revisionId, state, archived, labels, limit }) => {
|
|
1117
|
+
list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
|
|
1014
1118
|
// A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
|
|
1015
|
-
// count, stat or notice names it.
|
|
1016
|
-
const where = [NOT_A_LEARNING_RUN];
|
|
1119
|
+
// count, stat or notice names it. A purged run is a tombstone: only the readers that sum or count ask for it.
|
|
1120
|
+
const where = [NOT_A_LEARNING_RUN, ...(purged ? [] : ["purged_at IS NULL"])];
|
|
1017
1121
|
const params = [];
|
|
1018
1122
|
if (agentId !== undefined)
|
|
1019
1123
|
(where.push("agent_id = ?"), params.push(agentId));
|
|
@@ -1046,7 +1150,7 @@ class SqliteStore {
|
|
|
1046
1150
|
(where.push("runs.revision_id = ?"), params.push(revisionId));
|
|
1047
1151
|
for (const [key, value] of Object.entries(labels ?? {}))
|
|
1048
1152
|
(where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
|
|
1049
|
-
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}
|
|
1153
|
+
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`, "runs.purged_at IS NULL");
|
|
1050
1154
|
if (status !== undefined)
|
|
1051
1155
|
(where.push("runs.list_status = ?"), params.push(status));
|
|
1052
1156
|
// A run still going (no settled status on its row) whose listing is behind: its list_status may say what it was.
|
|
@@ -1069,7 +1173,7 @@ class SqliteStore {
|
|
|
1069
1173
|
const [row] = await db.all(`SELECT COUNT(*) AS count, SUM(CASE WHEN runs.state IN ('queued', 'running', 'parked')
|
|
1070
1174
|
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
|
|
1071
1175
|
FROM runs JOIN revisions ON revisions.id = runs.revision_id
|
|
1072
|
-
WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN}`, agentId);
|
|
1176
|
+
WHERE runs.agent_id = ? AND ${NOT_A_SHADOW_RUN} AND runs.${NOT_A_LEARNING_RUN} AND runs.purged_at IS NULL`, agentId);
|
|
1073
1177
|
return { count: Number(row?.count ?? 0), live: Number(row?.live ?? 0) };
|
|
1074
1178
|
},
|
|
1075
1179
|
// The rows whose listing is behind, by the three ways one falls behind, each over its own partial index.
|
|
@@ -1077,7 +1181,7 @@ class SqliteStore {
|
|
|
1077
1181
|
const n = clock();
|
|
1078
1182
|
const held = heldAt(n.sql);
|
|
1079
1183
|
const rows = await db.all(`SELECT id, list_mark AS mark, held FROM (
|
|
1080
|
-
SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark
|
|
1184
|
+
SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_mark < list_mark AND purged_at IS NULL
|
|
1081
1185
|
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_live = 1 AND NOT ${held}
|
|
1082
1186
|
UNION SELECT id, list_mark, started_at, ${held} AS held FROM runs WHERE listing_until IS NOT NULL AND listing_until <= ${n.sql}
|
|
1083
1187
|
) AS behind ORDER BY held, started_at DESC, id DESC LIMIT ? OFFSET ?`, ...n.params, ...n.params, ...n.params, ...n.params, ...n.params, limit, offset);
|
|
@@ -1094,19 +1198,34 @@ class SqliteStore {
|
|
|
1094
1198
|
const row = await db.get("SELECT list_mark FROM runs WHERE id = ?", runId);
|
|
1095
1199
|
return row === undefined ? undefined : Number(row.list_mark);
|
|
1096
1200
|
},
|
|
1097
|
-
// A heal of an ended run's unknown cost from its priced booking
|
|
1098
|
-
//
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1201
|
+
// A heal of an ended run's unknown cost from its priced booking, as its end writes one (the bound beside the figure
|
|
1202
|
+
// with it, applyRunPatch): one conditional UPDATE, only over a null with no bound beside it (cost_upper_bound 0, the
|
|
1203
|
+
// column's no-bound value: it is never NULL), only at the end it was read at (a reopen or a later end moves ended_at
|
|
1204
|
+
// or the epoch), so it never overwrites a figure or a bound, whatever its caller read.
|
|
1205
|
+
healCost: async (runId, { epoch, endedAt }, { costUsd, costUpperBound }) => {
|
|
1206
|
+
if (!Number.isFinite(costUsd) || costUsd < 0)
|
|
1207
|
+
throw new TypeError(`a healed cost is a figure of $0 or more (got ${costUsd})`);
|
|
1102
1208
|
const [result] = await db.write([{
|
|
1103
|
-
sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound =
|
|
1104
|
-
params: [
|
|
1209
|
+
sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING id`,
|
|
1210
|
+
params: [costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt],
|
|
1105
1211
|
}]);
|
|
1106
1212
|
return (result?.rows.length ?? 0) > 0;
|
|
1107
1213
|
},
|
|
1214
|
+
// The runs healCost may write that the heal's rule (store-view.ts bookedCostOf, healOf) does not refuse by its
|
|
1215
|
+
// columns alone, so the start sweep never reads one that cannot heal again at each start: left out are a person's
|
|
1216
|
+
// stop of an agentic run (it reads running, stoppedByPerson), an agentic run whose launch names a native connection
|
|
1217
|
+
// (its end reads its own cost; a launch whose `native` is no connection is one no runner could read, so it booked
|
|
1218
|
+
// nothing either), and a run whose journal holds no runner.turn (no request booked with an answer: no figure to heal
|
|
1219
|
+
// to). Kept, and read at each start while their cost stays null: runs with a booked request whose booking still
|
|
1220
|
+
// gives no figure (a charge of no known cost, every request given back). Telling them apart is the booking rule
|
|
1221
|
+
// itself (turnCostOf over each turn's data), which no column holds.
|
|
1108
1222
|
costUnknown: async ({ limit, after }) => {
|
|
1109
|
-
const
|
|
1223
|
+
const agentic = "COALESCE((SELECT kind FROM revisions WHERE revisions.id = runs.revision_id), 'agentic') = 'agentic'";
|
|
1224
|
+
const rows = await db.all(`SELECT id FROM runs WHERE ${COST_UNKNOWN}
|
|
1225
|
+
AND NOT (state = 'stopped' AND COALESCE(outcome, '') = 'stopped' AND ${agentic})
|
|
1226
|
+
AND NOT (${agentic} AND EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${db.dialect.jsonText("run_launch.body", ["native"])} IS NOT NULL))
|
|
1227
|
+
AND EXISTS (SELECT 1 FROM ${PI_TABLE.entries} AS entry WHERE entry.run_id = runs.id AND ${db.dialect.jsonText("entry.record", ["kind"])} = ?)
|
|
1228
|
+
${after === undefined ? "" : "AND id > ? "}ORDER BY id LIMIT ?`, RUNNER_RECORDS.turn, ...(after === undefined ? [] : [after]), limit);
|
|
1110
1229
|
return rows.map((row) => row.id);
|
|
1111
1230
|
},
|
|
1112
1231
|
relist: async ({ flags, agentId }) => {
|
|
@@ -1136,7 +1255,66 @@ class SqliteStore {
|
|
|
1136
1255
|
// Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
|
|
1137
1256
|
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] }]);
|
|
1138
1257
|
},
|
|
1139
|
-
every: async (agentId) => db.all("SELECT id, state FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId)
|
|
1258
|
+
every: async (agentId) => (await db.all("SELECT id, state, runner, purged_at FROM runs WHERE agent_id = ? ORDER BY started_at, id", agentId))
|
|
1259
|
+
.map((row) => ({ id: row.id, state: row.state, runner: row.runner, purgedAt: row.purged_at ?? null })),
|
|
1260
|
+
madeFrom: async (runId) => {
|
|
1261
|
+
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);
|
|
1262
|
+
return [...new Set([...(await launchedFrom(db, runId)), ...learning])].sort();
|
|
1263
|
+
},
|
|
1264
|
+
purge: async (runId, kept) => {
|
|
1265
|
+
const purged = await db.transaction(async (tx) => {
|
|
1266
|
+
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds it final.
|
|
1267
|
+
await d.lockRow(tx, "runs", "id", runId, "update");
|
|
1268
|
+
const run = await tx.get("SELECT state, runner, metrics, purged_at FROM runs WHERE id = ?", runId);
|
|
1269
|
+
if (!run || run.purged_at !== null)
|
|
1270
|
+
return false;
|
|
1271
|
+
if (!FINAL_STATES.includes(run.state) || run.runner !== null)
|
|
1272
|
+
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`);
|
|
1273
|
+
// A replay or shadow made from it after its purge read them (runs.create, under this row's lock) holds a copy of
|
|
1274
|
+
// its input: each is purged first.
|
|
1275
|
+
const left = [];
|
|
1276
|
+
for (const id of await launchedFrom(tx, runId)) {
|
|
1277
|
+
if ((await tx.get("SELECT purged_at FROM runs WHERE id = ?", id))?.purged_at === null)
|
|
1278
|
+
left.push(id);
|
|
1279
|
+
}
|
|
1280
|
+
if (left.length)
|
|
1281
|
+
throw new RunsMadeFromLeft(runId, left);
|
|
1282
|
+
for (const table of PI_TABLES)
|
|
1283
|
+
await tx.run(`DELETE FROM ${table} WHERE run_id = ?`, runId);
|
|
1284
|
+
await tx.run("DELETE FROM commands WHERE run_id = ?", runId);
|
|
1285
|
+
await tx.run("DELETE FROM run_origins WHERE run_id = ?", runId);
|
|
1286
|
+
await tx.run("DELETE FROM run_launch WHERE run_id = ?", runId);
|
|
1287
|
+
await tx.run("DELETE FROM run_live WHERE run_id = ?", runId);
|
|
1288
|
+
await tx.run("DELETE FROM computer_viewers WHERE run_id = ?", runId);
|
|
1289
|
+
await tx.run("DELETE FROM channel_attempts WHERE post_id IN (SELECT id FROM channel_posts WHERE run_id = ?)", runId);
|
|
1290
|
+
await tx.run("DELETE FROM channel_posts WHERE run_id = ?", runId);
|
|
1291
|
+
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
1292
|
+
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
1293
|
+
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1294
|
+
// What names it, let go: a trigger's last run, the firing that started it (its key and status kept, so it never
|
|
1295
|
+
// fires again; the event it was given, its payload and attributes, gone), a firing's wait behind it (the
|
|
1296
|
+
// trigger's room is read again, as for a run that ended), the run a machine's token was minted for.
|
|
1297
|
+
await tx.run("UPDATE triggers SET last_run_id = NULL WHERE last_run_id = ?", runId);
|
|
1298
|
+
await tx.run("UPDATE trigger_firings SET run_id = NULL, payload = NULL, attrs = NULL WHERE run_id = ?", runId);
|
|
1299
|
+
await tx.run("UPDATE trigger_firings SET waits_on = NULL WHERE waits_on = ?", runId);
|
|
1300
|
+
await tx.run("UPDATE minted_tokens SET run = NULL WHERE run = ?", runId);
|
|
1301
|
+
// Its kept learning: what its turn asked and answered and the proposal go; each row stays, with the proposal's
|
|
1302
|
+
// state alone, as the learning meter (learning.spend) and the list's leaving out of learning runs read it.
|
|
1303
|
+
for (const row of await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ?", runId)) {
|
|
1304
|
+
const state = JSON.parse(row.proposal)?.state;
|
|
1305
|
+
await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
|
|
1306
|
+
}
|
|
1307
|
+
// Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
|
|
1308
|
+
// read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
|
|
1309
|
+
const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
|
|
1310
|
+
await tx.run("UPDATE runs SET summary = NULL, labels = NULL, sign_in_handed = NULL, metrics = ? WHERE id = ?", json(metrics), runId);
|
|
1311
|
+
// Its listing, and its purge time last: no list shows it, and no lister builds it again.
|
|
1312
|
+
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);
|
|
1313
|
+
return true;
|
|
1314
|
+
});
|
|
1315
|
+
if (purged)
|
|
1316
|
+
await this.#purged(`run ${runId}`);
|
|
1317
|
+
},
|
|
1140
1318
|
remove: async (runId) => {
|
|
1141
1319
|
await db.transaction(async (tx) => {
|
|
1142
1320
|
// Held as a run's end holds it: a write under a claim of it is either in before this, or finds no row.
|
|
@@ -1159,10 +1337,11 @@ class SqliteStore {
|
|
|
1159
1337
|
await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
|
|
1160
1338
|
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
1161
1339
|
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
1340
|
+
await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
|
|
1162
1341
|
await tx.run("DELETE FROM runs WHERE id = ?", runId);
|
|
1163
1342
|
});
|
|
1164
1343
|
},
|
|
1165
|
-
reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => {
|
|
1344
|
+
reopen: async (runId, { kind, body = null }, { launchSealed, endedAt } = {}) => {
|
|
1166
1345
|
const command = await db.transaction(async (tx) => {
|
|
1167
1346
|
// Never a run of an agent being deleted opened again (its mark, read in this transaction).
|
|
1168
1347
|
const of = await tx.get("SELECT agent_id FROM runs WHERE id = ?", runId);
|
|
@@ -1170,7 +1349,8 @@ class SqliteStore {
|
|
|
1170
1349
|
await refuseDeleting(tx, of.agent_id);
|
|
1171
1350
|
// Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
|
|
1172
1351
|
// spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
|
|
1173
|
-
const
|
|
1352
|
+
const at = endedAt === undefined ? { sql: "", params: [] } : { sql: " AND ended_at = ?", params: [endedAt] };
|
|
1353
|
+
const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}${at.sql}`, runId, ...at.params);
|
|
1174
1354
|
if (reopened === 0)
|
|
1175
1355
|
throw new RunFinal(runId);
|
|
1176
1356
|
// The message's launch secrets, with it: the claim that runs its turn reads them.
|
|
@@ -1245,7 +1425,7 @@ class SqliteStore {
|
|
|
1245
1425
|
}
|
|
1246
1426
|
}
|
|
1247
1427
|
// An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
|
|
1248
|
-
await refuseLeftovers(tx, claim.runId, patch.state, at, d);
|
|
1428
|
+
await refuseLeftovers(tx, claim.runId, patch.state, at, d, patch.keepsEnd === true);
|
|
1249
1429
|
// The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
|
|
1250
1430
|
// SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
|
|
1251
1431
|
// or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
|
|
@@ -1451,18 +1631,20 @@ class SqliteStore {
|
|
|
1451
1631
|
...(row.learning_run_id === null ? {} : { learningRunId: row.learning_run_id }), createdAt: row.created_at,
|
|
1452
1632
|
});
|
|
1453
1633
|
const PROPOSAL_COLUMNS = "run_id, round, agent_id, turn, proposal, learning_run_id, created_at";
|
|
1634
|
+
// A purged run's kept learning is its state alone (Runs.purge), for the learning meter: no reader of learning reads it.
|
|
1635
|
+
const NOT_PURGED = "NOT EXISTS (SELECT 1 FROM runs WHERE runs.id = learning_proposals.run_id AND runs.purged_at IS NOT NULL)";
|
|
1454
1636
|
this.learning = {
|
|
1455
1637
|
// A round asked for, else the run's newest.
|
|
1456
1638
|
proposal: async (runId, round) => {
|
|
1457
1639
|
const row = round === undefined
|
|
1458
|
-
? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? ORDER BY round DESC LIMIT 1`, runId)
|
|
1459
|
-
: await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round =
|
|
1640
|
+
? await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND ${NOT_PURGED} ORDER BY round DESC LIMIT 1`, runId)
|
|
1641
|
+
: await db.get(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE run_id = ? AND round = ? AND ${NOT_PURGED}`, runId, round);
|
|
1460
1642
|
return row ? proposalOf(row) : undefined;
|
|
1461
1643
|
},
|
|
1462
|
-
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),
|
|
1644
|
+
proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
|
|
1463
1645
|
kept: async (agentId) => {
|
|
1464
|
-
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1465
|
-
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);
|
|
1646
|
+
const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? AND ${NOT_PURGED} ORDER BY run_id, round`, agentId)).map(proposalOf);
|
|
1647
|
+
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 AND ${NOT_PURGED})`, agentId)).map(runOf);
|
|
1466
1648
|
return { proposals, learningRuns };
|
|
1467
1649
|
},
|
|
1468
1650
|
spend: async ({ from, to }) => {
|
|
@@ -1626,6 +1808,21 @@ class SqliteStore {
|
|
|
1626
1808
|
return (result?.changes ?? 0) === 1;
|
|
1627
1809
|
},
|
|
1628
1810
|
};
|
|
1811
|
+
this.computerIntervals = {
|
|
1812
|
+
opened: async (row) => {
|
|
1813
|
+
await db.write([{
|
|
1814
|
+
sql: "INSERT INTO computer_intervals (provider, provider_id, run_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (provider, provider_id) DO NOTHING",
|
|
1815
|
+
params: [row.provider, row.providerId, row.runId, row.kind, row.gpuType, row.gpuCount, row.cpus, row.memoryMb, row.startedAt],
|
|
1816
|
+
}]);
|
|
1817
|
+
},
|
|
1818
|
+
kept: async (provider, providerId) => {
|
|
1819
|
+
await db.write([{ sql: "UPDATE computer_intervals SET kept = 1 WHERE provider = ? AND provider_id = ?", params: [provider, providerId] }]);
|
|
1820
|
+
},
|
|
1821
|
+
ended: async (provider, providerId, at) => {
|
|
1822
|
+
await db.write([{ sql: "UPDATE computer_intervals SET ended_at = ? WHERE provider = ? AND provider_id = ? AND ended_at IS NULL", params: [at, provider, providerId] }]);
|
|
1823
|
+
},
|
|
1824
|
+
forRun: async (runId) => (await db.all("SELECT run_id, provider, provider_id, kind, gpu_type, gpu_count, cpus, memory_mb, started_at, kept, ended_at FROM computer_intervals WHERE run_id = ? ORDER BY started_at, provider, provider_id", runId)).map(intervalOf),
|
|
1825
|
+
};
|
|
1629
1826
|
const PAIRED = "SELECT id, name, hello, driver, labels, pairing_id, created_at, seen_at, revoked_at FROM paired_computers";
|
|
1630
1827
|
this.pairedComputers = {
|
|
1631
1828
|
addCode: async (id, codeSha256, expiresAt) => {
|
|
@@ -1693,39 +1890,25 @@ class SqliteStore {
|
|
|
1693
1890
|
// runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
|
|
1694
1891
|
const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
|
|
1695
1892
|
this.runners = {
|
|
1696
|
-
put: async ({ runner, incarnation, refused, host = null, port = null }) => {
|
|
1697
|
-
const n = clock();
|
|
1698
|
-
await db.write([
|
|
1699
|
-
{ sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
|
|
1700
|
-
{
|
|
1701
|
-
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at`,
|
|
1702
|
-
params: [runner, incarnation, refused, host, port, ...n.params],
|
|
1703
|
-
},
|
|
1704
|
-
]);
|
|
1705
|
-
},
|
|
1706
|
-
putUnlessLive: async ({ runner, incarnation, refused, host = null, port = null }, staleMs) => {
|
|
1893
|
+
put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
|
|
1707
1894
|
const n = clock();
|
|
1708
|
-
//
|
|
1709
|
-
// read between, so a later process's put can never land between a look and this write.
|
|
1895
|
+
// With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
|
|
1896
|
+
// statement: no read between, so a later process's put can never land between a look and this write.
|
|
1897
|
+
const unlessLive = unlessLiveMs === undefined ? "" : ` WHERE runners.incarnation = excluded.incarnation OR runners.seen_at < excluded.seen_at - ${d.bigintParam}`;
|
|
1710
1898
|
const [, result] = await db.write([
|
|
1711
1899
|
{ sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
|
|
1712
1900
|
{
|
|
1713
|
-
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at
|
|
1714
|
-
params: [runner, incarnation, refused, host, port, ...n.params,
|
|
1901
|
+
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at) VALUES (?, ?, ?, ?, ?, ${n.sql}) ON CONFLICT (runner) DO UPDATE SET incarnation = excluded.incarnation, refused = excluded.refused, host = excluded.host, port = excluded.port, seen_at = excluded.seen_at${unlessLive}`,
|
|
1902
|
+
params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
|
|
1715
1903
|
},
|
|
1716
1904
|
]);
|
|
1717
1905
|
return (result?.changes ?? 0) === 1;
|
|
1718
1906
|
},
|
|
1719
|
-
|
|
1907
|
+
renew: async (runner, incarnation, at) => {
|
|
1720
1908
|
const n = clock();
|
|
1721
1909
|
const [result] = await db.write([{ sql: `UPDATE runners SET host = ?, port = ?, seen_at = ${n.sql} WHERE runner = ? AND incarnation = ?`, params: [at?.host ?? null, at?.port ?? null, ...n.params, runner, incarnation] }]);
|
|
1722
1910
|
return (result?.changes ?? 0) === 1;
|
|
1723
1911
|
},
|
|
1724
|
-
seen: async (runner, incarnation) => {
|
|
1725
|
-
const n = clock();
|
|
1726
|
-
const [result] = await db.write([{ sql: `UPDATE runners SET seen_at = ${n.sql} WHERE runner = ? AND incarnation = ?`, params: [...n.params, runner, incarnation] }]);
|
|
1727
|
-
return (result?.changes ?? 0) === 1;
|
|
1728
|
-
},
|
|
1729
1912
|
list: async () => (await db.all(`${RUNNERS_SELECT} ORDER BY runner`)).map(runnerOf),
|
|
1730
1913
|
live: async (staleMs) => {
|
|
1731
1914
|
const n = clock();
|
|
@@ -1939,6 +2122,35 @@ class SqliteStore {
|
|
|
1939
2122
|
handedAny: async () => (await handedAnyIn(db))?.id,
|
|
1940
2123
|
};
|
|
1941
2124
|
}
|
|
2125
|
+
/** After a purge of `what` committed (runs.purge, agents.purge), on a SQLite store with a file: a WAL checkpoint
|
|
2126
|
+
* (TRUNCATE). secure_delete (worker.ts open) zeroed the purged bytes in the pages the purge wrote, but those pages are
|
|
2127
|
+
* new frames in the WAL: the file keeps its earlier images of them, and the WAL its earlier frames, until a checkpoint
|
|
2128
|
+
* copies the zeroed pages into the file and truncates the log. A reader in another connection (a runner's read, a
|
|
2129
|
+
* backup) may hold the log back: the checkpoint waits PURGE_CHECKPOINT_BUSY_MS for it, not the connection's own busy
|
|
2130
|
+
* wait, since every request of the store's one connection queues behind it (the purge already committed). One retry
|
|
2131
|
+
* after a short pause, then a warning, and the old frames stay until the next purge's checkpoint (or the last
|
|
2132
|
+
* connection's close, which checkpoints and removes the log). An automatic checkpoint (PASSIVE) copies the zeroed
|
|
2133
|
+
* pages into the file but leaves the log's old frames in place. Never fails the purge, which committed. */
|
|
2134
|
+
async #purged(what) {
|
|
2135
|
+
const db = this.#db;
|
|
2136
|
+
if (this.#scrubMarker === undefined || !(db instanceof Connection))
|
|
2137
|
+
return;
|
|
2138
|
+
let why = "";
|
|
2139
|
+
for (let tries = 1; tries <= 2; tries++) {
|
|
2140
|
+
try {
|
|
2141
|
+
const checkpoint = await db.checkpoint(PURGE_CHECKPOINT_BUSY_MS);
|
|
2142
|
+
if (checkpoint?.busy === 0)
|
|
2143
|
+
return;
|
|
2144
|
+
why = "another connection held the log";
|
|
2145
|
+
}
|
|
2146
|
+
catch (error) {
|
|
2147
|
+
why = error instanceof StoreBusy ? "another connection held the log" : `the checkpoint failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
2148
|
+
}
|
|
2149
|
+
if (tries === 1)
|
|
2150
|
+
await new Promise((resolve) => setTimeout(resolve, PURGE_CHECKPOINT_RETRY_MS));
|
|
2151
|
+
}
|
|
2152
|
+
this.#warn(`the purge of ${what} committed, but its WAL checkpoint did not finish (${why}): the purged content's earlier page images may stay in the store's file and its -wal until the next purge's checkpoint or the server's stop`);
|
|
2153
|
+
}
|
|
1942
2154
|
async secureRewrite(work, options = {}) {
|
|
1943
2155
|
const marker = this.#scrubMarker;
|
|
1944
2156
|
if (this.#db.dialect.name !== "sqlite" || marker === undefined)
|
|
@@ -1947,14 +2159,8 @@ class SqliteStore {
|
|
|
1947
2159
|
// leaves it, and its next start scrubs though no row is left in the clear.
|
|
1948
2160
|
const pending = existsSync(marker);
|
|
1949
2161
|
markScrub(marker);
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
try {
|
|
1953
|
-
rewritten = await work();
|
|
1954
|
-
}
|
|
1955
|
-
finally {
|
|
1956
|
-
await this.#db.all("PRAGMA secure_delete = OFF");
|
|
1957
|
-
}
|
|
2162
|
+
// secure_delete is on for the connection's whole life (worker.ts open): a rewritten row's old bytes are zeroed in its page.
|
|
2163
|
+
const rewritten = await work();
|
|
1958
2164
|
if (rewritten === 0 && !pending) {
|
|
1959
2165
|
rmSync(marker, { force: true });
|
|
1960
2166
|
return { rewritten };
|
|
@@ -1962,8 +2168,8 @@ class SqliteStore {
|
|
|
1962
2168
|
// Asked with no VACUUM (a server already serving): the marker stays, and the next start's scrub runs it before it serves.
|
|
1963
2169
|
if (options.vacuum === false)
|
|
1964
2170
|
return { rewritten, left: "deferred" };
|
|
1965
|
-
//
|
|
1966
|
-
//
|
|
2171
|
+
// A copy an update of the row left before secure_delete was on (a store an earlier server wrote: a pause, a rename, a
|
|
2172
|
+
// firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
|
|
1967
2173
|
// checkpoint copies it into the file and truncates the log. Run outside any transaction.
|
|
1968
2174
|
try {
|
|
1969
2175
|
// Another connection's write (a runner's) may hold the lock past the busy wait: one retry after a short pause.
|