@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41
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 +114 -0
- package/README.md +129 -16
- package/dist/api-only.d.ts +3 -1
- package/dist/api-only.js +4 -2
- package/dist/api-token.d.ts +30 -0
- package/dist/api-token.js +89 -0
- package/dist/cli.js +19 -5
- package/dist/composio-made.d.ts +54 -0
- package/dist/composio-made.js +83 -0
- package/dist/composio-preset.d.ts +16 -8
- package/dist/composio-preset.js +106 -43
- package/dist/composio-triggers.d.ts +7 -2
- package/dist/composio-triggers.js +13 -7
- package/dist/computer-attach.d.ts +29 -11
- package/dist/computer-attach.js +141 -47
- package/dist/computer-keys.d.ts +4 -0
- package/dist/computer-keys.js +5 -0
- package/dist/computers.d.ts +11 -1
- package/dist/computers.js +21 -12
- package/dist/console/assets/index-C3gNPz58.css +1 -0
- package/dist/console/assets/index-COGhx_2Z.js +711 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +9 -2
- package/dist/email/account.d.ts +0 -1
- package/dist/email/account.js +3 -3
- package/dist/email/answer.d.ts +5 -0
- package/dist/email/answer.js +35 -0
- package/dist/email/mail.js +19 -26
- package/dist/email/names.d.ts +30 -0
- package/dist/email/names.js +34 -0
- package/dist/email/routes.d.ts +1 -0
- package/dist/email/routes.js +1 -1
- package/dist/email/tools.d.ts +11 -4
- package/dist/email/tools.js +91 -46
- package/dist/eval-feed.d.ts +26 -0
- package/dist/eval-feed.js +68 -0
- package/dist/eval-mailbox.d.ts +5 -2
- package/dist/eval-mailbox.js +14 -6
- package/dist/exa-keyless.d.ts +1 -1
- package/dist/exa-keyless.js +1 -1
- package/dist/feed/feed-faux.d.ts +62 -0
- package/dist/feed/feed-faux.js +123 -0
- package/dist/feed/fetch.d.ts +41 -0
- package/dist/feed/fetch.js +128 -0
- package/dist/feed/parse.d.ts +41 -0
- package/dist/feed/parse.js +300 -0
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +57 -2
- package/dist/learn/compile.d.ts +3 -2
- package/dist/learn/compile.js +7 -6
- package/dist/learn/promote.d.ts +25 -14
- package/dist/learn/promote.js +32 -14
- package/dist/learned-nodes.d.ts +21 -4
- package/dist/learned-nodes.js +21 -8
- package/dist/learned-workflow.d.ts +3 -3
- package/dist/learned-workflow.js +14 -5
- package/dist/learning-cost.d.ts +17 -8
- package/dist/learning-cost.js +12 -4
- package/dist/local-models.d.ts +7 -1
- package/dist/local-models.js +11 -5
- package/dist/mcp-oauth.d.ts +15 -1
- package/dist/mcp-oauth.js +39 -5
- package/dist/mcp-pin-first.d.ts +4 -2
- package/dist/mcp-pin-first.js +4 -3
- package/dist/mcp-servers-store.d.ts +58 -5
- package/dist/mcp-servers-store.js +136 -17
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/observation/http.d.ts +4 -1
- package/dist/observation/http.js +5 -4
- package/dist/openapi.d.ts +1 -1
- package/dist/openapi.js +63 -27
- package/dist/port-models.d.ts +4 -1
- package/dist/port-models.js +1 -0
- package/dist/print.d.ts +6 -3
- package/dist/print.js +4 -2
- package/dist/refusal-words.d.ts +3 -0
- package/dist/refusal-words.js +3 -0
- package/dist/run-labels.d.ts +23 -0
- package/dist/run-labels.js +79 -0
- package/dist/run-launch.d.ts +2 -0
- package/dist/run-launch.js +2 -0
- package/dist/run-secrets.js +12 -4
- package/dist/run-view.d.ts +3 -4
- package/dist/run-view.js +26 -24
- package/dist/runner/adapter-loop.d.ts +6 -2
- package/dist/runner/adapter-loop.js +136 -22
- package/dist/runner/adapter-run-spec.d.ts +5 -0
- package/dist/runner/adapter-run-spec.js +75 -32
- package/dist/runner/beside.d.ts +6 -3
- package/dist/runner/beside.js +9 -7
- package/dist/runner/cli-run-spec.js +33 -26
- package/dist/runner/conformance/harness.js +69 -14
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/journal-kinds.d.ts +22 -0
- package/dist/runner/journal-kinds.js +39 -0
- package/dist/runner/main.d.ts +1 -1
- package/dist/runner/main.js +2 -2
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +4 -0
- package/dist/runner/mcp-run.js +5 -3
- package/dist/runner/model-route.d.ts +7 -3
- package/dist/runner/model-route.js +24 -9
- package/dist/runner/promotion.d.ts +16 -8
- package/dist/runner/promotion.js +178 -55
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +9 -7
- package/dist/runs-over-store.js +5 -2
- package/dist/sdk/runs.d.ts +7 -1
- package/dist/sdk/runs.js +19 -6
- package/dist/secret-cut.js +3 -1
- package/dist/secrets.js +3 -1
- package/dist/server.d.ts +27 -2
- package/dist/server.js +181 -56
- package/dist/store/dialect.d.ts +6 -0
- package/dist/store/dialect.js +2 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/postgres/connection.d.ts +11 -5
- package/dist/store/postgres/connection.js +44 -17
- package/dist/store/postgres/dialect.js +6 -0
- package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
- package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
- package/dist/store/postgres/store.d.ts +7 -3
- package/dist/store/postgres/store.js +1 -0
- package/dist/store/schema.d.ts +9 -0
- package/dist/store/schema.js +26 -2
- package/dist/store/sqlite/connection.js +80 -8
- package/dist/store/sqlite/run-launch.d.ts +11 -0
- package/dist/store/sqlite/run-launch.js +8 -0
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +3 -2
- package/dist/store/sqlite/store.js +101 -26
- package/dist/store/sqlite/worker.d.ts +2 -0
- package/dist/store/sqlite/worker.js +13 -10
- package/dist/store/store.d.ts +53 -1
- package/dist/store-reads/journal.js +2 -1
- package/dist/store-reads/learning.d.ts +30 -13
- package/dist/store-reads/learning.js +130 -51
- package/dist/store-reads/runs.d.ts +4 -3
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +4 -2
- package/dist/template-eval.d.ts +4 -0
- package/dist/template-eval.js +127 -50
- package/dist/templates.d.ts +24 -1
- package/dist/templates.js +129 -21
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/tool-gate.d.ts +5 -3
- package/dist/tool-gate.js +5 -2
- package/dist/tools.d.ts +13 -0
- package/dist/tools.js +15 -10
- package/dist/trigger-adapter.d.ts +12 -36
- package/dist/trigger-adapters.js +2 -1
- package/dist/trigger-email.js +30 -77
- package/dist/trigger-feed.d.ts +12 -0
- package/dist/trigger-feed.js +371 -0
- package/dist/triggers.d.ts +27 -14
- package/dist/triggers.js +121 -80
- package/dist/webhooks.js +9 -5
- package/dist/workflow/decision-recovery.js +5 -2
- package/dist/workflow/decisions.d.ts +7 -0
- package/dist/workspace/computer-deps.d.ts +5 -1
- package/dist/workspace/computer-deps.js +2 -2
- package/dist/workspace/index.d.ts +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/resolve-computer.d.ts +32 -3
- package/dist/workspace/resolve-computer.js +47 -9
- package/launcher/agentrun-serve +6 -1
- package/package.json +10 -9
- package/templates/README.md +27 -2
- package/dist/console/assets/index-BNhZs-jp.css +0 -1
- package/dist/console/assets/index-BQv5aOGB.js +0 -700
package/dist/store/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { AgentArchived, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull } from "./store.js";
|
|
2
|
-
export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
|
|
2
|
+
export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
|
|
3
3
|
export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunMcpAuth, type RunMcpAuth, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.js";
|
|
4
4
|
export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
|
|
5
5
|
export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
|
|
@@ -30,12 +30,18 @@ export interface PgConnectionOptions {
|
|
|
30
30
|
readonly poolSize?: number;
|
|
31
31
|
/** Deadlines on the store's own (test) clock, bound as parameters, instead of the database's (postgresDialect). */
|
|
32
32
|
readonly testClock?: boolean;
|
|
33
|
-
/** How long
|
|
34
|
-
*
|
|
35
|
-
*
|
|
33
|
+
/** How long a new connection's connect and startup may take (STORE_CONNECT_TIMEOUT_MS by default). Past it the call is
|
|
34
|
+
* refused (StoreDeadline, naming the database's place, never its URL, in words that say it does not answer), never left
|
|
35
|
+
* hanging on a database that does not answer. */
|
|
36
36
|
readonly connectTimeoutMs?: number;
|
|
37
|
+
/** How long a call may wait for one of the pool's connections to come free while every one is in use
|
|
38
|
+
* (STORE_WRITE_DEADLINE_MS by default, and never less than connectTimeoutMs): a busy pool is waited out to a write's own
|
|
39
|
+
* deadline, never failed at the connect timeout. Past it the call is refused (StoreDeadline, in words that say every
|
|
40
|
+
* connection stayed in use), nothing of it sent. */
|
|
41
|
+
readonly poolWaitMs?: number;
|
|
37
42
|
}
|
|
38
|
-
/** The default bound on
|
|
43
|
+
/** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
|
|
44
|
+
* in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
|
|
39
45
|
* the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
|
|
40
46
|
* landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
|
|
41
47
|
* renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
|
|
@@ -70,7 +76,7 @@ export declare class PgConnection implements StoreConnection {
|
|
|
70
76
|
readonly where: string;
|
|
71
77
|
private constructor();
|
|
72
78
|
/** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
|
|
73
|
-
static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
|
|
79
|
+
static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, poolWaitMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
|
|
74
80
|
get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
|
|
75
81
|
all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
|
|
76
82
|
/** One statement on its own (autocommit), its changes counted: the shared code's run outside a transaction. */
|
|
@@ -8,7 +8,7 @@ import pg from "pg";
|
|
|
8
8
|
import { runnableDeadline } from "../deadline.js";
|
|
9
9
|
import { cleanText } from "../dialect.js";
|
|
10
10
|
import { ONE_ANSWER_INDEX } from "../schema.js";
|
|
11
|
-
import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned } from "../store.js";
|
|
11
|
+
import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, STORE_WRITE_DEADLINE_MS } from "../store.js";
|
|
12
12
|
import { DEFAULT_TRANSACTION_DEADLINE_MS } from "../sqlite/connection.js";
|
|
13
13
|
import { postgresDialect } from "./dialect.js";
|
|
14
14
|
/** Which store this is, as two opens of the same data agree on it (StoreConnection.where): "postgres:" and the URL's host
|
|
@@ -26,7 +26,8 @@ export function postgresWhere(url, schema) {
|
|
|
26
26
|
}
|
|
27
27
|
/** A schema name the store takes: a plain lower-case identifier, so it is never quoted, and never input in SQL. */
|
|
28
28
|
export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
29
|
-
/** The default bound on
|
|
29
|
+
/** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
|
|
30
|
+
* in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
|
|
30
31
|
* the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
|
|
31
32
|
* landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
|
|
32
33
|
* renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
|
|
@@ -34,17 +35,20 @@ export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
|
34
35
|
* renew, connect to commit, is bounded from its call (LEASE_DEADLINE_MS), so one sent at +10 s whose connection went
|
|
35
36
|
* silent fails by +19 s and the +20 s tick renews on a fresh connection before +25 s. */
|
|
36
37
|
export const STORE_CONNECT_TIMEOUT_MS = 4_000;
|
|
37
|
-
/** pg's and pg-pool's words for a connection
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
/** pg's and pg-pool's words for a new connection's connect or startup that never finished in time. */
|
|
39
|
+
const CONNECT_TIMEOUT = /timeout expired|Connection terminated due to connection timeout/i;
|
|
40
|
+
/** pg-pool's words for a wait in its queue that no client came free for in time (every one in use). */
|
|
41
|
+
const POOL_WAIT_TIMEOUT = /timeout exceeded when trying to connect/i;
|
|
42
|
+
/** Whether `error`, or an error it was made from, says `words`. */
|
|
43
|
+
function says(error, words) {
|
|
42
44
|
for (let e = error, depth = 0; e && depth < 5; e = e.cause, depth++) {
|
|
43
|
-
if (
|
|
45
|
+
if (words.test(String(e.message ?? "")))
|
|
44
46
|
return true;
|
|
45
47
|
}
|
|
46
48
|
return false;
|
|
47
49
|
}
|
|
50
|
+
/** Whether `error`, or an error it was made from, is a new connection not had in time. */
|
|
51
|
+
const connectTimedOut = (error) => says(error, CONNECT_TIMEOUT);
|
|
48
52
|
/** A COMMIT is bounded by what is left of its transaction's deadline, never less than this (a commit sent at the deadline
|
|
49
53
|
* still gets an answer's time). Past it the connection is taken as silent and let go (destroyed); the commit's outcome is
|
|
50
54
|
* then unknown, and the caller is told so (Unanswered). STORE_WRITE_DEADLINE_MS's users keep 2 s spare for it. */
|
|
@@ -89,9 +93,14 @@ async function answered(query, ms, what) {
|
|
|
89
93
|
async function rollBackAndRelease(client) {
|
|
90
94
|
await answered(client.query("ROLLBACK"), ROLLBACK_ANSWER_MS, "its rollback").then(() => client.release(), (error) => client.release(error));
|
|
91
95
|
}
|
|
92
|
-
/** The refusal for a connection not
|
|
96
|
+
/** The refusal for a new connection not made within `ms` to the database at `where` (postgresWhere: no user or password). */
|
|
93
97
|
function connectDeadline(where, ms) {
|
|
94
|
-
return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer
|
|
98
|
+
return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer`);
|
|
99
|
+
}
|
|
100
|
+
/** The refusal for a call that waited `ms` for one of the `size` connections of the store's pool on the database at
|
|
101
|
+
* `where`, every one of them in use all that time: the store is busier than its pool, and the database answers. */
|
|
102
|
+
function poolBusy(where, ms, size) {
|
|
103
|
+
return new StoreDeadline(ms, `no connection of the store's Postgres at ${where} came free within ${ms} ms: all ${size} of this store's connections stayed in use, so the call was never sent`);
|
|
95
104
|
}
|
|
96
105
|
/** int8 as a JavaScript number: every integer the store keeps (ms, ids, epochs, counts) is one, and one outside the safe
|
|
97
106
|
* range is refused, as node:sqlite refuses it. */
|
|
@@ -277,8 +286,10 @@ export class PgConnection {
|
|
|
277
286
|
/** What taking the owner lock back needs. */
|
|
278
287
|
#ownerConfig;
|
|
279
288
|
#busyTimeoutMs;
|
|
280
|
-
/** The bound on
|
|
289
|
+
/** The bound on a new connection's connect and startup (PgConnectionOptions.connectTimeoutMs). */
|
|
281
290
|
#connectMs;
|
|
291
|
+
/** The bound on a wait for a busy pool's connection to come free (PgConnectionOptions.poolWaitMs), and the pool's size. */
|
|
292
|
+
#poolWait;
|
|
282
293
|
#closed = false;
|
|
283
294
|
/** Set while the owner lock is not held (its connection ended or failed, and it is being taken back), and for good once
|
|
284
295
|
* another server has the schema: every call is refused with it meanwhile. */
|
|
@@ -300,8 +311,9 @@ export class PgConnection {
|
|
|
300
311
|
}
|
|
301
312
|
return columns;
|
|
302
313
|
};
|
|
303
|
-
constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, ownerConfig) {
|
|
314
|
+
constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, poolWait, leasePool, ownerConfig) {
|
|
304
315
|
this.#connectMs = connectMs;
|
|
316
|
+
this.#poolWait = poolWait;
|
|
305
317
|
this.#pool = pool;
|
|
306
318
|
this.#leasePool = leasePool;
|
|
307
319
|
this.#owner = owner;
|
|
@@ -376,20 +388,31 @@ export class PgConnection {
|
|
|
376
388
|
this.#ownerConfig?.onLost?.(error);
|
|
377
389
|
}
|
|
378
390
|
/** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
|
|
379
|
-
static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
|
|
391
|
+
static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, poolWaitMs = STORE_WRITE_DEADLINE_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
|
|
380
392
|
if (!SCHEMA_NAME.test(schema))
|
|
381
393
|
throw new TypeError(`the store's schema is a lower-case name of letters, digits and underscores, not ${JSON.stringify(schema)}`);
|
|
382
394
|
// The database's end of the keepalives (KEEPALIVE_IDLE_S): a vanished client's session, and its locks, ended in ~25 s.
|
|
383
395
|
const keepalives = `-c tcp_keepalives_idle=${KEEPALIVE_IDLE_S} -c tcp_keepalives_interval=5 -c tcp_keepalives_count=3`;
|
|
384
396
|
const session = `-c search_path=${schema} -c lock_timeout=${Math.max(0, Math.floor(busyTimeoutMs))} -c synchronous_commit=on ${keepalives}`;
|
|
385
397
|
const connectMs = Math.max(1, Math.floor(connectTimeoutMs));
|
|
398
|
+
// Never below the connect's bound: pg-pool's one connectionTimeoutMillis also cuts a new client's connect, which must
|
|
399
|
+
// keep its own bound and its own words (StoreClient's).
|
|
400
|
+
const poolWait = Math.max(connectMs, Math.floor(poolWaitMs));
|
|
386
401
|
const where = postgresWhere(url, schema);
|
|
387
|
-
//
|
|
402
|
+
// Two bounds on getting a connection, each in one place. A new connection's connect and startup: connectMs, on the
|
|
403
|
+
// client itself (StoreClient), so a database that does not answer is refused fast. A wait in the pool's queue while
|
|
404
|
+
// every client is in use (a runner's loops' commits behind one another): pg-pool's connectionTimeoutMillis, poolWait,
|
|
405
|
+
// so a busy pool of a database that answers is waited out to a write's own deadline, never failed at connectMs.
|
|
406
|
+
class StoreClient extends pg.Client {
|
|
407
|
+
constructor(config) {
|
|
408
|
+
super({ ...(typeof config === "string" ? { connectionString: config } : config), connectionTimeoutMillis: connectMs });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
388
411
|
// keepAlive: this end's TCP keepalives, from KEEPALIVE_IDLE_S (pg's default delay, 0, is the OS's 2 h).
|
|
389
412
|
const tcp = { keepAlive: true, keepAliveInitialDelayMillis: KEEPALIVE_IDLE_S * 1_000 };
|
|
390
413
|
// Every connection named for its schema, as the lease's and the owner lock's are: pg_stat_activity tells which
|
|
391
414
|
// store holds each one.
|
|
392
|
-
const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, connectionTimeoutMillis:
|
|
415
|
+
const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, Client: StoreClient, connectionTimeoutMillis: poolWait, ...tcp };
|
|
393
416
|
let lock;
|
|
394
417
|
const waitMs = Math.max(0, Math.floor(ownerWaitMs));
|
|
395
418
|
if (owner) {
|
|
@@ -428,7 +451,7 @@ export class PgConnection {
|
|
|
428
451
|
each.on("error", () => undefined);
|
|
429
452
|
each.on("connect", (fresh) => fresh.on("error", () => undefined));
|
|
430
453
|
}
|
|
431
|
-
return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
|
|
454
|
+
return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, { ms: poolWait, size: poolSize }, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
|
|
432
455
|
}
|
|
433
456
|
/** `work`, counted in flight, refused after close. A connection it never got in time is StoreDeadline, naming the
|
|
434
457
|
* database's place. */
|
|
@@ -438,7 +461,11 @@ export class PgConnection {
|
|
|
438
461
|
if (this.#ownerLost)
|
|
439
462
|
return Promise.reject(this.#ownerLost);
|
|
440
463
|
const running = work().catch((error) => {
|
|
441
|
-
|
|
464
|
+
if (connectTimedOut(error))
|
|
465
|
+
throw connectDeadline(this.where, this.#connectMs);
|
|
466
|
+
if (says(error, POOL_WAIT_TIMEOUT))
|
|
467
|
+
throw poolBusy(this.where, this.#poolWait.ms, this.#poolWait.size);
|
|
468
|
+
throw error;
|
|
442
469
|
});
|
|
443
470
|
this.#inFlight.add(running);
|
|
444
471
|
const done = () => void this.#inFlight.delete(running);
|
|
@@ -12,6 +12,7 @@ export function postgresDialect(schema, { testClock = false } = {}) {
|
|
|
12
12
|
// SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
|
|
13
13
|
jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
|
|
14
14
|
jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
|
|
15
|
+
jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each_text(${column}::json) AS entry(key, value) WHERE entry.key = ? AND entry.value = ?)`,
|
|
15
16
|
jsonArrayLength: (column) => `json_array_length(${column}::json)`,
|
|
16
17
|
// Through jsonb, the one place: a body that loses a key is never read for its key order. Every Postgres JSON function
|
|
17
18
|
// decodes the whole document's strings, so a body holding a string jsonb refuses (an escaped NUL, a lone surrogate)
|
|
@@ -36,6 +37,11 @@ export function postgresDialect(schema, { testClock = false } = {}) {
|
|
|
36
37
|
lockRow: async (tx, table, column, value, mode) => {
|
|
37
38
|
await tx.run(`SELECT 1 FROM ${table} WHERE ${column} = ? FOR ${mode === "update" ? "UPDATE" : "NO KEY UPDATE"}`, value);
|
|
38
39
|
},
|
|
40
|
+
lockRows: async (tx, table, column, values) => {
|
|
41
|
+
if (values.length === 0)
|
|
42
|
+
return;
|
|
43
|
+
await tx.run(`SELECT 1 FROM ${table} WHERE ${column} IN (${values.map(() => "?").join(", ")}) ORDER BY ${column} FOR NO KEY UPDATE`, ...values);
|
|
44
|
+
},
|
|
39
45
|
lockKey: async (tx, key) => {
|
|
40
46
|
await tx.run("SELECT pg_advisory_xact_lock(hashtext(?), hashtext(?))", schema, key);
|
|
41
47
|
},
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
-- Version 15: a run's labels (runs.labels, as store/schema.ts keeps them on SQLite): the caller's labels, a JSON object of
|
|
2
|
+
-- strings set once at the run's start; null when it was given none, so a run started before reads as given none. Applied
|
|
3
|
+
-- once, after 0014, inside the transaction migrate.ts opens. Never edit this file once applied: a change is a new file.
|
|
4
|
+
ALTER TABLE runs ADD COLUMN IF NOT EXISTS labels TEXT COLLATE "C" CHECK (labels IS NULL OR labels::json IS NOT NULL);
|
|
5
|
+
UPDATE store_meta SET schema_version = 15 WHERE singleton = 1;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
-- The store's schema on Postgres, version 16: a hosted machine's minted token (a dial provider's create,
|
|
2
|
+
-- spec/computer/attach.md), as store/schema.ts keeps it on SQLite (MINTED_TOKENS). Applied once, after 0015, inside the
|
|
3
|
+
-- transaction migrate.ts opens. Never edit this file once applied: a change is a new file.
|
|
4
|
+
--
|
|
5
|
+
-- minted_tokens: one row per machine (its name, from its create's request id); the token's SHA-256 alone is kept (hex),
|
|
6
|
+
-- with what the machine must say it is at hello (kind, os, arch), when the token ends (expires_at, the machine's backstop)
|
|
7
|
+
-- and when it was revoked (its delete). The table is made only where it is missing, so a store whose record of this file
|
|
8
|
+
-- was lost applies it again unharmed.
|
|
9
|
+
|
|
10
|
+
CREATE TABLE IF NOT EXISTS minted_tokens (
|
|
11
|
+
machine TEXT COLLATE "C" PRIMARY KEY,
|
|
12
|
+
token_sha256 TEXT COLLATE "C" NOT NULL UNIQUE,
|
|
13
|
+
kind TEXT COLLATE "C" NOT NULL,
|
|
14
|
+
os TEXT COLLATE "C" NOT NULL,
|
|
15
|
+
arch TEXT COLLATE "C" NOT NULL,
|
|
16
|
+
expires_at BIGINT NOT NULL,
|
|
17
|
+
revoked_at BIGINT,
|
|
18
|
+
created_at BIGINT NOT NULL
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
UPDATE store_meta SET schema_version = 16 WHERE singleton = 1;
|
|
@@ -23,10 +23,14 @@ export interface PostgresStoreOptions {
|
|
|
23
23
|
readonly busyTimeoutMs?: number;
|
|
24
24
|
/** Most connections the store holds at once (10 by default). */
|
|
25
25
|
readonly poolSize?: number;
|
|
26
|
-
/** How long
|
|
27
|
-
*
|
|
28
|
-
*
|
|
26
|
+
/** How long a new connection's connect and startup may take, in ms (STORE_CONNECT_TIMEOUT_MS, 4 s, by default). Past it
|
|
27
|
+
* the call, or the open, is refused (StoreDeadline, naming the database's host, database and schema, never the URL:
|
|
28
|
+
* it does not answer), never left hanging. */
|
|
29
29
|
readonly connectTimeoutMs?: number;
|
|
30
|
+
/** How long a call may wait for one of the pool's connections to come free while every one is in use, in ms
|
|
31
|
+
* (STORE_WRITE_DEADLINE_MS, 10 s, by default; never less than connectTimeoutMs). Past it the call is refused
|
|
32
|
+
* (StoreDeadline: every connection stayed in use), nothing of it sent. */
|
|
33
|
+
readonly poolWaitMs?: number;
|
|
30
34
|
/** Told, at a runner's open, when its clock is more than CLOCK_WARN_MS from the database's; at a server's, when it waits
|
|
31
35
|
* for another server to let the schema go. */
|
|
32
36
|
readonly warn?: (message: string) => void;
|
|
@@ -29,6 +29,7 @@ export async function openPostgresStore(options) {
|
|
|
29
29
|
...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),
|
|
30
30
|
...(options.poolSize === undefined ? {} : { poolSize: options.poolSize }),
|
|
31
31
|
...(options.connectTimeoutMs === undefined ? {} : { connectTimeoutMs: options.connectTimeoutMs }),
|
|
32
|
+
...(options.poolWaitMs === undefined ? {} : { poolWaitMs: options.poolWaitMs }),
|
|
32
33
|
...(options.ownerWaitMs === undefined ? {} : { ownerWaitMs: options.ownerWaitMs }),
|
|
33
34
|
...(options.warn ? { onOwnerWait: options.warn } : {}),
|
|
34
35
|
...(options.onOwnerLost ? { onOwnerLost: options.onOwnerLost } : {}),
|
package/dist/store/schema.d.ts
CHANGED
|
@@ -16,12 +16,21 @@ export declare const REVISIONS_MONID_PIN: string;
|
|
|
16
16
|
/** The bound beside a run's cost: in STORE_DDL, and added at a server open to a store an earlier build of this version made,
|
|
17
17
|
* as REVISIONS_MCP_PIN is (a run it ended reads 0: an exact cost or an unknown one, as it was read then). */
|
|
18
18
|
export declare const RUNS_COST_UPPER_BOUND = "ALTER TABLE runs ADD COLUMN cost_upper_bound INTEGER NOT NULL DEFAULT 0 CHECK (cost_upper_bound IN (0, 1))";
|
|
19
|
+
/** A run's labels (JSON, null for none): in STORE_DDL, and added at a server open to a store an earlier build of this version
|
|
20
|
+
* made, as RUNS_COST_UPPER_BOUND is (a run started before reads as given none). */
|
|
21
|
+
export declare const RUNS_LABELS: string;
|
|
19
22
|
/** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
|
|
20
23
|
* source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
|
|
21
24
|
* (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
|
|
22
25
|
* as it loads them at its start (templates.ts readPackage); nothing in them runs. In STORE_DDL, and added at a server
|
|
23
26
|
* open to a store an earlier build of this version made. */
|
|
24
27
|
export declare const IMPORTED_TEMPLATES: string;
|
|
28
|
+
/** A hosted machine's minted token (a dial provider's create, spec/computer/attach.md): its computerd dials the attach
|
|
29
|
+
* socket and fetches the daemon with it. By the machine (its name, from its create's request id): the token's SHA-256
|
|
30
|
+
* alone (hex), what the machine must say it is at hello (kind, os, arch), and when the token ends (`expires_at`, the
|
|
31
|
+
* machine's backstop) or was revoked (its delete). A row past its end goes at the next mint. In STORE_DDL, and added at
|
|
32
|
+
* a server open to a store an earlier build of this version made. */
|
|
33
|
+
export declare const MINTED_TOKENS = "CREATE TABLE IF NOT EXISTS minted_tokens (\n machine TEXT PRIMARY KEY,\n token_sha256 TEXT NOT NULL UNIQUE,\n kind TEXT NOT NULL,\n os TEXT NOT NULL,\n arch TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n revoked_at INTEGER,\n created_at INTEGER NOT NULL\n ) STRICT";
|
|
25
34
|
export declare const STORE_DDL: readonly string[];
|
|
26
35
|
/** pi-durable's journal tables (its SqliteStorage schema, version 2, the `sleeping` task status included; MIT, see NOTICE),
|
|
27
36
|
* every one keyed by (run_id, …) with run_id leading its indexes, so one run's scans read only its rows and two runs never
|
package/dist/store/schema.js
CHANGED
|
@@ -13,10 +13,11 @@
|
|
|
13
13
|
// build of this version made and drops the table, so a revision saved before has no pin until its first run pins it.
|
|
14
14
|
// Its monid endpoints are pinned beside them (revisions.monid_pin, REVISIONS_MONID_PIN), added at a server open the same way.
|
|
15
15
|
// A run's cost says whether it is the most the run can have cost (runs.cost_upper_bound, RUNS_COST_UPPER_BOUND), added at a
|
|
16
|
-
// server open the same way.
|
|
16
|
+
// server open the same way. A run's labels (runs.labels, RUNS_LABELS) are added at a server open the same way.
|
|
17
17
|
// The template packages imported from GitHub (imported_templates) are a table of their own that nothing
|
|
18
18
|
// else reads, so it needs no version: the server adds it at its open to a store an earlier build of this version made
|
|
19
|
-
// (IMPORTED_TEMPLATES), as it does the one-answer index.
|
|
19
|
+
// (IMPORTED_TEMPLATES), as it does the one-answer index. A hosted machine's minted token (minted_tokens, MINTED_TOKENS) is
|
|
20
|
+
// added the same way.
|
|
20
21
|
// Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
|
|
21
22
|
// sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
|
|
22
23
|
// in the clear. Foreign keys are on (the connection's pragma).
|
|
@@ -50,6 +51,9 @@ const COST_UPPER_BOUND = "cost_upper_bound INTEGER NOT NULL DEFAULT 0 CHECK (cos
|
|
|
50
51
|
/** The bound beside a run's cost: in STORE_DDL, and added at a server open to a store an earlier build of this version made,
|
|
51
52
|
* as REVISIONS_MCP_PIN is (a run it ended reads 0: an exact cost or an unknown one, as it was read then). */
|
|
52
53
|
export const RUNS_COST_UPPER_BOUND = `ALTER TABLE runs ADD COLUMN ${COST_UPPER_BOUND}`;
|
|
54
|
+
/** A run's labels (JSON, null for none): in STORE_DDL, and added at a server open to a store an earlier build of this version
|
|
55
|
+
* made, as RUNS_COST_UPPER_BOUND is (a run started before reads as given none). */
|
|
56
|
+
export const RUNS_LABELS = `ALTER TABLE runs ADD COLUMN ${json("labels", true)}`;
|
|
53
57
|
/** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
|
|
54
58
|
* source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
|
|
55
59
|
* (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
|
|
@@ -63,6 +67,21 @@ export const IMPORTED_TEMPLATES = `CREATE TABLE IF NOT EXISTS imported_templates
|
|
|
63
67
|
${json("files")},
|
|
64
68
|
imported_at INTEGER NOT NULL
|
|
65
69
|
) STRICT`;
|
|
70
|
+
/** A hosted machine's minted token (a dial provider's create, spec/computer/attach.md): its computerd dials the attach
|
|
71
|
+
* socket and fetches the daemon with it. By the machine (its name, from its create's request id): the token's SHA-256
|
|
72
|
+
* alone (hex), what the machine must say it is at hello (kind, os, arch), and when the token ends (`expires_at`, the
|
|
73
|
+
* machine's backstop) or was revoked (its delete). A row past its end goes at the next mint. In STORE_DDL, and added at
|
|
74
|
+
* a server open to a store an earlier build of this version made. */
|
|
75
|
+
export const MINTED_TOKENS = `CREATE TABLE IF NOT EXISTS minted_tokens (
|
|
76
|
+
machine TEXT PRIMARY KEY,
|
|
77
|
+
token_sha256 TEXT NOT NULL UNIQUE,
|
|
78
|
+
kind TEXT NOT NULL,
|
|
79
|
+
os TEXT NOT NULL,
|
|
80
|
+
arch TEXT NOT NULL,
|
|
81
|
+
expires_at INTEGER NOT NULL,
|
|
82
|
+
revoked_at INTEGER,
|
|
83
|
+
created_at INTEGER NOT NULL
|
|
84
|
+
) STRICT`;
|
|
66
85
|
export const STORE_DDL = [
|
|
67
86
|
`CREATE TABLE IF NOT EXISTS store_meta (
|
|
68
87
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
@@ -147,6 +166,10 @@ export const STORE_DDL = [
|
|
|
147
166
|
-- the write-back (sign-ins-store.ts / runs.update's save decision). Null until it first leaves running. Other vendors
|
|
148
167
|
-- free the lease the instant it leaves running (no settle window), so this is read only with one.
|
|
149
168
|
left_running_at INTEGER,
|
|
169
|
+
-- The caller's labels (RunLabels): a JSON object of strings, set once with the queued run (runs.create), opaque to the
|
|
170
|
+
-- server and only filtered on (runs.list). Null when it was given none. Added at a server open to a store an earlier
|
|
171
|
+
-- build of this version made (RUNS_LABELS), its runs reading as given none.
|
|
172
|
+
${json("labels", true)},
|
|
150
173
|
started_at INTEGER NOT NULL,
|
|
151
174
|
ended_at INTEGER
|
|
152
175
|
) STRICT`,
|
|
@@ -385,6 +408,7 @@ export const STORE_DDL = [
|
|
|
385
408
|
PRIMARY KEY (agent_id, key)
|
|
386
409
|
) STRICT`,
|
|
387
410
|
IMPORTED_TEMPLATES,
|
|
411
|
+
MINTED_TOKENS,
|
|
388
412
|
// An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
|
|
389
413
|
// pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
|
|
390
414
|
// sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
|
|
@@ -15,8 +15,19 @@ export const DEFAULT_TRANSACTION_DEADLINE_MS = 10_000;
|
|
|
15
15
|
/** The interactive transactions open in this process, on any of its connections: each with where it was opened and when
|
|
16
16
|
* it began. A transaction's StoreDeadline, and a begin's StoreBusy, name them in their stack (never their message, which
|
|
17
17
|
* an answer may carry), so a log says who held the store: the deadline's own transaction, or another of this process's
|
|
18
|
-
* (an in-process runner's) holding the lock a begin waited on.
|
|
18
|
+
* (an in-process runner's) holding the lock a begin waited on. `where`: its database (Connection.where), so a wait for
|
|
19
|
+
* the write lock knows a holder of this process on the same database (lockWait). */
|
|
19
20
|
const OPEN = new Set();
|
|
21
|
+
/** The interactive transactions of this process whose begin is with its worker, not yet answered: each on its database
|
|
22
|
+
* (`where`). Such a begin may hold the write lock already, its answer waiting for the event loop, and after a hold-up
|
|
23
|
+
* the answers of two workers come back in no set order, so a wait that ran out then can be read before that begin's
|
|
24
|
+
* answer adds it to OPEN (lockWait). */
|
|
25
|
+
const BEGINNING = new Set();
|
|
26
|
+
/** How many interactive transactions of this process have ended on each database (`where`), counted once the worker has
|
|
27
|
+
* answered their commit or rollback. A wait whose busy answer is read after a holder of this process let go (its
|
|
28
|
+
* commit's answer read first: two workers' answers come back in no set order) finds it in neither set, yet that holder
|
|
29
|
+
* held the lock through the wait: the count moved since the wait was sent says so (lockWait). */
|
|
30
|
+
const ENDED = new Map();
|
|
20
31
|
/** `opened`'s frames: where a transaction was asked for, without the Error line itself. */
|
|
21
32
|
const framesOf = (opened) => (opened.stack ?? "").split("\n").slice(1).join("\n");
|
|
22
33
|
/** `error` with its stack naming who held the store: `opened` (its own transaction's opener, when it has one), and every
|
|
@@ -198,8 +209,54 @@ export class Connection {
|
|
|
198
209
|
this.#tail = run.catch(() => undefined);
|
|
199
210
|
return run;
|
|
200
211
|
}
|
|
201
|
-
#stmt(sql, params, mode) {
|
|
202
|
-
return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode });
|
|
212
|
+
#stmt(sql, params, mode, busyMs) {
|
|
213
|
+
return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode, ...(busyMs !== undefined ? { busyMs } : {}) });
|
|
214
|
+
}
|
|
215
|
+
/** `send`, a request that takes the database's write lock (a transaction's begin, a write, a statement outside a
|
|
216
|
+
* transaction), given how long it may wait for it (`busyMs`; undefined, the connection's own busy wait). A wait that
|
|
217
|
+
* ran out on a transaction of this process on the same database (another of its connections: the server's and its
|
|
218
|
+
* in-process runner's) while this process was held up (its event loop held by other work, the machine holding it) is
|
|
219
|
+
* sent again, with the held-up time given back: that holder's statements wait for the same event loop, and its deadline
|
|
220
|
+
* counts only the time this process could run (store/deadline.ts runnableDeadline), so the wait for it counts the same
|
|
221
|
+
* way, and the holder, once it runs again, commits or meets its deadline. A wait on another process's write, or one
|
|
222
|
+
* this process could run through, ends StoreBusy as ever.
|
|
223
|
+
* Every wait is measured, and the holder looked for when it runs out, never when it is sent: a holder's begin posted
|
|
224
|
+
* in the same turn may take the lock before its answer makes it known. A holder that ended while the wait was out
|
|
225
|
+
* counts too: its commit's answer may be read before the wait's busy answer. `self`: this request's own begin
|
|
226
|
+
* (BEGINNING), never its own holder. */
|
|
227
|
+
async #lockWait(send, self) {
|
|
228
|
+
let left = this.#busyTimeoutMs;
|
|
229
|
+
for (;;) {
|
|
230
|
+
const clock = runnableDeadline(left, () => { });
|
|
231
|
+
const sent = performance.now();
|
|
232
|
+
const ended = ENDED.get(this.#where) ?? 0;
|
|
233
|
+
try {
|
|
234
|
+
return await send(left < this.#busyTimeoutMs ? left : undefined);
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
if (!(error instanceof StoreBusy))
|
|
238
|
+
throw error;
|
|
239
|
+
const held = clock.held();
|
|
240
|
+
if (held === 0 || !(this.#heldHere(self) || (ENDED.get(this.#where) ?? 0) !== ended))
|
|
241
|
+
throw error;
|
|
242
|
+
left -= performance.now() - sent - held;
|
|
243
|
+
if (left <= 0)
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
finally {
|
|
247
|
+
clock.clear();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** A transaction of this process on this database is open, or its begin is with its worker (other than `self`). */
|
|
252
|
+
#heldHere(self) {
|
|
253
|
+
for (const open of OPEN)
|
|
254
|
+
if (open.where === this.#where)
|
|
255
|
+
return true;
|
|
256
|
+
for (const beginning of BEGINNING)
|
|
257
|
+
if (beginning !== self && beginning.where === this.#where)
|
|
258
|
+
return true;
|
|
259
|
+
return false;
|
|
203
260
|
}
|
|
204
261
|
/** The executor that sends straight to the worker: a transaction's handle, valid while `live()` says so. */
|
|
205
262
|
#executor(live) {
|
|
@@ -221,10 +278,10 @@ export class Connection {
|
|
|
221
278
|
return this.#queued(async () => void (await this.#send({ op: "exec", sql })));
|
|
222
279
|
}
|
|
223
280
|
run(sql, ...params) {
|
|
224
|
-
return this.#queued(async () => void (await this.#stmt(sql, params, "run")));
|
|
281
|
+
return this.#queued(async () => void (await this.#lockWait((busyMs) => this.#stmt(sql, params, "run", busyMs))));
|
|
225
282
|
}
|
|
226
283
|
runCounted(sql, ...params) {
|
|
227
|
-
return this.#queued(async () => (await this.#stmt(sql, params, "count")));
|
|
284
|
+
return this.#queued(async () => (await this.#lockWait((busyMs) => this.#stmt(sql, params, "count", busyMs))));
|
|
228
285
|
}
|
|
229
286
|
get(sql, ...params) {
|
|
230
287
|
return this.#queued(async () => ((await this.#stmt(sql, params, "get")) ?? undefined));
|
|
@@ -235,7 +292,10 @@ export class Connection {
|
|
|
235
292
|
/** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
|
|
236
293
|
* FULL commit, durable against a lost box together with every commit before it. */
|
|
237
294
|
write(statements, { full = false } = {}) {
|
|
238
|
-
return this.#queued(async () =>
|
|
295
|
+
return this.#queued(async () => {
|
|
296
|
+
const cleanedStatements = statements.map(cleanStatement);
|
|
297
|
+
return (await this.#lockWait((busyMs) => this.#send({ op: "write", statements: cleanedStatements, full, ...(busyMs !== undefined ? { busyMs } : {}) })));
|
|
298
|
+
});
|
|
239
299
|
}
|
|
240
300
|
/** A write transaction (BEGIN IMMEDIATE) the callback steps through its handle, deciding each statement from the ones
|
|
241
301
|
* before it. It commits when the callback resolves; when the callback rejects it rolls back and rejects with the same
|
|
@@ -259,15 +319,26 @@ export class Connection {
|
|
|
259
319
|
// Its wait for the database's lock (another process's write) bounded by what the deadline leaves: a lock still held
|
|
260
320
|
// when that runs out is the deadline's end, not the connection's own busy wait.
|
|
261
321
|
const busyMs = until !== undefined ? Math.max(0, until - Date.now()) : undefined;
|
|
322
|
+
// Until its begin is answered, it may hold the lock unknown to OPEN: another wait that runs out meanwhile finds it.
|
|
323
|
+
const beginning = { where: this.#where };
|
|
324
|
+
BEGINNING.add(beginning);
|
|
262
325
|
try {
|
|
263
|
-
|
|
326
|
+
// Counted from its call, its wait is the deadline's, the wall clock's; else its wait for a holder of this process
|
|
327
|
+
// gives back the time this process was held up (lockWait).
|
|
328
|
+
if (busyMs !== undefined)
|
|
329
|
+
await this.#send({ op: "begin", full, ...(read ? { read } : {}), busyMs });
|
|
330
|
+
else
|
|
331
|
+
await this.#lockWait((wait) => this.#send({ op: "begin", full, ...(read ? { read } : {}), ...(wait !== undefined ? { busyMs: wait } : {}) }), beginning);
|
|
264
332
|
}
|
|
265
333
|
catch (error) {
|
|
266
334
|
if (error instanceof StoreBusy && busyMs !== undefined && busyMs < this.#busyTimeoutMs)
|
|
267
335
|
throw holderNamed(new StoreDeadline(deadlineMs), { opened });
|
|
268
336
|
throw error instanceof StoreBusy ? holderNamed(error, { opened }) : error;
|
|
269
337
|
}
|
|
270
|
-
|
|
338
|
+
finally {
|
|
339
|
+
BEGINNING.delete(beginning);
|
|
340
|
+
}
|
|
341
|
+
const open = { opened, began: Date.now(), where: this.#where };
|
|
271
342
|
OPEN.add(open);
|
|
272
343
|
try {
|
|
273
344
|
let live = true;
|
|
@@ -320,6 +391,7 @@ export class Connection {
|
|
|
320
391
|
finally {
|
|
321
392
|
// Kept until the worker has answered the commit or rollback: until then this transaction still holds the lock.
|
|
322
393
|
OPEN.delete(open);
|
|
394
|
+
ENDED.set(open.where, (ENDED.get(open.where) ?? 0) + 1);
|
|
323
395
|
}
|
|
324
396
|
});
|
|
325
397
|
if (until === undefined)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type RunLaunchInput, type RunLaunchRow } from "../store.js";
|
|
2
|
+
import type { Dialect } from "../dialect.js";
|
|
2
3
|
import type { SqliteExecutor } from "./connection.js";
|
|
3
4
|
/** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
|
|
4
5
|
* trigger path both call it, so the row lands with its run or not at all. */
|
|
@@ -6,3 +7,13 @@ export declare function writeLaunch(tx: Pick<SqliteExecutor, "run">, runId: stri
|
|
|
6
7
|
/** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
|
|
7
8
|
* none, never a default. */
|
|
8
9
|
export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
|
|
10
|
+
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
11
|
+
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
12
|
+
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
13
|
+
* is the member's JSON text, null when the run's body names none. */
|
|
14
|
+
export declare function readLearningStarts(executor: Pick<SqliteExecutor, "all"> & {
|
|
15
|
+
readonly dialect: Dialect;
|
|
16
|
+
}, agentId: string, where: string): Promise<{
|
|
17
|
+
runId: string;
|
|
18
|
+
learning: unknown;
|
|
19
|
+
}[]>;
|
|
@@ -18,3 +18,11 @@ export async function readLaunch(executor, runId) {
|
|
|
18
18
|
throw new StoreLaunchMissing(runId);
|
|
19
19
|
return runLaunchOf(row);
|
|
20
20
|
}
|
|
21
|
+
/** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
|
|
22
|
+
* the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
|
|
23
|
+
* and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
|
|
24
|
+
* is the member's JSON text, null when the run's body names none. */
|
|
25
|
+
export async function readLearningStarts(executor, agentId, where) {
|
|
26
|
+
const rows = await executor.all(`SELECT run_id, ${executor.dialect.jsonText("body", ["learning"])} AS learning FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND ${where})`, agentId);
|
|
27
|
+
return rows.map((row) => ({ runId: row.run_id, learning: row.learning === null ? undefined : JSON.parse(row.learning) }));
|
|
28
|
+
}
|
|
@@ -43,10 +43,11 @@ export type RunRecord = {
|
|
|
43
43
|
archived_at: number | null;
|
|
44
44
|
imported_from: string | null;
|
|
45
45
|
sign_in_handed: string | null;
|
|
46
|
+
labels: string | null;
|
|
46
47
|
started_at: number;
|
|
47
48
|
ended_at: number | null;
|
|
48
49
|
};
|
|
49
|
-
export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
|
|
50
|
+
export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, started_at, ended_at";
|
|
50
51
|
/** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
|
|
51
52
|
* stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
|
|
52
53
|
export declare const EXACT_COST_USD: (alias: string) => string;
|
|
@@ -18,7 +18,7 @@ export const learningLaunchOf = (runId, model, round = 1, capUsd) => ({ harness:
|
|
|
18
18
|
/** The lock a write of a run's sign_in_handed and a sign-in's forget both take (Dialect.lockKey): the forget's check of
|
|
19
19
|
* the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
|
|
20
20
|
export const SIGN_IN_HANDED_LOCK = "sign_in_handed";
|
|
21
|
-
export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
|
|
21
|
+
export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, labels, started_at, ended_at";
|
|
22
22
|
/** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
|
|
23
23
|
* stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
|
|
24
24
|
export const EXACT_COST_USD = (alias) => `CASE WHEN ${alias}.cost_upper_bound = 1 THEN NULL ELSE ${alias}.cost_usd END`;
|
|
@@ -30,7 +30,8 @@ export const runOf = (r) => ({
|
|
|
30
30
|
id: r.id, agentId: r.agent_id, revisionId: r.revision_id, state: r.state, epoch: r.epoch, runner: r.runner, claimedUntil: r.claimed_until,
|
|
31
31
|
wakeAt: r.wake_at, backoffUntil: r.backoff_until, ...costOf(r.cost_usd, r.cost_upper_bound), metrics: r.metrics === null ? null : JSON.parse(r.metrics), summary: r.summary,
|
|
32
32
|
outcome: r.outcome ?? null, archivedAt: r.archived_at, importedFrom: r.imported_from === null ? null : JSON.parse(r.imported_from),
|
|
33
|
-
signInHanded: r.sign_in_handed === null ? null : JSON.parse(r.sign_in_handed),
|
|
33
|
+
signInHanded: r.sign_in_handed === null ? null : JSON.parse(r.sign_in_handed), labels: r.labels === null ? {} : JSON.parse(r.labels),
|
|
34
|
+
startedAt: r.started_at, endedAt: r.ended_at,
|
|
34
35
|
});
|
|
35
36
|
/** Applies `patch` to the claim's run, then writes `also`, through `tx` (an open transaction's handle). Fenced, with nothing
|
|
36
37
|
* of it written once the caller rolls back, when the run's epoch is not the claim's or the claim's lease ran out before
|