@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.58
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 +52 -0
- package/README.md +64 -33
- package/dist/api-only.d.ts +2 -4
- package/dist/api-only.js +2 -4
- package/dist/box-paths.d.ts +4 -3
- package/dist/box-paths.js +7 -4
- package/dist/claude-login-token.d.ts +117 -0
- package/dist/claude-login-token.js +737 -0
- package/dist/claude-login.d.ts +52 -12
- package/dist/claude-login.js +164 -39
- package/dist/cli.js +7 -41
- package/dist/computer-attach.d.ts +35 -17
- package/dist/computer-attach.js +301 -49
- package/dist/computers.d.ts +10 -10
- package/dist/computers.js +5 -5
- package/dist/console/assets/{backend-DVhHzJX2.js → backend-CSAWUqtZ.js} +1 -1
- package/dist/console/assets/index-DPh29cyz.js +747 -0
- package/dist/console/index.html +1 -1
- package/dist/dial-relay.d.ts +25 -4
- package/dist/dial-relay.js +129 -1
- package/dist/env-switch.d.ts +1 -3
- package/dist/env-switch.js +1 -3
- package/dist/fal-price.d.ts +1 -3
- package/dist/fal-price.js +77 -26
- package/dist/learn/ledger.d.ts +170 -0
- package/dist/learn/ledger.js +218 -0
- package/dist/learn/promote.d.ts +3 -3
- package/dist/learn/promote.js +1 -1
- package/dist/learning-cost.d.ts +22 -20
- package/dist/learning-cost.js +15 -21
- package/dist/live-reach.d.ts +2 -0
- package/dist/live-reach.js +2 -0
- package/dist/mcp-api-only-origins.d.ts +8 -3
- package/dist/mcp-api-only-origins.js +17 -17
- package/dist/micro.d.ts +2 -0
- package/dist/micro.js +2 -0
- package/dist/model.d.ts +5 -4
- package/dist/model.js +7 -6
- package/dist/monid.d.ts +14 -1
- package/dist/monid.js +103 -26
- package/dist/openapi.js +34 -12
- package/dist/place-offers.d.ts +4 -0
- package/dist/place-offers.js +7 -4
- package/dist/provider.d.ts +2 -2
- package/dist/provider.js +9 -5
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-view.d.ts +1 -2
- package/dist/run-view.js +2 -1
- package/dist/runner/adapter-loop.js +3 -16
- package/dist/runner/adapter-run-spec.d.ts +20 -13
- package/dist/runner/adapter-run-spec.js +57 -48
- package/dist/runner/beside.d.ts +9 -2
- package/dist/runner/beside.js +24 -7
- package/dist/runner/claim-secrets.d.ts +17 -15
- package/dist/runner/claim-secrets.js +32 -34
- package/dist/runner/cli-run-spec.js +21 -9
- package/dist/runner/held.d.ts +16 -4
- package/dist/runner/main.d.ts +11 -6
- package/dist/runner/main.js +12 -7
- package/dist/runner/mcp-claim.js +3 -2
- package/dist/runner/mcp-run.d.ts +3 -6
- package/dist/runner/mcp-run.js +3 -4
- package/dist/runner/presence.d.ts +11 -1
- package/dist/runner/presence.js +7 -0
- package/dist/runner/reflect-hook.js +1 -1
- package/dist/runner/run-child-host.d.ts +19 -8
- package/dist/runner/run-child-host.js +80 -34
- package/dist/runner/runner.d.ts +3 -0
- package/dist/runner/runner.js +1 -1
- package/dist/runner/save-slots.js +2 -1
- package/dist/runner/subagent.d.ts +11 -0
- package/dist/runner/subagent.js +17 -3
- package/dist/runner/workflow-first.d.ts +27 -14
- package/dist/runner/workflow-first.js +29 -22
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/server.d.ts +18 -7
- package/dist/server.js +150 -64
- package/dist/slots.d.ts +9 -0
- package/dist/slots.js +45 -0
- package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
- package/dist/store/schema.d.ts +17 -0
- package/dist/store/schema.js +47 -1
- package/dist/store/sqlite/run-patch.d.ts +11 -1
- package/dist/store/sqlite/run-patch.js +29 -1
- package/dist/store/sqlite/store.js +72 -9
- package/dist/store/store.d.ts +14 -0
- package/dist/store-reads/learning.d.ts +81 -124
- package/dist/store-reads/learning.js +207 -286
- package/dist/template-eval.d.ts +19 -0
- package/dist/template-eval.js +92 -43
- package/dist/template-import.d.ts +0 -10
- package/dist/template-import.js +5 -10
- package/dist/timeline/web-calls.d.ts +12 -14
- package/dist/timeline/web-calls.js +14 -30
- package/dist/web-save.d.ts +4 -9
- package/dist/web-save.js +4 -43
- package/dist/workspace/attached-computers.d.ts +32 -9
- package/dist/workspace/attached-computers.js +77 -13
- package/dist/workspace/computer-deps.d.ts +6 -1
- package/dist/workspace/computer-deps.js +1 -1
- package/dist/workspace/computer-for-claim.js +6 -3
- package/dist/workspace/paired-route.d.ts +91 -0
- package/dist/workspace/paired-route.js +153 -0
- package/dist/wrapped.d.ts +8 -2
- package/dist/wrapped.js +21 -6
- package/package.json +12 -12
- package/templates/README.md +3 -3
- package/dist/console/assets/index-okP-y8PK.js +0 -747
package/dist/store/schema.js
CHANGED
|
@@ -21,7 +21,8 @@
|
|
|
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
22
|
// and each computer a run made, from its create to its proven delete (computer_intervals, COMPUTER_INTERVALS). Each runner's
|
|
23
23
|
// version and slots (runners.version, .slots: RUNNERS_ADDED), each hand-back (hand_backs, HAND_BACKS) and each claim of a
|
|
24
|
-
// run with the turn it works and its attempt at it (run_attempts, RUN_ATTEMPTS) are added the same way
|
|
24
|
+
// run with the turn it works and its attempt at it (run_attempts, RUN_ATTEMPTS) are added the same way, and so is the
|
|
25
|
+
// learning ledger (learning_ledger, learning_spend: LEARNING_LEDGER, LEARNING_SPEND).
|
|
25
26
|
// Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
|
|
26
27
|
// sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
|
|
27
28
|
// in the clear. Foreign keys are on (the connection's pragma).
|
|
@@ -223,6 +224,46 @@ export const RUN_ATTEMPTS = `CREATE TABLE IF NOT EXISTS run_attempts (
|
|
|
223
224
|
claimed_at INTEGER NOT NULL,
|
|
224
225
|
PRIMARY KEY (run_id, epoch)
|
|
225
226
|
) STRICT`;
|
|
227
|
+
/** The learning ledger (learn/ledger.ts): one row a run, written by each patch that leaves the run ended (applyRunPatch,
|
|
228
|
+
* in that patch's transaction) and by a healed cost: who answered it (`path`, null when its end named none), the
|
|
229
|
+
* revision that ran it, why it was not served alone, the job's own $ and its rounds' look-back, and whether its cost is
|
|
230
|
+
* known (`cost`), and the end it was written for (`epoch`: the run's epoch after that end, which every end moves).
|
|
231
|
+
* Gone with the run's purge or delete (its cost stays on the run's tombstone). Figures only, no run text. In STORE_DDL,
|
|
232
|
+
* and made at a server open on a store an earlier build of this version made: a run that ended before it has no row,
|
|
233
|
+
* and one a runner of that build ended again has a row for an earlier end; its reader records it from its run row
|
|
234
|
+
* either way (store-reads/learning.ts). */
|
|
235
|
+
export const LEARNING_LEDGER = `CREATE TABLE IF NOT EXISTS learning_ledger (
|
|
236
|
+
run_id TEXT PRIMARY KEY,
|
|
237
|
+
agent_id TEXT NOT NULL,
|
|
238
|
+
started_at INTEGER NOT NULL,
|
|
239
|
+
path TEXT CHECK (path IS NULL OR path IN ('agent', 'handed_back', 'workflow', 'replay', 'audit')),
|
|
240
|
+
workflow TEXT,
|
|
241
|
+
digest TEXT,
|
|
242
|
+
not_served TEXT CHECK (not_served IS NULL OR not_served IN ('cost_stop', 'cut')),
|
|
243
|
+
job_usd REAL,
|
|
244
|
+
look_back_usd REAL,
|
|
245
|
+
cost TEXT NOT NULL CHECK (cost IN ('known', 'unknown', 'at_most')),
|
|
246
|
+
epoch INTEGER NOT NULL
|
|
247
|
+
) STRICT`;
|
|
248
|
+
export const LEARNING_LEDGER_AGENT = "CREATE INDEX IF NOT EXISTS learning_ledger_agent ON learning_ledger (agent_id)";
|
|
249
|
+
/** Each learning cost, by the revision it is for (learn/ledger.ts SpendRow): a compile turn (`round`, the round that asked
|
|
250
|
+
* it), a check's replay run or an audit's shadow run (round 0, `of_run` the run it audits), with its $ (null: unknown).
|
|
251
|
+
* Written with its run's ledger row, replaced whole each time; gone with its run's purge or delete, and with the purge
|
|
252
|
+
* or delete of the run it audits. */
|
|
253
|
+
export const LEARNING_SPEND = `CREATE TABLE IF NOT EXISTS learning_spend (
|
|
254
|
+
run_id TEXT NOT NULL,
|
|
255
|
+
kind TEXT NOT NULL CHECK (kind IN ('compile', 'check', 'audit')),
|
|
256
|
+
round INTEGER NOT NULL CHECK (round >= 0),
|
|
257
|
+
agent_id TEXT NOT NULL,
|
|
258
|
+
of_run TEXT,
|
|
259
|
+
workflow TEXT,
|
|
260
|
+
digest TEXT,
|
|
261
|
+
usd REAL,
|
|
262
|
+
at INTEGER NOT NULL,
|
|
263
|
+
PRIMARY KEY (run_id, kind, round)
|
|
264
|
+
) STRICT`;
|
|
265
|
+
export const LEARNING_SPEND_AGENT = "CREATE INDEX IF NOT EXISTS learning_spend_agent ON learning_spend (agent_id)";
|
|
266
|
+
export const LEARNING_SPEND_OF_RUN = "CREATE INDEX IF NOT EXISTS learning_spend_of_run ON learning_spend (of_run) WHERE of_run IS NOT NULL";
|
|
226
267
|
/** Version 13 → 14 on SQLite (the server's open, sqlite/store.ts), given the runs' and the agents' columns now: when each
|
|
227
268
|
* run and each agent was purged (null: none was), and the version, in one durable write. */
|
|
228
269
|
export function purgeUpgrade(runColumns, agentColumns) {
|
|
@@ -682,6 +723,11 @@ export const STORE_DDL = [
|
|
|
682
723
|
COMPUTER_INTERVALS,
|
|
683
724
|
COMPUTER_INTERVALS_RUN,
|
|
684
725
|
RUN_ATTEMPTS,
|
|
726
|
+
LEARNING_LEDGER,
|
|
727
|
+
LEARNING_LEDGER_AGENT,
|
|
728
|
+
LEARNING_SPEND,
|
|
729
|
+
LEARNING_SPEND_AGENT,
|
|
730
|
+
LEARNING_SPEND_OF_RUN,
|
|
685
731
|
// An agent's saved browser sign-ins (design 2.1, the browser sign-in rules): one live row per agent and browser provider, its
|
|
686
732
|
// pointer (the vendor's context or profile id) sealed with the store's one rule (store/seal.ts, AAD
|
|
687
733
|
// sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
|
|
@@ -45,7 +45,17 @@ export declare const runOf: (r: RunRecord) => RunRow;
|
|
|
45
45
|
* `now` (the store's clock, read in the transaction). A final state with no `endedAt` is stamped `now`, and releases the
|
|
46
46
|
* run in the same statement. `dialect`: the connection's (store/dialect.ts), SQLite's by default. `clock`: the deadlines'
|
|
47
47
|
* clock (fence.ts storeNow) the fence and left_running_at read; `now` bound by default. */
|
|
48
|
-
export declare function applyRunPatch(tx: Pick<SqliteExecutor, "run" | "get">, claim: Pick<Claim, "runId" | "epoch">, patch: RunPatch, also: readonly AlsoRow[], now: number, dialect?: Dialect, clock?: StoreNow): Promise<RunRow>;
|
|
48
|
+
export declare function applyRunPatch(tx: Pick<SqliteExecutor, "run" | "get" | "all">, claim: Pick<Claim, "runId" | "epoch">, patch: RunPatch, also: readonly AlsoRow[], now: number, dialect?: Dialect, clock?: StoreNow): Promise<RunRow>;
|
|
49
|
+
/** Writes run `run`'s ledger row and spend rows (learn/ledger.ts record) through `tx`, from its row and every round its
|
|
50
|
+
* learning kept, in place of any it had: the one writer of learning_ledger and learning_spend (a run's end, and a heal
|
|
51
|
+
* of its cost). Each row says the end it was written for (`epoch`: the run's epoch after that end), which a reader
|
|
52
|
+
* checks against the run's (store-reads/learning.ts ledgerRowStands). Every end moves the epoch (applyRunPatch's
|
|
53
|
+
* `ending`, Runs.failUnclaimed), on every build, and so does every claim before one; an end that keeps its job's end
|
|
54
|
+
* (`keepsEnd`: a grade's round) leaves ended_at where it was, so ended_at never says which end a row is for. A runner
|
|
55
|
+
* or server of the build before the ledger, ending the run again, writes none, and its row reads as stale until a later
|
|
56
|
+
* end writes it again. A cancel that wins an end (refuseLeftovers, after this) moves ended_at, never the epoch: the row
|
|
57
|
+
* still stands. */
|
|
58
|
+
export declare function recordLedger(tx: Pick<SqliteExecutor, "run" | "all">, run: RunRow, now: number): Promise<void>;
|
|
49
59
|
/** The one reopen a run that ended may take (runs.reopen, and a run's end with a person's message waiting): back to running
|
|
50
60
|
* with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
|
|
51
61
|
* metrics kept. `where` holds only for an agentic run that ended completed or that a person stopped (state 'stopped',
|
|
@@ -7,6 +7,7 @@ import { CENSUS_UNSCANNED, endedReason, FINAL_STATES, Fenced } from "../store.js
|
|
|
7
7
|
import { settledBody, SQLITE } from "../dialect.js";
|
|
8
8
|
import { claimFence, storeNow } from "../fence.js";
|
|
9
9
|
import { readableJson } from "./run-launch.js";
|
|
10
|
+
import { record } from "../../learn/ledger.js";
|
|
10
11
|
/** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
|
|
11
12
|
* list of runs names. */
|
|
12
13
|
export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
|
|
@@ -101,7 +102,34 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
|
|
|
101
102
|
break;
|
|
102
103
|
}
|
|
103
104
|
}
|
|
104
|
-
|
|
105
|
+
const run = runOf(row);
|
|
106
|
+
// A run this patch leaves ended has its ledger row and spend rows (learn/ledger.ts record) in this same commit, over
|
|
107
|
+
// every round its learning kept, this patch's included: an end, a later end after a follow-up and a patch of an ended
|
|
108
|
+
// run's metrics each write them whole again.
|
|
109
|
+
if (FINAL_STATES.includes(run.state))
|
|
110
|
+
await recordLedger(tx, run, now);
|
|
111
|
+
return run;
|
|
112
|
+
}
|
|
113
|
+
/** Writes run `run`'s ledger row and spend rows (learn/ledger.ts record) through `tx`, from its row and every round its
|
|
114
|
+
* learning kept, in place of any it had: the one writer of learning_ledger and learning_spend (a run's end, and a heal
|
|
115
|
+
* of its cost). Each row says the end it was written for (`epoch`: the run's epoch after that end), which a reader
|
|
116
|
+
* checks against the run's (store-reads/learning.ts ledgerRowStands). Every end moves the epoch (applyRunPatch's
|
|
117
|
+
* `ending`, Runs.failUnclaimed), on every build, and so does every claim before one; an end that keeps its job's end
|
|
118
|
+
* (`keepsEnd`: a grade's round) leaves ended_at where it was, so ended_at never says which end a row is for. A runner
|
|
119
|
+
* or server of the build before the ledger, ending the run again, writes none, and its row reads as stale until a later
|
|
120
|
+
* end writes it again. A cancel that wins an end (refuseLeftovers, after this) moves ended_at, never the epoch: the row
|
|
121
|
+
* still stands. */
|
|
122
|
+
export async function recordLedger(tx, run, now) {
|
|
123
|
+
const rounds = (await tx.all("SELECT round, proposal FROM learning_proposals WHERE run_id = ? ORDER BY round", run.id))
|
|
124
|
+
.map((one) => ({ round: Number(one.round), proposal: JSON.parse(one.proposal) }));
|
|
125
|
+
const { row, spend } = record({ id: run.id, agentId: run.agentId, startedAt: run.startedAt, costUsd: run.costUsd, costAtMostUsd: run.costAtMostUsd, metrics: run.metrics, rounds });
|
|
126
|
+
await tx.run(`INSERT INTO learning_ledger (run_id, agent_id, started_at, path, workflow, digest, not_served, job_usd, look_back_usd, cost, epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
127
|
+
ON CONFLICT (run_id) DO UPDATE SET agent_id = excluded.agent_id, started_at = excluded.started_at, path = excluded.path, workflow = excluded.workflow, digest = excluded.digest,
|
|
128
|
+
not_served = excluded.not_served, job_usd = excluded.job_usd, look_back_usd = excluded.look_back_usd, cost = excluded.cost, epoch = excluded.epoch`, row.runId, row.agentId, row.startedAt, row.path, row.workflow, row.digest, row.notServed, row.jobUsd, row.lookBackUsd, row.cost, run.epoch);
|
|
129
|
+
await tx.run("DELETE FROM learning_spend WHERE run_id = ?", run.id);
|
|
130
|
+
for (const one of spend) {
|
|
131
|
+
await tx.run("INSERT INTO learning_spend (run_id, kind, round, agent_id, of_run, workflow, digest, usd, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", one.runId, one.kind, one.round, one.agentId, one.ofRun, one.workflow, one.digest, one.usd, now);
|
|
132
|
+
}
|
|
105
133
|
}
|
|
106
134
|
/** The one reopen a run that ended may take (runs.reopen, and a run's end with a person's message waiting): back to running
|
|
107
135
|
* with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
|
|
@@ -12,7 +12,7 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
|
|
|
12
12
|
import { claimFence, storeNow } from "../fence.js";
|
|
13
13
|
import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
|
|
14
14
|
import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
15
|
-
import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUN_LAUNCH_CENSUS, RUN_LAUNCH_CENSUS_PENDING, 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, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, LEARNING_LEDGER, LEARNING_LEDGER_AGENT, LEARNING_SPEND, LEARNING_SPEND_AGENT, LEARNING_SPEND_OF_RUN, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUN_LAUNCH_CENSUS, RUN_LAUNCH_CENSUS_PENDING, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
|
|
16
16
|
import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, FiringMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, KEPT_PREFIX, RUNNER_ROWS_KEPT_MS, RUNNER_STALE_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) => {
|
|
@@ -32,7 +32,7 @@ const seqOf = (cursor) => {
|
|
|
32
32
|
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
|
-
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
35
|
+
import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, recordLedger, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
|
|
36
36
|
import { launchDiskOf, readableJson, readLaunch, readLearningStarts, readSeededBefore, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
|
|
37
37
|
import { canonical } from "../agent-body.js";
|
|
38
38
|
import { readProjectCheckpoints } from "./project-checkpoints.js";
|
|
@@ -281,6 +281,9 @@ export const SQLITE_RUNNER_NEEDS = [
|
|
|
281
281
|
{ 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)" },
|
|
282
282
|
{ table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
|
|
283
283
|
{ table: "run_attempts", columns: ["run_id"], why: "keep each claim's turn and attempt (run_attempts)" },
|
|
284
|
+
// A run's end writes its ledger row and spend rows (run-patch.ts applyRunPatch) in its own transaction.
|
|
285
|
+
{ table: "learning_ledger", columns: ["run_id"], why: "write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)" },
|
|
286
|
+
{ table: "learning_spend", columns: ["run_id"], why: "write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)" },
|
|
284
287
|
];
|
|
285
288
|
/** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
|
|
286
289
|
* or undefined when it opens; `columnsOf` reads a table's columns. */
|
|
@@ -487,6 +490,11 @@ export async function openSqliteStore(options) {
|
|
|
487
490
|
if (role === "runner" && (await connection.all("SELECT name FROM pragma_table_info('run_attempts')")).length === 0) {
|
|
488
491
|
throw new StoreAwaitsServer("keep each claim's turn and attempt (run_attempts)");
|
|
489
492
|
}
|
|
493
|
+
// A run's end writes its ledger row and spend rows (schema.ts LEARNING_LEDGER, LEARNING_SPEND) in its own transaction:
|
|
494
|
+
// a runner waits for the server that adds the tables (STORE_DDL at its start).
|
|
495
|
+
if (role === "runner" && (await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name IN ('learning_ledger', 'learning_spend')")).length < 2) {
|
|
496
|
+
throw new StoreAwaitsServer("write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)");
|
|
497
|
+
}
|
|
490
498
|
// The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
|
|
491
499
|
// migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
|
|
492
500
|
// An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
|
|
@@ -523,6 +531,13 @@ export async function openSqliteStore(options) {
|
|
|
523
531
|
{ sql: COMPUTER_INTERVALS_RUN },
|
|
524
532
|
// Nor any claim's turn and attempt (schema.ts RUN_ATTEMPTS): a claim made before it has no row.
|
|
525
533
|
{ sql: RUN_ATTEMPTS },
|
|
534
|
+
// Nor any learning ledger (schema.ts LEARNING_LEDGER, LEARNING_SPEND): a run that ended before it has no row, and
|
|
535
|
+
// its reader records it from its run row.
|
|
536
|
+
{ sql: LEARNING_LEDGER },
|
|
537
|
+
{ sql: LEARNING_LEDGER_AGENT },
|
|
538
|
+
{ sql: LEARNING_SPEND },
|
|
539
|
+
{ sql: LEARNING_SPEND_AGENT },
|
|
540
|
+
{ sql: LEARNING_SPEND_OF_RUN },
|
|
526
541
|
{ sql: NATIVE_COMMANDS_INDEX },
|
|
527
542
|
], { full: true });
|
|
528
543
|
// A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
|
|
@@ -633,6 +648,12 @@ export function storeOver(connection, now, file) {
|
|
|
633
648
|
/** How long a purge's checkpoint waits for another connection's reader or writer before it leaves the log to the next
|
|
634
649
|
* start's scrub: short, since every other request of the store's connection queues behind it. */
|
|
635
650
|
const PURGE_CHECKPOINT_BUSY_MS = 20;
|
|
651
|
+
/** Run `runId`'s learning ledger (learn/ledger.ts), gone: its row, each spend row it booked, and an audit's spend row of
|
|
652
|
+
* it (its shadow's, of_run). What a run's purge (Runs.purge) and its delete (Runs.remove) both drop. */
|
|
653
|
+
async function dropLedger(tx, runId) {
|
|
654
|
+
await tx.run("DELETE FROM learning_ledger WHERE run_id = ?", runId);
|
|
655
|
+
await tx.run("DELETE FROM learning_spend WHERE run_id = ? OR of_run = ?", runId, runId);
|
|
656
|
+
}
|
|
636
657
|
/** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
|
|
637
658
|
* (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
|
|
638
659
|
async function dropRunContent(tx, runId) {
|
|
@@ -923,6 +944,8 @@ class SqliteStore {
|
|
|
923
944
|
if (left.length)
|
|
924
945
|
throw new TriggersLeft(agentId, left.map((one) => one.id));
|
|
925
946
|
await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
|
|
947
|
+
await tx.run("DELETE FROM learning_ledger WHERE agent_id = ?", agentId);
|
|
948
|
+
await tx.run("DELETE FROM learning_spend WHERE agent_id = ?", agentId);
|
|
926
949
|
await dropAgentPrivate(tx, agentId);
|
|
927
950
|
// Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
|
|
928
951
|
// agent's pointer at its current one cleared first.
|
|
@@ -1383,7 +1406,7 @@ class SqliteStore {
|
|
|
1383
1406
|
},
|
|
1384
1407
|
// A list's page from the rows alone: filtered, ordered and cut to the page in the query, one read whatever the number
|
|
1385
1408
|
// of runs, each row with its listing (schema.ts RUN_LISTING_COLUMNS) and its agent's archive time.
|
|
1386
|
-
listed: async ({ agentId, revisionId, labels, archived, status, going, after, limit, offset = 0 }) => {
|
|
1409
|
+
listed: async ({ agentId, revisionId, labels, source, archived, status, going, after, limit, offset = 0 }) => {
|
|
1387
1410
|
const n = clock();
|
|
1388
1411
|
const behind = listingBehind(n.sql);
|
|
1389
1412
|
// Neither a built-in learning run nor an audit's shadow run (learn/audit.ts SHADOW_PREFIX, matched as it is, case and all).
|
|
@@ -1395,6 +1418,10 @@ class SqliteStore {
|
|
|
1395
1418
|
(where.push("runs.revision_id = ?"), params.push(revisionId));
|
|
1396
1419
|
for (const [key, value] of Object.entries(labels ?? {}))
|
|
1397
1420
|
(where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
|
|
1421
|
+
if (source === "live")
|
|
1422
|
+
where.push("runs.imported_from IS NULL");
|
|
1423
|
+
else if (source !== undefined)
|
|
1424
|
+
(where.push(`${d.jsonText("runs.imported_from", ["source"])} = ?`), params.push(source));
|
|
1398
1425
|
where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`, "runs.purged_at IS NULL");
|
|
1399
1426
|
if (status !== undefined)
|
|
1400
1427
|
(where.push("runs.list_status = ?"), params.push(status));
|
|
@@ -1450,11 +1477,14 @@ class SqliteStore {
|
|
|
1450
1477
|
healCost: async (runId, { epoch, endedAt }, { costUsd, costUpperBound }) => {
|
|
1451
1478
|
if (!Number.isFinite(costUsd) || costUsd < 0)
|
|
1452
1479
|
throw new TypeError(`a healed cost is a figure of $0 or more (got ${costUsd})`);
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1480
|
+
// Its ledger row is recorded again with it, in the same transaction: the job's cost it reads is the healed one.
|
|
1481
|
+
return db.transaction(async (tx) => {
|
|
1482
|
+
const row = await tx.get(`UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING ${RUN_COLUMNS}`, costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt);
|
|
1483
|
+
if (!row)
|
|
1484
|
+
return false;
|
|
1485
|
+
await recordLedger(tx, runOf(row), now());
|
|
1486
|
+
return true;
|
|
1487
|
+
});
|
|
1458
1488
|
},
|
|
1459
1489
|
// The runs healCost may write that the heal's rule (store-view.ts bookedCostOf, healOf) does not refuse by its
|
|
1460
1490
|
// columns alone, so the start sweep never reads one that cannot heal again at each start: left out are a person's
|
|
@@ -1537,6 +1567,9 @@ class SqliteStore {
|
|
|
1537
1567
|
const state = JSON.parse(row.proposal)?.state;
|
|
1538
1568
|
await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
|
|
1539
1569
|
}
|
|
1570
|
+
// Its ledger row and every spend row it booked or that audits it, as a remove takes them: what it cost stays on its
|
|
1571
|
+
// tombstone (cost_usd, the metrics' figures), which the readers of money (usage, stats) read; no series shows it.
|
|
1572
|
+
await dropLedger(tx, runId);
|
|
1540
1573
|
// Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
|
|
1541
1574
|
// read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
|
|
1542
1575
|
const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
|
|
@@ -1556,6 +1589,8 @@ class SqliteStore {
|
|
|
1556
1589
|
throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
|
|
1557
1590
|
await dropRunContent(tx, runId);
|
|
1558
1591
|
await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
|
|
1592
|
+
// Its ledger row and every spend row it booked or that audits it, as a purge takes them.
|
|
1593
|
+
await dropLedger(tx, runId);
|
|
1559
1594
|
// Its computers' usage, which a purge keeps (figures, no words).
|
|
1560
1595
|
await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
|
|
1561
1596
|
await tx.run("DELETE FROM runs WHERE id = ?", runId);
|
|
@@ -1606,9 +1641,11 @@ class SqliteStore {
|
|
|
1606
1641
|
await d.lockRow(tx, "runs", "id", id, "update");
|
|
1607
1642
|
const at = now();
|
|
1608
1643
|
const n = storeNow(d, () => at);
|
|
1609
|
-
const row = await tx.get(`UPDATE runs SET state = 'failed', summary = ?, ended_at = ?, left_running_at = ${n.sql}, epoch = epoch + 1 WHERE id = ? AND state = 'queued' AND epoch = 0 AND runner IS NULL RETURNING
|
|
1644
|
+
const row = await tx.get(`UPDATE runs SET state = 'failed', summary = ?, ended_at = ?, left_running_at = ${n.sql}, epoch = epoch + 1 WHERE id = ? AND state = 'queued' AND epoch = 0 AND runner IS NULL RETURNING ${RUN_COLUMNS}`, summary, at, ...n.params, id);
|
|
1610
1645
|
if (!row)
|
|
1611
1646
|
return false;
|
|
1647
|
+
// Its ledger row, as an end writes one (applyRunPatch).
|
|
1648
|
+
await recordLedger(tx, runOf(row), at);
|
|
1612
1649
|
// As an end does: its untaken commands refused, its launch's secrets erased, in this same commit.
|
|
1613
1650
|
await refuseLeftovers(tx, id, "failed", at, d);
|
|
1614
1651
|
return true;
|
|
@@ -1928,6 +1965,32 @@ class SqliteStore {
|
|
|
1928
1965
|
return kept?.state === "proposed" ? [] : [{ agentId: row.agent_id, at: row.created_at, costUsd: 0 }];
|
|
1929
1966
|
});
|
|
1930
1967
|
},
|
|
1968
|
+
ledger: async (agentId, runIds) => {
|
|
1969
|
+
if (runIds !== undefined && runIds.length === 0)
|
|
1970
|
+
return { rows: [], spend: [] };
|
|
1971
|
+
const list = runIds === undefined ? "" : runIds.map(() => "?").join(", ");
|
|
1972
|
+
const rowsOf = runIds === undefined ? { sql: "", params: [] } : { sql: ` AND run_id IN (${list})`, params: [...runIds] };
|
|
1973
|
+
const spendOf = runIds === undefined ? { sql: "", params: [] } : { sql: ` AND (run_id IN (${list}) OR of_run IN (${list}))`, params: [...runIds, ...runIds] };
|
|
1974
|
+
const text = "CAST(NULL AS TEXT)", whole = "CAST(NULL AS BIGINT)", usd = "CAST(NULL AS DOUBLE PRECISION)";
|
|
1975
|
+
const parts = await db.all(`SELECT 'row' AS part, run_id, agent_id, started_at, path, workflow, digest, not_served, job_usd, look_back_usd, cost, epoch, ${text} AS kind, ${whole} AS round, ${text} AS of_run, ${usd} AS usd
|
|
1976
|
+
FROM learning_ledger WHERE agent_id = ?${rowsOf.sql}
|
|
1977
|
+
UNION ALL
|
|
1978
|
+
SELECT 'spend' AS part, run_id, agent_id, ${whole}, ${text}, workflow, digest, ${text}, ${usd}, ${usd}, ${text}, ${whole}, kind, round, of_run, usd
|
|
1979
|
+
FROM learning_spend WHERE agent_id = ?${spendOf.sql}`, agentId, ...rowsOf.params, agentId, ...spendOf.params);
|
|
1980
|
+
const usdOf = (value) => (value === null ? null : Number(value));
|
|
1981
|
+
const rows = parts.filter((one) => one.part === "row").map((row) => ({
|
|
1982
|
+
runId: row.run_id, agentId: row.agent_id, startedAt: Number(row.started_at), path: row.path, workflow: row.workflow, digest: row.digest,
|
|
1983
|
+
notServed: row.not_served, jobUsd: usdOf(row.job_usd), lookBackUsd: usdOf(row.look_back_usd), cost: row.cost, epoch: Number(row.epoch),
|
|
1984
|
+
}));
|
|
1985
|
+
const spend = parts.filter((one) => one.part === "spend").map((row) => ({
|
|
1986
|
+
runId: row.run_id, round: Number(row.round), agentId: row.agent_id, kind: row.kind, ofRun: row.of_run, workflow: row.workflow, digest: row.digest, usd: usdOf(row.usd),
|
|
1987
|
+
}));
|
|
1988
|
+
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
1989
|
+
return {
|
|
1990
|
+
rows: rows.sort((a, b) => a.startedAt - b.startedAt || byText(a.runId, b.runId)),
|
|
1991
|
+
spend: spend.sort((a, b) => byText(a.runId, b.runId) || byText(a.kind, b.kind) || a.round - b.round),
|
|
1992
|
+
};
|
|
1993
|
+
},
|
|
1931
1994
|
};
|
|
1932
1995
|
this.settings = {
|
|
1933
1996
|
get: async (key) => {
|
package/dist/store/store.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { Context } from "@earendil-works/chord/context";
|
|
|
2
2
|
import type { Storage, StorageWrite } from "@earendil-works/pi-durable";
|
|
3
3
|
import type { JournalPage } from "./journal/storage.js";
|
|
4
4
|
import type { MonidPinBody } from "./agent-body.js";
|
|
5
|
+
import type { LedgerRow, SpendRow } from "../learn/ledger.js";
|
|
5
6
|
/** A run's state. queued: a row, no runner yet. running: a runner holds the claim. parked: waiting for a person (an
|
|
6
7
|
* approval, a raised cap) with no claim held; a command row or its wake_at makes it claimable again. ended, stopped and
|
|
7
8
|
* failed are final. A running run whose runner died is claimable once its claim runs out. */
|
|
@@ -163,6 +164,8 @@ export interface ListedFilter {
|
|
|
163
164
|
readonly agentId?: string;
|
|
164
165
|
readonly revisionId?: string;
|
|
165
166
|
readonly labels?: RunLabels;
|
|
167
|
+
/** Only runs imported from this source (imported_from.source), or with "live" the runs not imported. */
|
|
168
|
+
readonly source?: string;
|
|
166
169
|
readonly archived: boolean;
|
|
167
170
|
readonly status?: string;
|
|
168
171
|
/** Only runs still going (no settled status on the row) whose listing is behind. */
|
|
@@ -466,6 +469,17 @@ export interface Learning {
|
|
|
466
469
|
from: number;
|
|
467
470
|
to: number;
|
|
468
471
|
}): Promise<LearningSpend[]>;
|
|
472
|
+
/** Agent `agentId`'s ledger (learn/ledger.ts), in one read (one snapshot of both tables): every run's row its end
|
|
473
|
+
* recorded, oldest first, each with the end it was recorded for (`epoch`, its run's epoch then), and every spend row.
|
|
474
|
+
* With `runIds`, those runs' rows alone and the spend rows they booked or that audit them (none for none). Written
|
|
475
|
+
* only beside a run's end and a heal of its cost (run-patch.ts recordLedger); a purge or a delete of the run takes its
|
|
476
|
+
* row and its spend. */
|
|
477
|
+
ledger(agentId: string, runIds?: readonly string[]): Promise<{
|
|
478
|
+
rows: (LedgerRow & {
|
|
479
|
+
readonly epoch: number;
|
|
480
|
+
})[];
|
|
481
|
+
spend: SpendRow[];
|
|
482
|
+
}>;
|
|
469
483
|
}
|
|
470
484
|
/** One run's learning end as GET /usage's learning meter counts it (Learning.spend). */
|
|
471
485
|
export interface LearningSpend {
|