@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.56

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.
Files changed (80) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +44 -10
  3. package/dist/adapters.d.ts +3 -2
  4. package/dist/adapters.js +6 -3
  5. package/dist/answer-json.d.ts +6 -2
  6. package/dist/answer-json.js +22 -4
  7. package/dist/api-only.js +2 -0
  8. package/dist/calendar/tools.js +3 -2
  9. package/dist/chatgpt-plan.d.ts +16 -1
  10. package/dist/chatgpt-plan.js +116 -12
  11. package/dist/claude-login.d.ts +34 -5
  12. package/dist/claude-login.js +31 -7
  13. package/dist/claude-sign-in.d.ts +35 -0
  14. package/dist/claude-sign-in.js +90 -0
  15. package/dist/console/assets/{backend-D5EmB4N3.js → backend-Boh7tC4i.js} +1 -1
  16. package/dist/console/assets/{index-DUYLaqiR.js → index-CQ3cJRzI.js} +130 -130
  17. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/host-check.d.ts +4 -0
  20. package/dist/host-check.js +4 -0
  21. package/dist/key-refusal.d.ts +21 -5
  22. package/dist/key-refusal.js +231 -37
  23. package/dist/learn/secrets.d.ts +20 -10
  24. package/dist/learn/secrets.js +44 -184
  25. package/dist/llms.txt +1 -1
  26. package/dist/openapi.d.ts +3 -3
  27. package/dist/openapi.js +70 -18
  28. package/dist/place-offers.d.ts +14 -6
  29. package/dist/place-offers.js +26 -13
  30. package/dist/redact/match.d.ts +74 -0
  31. package/dist/redact/match.js +771 -0
  32. package/dist/run-timeline-served.d.ts +1 -1
  33. package/dist/run-timeline-served.js +4 -4
  34. package/dist/runner/adapter-loop.d.ts +3 -0
  35. package/dist/runner/adapter-loop.js +1 -1
  36. package/dist/runner/adapter-run-spec.js +4 -1
  37. package/dist/runner/beside.js +7 -3
  38. package/dist/runner/cli-run-spec.js +3 -1
  39. package/dist/runner/loop-contract.d.ts +4 -0
  40. package/dist/runner/main.js +8 -4
  41. package/dist/runner/presence.d.ts +4 -3
  42. package/dist/runner/presence.js +4 -2
  43. package/dist/runner/run-child-host.d.ts +2 -0
  44. package/dist/runner/run-child-host.js +2 -2
  45. package/dist/runner/runner.d.ts +4 -0
  46. package/dist/runner/runner.js +33 -3
  47. package/dist/server.d.ts +5 -2
  48. package/dist/server.js +41 -10
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/index.d.ts +1 -1
  52. package/dist/store/index.js +1 -1
  53. package/dist/store/postgres/dialect.js +3 -0
  54. package/dist/store/sqlite/store.js +43 -13
  55. package/dist/store/store.d.ts +10 -1
  56. package/dist/store/store.js +7 -0
  57. package/dist/store-view.js +1 -1
  58. package/dist/template-eval.d.ts +2 -2
  59. package/dist/template-eval.js +9 -8
  60. package/dist/timeline/index.d.ts +1 -1
  61. package/dist/timeline/index.js +1 -1
  62. package/dist/timeline/timeline.d.ts +12 -7
  63. package/dist/timeline/timeline.js +14 -6
  64. package/dist/tool-gate.js +3 -1
  65. package/dist/validate.js +1 -1
  66. package/dist/workspace/computer-deps.d.ts +2 -1
  67. package/dist/workspace/computer-deps.js +5 -4
  68. package/dist/workspace/computer-for-claim.d.ts +8 -2
  69. package/dist/workspace/computer-for-claim.js +28 -9
  70. package/dist/workspace/computer-janitor.d.ts +15 -7
  71. package/dist/workspace/computer-janitor.js +33 -8
  72. package/dist/workspace/computer-kept.d.ts +52 -4
  73. package/dist/workspace/computer-kept.js +118 -6
  74. package/dist/workspace/run-end-computers.d.ts +5 -1
  75. package/dist/workspace/run-end-computers.js +27 -1
  76. package/dist/wrapped.d.ts +57 -0
  77. package/dist/wrapped.js +51 -0
  78. package/package.json +11 -11
  79. package/templates/README.md +8 -7
  80. package/dist/console/assets/index-DYhU4adm.css +0 -1
@@ -13,6 +13,6 @@ export type ServedTimelineDeps = {
13
13
  readonly statuses?: (agentId: string) => Promise<ReadonlyMap<string, ItemStatus> | undefined>;
14
14
  };
15
15
  /** Run `runId`'s Timeline rows as served: cut by its one cut set, its decision rows among them, its error rows in the
16
- * run's error's words; none for a run withheld. `calls`: each call's arguments whole and its output's head to
16
+ * run's error's words; none for a run withheld. `calls`: each call's arguments whole and its output whole to
17
17
  * CALL_RESULT_CHARS too (TimelineOptions.calls), through the same cut, for a reader that grades the run. */
18
18
  export declare function servedTimelineRows(deps: ServedTimelineDeps, store: Store, runId: string, context: Context, calls?: boolean): Promise<TimelineEvent[]>;
@@ -1,9 +1,9 @@
1
- import { CALL_RESULT_CHARS, TRIGGER_LABELS } from "./timeline/index.js";
1
+ import { CALL_RESULT_CHARS, scrubUrls, TRIGGER_LABELS } from "./timeline/index.js";
2
2
  import { withDecisions } from "./decision-rows.js";
3
3
  import { currentLearning, holdsForOk, secretsShown } from "./learning.js";
4
4
  import { withLearning } from "./learning-run.js";
5
5
  import { runLearningEnd } from "./store-reads/learning.js";
6
- import { heldNumber, redacted } from "./key-refusal.js";
6
+ import { heldNumber, redacted, redactedCall } from "./key-refusal.js";
7
7
  import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
8
8
  import { answersOf, asksOf, shownOf, stopAsked, withApprovalRows, withAsks, withBudgetRows, withOverCap } from "./run-view.js";
9
9
  import { launchOf } from "./handed-values.js";
@@ -14,7 +14,7 @@ import { readRun } from "./store-reads/runs.js";
14
14
  import { runTimeline, servedSince, wholeAnswerFor, wholeAnswers } from "./store-reads/journal.js";
15
15
  import { FINAL_STATES } from "./store/store.js";
16
16
  /** Run `runId`'s Timeline rows as served: cut by its one cut set, its decision rows among them, its error rows in the
17
- * run's error's words; none for a run withheld. `calls`: each call's arguments whole and its output's head to
17
+ * run's error's words; none for a run withheld. `calls`: each call's arguments whole and its output whole to
18
18
  * CALL_RESULT_CHARS too (TimelineOptions.calls), through the same cut, for a reader that grades the run. */
19
19
  export async function servedTimelineRows(deps, store, runId, context, calls = false) {
20
20
  // The run's rows, its decisions, its learning end and the triggers' names, all read in one snapshot of the store (one
@@ -48,7 +48,7 @@ export async function servedTimelineRows(deps, store, runId, context, calls = fa
48
48
  // And every call still waiting once a stop is asked and not yet taken, as the run's view reads it (stopAsked).
49
49
  const final = run?.state === "stopped" || run?.state === "failed" ? run.state
50
50
  : stopAsked(view, run, await snapshot.commands(runId, 0)) ? "stopped" : undefined;
51
- const options = { redact, settled: ended, ended: view ? view.state !== "running" : false, ...(calls ? { calls: { result: CALL_RESULT_CHARS, redact: (text) => redacted(text, values, CALL_RESULT_CHARS), held: (value) => heldNumber(value, values) } } : {}) };
51
+ const options = { redact, settled: ended, ended: view ? view.state !== "running" : false, ...(calls ? { calls: { result: CALL_RESULT_CHARS, redact: (text) => redactedCall(text, values, CALL_RESULT_CHARS, scrubUrls), held: (value) => heldNumber(value, values) } } : {}) };
52
52
  const timeline = await wholeAnswers(snapshot, runId, context, await runTimeline(snapshot, runId, context, options), options, wholeAnswerFor(values), since);
53
53
  // A run whose booked spend passed its cap says so, by how much, after its usage row (run-view.ts withOverCap, as main's
54
54
  // served Timeline did): at the cap as it stands (a raise taken counts, capNowOf).
@@ -307,6 +307,9 @@ export type AdapterRun = PiRun & {
307
307
  * while it is built (a CLI harness's first-use install), so a stop ends that wait at once and never the work it waits
308
308
  * for. Absent where no loop gave one. */
309
309
  readonly stopped?: AbortSignal;
310
+ /** The runner's presence incarnation (LoopDeps.incarnation): with the claim's runner, who keeps a computer a park pins
311
+ * to its runner (computer-for-claim.ts ClaimLaunch.holder). Absent where no loop gave one. */
312
+ readonly incarnation?: string;
310
313
  /** Stages the run row's `summary` on the next commit of this pass that writes a root entry of `kind` whose data `test`
311
314
  * takes, in that commit (a tool host's wait on the person, its claim held: the server tells run.needs_input by the
312
315
  * summary). Absent where no loop gave one. */
@@ -1510,7 +1510,7 @@ function adapterLoop(specOf, options, deps) {
1510
1510
  return;
1511
1511
  passGate.expect(writesEntry(kind, test), { run: { summary } }).catch(() => undefined);
1512
1512
  };
1513
- const runOf = { harness, registry, setModels: (given) => (models = given), ledger, redact: deps.redact, signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn };
1513
+ const runOf = { harness, registry, setModels: (given) => (models = given), ledger, redact: deps.redact, signal: deps.signal, stopped: AbortSignal.any([deps.signal, stopAbort.signal]), phase, rowSummaryOn, ...(deps.incarnation ? { incarnation: deps.incarnation } : {}) };
1514
1514
  // The spec, its MCP claim step among it (mcpForClaim, before the session opens). A refusal there ends the run in its
1515
1515
  // words with nothing sent; a claim lost during its refresh ends the loop with nothing more written. A claim the spec
1516
1516
  // refuses (ClaimRefused: a handed sign-in that won't read back) ends the run in its words too.
@@ -358,7 +358,10 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
358
358
  // Docker container for a sandbox, under the claim's epoch (the one fence). It throws computer_unavailable (nothing made)
359
359
  // when the computer cannot be had: the run fails in its words.
360
360
  const claimSignal = run.stopped ?? run.signal;
361
- const computer = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, claim, agentId: runRow.agentId, revisionId: runRow.revisionId, place: launch.place }, deps.store,
361
+ const computer = await deps.computerForClaim(
362
+ // The runner holding the claim (its name, its presence incarnation): a computer a park keeps that only it can reach
363
+ // again is pinned to it.
364
+ { runId: claim.runId, epoch: claim.epoch, claim, agentId: runRow.agentId, revisionId: runRow.revisionId, place: launch.place, ...(run.incarnation ? { holder: { runner: claim.runner, incarnation: run.incarnation } } : {}) }, deps.store,
362
365
  // revokeMount removes the run's Archil mount credential when the computer is released (and if a start fails after a mint);
363
366
  // the run's end revokes it too (below), so it goes on every outcome even when no computer is made. Idempotent. What
364
367
  // became of the agent's own computer (a persistent setting) is said on the run's timeline.
@@ -120,15 +120,19 @@ export async function runnerBeside(dataDir, { loops, loopsTold, drainMs, env, ja
120
120
  if (event.type === "ended")
121
121
  onRunEnded?.(event.status);
122
122
  };
123
- // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts).
123
+ // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts), as
124
+ // the runner beside it (read at each end, once it has started): a computer kept pinned to another runner is that one's.
124
125
  const { runEndComputers } = await import("../workspace/run-end-computers.js");
125
126
  const { projectRunEnded } = await import("../source-sync/checkpoints.js");
126
- const runEnded = projectRunEnded(store, runEndComputers({ store, computers: computers.computerDeps, log: (line) => console.error(`agentrun-serve runner: ${line}`) }));
127
+ const self = () => (runner.incarnation ? { runner: name, incarnation: runner.incarnation } : undefined);
128
+ const runEnded = projectRunEnded(store, runEndComputers({ store, computers: computers.computerDeps, log: (line) => console.error(`agentrun-serve runner: ${line}`), self }));
127
129
  const runner = startRunner({ store, name, createLoop, memory: runnerMemory(store, undefined, runs, isolation ? RUN_PROCESS_MIB : 0), onEvent: said, runEnded, ...(held !== undefined ? { loops: held } : {}), ...(drainMs !== undefined ? { drainMs } : {}) });
128
130
  // The computer janitor over the same computers, when the start asks for it: never under --faux. Its lines are the
129
131
  // runner's, on stderr (a stderr whose reader closed loses them, never the process: cli.ts).
130
132
  const { startJanitor } = await import("../workspace/computer-janitor.js");
131
- const swept = janitor ? startJanitor({ store, computers: computers.computerDeps, env: runs, log: (line) => console.error(`agentrun-serve runner: ${line}`) }) : undefined;
133
+ // As the runner beside it (its name and its presence's incarnation): a kept computer pinned to another runner still
134
+ // there is that runner's to end (computer-kept.ts sweepKept).
135
+ const swept = janitor ? startJanitor({ store, computers: computers.computerDeps, env: runs, log: (line) => console.error(`agentrun-serve runner: ${line}`), ...(runner.incarnation ? { self: { runner: name, incarnation: runner.incarnation } } : {}) }) : undefined;
132
136
  // Its close waits for any first-use install its claims let go of to stop (its npm ended) before it lets go of the data.
133
137
  const { claimInstallsStopped } = await import("../harness-install.js");
134
138
  // The janitor's sweep is cut and waited for on a bound of its own, beside the runner's close, never before it.
@@ -388,7 +388,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
388
388
  // The run's computer, from the one shared claim-time function (the pi spec takes the same): none for a runner place.
389
389
  // It throws computer_unavailable (nothing made) when the computer cannot be had: the run fails in its words.
390
390
  const claimSignal = run.stopped ?? run.signal;
391
- const computer = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, claim, agentId: runRow.agentId, revisionId: runRow.revisionId, place: launch.place }, deps.store,
391
+ const computer = await deps.computerForClaim(
392
+ // The runner holding the claim, as the pi spec hands it: a computer kept that only it can reach again is pinned to it.
393
+ { runId: claim.runId, epoch: claim.epoch, claim, agentId: runRow.agentId, revisionId: runRow.revisionId, place: launch.place, ...(run.incarnation ? { holder: { runner: claim.runner, incarnation: run.incarnation } } : {}) }, deps.store,
392
394
  // revokeMount removes the run's Archil mount credential at the computer's release (and if a start fails after a mint); the
393
395
  // run's end revokes it too, so it goes on every outcome even with no computer. Idempotent. As the pi spec does, with
394
396
  // what became of the agent's own computer said on the run's timeline.
@@ -191,6 +191,10 @@ export interface LoopDeps {
191
191
  * end goes through it, so no secret the runner holds is stored, its values cut the run's live view (live-ticker.ts),
192
192
  * and a claim carries the run's own tool keys into it (claim-secrets.ts). */
193
193
  redact: HeldRedact;
194
+ /** The incarnation of the runner's word in the store (runner/presence.ts), the claim's runner being the claim's own
195
+ * `runner`: a park that keeps a computer only this runner can reach again pins it to both (workspace/computer-kept.ts
196
+ * pinnedOf), so the claim rule gives the run back to this runner while it is there. Absent: nothing is pinned. */
197
+ incarnation?: string;
194
198
  }
195
199
  /** A run's held state: what pi shows before it stores it. The live view (live/stream.ts) streams it beside the stored
196
200
  * commits' events, in the door's vocabulary (a running tool's tool_execution_start, a partial's message_update). */
@@ -257,7 +257,8 @@ export async function startRunnerProcess(options) {
257
257
  // tokens and proofs name the same one, so the server's "restarted since" and the runner's row speak of one process.
258
258
  // The presence first, then the relay says where it answers on the presence's row.
259
259
  // Its row says this build's version and the most runs it holds (its loops), for the server's capacity read.
260
- presence = keepPresence(store.runners, name, null, { warn, incarnation: randomUUID(), slots: options.loops ?? RUNNER_LOOPS });
260
+ const incarnation = randomUUID();
261
+ presence = keepPresence(store.runners, name, null, { warn, incarnation, slots: options.loops ?? RUNNER_LOOPS });
261
262
  // Its relay (dial-relay.ts), where its environment names the server's public address: a machine that dials the
262
263
  // server lands in this runner's hub, through the server. Its log lines are the runner's warnings.
263
264
  relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, presence, env, log: warn });
@@ -267,12 +268,15 @@ export async function startRunnerProcess(options) {
267
268
  const createLoop = typeof parts === "function" ? parts : parts.createLoop;
268
269
  // The janitor sweeps with the computers the loop composed, never a second composition. Its lines are the runner's
269
270
  // warnings, said where the runner says its others (warn: stderr unless a test gives its own).
271
+ // It sweeps as this runner (its name and its presence's incarnation): a computer kept at a park pinned to another
272
+ // runner still there is that runner's to end (computer-kept.ts sweepKept).
270
273
  if (options.janitor && typeof parts !== "function")
271
- janitor = startJanitor({ store, computers: parts.computers, env: parts.env, log: warn });
274
+ janitor = startJanitor({ store, computers: parts.computers, env: parts.env, log: warn, self: { runner: name, incarnation } });
272
275
  // Before it claims: the scratch folders of runs that ended after their runner died (scratch-sweep.ts), said as warnings.
273
276
  await sweepEndedScratch(store, options.dataDir, { log: warn });
274
- // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts).
275
- const runEnded = projectRunEnded(store, typeof parts !== "function" ? runEndComputers({ store, computers: parts.computers, log: warn }) : undefined);
277
+ // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts), as
278
+ // this runner, as the janitor sweeps: a computer kept pinned to another runner still keeping it is that runner's.
279
+ const runEnded = projectRunEnded(store, typeof parts !== "function" ? runEndComputers({ store, computers: parts.computers, log: warn, self: () => ({ runner: name, incarnation }) }) : undefined);
276
280
  runner = startRunner({
277
281
  store,
278
282
  createLoop,
@@ -1,8 +1,9 @@
1
- import type { Runners } from "../store/store.js";
1
+ import { type Runners } from "../store/store.js";
2
2
  /** How often a runner says again that it is there. */
3
3
  export declare const PRESENCE_RENEW_MS = 10000;
4
- /** How old a runner's word can be and still count: three renewals missed. */
5
- export declare const PRESENCE_STALE_MS: number;
4
+ /** How old a runner's word can be and still count: three renewals missed. The store's (RUNNER_STALE_MS), which its claim
5
+ * rule reads for a kept computer's pin. */
6
+ export declare const PRESENCE_STALE_MS = 30000;
6
7
  /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
7
8
  * capacity read (GET /v2/capacity). */
8
9
  export declare const RUNNER_VERSION: string;
@@ -12,10 +12,12 @@
12
12
  import { randomUUID } from "node:crypto";
13
13
  import { readFileSync } from "node:fs";
14
14
  import { ApiError } from "../errors.js";
15
+ import { RUNNER_STALE_MS } from "../store/store.js";
15
16
  /** How often a runner says again that it is there. */
16
17
  export const PRESENCE_RENEW_MS = 10_000;
17
- /** How old a runner's word can be and still count: three renewals missed. */
18
- export const PRESENCE_STALE_MS = 3 * PRESENCE_RENEW_MS;
18
+ /** How old a runner's word can be and still count: three renewals missed. The store's (RUNNER_STALE_MS), which its claim
19
+ * rule reads for a kept computer's pin. */
20
+ export const PRESENCE_STALE_MS = RUNNER_STALE_MS;
19
21
  /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
20
22
  * capacity read (GET /v2/capacity). */
21
23
  export const RUNNER_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
@@ -117,6 +117,8 @@ interface ClaimReads {
117
117
  };
118
118
  readonly claimed: NodeJS.ProcessEnv;
119
119
  readonly signal?: AbortSignal;
120
+ /** The runner's presence incarnation (LoopDeps.incarnation): with the claim's runner, who keeps a computer a park pins. */
121
+ readonly incarnation?: string;
120
122
  }
121
123
  /** Held (held.ts) for one claim, on the runner: each answer the claim's own, read with the runner's seal key from the
122
124
  * runner's own reads of the claim; every argument from the run's process is checked or ignored. `bigs`: the run's pieced
@@ -812,7 +812,7 @@ export function heldFor(deps, reads, cut, log, bigs = runBigWrites()) {
812
812
  ? await openRunWorkspace({ mode: 1, agentId: run.agentId, runId: claim.runId, data: deps.data, log })
813
813
  : await openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: made, log });
814
814
  const say = typeof ask.say === "function" ? ask.say : undefined;
815
- const got = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, claim, agentId: run.agentId, revisionId: run.revisionId, place: launch.place }, store, {
815
+ const got = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, claim, agentId: run.agentId, revisionId: run.revisionId, place: launch.place, ...(reads.incarnation ? { holder: { runner: claim.runner, incarnation: reads.incarnation } } : {}) }, store, {
816
816
  ...deps.computerDeps, mode, workspace: ws.workspace, sealKey,
817
817
  recordings: { folder: recordingsFolder(deps.data, run.agentId, claim.runId), say: (words) => say?.(cut(words)) },
818
818
  hadComputer: async () => (await ask.hadComputer()) === true,
@@ -1213,7 +1213,7 @@ function childLoop(options, slots, loopDeps) {
1213
1213
  const tops = runTops(deps.data, runRow.agentId, claim.runId);
1214
1214
  // The run's pieced writes (big-writes.ts): let go when its channel ends, or at the claim's release.
1215
1215
  const bigs = runBigWrites();
1216
- const heldSide = heldFor({ ...deps, env: claimEnv }, { claim, run: runRow, launch, revision, claimed: gatewayKey ? withGatewayKey(claimed, gatewayKey) : claimed, signal: loopDeps.signal }, cut, log, bigs);
1216
+ const heldSide = heldFor({ ...deps, env: claimEnv }, { claim, run: runRow, launch, revision, claimed: gatewayKey ? withGatewayKey(claimed, gatewayKey) : claimed, signal: loopDeps.signal, ...(loopDeps.incarnation ? { incarnation: loopDeps.incarnation } : {}) }, cut, log, bigs);
1217
1217
  try {
1218
1218
  let extra = {};
1219
1219
  let argv = [...(options.argv ?? childArgv())];
@@ -197,6 +197,10 @@ export type RunnerEvent = {
197
197
  export type HandBackCause = "drain" | "interrupted" | "end_retry" | "give_back";
198
198
  export interface Runner {
199
199
  readonly name: string;
200
+ /** The incarnation of its word in the store (presence.ts: its caller's, else its own), which its loops hand each claim's
201
+ * computer (LoopDeps.incarnation): a computer a park keeps pinned to this runner names it. Absent with no store
202
+ * runners, where no word is kept. */
203
+ readonly incarnation?: string;
200
204
  /** The claims this runner holds and has not lost. */
201
205
  held(): Claim[];
202
206
  /** Stops claiming, lets each held run go on to its own end for up to drainMs, then stops every loop left where it can
@@ -23,6 +23,7 @@ import { isFenced } from "./store-port.js";
23
23
  import { FINAL_STATES } from "../store/store.js";
24
24
  import { Unanswered } from "../store/postgres/connection.js";
25
25
  import { clearWaitEnded } from "../browser-wait-ended.js";
26
+ import { keptBy, readKept } from "../workspace/computer-kept.js";
26
27
  import { cutDeep, heldRedactor, processSecretRedactor } from "./redact.js";
27
28
  import { withLiveTicker } from "./live-ticker.js";
28
29
  import { keepPresence } from "./presence.js";
@@ -545,6 +546,23 @@ export function startRunner(options) {
545
546
  return false;
546
547
  }
547
548
  };
549
+ /** Whether the run under `claim` has a computer its park kept pinned to a runner other than this one, this process
550
+ * (computer-kept.ts: the row names a runner and incarnation, keptBy). A row that cannot be read says yes: a loop
551
+ * started on a guess would read the row again in its claim's computer, take it and try the machine from here,
552
+ * dropping the row that runner's timer ends it by. Ending the stop with no loop touches no computer, and the row's
553
+ * runner (or any janitor, once that runner is gone) still ends it. */
554
+ const keptElsewhere = async (claim) => {
555
+ if (!store.settings)
556
+ return false;
557
+ try {
558
+ const kept = await readKept(store.settings, claim.runId);
559
+ const ours = (options.presence ?? presence)?.incarnation;
560
+ return kept?.runner !== undefined && !keptBy(kept, ours ? { runner: name, incarnation: ours } : undefined);
561
+ }
562
+ catch {
563
+ return true;
564
+ }
565
+ };
548
566
  /** A claim of a run whose stopped end was refused (its untaken stop row has tries): it only ends the run, with no loop,
549
567
  * so no turn, model request or tool runs on a run that is stopping. */
550
568
  const endRetried = async (claim, stop) => {
@@ -698,7 +716,11 @@ export function startRunner(options) {
698
716
  let ending = () => { };
699
717
  // Set below, once held is made: the loop asks deliverNow only once its first turn has ended, well after.
700
718
  let heldNow;
719
+ // This runner's process as its word in the store names it (presence.ts), for the claim's computer: a park that keeps one
720
+ // only this runner can reach again pins it to this runner and this incarnation (computer-kept.ts pinnedOf).
721
+ const ours = (options.presence ?? presence)?.incarnation;
701
722
  const loop = loopsOf({
723
+ ...(ours ? { incarnation: ours } : {}),
702
724
  journal: (forClaim) => fenced(store.journal(forClaim), fence, forClaim.runId, () => ending()),
703
725
  flush: () => store.flush(),
704
726
  signal: abort.signal,
@@ -849,13 +871,18 @@ export function startRunner(options) {
849
871
  // starts now, not even its first input: a loop started first would send that input before the stop reached it;
850
872
  // - a run whose untaken stop row has tries, which failed to apply that stop before. Either source of tries counts: a
851
873
  // refused stopped end (endRefused, released running) or a failed resume (resumeFailed's store.retry, released
852
- // parked).
874
+ // parked);
875
+ // - a parked run stopped or cancelled whose computer its park kept pinned to another runner, or whose kept row can't
876
+ // be read (keptElsewhere): the store gives a stop to any runner at once, never waiting on the pin, and this
877
+ // runner can't reach that machine.
878
+ // A loop would take the kept row (takeKept) and try to attach it, orphaning it on that runner's host; ending here
879
+ // leaves the row that runner's, whose own timer at its time, or its janitor once the run is final, ends it.
853
880
  // One read of those claims' rows, made only when the batch has a queued or a released run.
854
881
  const reread = claims.filter((claim) => claim.from === "queued" || claim.from === "running" || claim.from === "parked");
855
882
  const rows = reread.length ? await store.commandsOf(reread.map((claim) => ({ runId: claim.runId, after: 0 }))) : new Map();
856
883
  for (const claim of claims) {
857
884
  const stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
858
- const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))));
885
+ const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))) || (claim.from === "parked" && (await keptElsewhere(claim))));
859
886
  if (stop && endsOnly && !closed && !killed && !runs.has(claim.runId)) {
860
887
  const key = `${claim.runId}:${claim.epoch}`;
861
888
  endingClaims.add(key);
@@ -903,7 +930,8 @@ export function startRunner(options) {
903
930
  * claim's loop still running holds its weight too): each claimed on its own, its weight put in `weights`. The first that
904
931
  * does not fit ends the claim, unless the runner holds nothing: then it is claimed alone. */
905
932
  const claimByMemory = async (budget, free, weights) => {
906
- const waiting = await store.runs.claimable({ limit: free });
933
+ // As this runner's claimer: a run whose computer is kept for another runner still there is not among them.
934
+ const waiting = await store.runs.claimable({ limit: free, runner: name });
907
935
  if (waiting.length === 0)
908
936
  return [];
909
937
  const weighed = await budget.weigh(waiting);
@@ -1068,8 +1096,10 @@ export function startRunner(options) {
1068
1096
  for (const held of runs.values())
1069
1097
  clock.clearTimeout(held.deadline);
1070
1098
  };
1099
+ const incarnation = (options.presence ?? presence)?.incarnation;
1071
1100
  return {
1072
1101
  name,
1102
+ ...(incarnation ? { incarnation } : {}),
1073
1103
  held: () => [...runs.values()].filter((held) => !held.fence.lost && !held.ending).map((held) => held.claim),
1074
1104
  async close() {
1075
1105
  if (closed || killed)
package/dist/server.d.ts CHANGED
@@ -165,6 +165,9 @@ export type ServeOptions = {
165
165
  harnessSignIn?: boolean;
166
166
  /** With `faux` only: Docker answers, so docker is available, and nothing asks Docker (place-offers.ts). */
167
167
  fauxDocker?: boolean;
168
+ /** For tests: how long the Claude Code CLI's own sign-in this server starts waits for its browser before it is ended
169
+ * (claude-sign-in.ts), in place of 10 minutes. */
170
+ claudeSignInLimitMs?: number;
168
171
  /** For tests: the lock each harness's first use installs by (harness-install.ts), by harness, with the package.json it
169
172
  * locks beside it, in place of the one AgentRun ships, whose packages a test's own registry serves. */
170
173
  harnessLocks?: Readonly<Record<string, string>>;
@@ -636,7 +639,7 @@ export declare function readingOf(base: NodeJS.ProcessEnv, maxRuns: number, stor
636
639
  * grant (runnable.ts takes one on any), a module's among them. */
637
640
  mcp_client: {
638
641
  transports: string[];
639
- auth: ("headers" | "none" | "oauth" | "bearer" | "github_app" | "per_run")[];
642
+ auth: ("headers" | "none" | "bearer" | "oauth" | "github_app" | "per_run")[];
640
643
  at_rest: string;
641
644
  harnesses: string[];
642
645
  };
@@ -971,7 +974,7 @@ export declare function capabilities(env?: NodeJS.ProcessEnv, maxRuns?: number,
971
974
  * grant (runnable.ts takes one on any), a module's among them. */
972
975
  mcp_client: {
973
976
  transports: string[];
974
- auth: ("headers" | "none" | "oauth" | "bearer" | "github_app" | "per_run")[];
977
+ auth: ("headers" | "none" | "bearer" | "oauth" | "github_app" | "per_run")[];
975
978
  at_rest: string;
976
979
  harnesses: string[];
977
980
  };
package/dist/server.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CALLS_PAGE_ROWS } from "./timeline/index.js";
1
2
  import { prepareProjectSkillEdit } from "./source-sync/skill-edits.js";
2
3
  import { sourceSyncOf } from "./source-sync/types.js";
3
4
  import { sourceService, SOURCE_BODY_BYTES } from "./source-sync/service.js";
@@ -77,7 +78,7 @@ import { dockerLimitsOf } from "./workspace/computer-deps.js";
77
78
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
78
79
  import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
79
80
  import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, consoleEntry, heldSessions, isJson, overHttps, ownerCookie, ownerCookieName, ownOrigin, sessionsAtEveryPort, sendHostRefused, sendMoved, sendMovedPage, signedIn } from "./page.js";
80
- import { hostFix, hostName, loopbackNames, movedFix } from "./host-check.js";
81
+ import { hostFix, hostName, isLoopbackName, loopbackNames, movedFix } from "./host-check.js";
81
82
  import { movedAddress, publicAddressChanged, readPublicAddress } from "./public-address.js";
82
83
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
83
84
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
@@ -142,12 +143,14 @@ import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWri
142
143
  import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
143
144
  import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
144
145
  import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, loopback, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
146
+ import { ClaudeSignIns } from "./claude-sign-in.js";
145
147
  import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
146
148
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
147
149
  import { recordDataRoot } from "./runner/disk-free.js";
148
150
  import { recordRunEnv, runFacingNames } from "./runner/runner-check.js";
149
151
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
150
152
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
153
+ import { readWrapped, wrappedView } from "./wrapped.js";
151
154
  import { joinedBasis } from "./runner/metrics.js";
152
155
  import { unifiedUsage } from "./unified-usage.js";
153
156
  import { agentLoopOverStore } from "./store-reads/loop.js";
@@ -442,6 +445,8 @@ export const ROUTES = [
442
445
  { method: "GET", pattern: /^\/stats$/, name: "getStats" },
443
446
  // The runs waiting and held, the live runners and their free slots, and the recent hand-backs (capacity.ts).
444
447
  { method: "GET", pattern: /^\/capacity$/, name: "getCapacity" },
448
+ // A year of the work under this machine's home (wrapped.ts), on a server on the person's own machine alone.
449
+ { method: "GET", pattern: /^\/wrapped$/, name: "getWrapped" },
445
450
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
446
451
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
447
452
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
@@ -1272,15 +1277,22 @@ async function startHolding(options, data, checked, stops) {
1272
1277
  savedGateway = await readSavedGateway(store, seal.key);
1273
1278
  await keysChanged();
1274
1279
  };
1275
- /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
1280
+ /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again;
1281
+ * so does a sign-in's change this server failed to take (changed_failed), until it takes. */
1276
1282
  const planNow = async () => {
1277
1283
  const was = plan.state;
1278
1284
  if ((await plan.load()).state !== was)
1279
1285
  await keysChanged();
1286
+ else
1287
+ await plan.changeAgain();
1280
1288
  };
1281
1289
  /** What Claude Code's login routes use: a turn on or off reads the setting again, then env, as a key's save does. A
1282
- * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here. */
1290
+ * sign-in this server starts opens a browser on its machine, so only where the console is on loopback here; it is
1291
+ * kept for this process (claude-sign-in.ts), and one still waiting is ended at the stop. */
1292
+ const claudeSignIns = new ClaudeSignIns({ limitMs: options.claudeSignInLimitMs });
1293
+ stops.push(async () => claudeSignIns.close());
1283
1294
  const loginDeps = () => ({
1295
+ signIns: claudeSignIns,
1284
1296
  settings: store.settings,
1285
1297
  data,
1286
1298
  env: base,
@@ -4066,16 +4078,18 @@ async function startHolding(options, data, checked, stops) {
4066
4078
  async function timeline(req, res, url, runId) {
4067
4079
  const after = integerParam(url.searchParams.get("after"), "after", Number.MAX_SAFE_INTEGER);
4068
4080
  const waitMs = integerParam(url.searchParams.get("wait_ms"), "wait_ms", MAX_WAIT_MS);
4069
- // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's).
4070
- const asked = url.searchParams.get("limit");
4071
- if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
4072
- throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
4073
- const limit = asked === null ? PAGE_ROWS : Number(asked);
4074
- // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
4081
+ // `calls=whole`: each call's arguments and its output too, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), for a grader.
4075
4082
  const shape = url.searchParams.get("calls");
4076
4083
  if (shape !== null && shape !== "whole")
4077
4084
  throw new ApiError("bad_request", "calls is whole, or absent");
4078
4085
  const calls = shape === "whole";
4086
+ // This server's own: a page of at most `limit` rows, for a client that reads a little at a time (the MCP tool's). A
4087
+ // calls=whole page holds at most CALLS_PAGE_ROWS, as each row's result may be CALL_RESULT_CHARS long.
4088
+ const most = calls ? CALLS_PAGE_ROWS : PAGE_ROWS;
4089
+ const asked = url.searchParams.get("limit");
4090
+ if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= most))
4091
+ throw new ApiError("bad_request", `limit is an integer from 1 to ${most}${calls ? " with calls=whole" : ""}`);
4092
+ const limit = asked === null ? most : Number(asked);
4079
4093
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
4080
4094
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
4081
4095
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
@@ -4525,7 +4539,7 @@ async function startHolding(options, data, checked, stops) {
4525
4539
  return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) }, claude_login: !loginOff && !options.apiOnly } });
4526
4540
  }
4527
4541
  if (found.name === "getOpenapi")
4528
- return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
4542
+ return send(res, 200, servedOpenapi(openapi, ownerCookieName(req)));
4529
4543
  // With accounts off there is no owner, and the console still asks whether it may save a secret: secret-writes.ts'
4530
4544
  // verdict over the request the page just marked, never a signed-in user it doesn't have.
4531
4545
  if (found.name === "getAuthSession")
@@ -5646,6 +5660,19 @@ async function startHolding(options, data, checked, stops) {
5646
5660
  return send(res, 200, await usage(url));
5647
5661
  case "getCapacity":
5648
5662
  return send(res, 200, await capacityOverStore(store.runners, capacityWindowOf(url)));
5663
+ case "getWrapped": {
5664
+ // The session files of the machine this server runs on: only a server bound to loopback with no public URL answers.
5665
+ // A name an operator allowed (--allow-host) passes the server's Host check for its other routes, but a page that rebound
5666
+ // one to this address must not read the machine's files: here the Host is a loopback name or address, or it is refused.
5667
+ if (options.apiOnly || options.publicUrl || !isLoopback(host) || !isLoopbackName(hostName(req.headers.host)))
5668
+ throw new ApiError("forbidden", "wrapped reads this machine's own session files, so only a server on loopback with no public URL, reached by a loopback name, answers it");
5669
+ const given = url.searchParams.get("year");
5670
+ const year = given === null ? new Date().getFullYear() : Number(given);
5671
+ if (given !== null && !/^[1-9]\d{3}$/.test(given))
5672
+ throw new ApiError("bad_request", "year is a four-digit year");
5673
+ const [{ wrapped, unread }, analytics] = await Promise.all([readWrapped(year), analyticsOverStore(store, { from: new Date(year, 0, 1).toISOString(), to: new Date(year + 1, 0, 1).toISOString() })]);
5674
+ return send(res, 200, wrappedView(wrapped, analytics.bySource.filter((g) => g.source !== "live").map((g) => ({ source: g.source, runs: g.runs })), unread));
5675
+ }
5649
5676
  case "getStats": {
5650
5677
  const filter = analyticsFilter(url);
5651
5678
  // The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
@@ -6879,6 +6906,9 @@ async function startHolding(options, data, checked, stops) {
6879
6906
  clearInterval(localSourceTimer);
6880
6907
  // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
6881
6908
  plan.close();
6909
+ // The CLI's sign-in still waiting for its browser ends with the server, which forgets it: left running, its CLI would
6910
+ // keep the browser's callback port from the next server's sign-in. Awaited until its process is gone.
6911
+ const signInStopped = claudeSignIns.close();
6882
6912
  const observationStopped = stopObservationRetention();
6883
6913
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
6884
6914
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
@@ -6898,6 +6928,7 @@ async function startHolding(options, data, checked, stops) {
6898
6928
  await importing;
6899
6929
  await schemaSealed;
6900
6930
  await installStopped;
6931
+ await signInStopped;
6901
6932
  await observationStopped;
6902
6933
  await localSourceSweep;
6903
6934
  // The ends' follower stops before the webhooks it feeds and the store it reads.
@@ -10,6 +10,9 @@ export interface Dialect {
10
10
  jsonValue(column: string, path: readonly string[]): string;
11
11
  /** True unless the JSON TEXT column's value at `path` is false or 0 (absent or null count as true). */
12
12
  jsonNotFalse(column: string, path: readonly string[]): string;
13
+ /** The JSON TEXT column's value at `path` as a number to compare with one, or SQL NULL when it is absent or not a JSON
14
+ * number (never a cast that fails on a row's text). */
15
+ jsonNumber(column: string, path: readonly string[]): string;
13
16
  /** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
14
17
  jsonArrayHas(column: string): string;
15
18
  /** True when the JSON object of strings in TEXT column `column` holds the key and the value of the two string parameters
@@ -15,6 +15,7 @@ export const SQLITE = {
15
15
  jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
16
16
  jsonValue: (column, path) => `${column} -> ${jsonPath(path)}`,
17
17
  jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
18
+ jsonNumber: (column, path) => `(CASE WHEN json_type(${column}, ${jsonPath(path)}) IN ('integer', 'real') THEN json_extract(${column}, ${jsonPath(path)}) END)`,
18
19
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
19
20
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
20
21
  jsonArrayLength: (column) => `json_array_length(${column})`,
@@ -1,4 +1,4 @@
1
- export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
1
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
2
  export type { ConstraintRule, SettingsGuard, McpGuard, AgentRow, Agents, AlsoRow, AttemptCause, ChannelPost, Claim, Command, ComputerIntervalRow, ComputerIntervals, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpTokensMark, McpOwnersMark, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunAttemptRow, RunAttempts, RunnerRow, Runners, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, StoreSchemaState, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, PurgeKept, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
3
  export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type ComposioBinding, type RunMcpAuth, type RunMcpEntry, type RunModelKey, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunLaunch, 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";
@@ -1,5 +1,5 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
2
+ export { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, KEPT_PREFIX, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, RunPurged, RunnerBelowFloor, RUNNER_STALE_MS, RunsMadeFromLeft, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreAwaitsServer, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull, TriggersLeft, UPLOAD_PREFIX } from "./store.js";
3
3
  export { aadOf, openMcpCredential, openRunLaunch, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunLaunch, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
@@ -12,6 +12,9 @@ export function postgresDialect(schema, { testClock = false } = {}) {
12
12
  jsonValue: (column, keys) => `(${column}::json #> ${path(keys)})::text`,
13
13
  // SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
14
14
  jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
15
+ // SQLite's json_type(...) IN ('integer', 'real'): a JSON number read as numeric, anything else NULL, never a cast of
16
+ // text that would fail the statement.
17
+ jsonNumber: (column, keys) => `(CASE WHEN json_typeof(${column}::json #> ${path(keys)}) = 'number' THEN (${column}::json #>> ${path(keys)})::numeric END)`,
15
18
  jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
16
19
  jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each_text(${column}::json) AS entry(key, value) WHERE entry.key = ? AND entry.value = ?)`,
17
20
  jsonArrayLength: (column) => `json_array_length(${column}::json)`,