@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51
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 +147 -0
- package/README.md +142 -17
- package/dist/agents-store.js +7 -3
- package/dist/api-only.d.ts +2 -1
- package/dist/api-only.js +3 -2
- package/dist/capacity.d.ts +50 -0
- package/dist/capacity.js +49 -0
- package/dist/cli-learning/claude-wire.d.ts +41 -0
- package/dist/cli-learning/claude-wire.js +258 -0
- package/dist/cli-learning/cli.d.ts +11 -0
- package/dist/cli-learning/cli.js +241 -0
- package/dist/cli-learning/codex-worktree.d.ts +10 -0
- package/dist/cli-learning/codex-worktree.js +119 -0
- package/dist/cli-learning/connections.d.ts +62 -0
- package/dist/cli-learning/connections.js +87 -0
- package/dist/cli-learning/entry.d.ts +1 -0
- package/dist/cli-learning/entry.js +4 -0
- package/dist/cli-learning/evidence.d.ts +78 -0
- package/dist/cli-learning/evidence.js +492 -0
- package/dist/cli-learning/hook.d.ts +33 -0
- package/dist/cli-learning/hook.js +544 -0
- package/dist/cli-learning/install.d.ts +33 -0
- package/dist/cli-learning/install.js +335 -0
- package/dist/cli-learning/observation-proof.d.ts +14 -0
- package/dist/cli-learning/observation-proof.js +10 -0
- package/dist/cli-learning/policy.d.ts +48 -0
- package/dist/cli-learning/policy.js +363 -0
- package/dist/cli-learning/schema.d.ts +16 -0
- package/dist/cli-learning/schema.js +27 -0
- package/dist/cli-learning/state.d.ts +23 -0
- package/dist/cli-learning/state.js +61 -0
- package/dist/cli.js +24 -2
- package/dist/console/assets/index-Bt1B51b7.js +733 -0
- package/dist/console/assets/index-sVftE9Ht.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/email/email-faux.d.ts +3 -1
- package/dist/email/email-faux.js +3 -2
- package/dist/email/routes.js +22 -12
- package/dist/harness-install.d.ts +6 -2
- package/dist/harness-install.js +40 -8
- package/dist/harness.d.ts +1 -1
- package/dist/harness.js +2 -2
- package/dist/learn/secrets.js +14 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +1 -1
- package/dist/mcp-pin-first.js +2 -1
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/model-gateway.d.ts +2 -0
- package/dist/model-gateway.js +3 -1
- package/dist/native/runtimes.d.ts +2 -0
- package/dist/native/runtimes.js +2 -0
- package/dist/observation/learning.d.ts +32 -0
- package/dist/observation/learning.js +66 -0
- package/dist/observation/observer.d.ts +8 -1
- package/dist/observation/observer.js +89 -9
- package/dist/observation/schema.js +12 -4
- package/dist/observation/usage-identity.d.ts +9 -0
- package/dist/observation/usage-identity.js +11 -0
- package/dist/openapi.js +89 -13
- package/dist/run-launch.d.ts +14 -0
- package/dist/run-launch.js +4 -0
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +12 -7
- package/dist/runner/adapter-loop.js +29 -26
- package/dist/runner/adapter-run-spec.js +2 -2
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/cli-run-spec.js +2 -2
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +3 -1
- package/dist/runner/journal-kinds.d.ts +1 -1
- package/dist/runner/learning-end.js +4 -0
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/run-child-host.d.ts +12 -15
- package/dist/runner/run-child-host.js +46 -108
- package/dist/runner/run-errors.js +2 -0
- package/dist/runner/runner-check.d.ts +51 -0
- package/dist/runner/runner-check.js +206 -0
- package/dist/runner/runner-metrics.d.ts +19 -0
- package/dist/runner/runner-metrics.js +49 -0
- package/dist/runner/runner.d.ts +37 -0
- package/dist/runner/runner.js +43 -3
- package/dist/runner/sdk-loop.js +34 -22
- package/dist/runs-over-store.d.ts +8 -1
- package/dist/runs-over-store.js +57 -9
- package/dist/sdk/runs.d.ts +22 -2
- package/dist/sdk/runs.js +103 -34
- package/dist/server.d.ts +3 -0
- package/dist/server.js +149 -26
- package/dist/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/start-switches.js +2 -0
- package/dist/stats.d.ts +4 -0
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +12 -0
- package/dist/store/agent-body.js +16 -2
- package/dist/store/dialect.d.ts +2 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/postgres/connection.d.ts +5 -2
- package/dist/store/postgres/connection.js +19 -7
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrate.d.ts +30 -0
- package/dist/store/postgres/migrate.js +72 -5
- package/dist/store/postgres/migration-lint.d.ts +8 -0
- package/dist/store/postgres/migration-lint.js +119 -0
- package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +18 -1
- package/dist/store/schema.js +33 -2
- package/dist/store/sqlite/run-launch.d.ts +9 -1
- package/dist/store/sqlite/run-launch.js +44 -0
- package/dist/store/sqlite/store.d.ts +17 -0
- package/dist/store/sqlite/store.js +87 -10
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +53 -1
- package/dist/store/store.js +13 -0
- package/dist/store-reads/analytics.d.ts +3 -2
- package/dist/store-reads/analytics.js +20 -8
- package/dist/store-view.d.ts +4 -3
- package/dist/store-view.js +11 -7
- package/dist/templates.d.ts +3 -2
- package/dist/tool-gate.d.ts +4 -2
- package/dist/unified-usage.d.ts +24 -0
- package/dist/unified-usage.js +400 -0
- package/dist/uploads-archil.d.ts +100 -0
- package/dist/uploads-archil.js +430 -0
- package/dist/uploads.d.ts +55 -1
- package/dist/uploads.js +185 -98
- package/dist/validate.js +1 -1
- package/dist/workspace/archil-disk.d.ts +6 -5
- package/dist/workspace/archil-disk.js +27 -12
- package/dist/workspace/archil.js +3 -2
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/console/assets/index-D0mr9wfZ.css +0 -1
- package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/store/schema.d.ts
CHANGED
|
@@ -65,7 +65,24 @@ export declare const COMPUTER_INTERVALS_RUN = "CREATE INDEX IF NOT EXISTS comput
|
|
|
65
65
|
* STORE_DDL. A store an earlier build of version 13 made kept the relays in a table of their own (runner_relays): the
|
|
66
66
|
* server's open drops it and makes this one (sqlite/store.ts), as it drops browser_viewers, with no version: the rows
|
|
67
67
|
* are heartbeats renewed every 10 s, so none is copied, and a runner waits for that server (StoreAwaitsServer). */
|
|
68
|
-
export declare const RUNNERS = "CREATE TABLE IF NOT EXISTS runners (\n runner TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n refused TEXT,\n host TEXT,\n port INTEGER,\n seen_at INTEGER NOT NULL\n ) STRICT";
|
|
68
|
+
export declare const RUNNERS = "CREATE TABLE IF NOT EXISTS runners (\n runner TEXT PRIMARY KEY,\n incarnation TEXT NOT NULL,\n refused TEXT,\n host TEXT,\n port INTEGER,\n seen_at INTEGER NOT NULL,\n version TEXT,\n slots INTEGER\n ) STRICT";
|
|
69
|
+
/** What a runner says of itself for the server's capacity read (GET /v2/capacity, capacity.ts): its build's version
|
|
70
|
+
* (`version`) and the most runs it holds at once (`slots`), each null on a row an earlier build wrote. In RUNNERS, and
|
|
71
|
+
* added where missing at a server open to a runners table an earlier build of this version made, as
|
|
72
|
+
* COMPUTER_INTERVALS_ADDED is: nullable, so nothing is copied and no row is refused. */
|
|
73
|
+
export declare const RUNNERS_ADDED: Readonly<Record<string, string>>;
|
|
74
|
+
/** Each hand-back (store.release that leaves its run running: a runner's drain, a loop that closed itself, a claim given
|
|
75
|
+
* back): the run, the runner that let it go, the epoch it let go of and when, on the deadlines' clock. Counts and ids
|
|
76
|
+
* only; the capacity read (capacity.ts) counts the rows within its window. A release's own write keeps it, in the same
|
|
77
|
+
* transaction, and removes the rows older than HAND_BACKS_KEPT_MS. In STORE_DDL, and made at a server open on a store an
|
|
78
|
+
* earlier build of this version made. */
|
|
79
|
+
export declare const HAND_BACKS = "CREATE TABLE IF NOT EXISTS hand_backs (\n run_id TEXT NOT NULL,\n runner TEXT NOT NULL,\n epoch INTEGER NOT NULL,\n at INTEGER NOT NULL\n ) STRICT";
|
|
80
|
+
/** The hand-backs by time, for the capacity read's window and the release's prune. */
|
|
81
|
+
export declare const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_backs (at)";
|
|
82
|
+
/** A run's hand-backs, for its purge and its delete (dropRunContent), so neither scans every hand-back kept. */
|
|
83
|
+
export declare const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
|
|
84
|
+
/** How long a hand-back's row is kept: the longest window the capacity read takes. */
|
|
85
|
+
export declare const HAND_BACKS_KEPT_MS: number;
|
|
69
86
|
/** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
|
|
70
87
|
* run and each agent was purged (null: none was), and the version, in one durable write. */
|
|
71
88
|
export declare function purgeUpgrade(runColumns: ReadonlySet<string>, agentColumns: ReadonlySet<string>): readonly string[];
|
package/dist/store/schema.js
CHANGED
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
// else reads, so it needs no version: the server adds it at its open to a store an earlier build of this version made
|
|
20
20
|
// (IMPORTED_TEMPLATES), as it does the one-answer index. A hosted machine's minted token (minted_tokens, MINTED_TOKENS) is
|
|
21
21
|
// added the same way, and so is each runner's word that it is there and whether it refused to claim (runners, RUNNERS),
|
|
22
|
-
// and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS).
|
|
22
|
+
// and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS). Each runner's
|
|
23
|
+
// version and slots (runners.version, .slots: RUNNERS_ADDED) and each hand-back (hand_backs, HAND_BACKS) are added the same way.
|
|
23
24
|
// Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
|
|
24
25
|
// sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
|
|
25
26
|
// in the clear. Foreign keys are on (the connection's pragma).
|
|
@@ -153,8 +154,35 @@ export const RUNNERS = `CREATE TABLE IF NOT EXISTS runners (
|
|
|
153
154
|
refused TEXT,
|
|
154
155
|
host TEXT,
|
|
155
156
|
port INTEGER,
|
|
156
|
-
seen_at INTEGER NOT NULL
|
|
157
|
+
seen_at INTEGER NOT NULL,
|
|
158
|
+
version TEXT,
|
|
159
|
+
slots INTEGER
|
|
157
160
|
) STRICT`;
|
|
161
|
+
/** What a runner says of itself for the server's capacity read (GET /v2/capacity, capacity.ts): its build's version
|
|
162
|
+
* (`version`) and the most runs it holds at once (`slots`), each null on a row an earlier build wrote. In RUNNERS, and
|
|
163
|
+
* added where missing at a server open to a runners table an earlier build of this version made, as
|
|
164
|
+
* COMPUTER_INTERVALS_ADDED is: nullable, so nothing is copied and no row is refused. */
|
|
165
|
+
export const RUNNERS_ADDED = {
|
|
166
|
+
version: "ALTER TABLE runners ADD COLUMN version TEXT",
|
|
167
|
+
slots: "ALTER TABLE runners ADD COLUMN slots INTEGER",
|
|
168
|
+
};
|
|
169
|
+
/** Each hand-back (store.release that leaves its run running: a runner's drain, a loop that closed itself, a claim given
|
|
170
|
+
* back): the run, the runner that let it go, the epoch it let go of and when, on the deadlines' clock. Counts and ids
|
|
171
|
+
* only; the capacity read (capacity.ts) counts the rows within its window. A release's own write keeps it, in the same
|
|
172
|
+
* transaction, and removes the rows older than HAND_BACKS_KEPT_MS. In STORE_DDL, and made at a server open on a store an
|
|
173
|
+
* earlier build of this version made. */
|
|
174
|
+
export const HAND_BACKS = `CREATE TABLE IF NOT EXISTS hand_backs (
|
|
175
|
+
run_id TEXT NOT NULL,
|
|
176
|
+
runner TEXT NOT NULL,
|
|
177
|
+
epoch INTEGER NOT NULL,
|
|
178
|
+
at INTEGER NOT NULL
|
|
179
|
+
) STRICT`;
|
|
180
|
+
/** The hand-backs by time, for the capacity read's window and the release's prune. */
|
|
181
|
+
export const HAND_BACKS_AT = "CREATE INDEX IF NOT EXISTS hand_backs_at ON hand_backs (at)";
|
|
182
|
+
/** A run's hand-backs, for its purge and its delete (dropRunContent), so neither scans every hand-back kept. */
|
|
183
|
+
export const HAND_BACKS_RUN = "CREATE INDEX IF NOT EXISTS hand_backs_run ON hand_backs (run_id)";
|
|
184
|
+
/** How long a hand-back's row is kept: the longest window the capacity read takes. */
|
|
185
|
+
export const HAND_BACKS_KEPT_MS = 24 * 60 * 60_000;
|
|
158
186
|
/** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
|
|
159
187
|
* run and each agent was purged (null: none was), and the version, in one durable write. */
|
|
160
188
|
export function purgeUpgrade(runColumns, agentColumns) {
|
|
@@ -601,6 +629,9 @@ export const STORE_DDL = [
|
|
|
601
629
|
IMPORTED_TEMPLATES,
|
|
602
630
|
MINTED_TOKENS,
|
|
603
631
|
RUNNERS,
|
|
632
|
+
HAND_BACKS,
|
|
633
|
+
HAND_BACKS_AT,
|
|
634
|
+
HAND_BACKS_RUN,
|
|
604
635
|
COMPUTER_INTERVALS,
|
|
605
636
|
COMPUTER_INTERVALS_RUN,
|
|
606
637
|
// An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow } from "../store.js";
|
|
1
|
+
import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow, type Runs } from "../store.js";
|
|
2
2
|
import type { Dialect } from "../dialect.js";
|
|
3
3
|
import type { SqliteExecutor } from "./connection.js";
|
|
4
4
|
/** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
|
|
@@ -10,6 +10,14 @@ export declare function writeLaunchSealed(tx: Pick<SqliteExecutor, "run" | "get"
|
|
|
10
10
|
/** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
|
|
11
11
|
* none, never a default. */
|
|
12
12
|
export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
|
|
13
|
+
/** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
|
|
14
|
+
* the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
|
|
15
|
+
* Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
|
|
16
|
+
export declare function readUsageMetadata(executor: Pick<SqliteExecutor, "get"> & {
|
|
17
|
+
readonly dialect: Dialect;
|
|
18
|
+
}, runId: string, { completion }: {
|
|
19
|
+
completion: boolean;
|
|
20
|
+
}): ReturnType<Runs["usageMetadata"]>;
|
|
13
21
|
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
14
22
|
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
15
23
|
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
@@ -30,6 +30,50 @@ export async function readLaunch(executor, runId) {
|
|
|
30
30
|
throw new StoreLaunchMissing(runId);
|
|
31
31
|
return runLaunchOf(row);
|
|
32
32
|
}
|
|
33
|
+
/** Project accounting facts before crossing the database boundary. An SDK inbox can contain megabytes of replay;
|
|
34
|
+
* the raw-JSON projection preserves strings, nulls and invalid scalar shapes equally on SQLite and Postgres.
|
|
35
|
+
* Uses an ordinary store connection: a PostgreSQL Unicode refusal is retried outside a failed transaction. */
|
|
36
|
+
export async function readUsageMetadata(executor, runId, { completion }) {
|
|
37
|
+
const keys = ["runtime", "session_id", "turn_id"];
|
|
38
|
+
const counters = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"];
|
|
39
|
+
const columns = keys.map(key => `${executor.dialect.jsonValue("l.body", ["cli_learning", key])} AS ${key}`);
|
|
40
|
+
// Launch bodies are written with JSON.stringify: zero is canonically `0`. Read only the historical
|
|
41
|
+
// binding's truthiness, never its potentially private or large provider configuration.
|
|
42
|
+
const grading = executor.dialect.jsonValue("l.body", ["cli_learning", "native_grading"]);
|
|
43
|
+
columns.push(`CASE WHEN ${grading} IS NULL OR ${grading} IN ('null', 'false', '0', '""') THEN 0 ELSE 1 END AS native_grading`);
|
|
44
|
+
if (completion)
|
|
45
|
+
columns.push(...counters.map(key => `${executor.dialect.jsonValue("s.value", ["completion", "usage", key])} AS ${key}`));
|
|
46
|
+
const from = `FROM runs r LEFT JOIN run_launch l ON l.run_id = r.id${completion ? " LEFT JOIN settings s ON s.key = ?" : ""} WHERE r.id = ?`;
|
|
47
|
+
const params = [...(completion ? [`sdk-run:${runId}`] : []), runId];
|
|
48
|
+
let row;
|
|
49
|
+
try {
|
|
50
|
+
row = await executor.get(`SELECT ${columns.join(", ")} ${from}`, ...params);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
// PostgreSQL accepts escaped NUL/lone-surrogate strings in JSON TEXT but cannot extract ANY member of
|
|
54
|
+
// such a document. Only its exact Unicode refusal permits the former JS read/parse cost for that row.
|
|
55
|
+
// Never sanitize native identities or silently lose known counters to an unrelated replay string.
|
|
56
|
+
let unicode = false;
|
|
57
|
+
for (let cause = error, depth = 0; cause && depth < 6; cause = cause.cause, depth++)
|
|
58
|
+
if (cause.code === "22P05" || (cause.code === "22P02" && cause.reason === "json_surrogate"))
|
|
59
|
+
unicode = true;
|
|
60
|
+
if (executor.dialect.name !== "postgres" || !unicode)
|
|
61
|
+
throw error;
|
|
62
|
+
const raw = await executor.get(`SELECT l.body${completion ? ", s.value AS inbox" : ""} ${from}`, ...params);
|
|
63
|
+
if (!raw)
|
|
64
|
+
return undefined;
|
|
65
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
66
|
+
const cli = object(object(raw.body == null ? undefined : JSON.parse(raw.body)).cli_learning);
|
|
67
|
+
const usage = object(object(object(raw.inbox == null ? undefined : JSON.parse(raw.inbox)).completion).usage);
|
|
68
|
+
return { cli: { ...Object.fromEntries(keys.map(key => [key, cli[key]])), native_grading: Boolean(cli.native_grading) },
|
|
69
|
+
...(completion ? { completionUsage: Object.fromEntries(counters.map(key => [key, usage[key]])) } : {}) };
|
|
70
|
+
}
|
|
71
|
+
if (!row)
|
|
72
|
+
return undefined;
|
|
73
|
+
const value = (key) => row[key] == null ? undefined : JSON.parse(String(row[key]));
|
|
74
|
+
return { cli: { ...Object.fromEntries(keys.map(key => [key, value(key)])), native_grading: Boolean(row.native_grading) },
|
|
75
|
+
...(completion ? { completionUsage: Object.fromEntries(counters.map(key => [key, value(key)])) } : {}) };
|
|
76
|
+
}
|
|
33
77
|
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
34
78
|
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
35
79
|
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
@@ -22,6 +22,23 @@ export type SqliteStoreOptions = (
|
|
|
22
22
|
/** How long a write waits for another process's lock before StoreBusy. */
|
|
23
23
|
busyTimeoutMs?: number;
|
|
24
24
|
};
|
|
25
|
+
/** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
|
|
26
|
+
* at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
|
|
27
|
+
* words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
|
|
28
|
+
export declare const SQLITE_RUNNER_NEEDS: readonly {
|
|
29
|
+
readonly table: string;
|
|
30
|
+
readonly columns: readonly string[];
|
|
31
|
+
readonly why: string;
|
|
32
|
+
}[];
|
|
33
|
+
/** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
|
|
34
|
+
* or undefined when it opens; `columnsOf` reads a table's columns. */
|
|
35
|
+
export declare function runnerWaitsFor(columnsOf: (table: string) => Promise<ReadonlySet<string>> | ReadonlySet<string>): Promise<string | undefined>;
|
|
36
|
+
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
37
|
+
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
38
|
+
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
39
|
+
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
|
|
40
|
+
* this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
|
|
41
|
+
export declare function earlierVersionIn(dataDir: string, busyTimeoutMs: number): string[];
|
|
25
42
|
/** Opens the store in `dataDir` (its file is STORE_FILE there), or at `file` (the store's own tests). As the server (the
|
|
26
43
|
* default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
|
|
27
44
|
* no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
|
|
@@ -12,7 +12,7 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
|
|
|
12
12
|
import { claimFence, storeNow } from "../fence.js";
|
|
13
13
|
import { RunStorage } from "../journal/storage.js";
|
|
14
14
|
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
15
|
-
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, 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";
|
|
15
|
+
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, 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, RUNNERS, RUNNERS_ADDED, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
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
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) => {
|
|
@@ -33,7 +33,7 @@ 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 { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
36
|
+
import { readLaunch, readLearningStarts, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
37
37
|
import { canonical } from "../agent-body.js";
|
|
38
38
|
import { aadOf, sealedAt } from "../seal.js";
|
|
39
39
|
/** A claim's length when the caller names none. */
|
|
@@ -176,7 +176,7 @@ const intervalOf = (r) => ({
|
|
|
176
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 });
|
|
177
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 });
|
|
178
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 });
|
|
179
|
-
const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at) });
|
|
179
|
+
const runnerOf = (r) => ({ runner: r.runner, incarnation: r.incarnation, refused: r.refused, host: r.host, port: r.port === null ? null : Number(r.port), seenAt: Number(r.seen_at), version: r.version, slots: r.slots === null ? null : Number(r.slots) });
|
|
180
180
|
const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
|
|
181
181
|
const mcpOauthOf = (r) => ({ state: r.state, server: r.server, sealed: Uint8Array.from(r.sealed), working: r.working === null ? null : JSON.parse(r.working), expiresAt: r.expires_at });
|
|
182
182
|
const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
|
|
@@ -198,12 +198,35 @@ async function versionOf(db) {
|
|
|
198
198
|
* (webhook.json, webhook-outbox.json) do not refuse the directory either: nothing reads them, and the webhook, now in
|
|
199
199
|
* the store, is set again. */
|
|
200
200
|
const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
|
|
201
|
+
/** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
|
|
202
|
+
* at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
|
|
203
|
+
* words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
|
|
204
|
+
export const SQLITE_RUNNER_NEEDS = [
|
|
205
|
+
{ table: "revisions", columns: ["mcp_pin", "monid_pin"], why: "install MCP and Monid revision metadata" },
|
|
206
|
+
{ table: "settings", columns: ["connector_id"], why: "add native command ownership metadata" },
|
|
207
|
+
{ table: "runs", columns: ["cost_upper_bound"], why: "add the bound beside each run's cost" },
|
|
208
|
+
{ table: "runs", columns: ["labels"], why: "add each run's labels" },
|
|
209
|
+
{ table: "triggers", columns: ["template_id"], why: "add each trigger's package mark" },
|
|
210
|
+
{ table: "runners", columns: ["host"], why: "keep each runner's word that it is there and its relay in one table (runners)" },
|
|
211
|
+
{ table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
|
|
212
|
+
{ table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
|
|
213
|
+
];
|
|
214
|
+
/** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
|
|
215
|
+
* or undefined when it opens; `columnsOf` reads a table's columns. */
|
|
216
|
+
export async function runnerWaitsFor(columnsOf) {
|
|
217
|
+
for (const need of SQLITE_RUNNER_NEEDS) {
|
|
218
|
+
const present = await columnsOf(need.table);
|
|
219
|
+
if (need.columns.some((column) => !present.has(column)))
|
|
220
|
+
return need.why;
|
|
221
|
+
}
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
201
224
|
/** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
|
|
202
225
|
* store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
|
|
203
226
|
* disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
|
|
204
227
|
* (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. The store is read before
|
|
205
228
|
* this server holds its owner lock, so it waits `busyTimeoutMs` for another process's lock on it (isThisVersionsStore). */
|
|
206
|
-
function earlierVersionIn(dataDir, busyTimeoutMs) {
|
|
229
|
+
export function earlierVersionIn(dataDir, busyTimeoutMs) {
|
|
207
230
|
if (!existsSync(dataDir))
|
|
208
231
|
return [];
|
|
209
232
|
const found = [];
|
|
@@ -329,6 +352,13 @@ export async function openSqliteStore(options) {
|
|
|
329
352
|
if (found !== SCHEMA_VERSION && !upgrading)
|
|
330
353
|
throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
|
|
331
354
|
const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
|
|
355
|
+
// Every column a runner of this build needs that an earlier build of this version may lack (SQLITE_RUNNER_NEEDS), read
|
|
356
|
+
// at once: the same list store-schema reports from. Each check below says the same, where the server adds it.
|
|
357
|
+
if (role === "runner") {
|
|
358
|
+
const waits = await runnerWaitsFor(async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name)));
|
|
359
|
+
if (waits !== undefined)
|
|
360
|
+
throw new StoreAwaitsServer(waits);
|
|
361
|
+
}
|
|
332
362
|
if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
|
|
333
363
|
throw new StoreAwaitsServer("install MCP and Monid revision metadata");
|
|
334
364
|
const nativeOwners = (await connection.all("PRAGMA table_info(settings)")).some(column => column.name === 'connector_id');
|
|
@@ -363,9 +393,15 @@ export async function openSqliteStore(options) {
|
|
|
363
393
|
// An earlier build of version 13 kept each runner's relay in a table of its own (runner_relays), which the server's
|
|
364
394
|
// open below drops for runners (schema.ts RUNNERS). A runner says it is there, and where its relay answers, through
|
|
365
395
|
// runners alone, so it waits for that server.
|
|
366
|
-
|
|
396
|
+
const runnerColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
|
|
397
|
+
if (role === "runner" && !runnerColumns.has("host")) {
|
|
367
398
|
throw new StoreAwaitsServer("keep each runner's word that it is there and its relay in one table (runners)");
|
|
368
399
|
}
|
|
400
|
+
// An earlier build of this version kept no runner's version and slots (schema.ts RUNNERS_ADDED) and no hand-backs
|
|
401
|
+
// (HAND_BACKS): a runner writes both (its presence, its releases), so it waits for the server that adds them below.
|
|
402
|
+
if (role === "runner" && (Object.keys(RUNNERS_ADDED).some((column) => !runnerColumns.has(column)) || (await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'hand_backs'")).length === 0)) {
|
|
403
|
+
throw new StoreAwaitsServer("keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)");
|
|
404
|
+
}
|
|
369
405
|
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
370
406
|
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
371
407
|
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
@@ -393,6 +429,10 @@ export async function openSqliteStore(options) {
|
|
|
393
429
|
// dropped, its rows heartbeats that each relay's runner writes again within its renewal, so none is copied.
|
|
394
430
|
{ sql: "DROP TABLE IF EXISTS runner_relays" },
|
|
395
431
|
{ sql: RUNNERS },
|
|
432
|
+
// Nor any hand-back (schema.ts HAND_BACKS): a release before it kept none.
|
|
433
|
+
{ sql: HAND_BACKS },
|
|
434
|
+
{ sql: HAND_BACKS_AT },
|
|
435
|
+
{ sql: HAND_BACKS_RUN },
|
|
396
436
|
// Nor any computer a run made (schema.ts COMPUTER_INTERVALS): a computer made before it has no row.
|
|
397
437
|
{ sql: COMPUTER_INTERVALS },
|
|
398
438
|
{ sql: COMPUTER_INTERVALS_RUN },
|
|
@@ -404,6 +444,12 @@ export async function openSqliteStore(options) {
|
|
|
404
444
|
const missing = Object.entries(COMPUTER_INTERVALS_ADDED).filter(([column]) => !intervalColumns.has(column)).map(([, sql]) => ({ sql }));
|
|
405
445
|
if (missing.length > 0)
|
|
406
446
|
await connection.write(missing, { full: true });
|
|
447
|
+
// A runners table an earlier build of this version made has no version or slots (schema.ts RUNNERS_ADDED): each added
|
|
448
|
+
// where missing, every row's unknown (null) until its runner's next put.
|
|
449
|
+
const runnersNow = new Set((await connection.all("SELECT name FROM pragma_table_info('runners')")).map((column) => column.name));
|
|
450
|
+
const runnersMissing = Object.entries(RUNNERS_ADDED).filter(([column]) => !runnersNow.has(column)).map(([, sql]) => ({ sql }));
|
|
451
|
+
if (runnersMissing.length > 0)
|
|
452
|
+
await connection.write(runnersMissing, { full: true });
|
|
407
453
|
await backfillNativeCommandOwners(connection);
|
|
408
454
|
if (found === 11) {
|
|
409
455
|
const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
|
|
@@ -423,7 +469,14 @@ export async function openSqliteStore(options) {
|
|
|
423
469
|
await connection.close().catch(() => undefined);
|
|
424
470
|
throw error;
|
|
425
471
|
}
|
|
426
|
-
|
|
472
|
+
const store = storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
|
|
473
|
+
// A SQLite runner opens only its own version (the server upgrades the file in place at its start, never beside a
|
|
474
|
+
// runner on another build): its floor is the version itself.
|
|
475
|
+
const schemaState = async () => {
|
|
476
|
+
const version = await versionOf(connection);
|
|
477
|
+
return { version, runnerFloor: version, known: SCHEMA_VERSION };
|
|
478
|
+
};
|
|
479
|
+
return Object.assign(store, { schemaState });
|
|
427
480
|
}
|
|
428
481
|
/** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
|
|
429
482
|
const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
|
|
@@ -506,6 +559,7 @@ async function dropRunContent(tx, runId) {
|
|
|
506
559
|
await tx.run("DELETE FROM channel_told WHERE run_id = ?", runId);
|
|
507
560
|
await tx.run("DELETE FROM trigger_conversations WHERE run_id = ?", runId);
|
|
508
561
|
await tx.run("DELETE FROM run_changes WHERE run_id = ?", runId);
|
|
562
|
+
await tx.run("DELETE FROM hand_backs WHERE run_id = ?", runId);
|
|
509
563
|
}
|
|
510
564
|
/** An agent's own rows no tombstone keeps (its learning, its saved sign-ins and their tombstones), gone: what an agent's
|
|
511
565
|
* purge (Agents.purge) and its delete (Agents.remove) both drop. */
|
|
@@ -1137,6 +1191,7 @@ class SqliteStore {
|
|
|
1137
1191
|
return row && runOf(row);
|
|
1138
1192
|
},
|
|
1139
1193
|
launch: (runId) => readLaunch(db, runId),
|
|
1194
|
+
usageMetadata: (runId, options) => readUsageMetadata(db, runId, options),
|
|
1140
1195
|
learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
|
|
1141
1196
|
list: async ({ agentId, revisionId, state, archived, labels, limit, purged = false }) => {
|
|
1142
1197
|
// 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,
|
|
@@ -1896,9 +1951,9 @@ class SqliteStore {
|
|
|
1896
1951
|
};
|
|
1897
1952
|
// Stamped and judged on the deadlines' clock (fence.ts storeNow: the database's on Postgres), the one a claim's lease
|
|
1898
1953
|
// runs on, so a runner on another host whose own clock is behind the server's never reads as gone (nor its relay).
|
|
1899
|
-
const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at FROM runners";
|
|
1954
|
+
const RUNNERS_SELECT = "SELECT runner, incarnation, refused, host, port, seen_at, version, slots FROM runners";
|
|
1900
1955
|
this.runners = {
|
|
1901
|
-
put: async ({ runner, incarnation, refused, host = null, port = null }, { unlessLiveMs } = {}) => {
|
|
1956
|
+
put: async ({ runner, incarnation, refused, host = null, port = null, version = null, slots = null }, { unlessLiveMs } = {}) => {
|
|
1902
1957
|
const n = clock();
|
|
1903
1958
|
// With unlessLiveMs, the upsert's WHERE leaves a row another incarnation renewed within it as it is, in the same
|
|
1904
1959
|
// statement: no read between, so a later process's put can never land between a look and this write.
|
|
@@ -1906,8 +1961,8 @@ class SqliteStore {
|
|
|
1906
1961
|
const [, result] = await db.write([
|
|
1907
1962
|
{ sql: `DELETE FROM runners WHERE seen_at < ${n.sql} - ${d.bigintParam}`, params: [...n.params, RUNNER_ROWS_KEPT_MS] },
|
|
1908
1963
|
{
|
|
1909
|
-
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}`,
|
|
1910
|
-
params: [runner, incarnation, refused, host, port, ...n.params, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
|
|
1964
|
+
sql: `INSERT INTO runners (runner, incarnation, refused, host, port, seen_at, version, slots) 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, version = excluded.version, slots = excluded.slots${unlessLive}`,
|
|
1965
|
+
params: [runner, incarnation, refused, host, port, ...n.params, version, slots, ...(unlessLiveMs === undefined ? [] : [unlessLiveMs])],
|
|
1911
1966
|
},
|
|
1912
1967
|
]);
|
|
1913
1968
|
return (result?.changes ?? 0) === 1;
|
|
@@ -1925,6 +1980,22 @@ class SqliteStore {
|
|
|
1925
1980
|
remove: async (runner, incarnation) => {
|
|
1926
1981
|
await db.write([{ sql: "DELETE FROM runners WHERE runner = ? AND incarnation = ?", params: [runner, incarnation] }]);
|
|
1927
1982
|
},
|
|
1983
|
+
capacity: async (windowMs) => {
|
|
1984
|
+
// One read snapshot (Postgres: REPEATABLE READ READ ONLY; SQLite: one read transaction), so a claim or a release
|
|
1985
|
+
// that lands meanwhile never counts a run as both waiting and held, or as neither. The deadlines' clock is read
|
|
1986
|
+
// once in it, then bound into every count, so the counts judge one "now".
|
|
1987
|
+
return db.transaction(async (tx) => {
|
|
1988
|
+
const now = clock();
|
|
1989
|
+
const [read] = await tx.all(`SELECT ${now.sql} AS at`, ...now.params);
|
|
1990
|
+
const at = Number(read.at);
|
|
1991
|
+
const n = { sql: d.bigintParam, params: [at] };
|
|
1992
|
+
const claimable = claimableIn(d, n);
|
|
1993
|
+
const [queued] = await tx.all(`SELECT count(*) AS count FROM runs WHERE ${claimable.sql}`, ...claimable.params);
|
|
1994
|
+
const held = await tx.all(`SELECT runner, count(*) AS count FROM runs WHERE state IN ('running', 'parked') AND runner IS NOT NULL AND claimed_until >= ${n.sql} GROUP BY runner ORDER BY runner`, ...n.params);
|
|
1995
|
+
const [handBacks] = await tx.all(`SELECT count(*) AS count FROM hand_backs WHERE at >= ${n.sql} - ${d.bigintParam}`, ...n.params, windowMs);
|
|
1996
|
+
return { at, queued: Number(queued?.count ?? 0), held: new Map(held.map((row) => [row.runner, Number(row.count)])), handBacks: Number(handBacks?.count ?? 0) };
|
|
1997
|
+
}, { read: true });
|
|
1998
|
+
},
|
|
1928
1999
|
};
|
|
1929
2000
|
this.importedTemplates = {
|
|
1930
2001
|
list: async () => (await db.all("SELECT id, source, sha, publisher, files, imported_at FROM imported_templates ORDER BY id")).map((row) => ({
|
|
@@ -2311,6 +2382,12 @@ class SqliteStore {
|
|
|
2311
2382
|
// never live until the next claim. A claim whose lease ran out releases nothing: the run, running with its lease run
|
|
2312
2383
|
// out, is claimable at once, never stuck.
|
|
2313
2384
|
`UPDATE runs SET epoch = epoch + 1, runner = NULL, claimed_until = NULL, wake_at = ?, backoff_until = ?, state = coalesce(?, state)${leaving ? `, left_running_at = ${now.sql}` : ""} WHERE ${fence.where} AND runner = ?`, [wakeAt, backoffUntil, state ?? null, ...(leaving ? now.params : []), ...fence.params, claim.runner]));
|
|
2385
|
+
// A release that leaves the run running is a hand-back (schema.ts HAND_BACKS): kept in this same write for the
|
|
2386
|
+
// capacity read, with the rows past HAND_BACKS_KEPT_MS removed. A park, or a release of a parked run, is none.
|
|
2387
|
+
if ((state ?? final?.state) === "running") {
|
|
2388
|
+
await tx.run(`DELETE FROM hand_backs WHERE at < ${now.sql} - ${this.#db.dialect.bigintParam}`, ...now.params, HAND_BACKS_KEPT_MS);
|
|
2389
|
+
await tx.run(`INSERT INTO hand_backs (run_id, runner, epoch, at) VALUES (?, ?, ?, ${now.sql})`, claim.runId, claim.runner, claim.epoch, ...now.params);
|
|
2390
|
+
}
|
|
2314
2391
|
}, { full: true });
|
|
2315
2392
|
// The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
|
|
2316
2393
|
this.#journals.delete(journalKey(claim));
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type SchemaState } from "./postgres/migrate.js";
|
|
2
|
+
import { type StoreTarget } from "./open.js";
|
|
3
|
+
/** The line `agentrun-serve store-schema` prints. */
|
|
4
|
+
export interface StoreSchemaReport {
|
|
5
|
+
readonly store: StoreTarget["kind"];
|
|
6
|
+
/** Where the store is, in words: the SQLite file, or the Postgres schema (never its URL). */
|
|
7
|
+
readonly where: string;
|
|
8
|
+
readonly schema: number | null;
|
|
9
|
+
readonly runnerFloor: number | null;
|
|
10
|
+
readonly build: number;
|
|
11
|
+
readonly server: "sets up" | "opens" | "migrates" | "refuses";
|
|
12
|
+
readonly runner: "opens" | "waits" | "refused";
|
|
13
|
+
}
|
|
14
|
+
/** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
|
|
15
|
+
* version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
|
|
16
|
+
* on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
|
|
17
|
+
* its server adds at its start: the runner waits for it, as openSqliteStore makes it. */
|
|
18
|
+
export declare function storeSchemaReport(target: StoreTarget, state: SchemaState, build: number, earlier?: boolean, awaits?: boolean): StoreSchemaReport;
|
|
19
|
+
/** How long the read waits on Postgres (ms): for a lock (a server migrating holds the ledger's), for its one statement, and
|
|
20
|
+
* for any answer at all (a database that took the connection and went silent). Past one, the read fails: exit 1. */
|
|
21
|
+
export declare const STORE_SCHEMA_LOCK_MS = 2000;
|
|
22
|
+
export declare const STORE_SCHEMA_STATEMENT_MS = 5000;
|
|
23
|
+
export declare const STORE_SCHEMA_ANSWER_MS = 6000;
|
|
24
|
+
/** Reads the store `dataDir` and `env` name (and the URL, this process's AGENTRUN_STORE_URL secret unless given). */
|
|
25
|
+
export declare function readStoreSchema(dataDir: string, env?: NodeJS.ProcessEnv, url?: string): Promise<StoreSchemaReport>;
|
|
26
|
+
/** The versions this build knows, read from its own files, with no store: `postgres`, its newest migration; `sqlite`,
|
|
27
|
+
* SCHEMA_VERSION. */
|
|
28
|
+
export declare const buildSchema: () => {
|
|
29
|
+
readonly postgres: number;
|
|
30
|
+
readonly sqlite: number;
|
|
31
|
+
};
|
|
32
|
+
/** `agentrun-serve store-schema [--data DIR]`, or `--build` (this build's versions, no store read): the exit code (the
|
|
33
|
+
* file's head). */
|
|
34
|
+
export declare function storeSchemaMain(argv: readonly string[], defaultDataDir: string, usage: string): Promise<number>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// `agentrun-serve store-schema [--data DIR]`: the live store's schema version and runner floor, beside the version this
|
|
2
|
+
// build knows, as one line of JSON, for a deploy pipeline's skew guard. It reads, and nothing else: no owner lock, no
|
|
3
|
+
// migration, no schema made, no runner presence. The store is the one the server and a runner open (store/open.ts:
|
|
4
|
+
// Postgres when AGENTRUN_STORE_URL names one, in AGENTRUN_STORE_SCHEMA; else SQLite in --data), and its URL is never
|
|
5
|
+
// printed. Exit 0 once read (whatever it says), 1 when the store could not be read, 2 for bad arguments. `--build` reads no
|
|
6
|
+
// store: it prints the versions this build knows, `{"build":{"postgres":N,"sqlite":M}}`, for a label an image build stamps.
|
|
7
|
+
//
|
|
8
|
+
// What the line says, run with the build about to be deployed:
|
|
9
|
+
// schema the store's version now (null: none set up yet)
|
|
10
|
+
// runnerFloor the oldest version a runner's build must know to run on it (null: none set up yet)
|
|
11
|
+
// build the version this build knows
|
|
12
|
+
// server what this build's server does at its start: "sets up", "opens", "migrates", or "refuses" (the store is
|
|
13
|
+
// ahead of this build: a rollback across a migration, which the skew guard refuses)
|
|
14
|
+
// runner what this build's runner does: "opens", "waits" (for the server to migrate), or "refused" (none set up,
|
|
15
|
+
// or the floor is above this build)
|
|
16
|
+
import { existsSync } from "node:fs";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { DatabaseSync } from "node:sqlite";
|
|
19
|
+
import { parseArgs } from "node:util";
|
|
20
|
+
import { migrationsIn, runnerFloorOf, runnerOn } from "./postgres/migrate.js";
|
|
21
|
+
import { STORE_CONNECT_TIMEOUT_MS } from "./postgres/connection.js";
|
|
22
|
+
import { storePlace, storeTarget } from "./open.js";
|
|
23
|
+
import { SCHEMA_VERSION } from "./schema.js";
|
|
24
|
+
import { earlierVersionIn, runnerWaitsFor, STORE_FILE } from "./sqlite/store.js";
|
|
25
|
+
/** The SQLite store's versions the server upgrades in place (sqlite/store.ts openSqliteStore). */
|
|
26
|
+
const SQLITE_UPGRADES = new Set([11, 12, 13]);
|
|
27
|
+
/** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
|
|
28
|
+
* version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
|
|
29
|
+
* on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
|
|
30
|
+
* its server adds at its start: the runner waits for it, as openSqliteStore makes it. */
|
|
31
|
+
export function storeSchemaReport(target, state, build, earlier = false, awaits = false) {
|
|
32
|
+
const { version } = state;
|
|
33
|
+
const server = earlier
|
|
34
|
+
? "refuses"
|
|
35
|
+
: version === null ? "sets up" : version === build ? "opens" : version > build ? "refuses" : target.kind === "postgres" || SQLITE_UPGRADES.has(version) ? "migrates" : "refuses";
|
|
36
|
+
// A SQLite runner opens only its own version: its floor is the version (sqlite/store.ts schemaState).
|
|
37
|
+
// On SQLite a runner waits only for a version its server upgrades in place (11-13), and refuses any other earlier one.
|
|
38
|
+
const runner = target.kind === "sqlite" && version !== null && version < build && !SQLITE_UPGRADES.has(version)
|
|
39
|
+
? "refused"
|
|
40
|
+
: awaits && version === build ? "waits" : runnerOn(target.kind === "sqlite" ? { version, runnerFloor: version } : state, build);
|
|
41
|
+
return { store: target.kind, where: storePlace(target), schema: version, runnerFloor: state.runnerFloor, build, server, runner };
|
|
42
|
+
}
|
|
43
|
+
/** The SQLite store's version in `dataDir`, read-only: null when there is no file, or no schema in it; and whether a
|
|
44
|
+
* runner of this build would wait for its server to add a column (SQLITE_RUNNER_NEEDS). */
|
|
45
|
+
async function sqliteState(dataDir) {
|
|
46
|
+
const file = join(dataDir, STORE_FILE);
|
|
47
|
+
if (!existsSync(file))
|
|
48
|
+
return { version: null, runnerFloor: null, awaits: false };
|
|
49
|
+
const db = new DatabaseSync(file, { readOnly: true, timeout: 5_000 });
|
|
50
|
+
try {
|
|
51
|
+
const table = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'store_meta'").get();
|
|
52
|
+
const row = table ? db.prepare("SELECT schema_version FROM store_meta WHERE singleton = 1").get() : undefined;
|
|
53
|
+
const version = row?.schema_version ?? null;
|
|
54
|
+
const columnsOf = (name) => new Set(db.prepare("SELECT name FROM pragma_table_info(?)").all(name).map((column) => column.name));
|
|
55
|
+
const awaits = version !== null && (await runnerWaitsFor(columnsOf)) !== undefined;
|
|
56
|
+
return { version, runnerFloor: version, awaits };
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
db.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** How long the read waits on Postgres (ms): for a lock (a server migrating holds the ledger's), for its one statement, and
|
|
63
|
+
* for any answer at all (a database that took the connection and went silent). Past one, the read fails: exit 1. */
|
|
64
|
+
export const STORE_SCHEMA_LOCK_MS = 2_000;
|
|
65
|
+
export const STORE_SCHEMA_STATEMENT_MS = 5_000;
|
|
66
|
+
export const STORE_SCHEMA_ANSWER_MS = 6_000;
|
|
67
|
+
/** The Postgres schema's version and floor, on a connection of its own that writes nothing and is ended at once. Its
|
|
68
|
+
* session's timeouts bound it: a deploy check never waits on a server's migration or on a silent database. */
|
|
69
|
+
async function postgresState(url, schema) {
|
|
70
|
+
const { default: pg } = await import("pg");
|
|
71
|
+
const client = new pg.Client({
|
|
72
|
+
connectionString: url,
|
|
73
|
+
connectionTimeoutMillis: STORE_CONNECT_TIMEOUT_MS,
|
|
74
|
+
lock_timeout: STORE_SCHEMA_LOCK_MS,
|
|
75
|
+
statement_timeout: STORE_SCHEMA_STATEMENT_MS,
|
|
76
|
+
query_timeout: STORE_SCHEMA_ANSWER_MS,
|
|
77
|
+
application_name: "agentrun-store-schema",
|
|
78
|
+
});
|
|
79
|
+
client.on("error", () => undefined);
|
|
80
|
+
await client.connect();
|
|
81
|
+
try {
|
|
82
|
+
return await runnerFloorOf(client, schema);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
await client.end().catch(() => undefined);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** Reads the store `dataDir` and `env` name (and the URL, this process's AGENTRUN_STORE_URL secret unless given). */
|
|
89
|
+
export async function readStoreSchema(dataDir, env = process.env, url) {
|
|
90
|
+
const target = url === undefined ? storeTarget(dataDir, env) : storeTarget(dataDir, env, url);
|
|
91
|
+
if (target.kind === "sqlite") {
|
|
92
|
+
const { awaits, ...state } = await sqliteState(dataDir);
|
|
93
|
+
return storeSchemaReport(target, state, SCHEMA_VERSION, earlierVersionIn(dataDir, 5_000).length > 0, awaits);
|
|
94
|
+
}
|
|
95
|
+
return storeSchemaReport(target, await postgresState(target.url, target.schema), migrationsIn().at(-1).version);
|
|
96
|
+
}
|
|
97
|
+
/** The versions this build knows, read from its own files, with no store: `postgres`, its newest migration; `sqlite`,
|
|
98
|
+
* SCHEMA_VERSION. */
|
|
99
|
+
export const buildSchema = () => ({ postgres: migrationsIn().at(-1).version, sqlite: SCHEMA_VERSION });
|
|
100
|
+
/** `agentrun-serve store-schema [--data DIR]`, or `--build` (this build's versions, no store read): the exit code (the
|
|
101
|
+
* file's head). */
|
|
102
|
+
export async function storeSchemaMain(argv, defaultDataDir, usage) {
|
|
103
|
+
let data;
|
|
104
|
+
let build;
|
|
105
|
+
try {
|
|
106
|
+
({ data, build } = parseArgs({ args: [...argv], options: { data: { type: "string" }, build: { type: "boolean" } } }).values);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
console.error(`agentrun-serve store-schema: ${error.message}\n\n${usage}`);
|
|
110
|
+
return 2;
|
|
111
|
+
}
|
|
112
|
+
if (build) {
|
|
113
|
+
console.log(JSON.stringify({ build: buildSchema() }));
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
console.log(JSON.stringify(await readStoreSchema(data ?? defaultDataDir)));
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
// Never the URL: a connection error's own words name the host at most.
|
|
122
|
+
console.error(`agentrun-serve store-schema: the store could not be read: ${error?.message ?? String(error)}`);
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
}
|