@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.44

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 (141) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +213 -24
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.js +3 -0
  19. package/dist/harness-table.d.ts +51 -3
  20. package/dist/harness-table.js +101 -13
  21. package/dist/harness.d.ts +18 -1
  22. package/dist/harness.js +21 -9
  23. package/dist/host.d.ts +12 -10
  24. package/dist/host.js +18 -16
  25. package/dist/import-worker.d.ts +3 -0
  26. package/dist/import-worker.js +7 -5
  27. package/dist/import.d.ts +22 -1
  28. package/dist/import.js +141 -28
  29. package/dist/learn/check.d.ts +3 -0
  30. package/dist/learn/check.js +1 -1
  31. package/dist/learn/compile.js +1 -1
  32. package/dist/learn/delete.d.ts +17 -0
  33. package/dist/learn/delete.js +44 -0
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +8 -4
  36. package/dist/learn/skills.d.ts +4 -0
  37. package/dist/learn/skills.js +17 -1
  38. package/dist/learn/workflow-nodes.d.ts +22 -1
  39. package/dist/learn/workflow-nodes.js +28 -9
  40. package/dist/learning-cost.d.ts +100 -0
  41. package/dist/learning-cost.js +116 -1
  42. package/dist/learning-evals.d.ts +2 -0
  43. package/dist/learning-evals.js +4 -3
  44. package/dist/learning-routes.d.ts +8 -0
  45. package/dist/learning-routes.js +17 -0
  46. package/dist/learning.d.ts +1 -1
  47. package/dist/listen-first.d.ts +30 -0
  48. package/dist/listen-first.js +115 -0
  49. package/dist/llms.txt +2 -1
  50. package/dist/mcp-servers-store.d.ts +12 -12
  51. package/dist/model.d.ts +8 -4
  52. package/dist/model.js +16 -8
  53. package/dist/openapi.js +115 -39
  54. package/dist/owner.d.ts +8 -0
  55. package/dist/owner.js +11 -0
  56. package/dist/paid-calls.d.ts +6 -0
  57. package/dist/paid-calls.js +11 -1
  58. package/dist/place.d.ts +8 -3
  59. package/dist/place.js +13 -9
  60. package/dist/provider.js +15 -1
  61. package/dist/run-learning-served.d.ts +1 -1
  62. package/dist/run-model-key.d.ts +64 -0
  63. package/dist/run-model-key.js +147 -0
  64. package/dist/runner/adapter-loop.d.ts +6 -0
  65. package/dist/runner/adapter-loop.js +9 -2
  66. package/dist/runner/adapter-run-spec.d.ts +6 -3
  67. package/dist/runner/adapter-run-spec.js +70 -23
  68. package/dist/runner/adapters/index.d.ts +4 -2
  69. package/dist/runner/adapters/index.js +13 -4
  70. package/dist/runner/audit.d.ts +4 -0
  71. package/dist/runner/audit.js +15 -4
  72. package/dist/runner/beside.d.ts +2 -1
  73. package/dist/runner/beside.js +5 -2
  74. package/dist/runner/claim-secrets.d.ts +49 -0
  75. package/dist/runner/claim-secrets.js +110 -1
  76. package/dist/runner/cli-run-spec.d.ts +2 -1
  77. package/dist/runner/cli-run-spec.js +32 -13
  78. package/dist/runner/commands.d.ts +3 -6
  79. package/dist/runner/feedback-round.d.ts +3 -2
  80. package/dist/runner/feedback-round.js +7 -3
  81. package/dist/runner/harness-loops.js +30 -8
  82. package/dist/runner/journal-kinds.d.ts +5 -0
  83. package/dist/runner/learning-end.d.ts +3 -0
  84. package/dist/runner/learning-end.js +4 -0
  85. package/dist/runner/loop-contract.d.ts +6 -0
  86. package/dist/runner/loop-contract.js +4 -0
  87. package/dist/runner/loop.js +6 -2
  88. package/dist/runner/main.d.ts +1 -0
  89. package/dist/runner/main.js +24 -7
  90. package/dist/runner/memory-claim.d.ts +9 -6
  91. package/dist/runner/memory-claim.js +12 -9
  92. package/dist/runner/promotion.d.ts +5 -0
  93. package/dist/runner/promotion.js +46 -7
  94. package/dist/runner/reflect-hook.d.ts +4 -0
  95. package/dist/runner/reflect-hook.js +22 -3
  96. package/dist/runner/runner.js +57 -4
  97. package/dist/runner/store-secrets.js +9 -5
  98. package/dist/runner/workflow-spec.js +10 -2
  99. package/dist/runs-over-store.d.ts +5 -4
  100. package/dist/runs-over-store.js +13 -3
  101. package/dist/sdk/workflows.d.ts +1 -1
  102. package/dist/server.d.ts +64 -50
  103. package/dist/server.js +457 -120
  104. package/dist/store/index.d.ts +2 -2
  105. package/dist/store/index.js +1 -1
  106. package/dist/store/seal.d.ts +20 -2
  107. package/dist/store/seal.js +24 -8
  108. package/dist/store/sqlite/run-launch.d.ts +4 -1
  109. package/dist/store/sqlite/run-launch.js +12 -0
  110. package/dist/store/sqlite/store.d.ts +3 -2
  111. package/dist/store/sqlite/store.js +118 -16
  112. package/dist/store/store.d.ts +38 -3
  113. package/dist/store-reads/analytics.js +11 -1
  114. package/dist/store-reads/learning.d.ts +41 -2
  115. package/dist/store-reads/learning.js +158 -5
  116. package/dist/store-reads/stats.js +13 -3
  117. package/dist/store-view.d.ts +5 -1
  118. package/dist/store-view.js +12 -11
  119. package/dist/telemetry.d.ts +59 -0
  120. package/dist/telemetry.js +153 -0
  121. package/dist/tool-keys-store.d.ts +1 -1
  122. package/dist/tool-keys.d.ts +2 -2
  123. package/dist/tool-plane.d.ts +12 -12
  124. package/dist/tools.d.ts +11 -11
  125. package/dist/tools.js +18 -5
  126. package/dist/trigger-adapter.d.ts +3 -0
  127. package/dist/trigger-adapters.d.ts +4 -0
  128. package/dist/trigger-adapters.js +13 -0
  129. package/dist/trigger-composio.d.ts +58 -1
  130. package/dist/trigger-composio.js +160 -6
  131. package/dist/triggers.d.ts +4 -0
  132. package/dist/triggers.js +22 -3
  133. package/dist/validate.d.ts +11 -7
  134. package/dist/validate.js +8 -7
  135. package/dist/workspace/computer-for-claim.d.ts +15 -5
  136. package/dist/workspace/computer-for-claim.js +228 -32
  137. package/dist/workspace/resolve-computer.d.ts +8 -2
  138. package/dist/workspace/resolve-computer.js +1 -1
  139. package/package.json +10 -9
  140. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  141. package/dist/console/assets/index-Bz6IWncl.js +0 -711
@@ -1,6 +1,6 @@
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, 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
- export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunMcpAuth, type RunMcpAuth, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.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, LaunchSealed, LaunchSealedWrite, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
+ export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunLaunch, openRunMcpAuth, type RunLaunchSecrets, type RunMcpAuth, 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";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
6
6
  export { DDL, PI_DDL, PI_TABLE, PI_TABLES, SCHEMA_VERSION, STORE_DDL } from "./schema.js";
@@ -1,6 +1,6 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
2
  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";
3
- export { aadOf, openMcpCredential, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.js";
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";
6
6
  export { DDL, PI_DDL, PI_TABLE, PI_TABLES, SCHEMA_VERSION, STORE_DDL } from "./schema.js";
@@ -13,7 +13,8 @@ export declare const sealedAt: {
13
13
  signIn: (agentId: string, provider: string) => SealedAt;
14
14
  /** A run's computer session's live viewer token (browser-live.ts): one row per run, computer kind and session tag. */
15
15
  liveViewer: (runId: string, kind: string, tag: string) => SealedAt;
16
- /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth). */
16
+ /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth), and its own
17
+ * model key (model_key), with the gateway's origin it was handed for. */
17
18
  runLaunch: (runId: string) => SealedAt;
18
19
  };
19
20
  /** The AAD a value at `at` is sealed under. A part with the separator in it is refused: no two places share an AAD. */
@@ -54,7 +55,24 @@ export type RunMcpAuth = Readonly<Record<string, {
54
55
  readonly headers: Readonly<Record<string, string>>;
55
56
  readonly origin: string;
56
57
  }>>;
57
- /** Seals a run's handed MCP credentials as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
58
+ /** A run's own model key (`model_key` at its start or with a message): the key its model requests carry, and the origin
59
+ * of the gateway it was handed for (AGENT_MODEL_BASE_URL's then), so a gateway moved since never receives it. */
60
+ export type RunModelKey = {
61
+ readonly key: string;
62
+ readonly origin: string;
63
+ };
64
+ /** What a run's launch holds sealed: its handed MCP credentials and its own model key, each when it has one. */
65
+ export type RunLaunchSecrets = {
66
+ readonly mcp?: RunMcpAuth;
67
+ readonly model?: RunModelKey;
68
+ };
69
+ /** Seals a run's launch secrets as its launch's sealed column (AAD run_launch|<run_id>|sealed); null when it holds none. */
70
+ export declare function sealRunLaunch(key: Buffer, runId: string, secrets: RunLaunchSecrets): Uint8Array | null;
71
+ /** A run's launch secrets, opened: none when its launch holds none; undefined when the bytes do not open under `key` for
72
+ * this run (sealed for another run, or under another key). */
73
+ export declare function openRunLaunch(key: Buffer, runId: string, sealed: Uint8Array | null): RunLaunchSecrets | undefined;
74
+ /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed): a run started
75
+ * by the runner from another (a replay, an audit) takes its MCP credentials, never its model key. */
58
76
  export declare function sealRunMcpAuth(key: Buffer, runId: string, auth: RunMcpAuth): Uint8Array;
59
77
  /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
60
78
  * `key` for this run (sealed for another run, or under another key). */
@@ -25,7 +25,8 @@ export const sealedAt = {
25
25
  },
26
26
  /** A run's computer session's live viewer token (browser-live.ts): one row per run, computer kind and session tag. */
27
27
  liveViewer: (runId, kind, tag) => ({ table: "computer_viewers", row: `${runId}/${kind}:${tag}`, column: "sealed" }),
28
- /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth). */
28
+ /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth), and its own
29
+ * model key (model_key), with the gateway's origin it was handed for. */
29
30
  runLaunch: (runId) => ({ table: "run_launch", row: runId, column: "sealed" }),
30
31
  };
31
32
  /** The AAD a value at `at` is sealed under. A part with the separator in it is refused: no two places share an AAD. */
@@ -69,20 +70,35 @@ export function openMcpCredential(key, row) {
69
70
  }
70
71
  return { credential: credential };
71
72
  }
72
- /** Seals a run's handed MCP credentials as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
73
- export function sealRunMcpAuth(key, runId, auth) {
74
- return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ mcp: auth }));
73
+ /** Seals a run's launch secrets as its launch's sealed column (AAD run_launch|<run_id>|sealed); null when it holds none. */
74
+ export function sealRunLaunch(key, runId, secrets) {
75
+ const mcp = secrets.mcp && Object.keys(secrets.mcp).length ? secrets.mcp : undefined;
76
+ if (!mcp && !secrets.model)
77
+ return null;
78
+ return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ ...(mcp ? { mcp } : {}), ...(secrets.model ? { model: secrets.model } : {}) }));
75
79
  }
76
- /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
77
- * `key` for this run (sealed for another run, or under another key). */
78
- export function openRunMcpAuth(key, runId, sealed) {
80
+ /** A run's launch secrets, opened: none when its launch holds none; undefined when the bytes do not open under `key` for
81
+ * this run (sealed for another run, or under another key). */
82
+ export function openRunLaunch(key, runId, sealed) {
79
83
  if (sealed === null)
80
84
  return {};
81
85
  try {
82
86
  const opened = JSON.parse(unsealColumn(key, sealedAt.runLaunch(runId), sealed).toString("utf8"));
83
- return opened.mcp ?? {};
87
+ const model = typeof opened.model?.key === "string" && typeof opened.model.origin === "string" ? { key: opened.model.key, origin: opened.model.origin } : undefined;
88
+ return { ...(opened.mcp ? { mcp: opened.mcp } : {}), ...(model ? { model } : {}) };
84
89
  }
85
90
  catch {
86
91
  return undefined;
87
92
  }
88
93
  }
94
+ /** Seals a run's handed MCP credentials alone as its launch's sealed column (AAD run_launch|<run_id>|sealed): a run started
95
+ * by the runner from another (a replay, an audit) takes its MCP credentials, never its model key. */
96
+ export function sealRunMcpAuth(key, runId, auth) {
97
+ return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ mcp: auth }));
98
+ }
99
+ /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
100
+ * `key` for this run (sealed for another run, or under another key). */
101
+ export function openRunMcpAuth(key, runId, sealed) {
102
+ const opened = openRunLaunch(key, runId, sealed);
103
+ return opened && (opened.mcp ?? {});
104
+ }
@@ -1,9 +1,12 @@
1
- import { type RunLaunchInput, type RunLaunchRow } from "../store.js";
1
+ import { type LaunchSealed, type RunLaunchInput, type RunLaunchRow } from "../store.js";
2
2
  import type { Dialect } from "../dialect.js";
3
3
  import type { SqliteExecutor } from "./connection.js";
4
4
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
5
5
  * trigger path both call it, so the row lands with its run or not at all. */
6
6
  export declare function writeLaunch(tx: Pick<SqliteExecutor, "run">, runId: string, launch: RunLaunchInput, at: number): Promise<void>;
7
+ /** A message's launch secrets written over the run's (runs.command, runs.reopen), inside `tx`: the bytes as given, or a
8
+ * function's answer to the bytes the launch holds now, read in the same transaction. */
9
+ export declare function writeLaunchSealed(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, launchSealed: LaunchSealed): Promise<void>;
7
10
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
8
11
  * none, never a default. */
9
12
  export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
@@ -10,6 +10,18 @@ const runLaunchOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), sealed:
10
10
  export function writeLaunch(tx, runId, launch, at) {
11
11
  return tx.run("INSERT INTO run_launch (run_id, body, sealed, created_at) VALUES (?, ?, ?, ?)", runId, JSON.stringify(launch.body ?? null), launch.sealed ?? null, at);
12
12
  }
13
+ /** A message's launch secrets written over the run's (runs.command, runs.reopen), inside `tx`: the bytes as given, or a
14
+ * function's answer to the bytes the launch holds now, read in the same transaction. */
15
+ export async function writeLaunchSealed(tx, runId, launchSealed) {
16
+ let next;
17
+ if (typeof launchSealed === "function") {
18
+ const row = await tx.get("SELECT sealed FROM run_launch WHERE run_id = ?", runId);
19
+ next = launchSealed(row?.sealed == null ? null : Uint8Array.from(row.sealed));
20
+ }
21
+ else
22
+ next = launchSealed;
23
+ await tx.run("UPDATE run_launch SET sealed = ? WHERE run_id = ?", next, runId);
24
+ }
13
25
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
14
26
  * none, never a default. */
15
27
  export async function readLaunch(executor, runId) {
@@ -29,5 +29,6 @@ export type SqliteStoreOptions = (
29
29
  * directory) too. */
30
30
  export declare function openSqliteStore(options: SqliteStoreOptions): Promise<Store>;
31
31
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
32
- * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first. */
33
- export declare function storeOver(connection: StoreConnection, now: () => number): Store;
32
+ * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
33
+ * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX). */
34
+ export declare function storeOver(connection: StoreConnection, now: () => number, file?: string): Store;
@@ -4,15 +4,15 @@
4
4
  // with more than one statement is one transaction (connection.transaction, BEGIN IMMEDIATE): all of it or none of it.
5
5
  // The domain code below (the SqliteStore class, storeOver) is written once for SQLite and Postgres (a Postgres store opens
6
6
  // it on its own connection): what differs, and the locks Postgres's many writers take, is the connection's Dialect (store/dialect.ts).
7
- import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
8
- import { join } from "node:path";
7
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, rmSync, statSync, writeSync } from "node:fs";
8
+ import { dirname, join } from "node:path";
9
9
  import { DatabaseSync } from "node:sqlite";
10
10
  import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } from '../native-command-owner.js';
11
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { RunStorage } from "../journal/storage.js";
14
14
  import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, MINTED_TOKENS, NATIVE_COMMANDS_INDEX, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION } from "../schema.js";
15
- import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
15
+ import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
16
16
  /** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
17
17
  const seqOf = (cursor) => {
18
18
  if (!/^(0|[1-9][0-9]{0,15})$/.test(cursor))
@@ -20,9 +20,10 @@ const seqOf = (cursor) => {
20
20
  return Number(cursor);
21
21
  };
22
22
  import { cleanText, settledBody } from "../dialect.js";
23
+ import { inMemory } from "./memory.js";
23
24
  import { Connection } from "./connection.js";
24
25
  import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
25
- import { readLaunch, readLearningStarts, writeLaunch } from "./run-launch.js";
26
+ import { readLaunch, readLearningStarts, writeLaunch, writeLaunchSealed } from "./run-launch.js";
26
27
  import { canonical } from "../agent-body.js";
27
28
  import { aadOf, sealedAt } from "../seal.js";
28
29
  /** A claim's length when the caller names none. */
@@ -174,11 +175,34 @@ function earlierVersionIn(dataDir) {
174
175
  if (!existsSync(dataDir))
175
176
  return [];
176
177
  const found = [];
177
- const isFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile() === true;
178
+ // A path the server may not look into is not an earlier version's: that version wrote its files as the server's own
179
+ // user. A disk mounted as the data directory has one such, lost+found (root's, mode 700).
180
+ const stat = (path) => {
181
+ try {
182
+ return statSync(path, { throwIfNoEntry: false });
183
+ }
184
+ catch (error) {
185
+ if (error.code === "EACCES")
186
+ return undefined;
187
+ throw error;
188
+ }
189
+ };
190
+ const isFile = (path) => stat(path)?.isFile() === true;
178
191
  // A directory linked in counts as one (stat follows the link), as the server's check of old homes reads them: an
179
192
  // earlier version's home or run kept elsewhere and linked in is still the earlier version's.
180
- const isDir = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
181
- const dirsIn = (path) => (isDir(path) ? readdirSync(path).filter((name) => isDir(join(path, name))) : []);
193
+ const isDir = (path) => stat(path)?.isDirectory() === true;
194
+ const dirsIn = (path) => {
195
+ if (!isDir(path))
196
+ return [];
197
+ try {
198
+ return readdirSync(path).filter((name) => isDir(join(path, name)));
199
+ }
200
+ catch (error) {
201
+ if (error.code === "EACCES")
202
+ return [];
203
+ throw error;
204
+ }
205
+ };
182
206
  const store = join(dataDir, STORE_FILE);
183
207
  if (isFile(store) && !isThisVersionsStore(store))
184
208
  found.push(STORE_FILE);
@@ -317,7 +341,7 @@ export async function openSqliteStore(options) {
317
341
  await connection.close().catch(() => undefined);
318
342
  throw error;
319
343
  }
320
- return storeOver(connection, options.now ?? Date.now);
344
+ return storeOver(connection, options.now ?? Date.now, inMemory(file) ? undefined : file);
321
345
  }
322
346
  /** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
323
347
  const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
@@ -376,9 +400,33 @@ function readOnly(tx) {
376
400
  };
377
401
  }
378
402
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
379
- * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first. */
380
- export function storeOver(connection, now) {
381
- return new SqliteStore(connection, now);
403
+ * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first.
404
+ * `file`: a SQLite store's database file, beside which secureRewrite keeps its marker (SCRUB_SUFFIX). */
405
+ export function storeOver(connection, now, file) {
406
+ return new SqliteStore(connection, now, undefined, file === undefined ? undefined : `${file}${SCRUB_SUFFIX}`);
407
+ }
408
+ /** The suffix, after the database file's name, of the marker secureRewrite writes before a rewrite and removes once no
409
+ * file of the store keeps the bytes it replaced: a start that finds it finishes the scrub. */
410
+ const SCRUB_SUFFIX = ".scrub";
411
+ /** How long the scrub's VACUUM waits, once its busy wait ran out on another connection's write, before its one retry. */
412
+ const VACUUM_RETRY_MS = 400;
413
+ /** The marker at `path`, written and synced (its directory too) before the rewrite it marks changes a byte. */
414
+ function markScrub(path) {
415
+ const fd = openSync(path, "w", 0o600);
416
+ try {
417
+ writeSync(fd, "agentrun-serve: a rewrite of a secret this store kept in the clear may have left its old bytes in the store's free pages; the next start scrubs them and removes this file.\n");
418
+ fsyncSync(fd);
419
+ }
420
+ finally {
421
+ closeSync(fd);
422
+ }
423
+ const dir = openSync(dirname(path), "r");
424
+ try {
425
+ fsyncSync(dir);
426
+ }
427
+ finally {
428
+ closeSync(dir);
429
+ }
382
430
  }
383
431
  /** The store's domain code, written once for both databases: its SQL takes `?` parameters, and what a database says
384
432
  * differently, or must lock where SQLite's one writer serializes, is the connection's Dialect (store/dialect.ts). */
@@ -418,8 +466,11 @@ class SqliteStore {
418
466
  * but nothing is written through it: release moved the run's epoch on, so the journal's first commit is Fenced by the
419
467
  * epoch check in its own transaction. The map refuses early; the epoch is what guarantees it. */
420
468
  #released = new Map();
421
- constructor(db, now, origin) {
469
+ /** secureRewrite's marker (SCRUB_SUFFIX): set on a SQLite store with a file, never on a snapshot. */
470
+ #scrubMarker;
471
+ constructor(db, now, origin, scrubMarker) {
422
472
  this.#db = db;
473
+ this.#scrubMarker = scrubMarker;
423
474
  this.#now = now;
424
475
  this.origin = origin ?? this;
425
476
  this.where = db.where;
@@ -592,13 +643,18 @@ class SqliteStore {
592
643
  });
593
644
  return triggerOf(row);
594
645
  },
595
- update: async (id, patch, scopes) => {
646
+ update: async (id, patch, scopes, options) => {
596
647
  const { set, params } = triggerSet(patch, now());
648
+ // A compare-and-set (options.ifUpdatedAt): no row is changed once the trigger was updated or deleted since that read.
649
+ // Its source too (options.ifSource, compared as the JSON text the store wrote): one millisecond's writes share an
650
+ // updated_at, never a source.
651
+ const unchanged = `${options?.ifUpdatedAt === undefined ? "" : " AND updated_at = ?"}${options?.ifSource === undefined ? "" : " AND source = ?"}`;
652
+ const since = [...(options?.ifUpdatedAt === undefined ? [] : [options.ifUpdatedAt]), ...(options?.ifSource === undefined ? [] : [json(options.ifSource)])];
597
653
  const row = await db.transaction(async (tx) => {
598
654
  // Moved to another agent (its target re-aimed): one the store holds, refused in words otherwise.
599
655
  if (patch.agentId !== undefined && !(await tx.get("SELECT id FROM agents WHERE id = ?", patch.agentId)))
600
656
  throw new StoreConstraint(`no agent ${patch.agentId}: a trigger belongs to an agent the store holds`);
601
- const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ? RETURNING ${TRIGGER_COLUMNS}`, ...params, id);
657
+ const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ?${unchanged} RETURNING ${TRIGGER_COLUMNS}`, ...params, id, ...since);
602
658
  // Never left on for an archived agent (turned on, or moved there on): the whole update is undone.
603
659
  if (changed?.enabled === 1)
604
660
  await refuseArchived(tx, changed.agent_id);
@@ -906,7 +962,7 @@ class SqliteStore {
906
962
  throw new RunFinal(runId);
907
963
  // The message's launch secrets, with it: the claim that runs its turn reads them.
908
964
  if (launchSealed)
909
- await tx.run("UPDATE run_launch SET sealed = ? WHERE run_id = ?", launchSealed, runId);
965
+ await writeLaunchSealed(tx, runId, launchSealed);
910
966
  await lockCommandsOf(tx, runId);
911
967
  const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) VALUES (?, ?, ?, ?) RETURNING ${COMMAND_COLUMNS}`, runId, kind, json(body), now());
912
968
  return commandOf(row);
@@ -1621,6 +1677,52 @@ class SqliteStore {
1621
1677
  handedAny: async () => (await handedAnyIn(db))?.id,
1622
1678
  };
1623
1679
  }
1680
+ async secureRewrite(work, options = {}) {
1681
+ const marker = this.#scrubMarker;
1682
+ if (this.#db.dialect.name !== "sqlite" || marker === undefined)
1683
+ return { rewritten: await work() };
1684
+ // Written before any byte changes: a server that dies after the rewrite committed, and before the scrub below is done,
1685
+ // leaves it, and its next start scrubs though no row is left in the clear.
1686
+ const pending = existsSync(marker);
1687
+ markScrub(marker);
1688
+ let rewritten;
1689
+ await this.#db.all("PRAGMA secure_delete = ON");
1690
+ try {
1691
+ rewritten = await work();
1692
+ }
1693
+ finally {
1694
+ await this.#db.all("PRAGMA secure_delete = OFF");
1695
+ }
1696
+ if (rewritten === 0 && !pending) {
1697
+ rmSync(marker, { force: true });
1698
+ return { rewritten };
1699
+ }
1700
+ // Asked with no VACUUM (a server already serving): the marker stays, and the next start's scrub runs it before it serves.
1701
+ if (options.vacuum === false)
1702
+ return { rewritten, left: "deferred" };
1703
+ // secure_delete zeroes only the bytes `work` freed: a copy an earlier, ordinary update of the row left (a pause, a
1704
+ // rename, a firing) is in a free block or page still. VACUUM rebuilds the file with neither, through the log; the
1705
+ // checkpoint copies it into the file and truncates the log. Run outside any transaction.
1706
+ try {
1707
+ // Another connection's write (a runner's) may hold the lock past the busy wait: one retry after a short pause.
1708
+ await this.#db.all("VACUUM").catch(async (error) => {
1709
+ if (!(error instanceof StoreBusy))
1710
+ throw error;
1711
+ await new Promise((resolve) => setTimeout(resolve, VACUUM_RETRY_MS));
1712
+ await this.#db.all("VACUUM");
1713
+ });
1714
+ const [checkpoint] = await this.#db.all("PRAGMA wal_checkpoint(TRUNCATE)");
1715
+ // A reader in another connection (a runner, a backup) held the log back: the old frames are there until a
1716
+ // checkpoint is done, so the marker stays.
1717
+ if (checkpoint?.busy !== 0)
1718
+ return { rewritten, left: "busy" };
1719
+ }
1720
+ catch (error) {
1721
+ return { rewritten, left: error instanceof StoreBusy ? "busy" : "failed" };
1722
+ }
1723
+ rmSync(marker, { force: true });
1724
+ return { rewritten };
1725
+ }
1624
1726
  async claim(runId, runner, { leaseMs = DEFAULT_LEASE_MS } = {}) {
1625
1727
  return (await this.#claimRuns(runner, leaseMs, { runId }))[0] ?? null;
1626
1728
  }
@@ -1786,7 +1888,7 @@ class SqliteStore {
1786
1888
  });
1787
1889
  // The message's launch secrets, in the command's own write: written only when the command is (a final run refuses both).
1788
1890
  if (launchSealed)
1789
- await tx.run("UPDATE run_launch SET sealed = ? WHERE run_id = ?", launchSealed, runId);
1891
+ await writeLaunchSealed(tx, runId, launchSealed);
1790
1892
  return inserted;
1791
1893
  });
1792
1894
  wakeCommands(this.where, { runId, what: "written" });
@@ -207,9 +207,13 @@ export interface RunLaunchRow {
207
207
  readonly createdAt: number;
208
208
  }
209
209
  /** A message's new launch secrets (runs.command, runs.reopen): `launchSealed` replaces the run's launch `sealed` in the
210
- * command's own transaction, so the runner that takes the command reads them, and a run already final takes neither. */
210
+ * command's own transaction, so the runner that takes the command reads them, and a run already final takes neither.
211
+ * Given as a function, it is called inside that transaction with the sealed bytes the launch holds then (null when none:
212
+ * a run whose end erased them), and its answer is written (null erases): a message that hands one secret keeps the
213
+ * others the run holds, with no read outside the write that could bring back what an end erased. */
214
+ export type LaunchSealed = Uint8Array | ((current: Uint8Array | null) => Uint8Array | null);
211
215
  export interface LaunchSealedWrite {
212
- readonly launchSealed?: Uint8Array;
216
+ readonly launchSealed?: LaunchSealed;
213
217
  }
214
218
  /** A run imported from another harness's session: an ended run with where it came from, its launch (built from the
215
219
  * session), its cost and metrics, and its transcript as journal batches — the whole thing written in one transaction.
@@ -568,6 +572,14 @@ export interface NewTrigger {
568
572
  }
569
573
  /** A trigger's fields changed; the ones absent stay. */
570
574
  /** `agentId`: the agent it belongs to, which follows its target (a PATCH may aim it at another agent's run or agent). */
575
+ /** A trigger update's options: a compare-and-set, written only while the row is still the read the patch was made from,
576
+ * undefined otherwise, as when there is no such trigger. `ifUpdatedAt`: the row's updatedAt is still this one.
577
+ * `ifSource`: its source is still this one, as the store keeps it; two writes in one millisecond share an updatedAt, so a
578
+ * write that must never land over another source write (a seal, an edit) gives both. */
579
+ export type TriggerUpdateOptions = {
580
+ readonly ifUpdatedAt?: number;
581
+ readonly ifSource?: unknown;
582
+ };
571
583
  export type TriggerPatch = Partial<Pick<TriggerRow, "agentId" | "name" | "enabled" | "source" | "target" | "nextAt" | "catchupWindowS" | "failuresInARow" | "disabled" | "maxActiveRuns">>;
572
584
  /** A firing's new state. Out of due, a firing keeps no retry, wait, payload nor the reason its last try gave (unless given). */
573
585
  export interface FiringChange {
@@ -692,7 +704,7 @@ export interface Triggers {
692
704
  /** The fields given changed, `updatedAt` set: undefined when there is no such trigger. With `scopes`, its scope rows
693
705
  * rewritten in the same transaction (none while it is off); a patch that turns it off drops them. One that leaves it
694
706
  * on for an archived agent, turned on or moved there, is refused (AgentArchived), nothing written. */
695
- update(id: string, patch: TriggerPatch, scopes?: readonly TriggerScope[]): Promise<TriggerRow | undefined>;
707
+ update(id: string, patch: TriggerPatch, scopes?: readonly TriggerScope[], options?: TriggerUpdateOptions): Promise<TriggerRow | undefined>;
696
708
  /** The trigger, its scope rows and its firings gone. */
697
709
  remove(id: string): Promise<void>;
698
710
  /** Enables the trigger and writes its scope rows, in one transaction; refused for an archived agent's (AgentArchived). */
@@ -1491,6 +1503,21 @@ export interface LiveViewers {
1491
1503
  /** Who opens the store. The server sets the schema up at its start and holds the store's owner lock (one server per
1492
1504
  * store); a runner never sets anything up, and refuses a schema version it does not know. */
1493
1505
  export type StoreRole = "server" | "runner";
1506
+ /** What Store.secureRewrite did: how many rows `work` rewrote and, when old bytes may still be in the store's files (the
1507
+ * marker kept for the next start), why: "busy", a reader in another connection held the log back from the checkpoint, or
1508
+ * a write of another connection held the VACUUM off through its busy wait and its one retry; "failed", the VACUUM or
1509
+ * the checkpoint failed otherwise; "deferred", the rewrite was asked with no VACUUM (a server already serving), so the
1510
+ * next start's scrub finishes it. */
1511
+ export interface SecureRewrite {
1512
+ readonly rewritten: number;
1513
+ readonly left?: "busy" | "failed" | "deferred";
1514
+ }
1515
+ /** secureRewrite's options: `vacuum: false` rewrites with secure_delete on and leaves the marker, with no VACUUM or
1516
+ * checkpoint: for a server already serving, where a VACUUM would hold every store call (and another process's writes)
1517
+ * while it rebuilds the whole file, and needs about its size again on disk. The next start's scrub runs it. */
1518
+ export type SecureRewriteOptions = {
1519
+ readonly vacuum?: boolean;
1520
+ };
1494
1521
  export interface Store {
1495
1522
  /** Where this store's data is, as an identity two instances over the same data share and two over different data never
1496
1523
  * do: "sqlite:" and the database file's real path, or "sqlite:memory:<n>" for an in-memory one (each its own data);
@@ -1528,6 +1555,14 @@ export interface Store {
1528
1555
  readonly signIns: SignIns;
1529
1556
  /** Every sealed value the store keeps, across all its planes, in one read (a runner's redaction set at each claim). */
1530
1557
  readonly sealedSecrets: SealedSecrets;
1558
+ /** Runs `work`, writes that replace a secret the store kept in the clear (it answers how many rows it rewrote), so the
1559
+ * bytes they replace are not left in the store's files. SQLite: a marker file beside the database is written first;
1560
+ * secure_delete is on while `work` runs (a rewritten row's old bytes zeroed in its page); then, when a row was rewritten
1561
+ * or an earlier start left the marker, a VACUUM (no free page or free block keeps a copy an earlier, ordinary update
1562
+ * left) and a WAL checkpoint (TRUNCATE: the log keeps no older frame). The marker is removed once the checkpoint is
1563
+ * done; `left` says why it was kept, for the next start to finish. Postgres: `work` alone (a replaced row version is
1564
+ * the database's until its vacuum). */
1565
+ secureRewrite?(work: () => Promise<number>, options?: SecureRewriteOptions): Promise<SecureRewrite>;
1531
1566
  /** Claims the run for `runner` until now + `leaseMs`: the run's epoch + 1 when it is claimable (runs.claimable); null when
1532
1567
  * another claim holds it, or it is final, or parked with nothing to wake it. A queued or parked run becomes running. */
1533
1568
  claim(runId: string, runner: string, options?: {
@@ -6,6 +6,7 @@
6
6
  import { sdkOf } from "../sdk/runs.js";
7
7
  import { DEFAULT_HARNESS } from "../harness.js";
8
8
  import { runReadState } from "./runs.js";
9
+ import { isShadowRun, shadowRunId } from "../learn/audit.js";
9
10
  const PENDING_ENDS = new Set(["completed", "escalated", "failed", "stopped"]);
10
11
  const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
11
12
  const metricsOf = (run) => (run.metrics !== null && typeof run.metrics === "object" && !Array.isArray(run.metrics) ? run.metrics : null);
@@ -24,7 +25,11 @@ export async function analytics(store, filter = {}) {
24
25
  const agentArchived = new Map();
25
26
  const harnessOf = new Map();
26
27
  const facts = [];
28
+ // Each audit's shadow run by id: its cost is the run it audits' (shadowUsd).
29
+ const shadows = new Map(runs.filter((run) => isShadowRun(run.id)).map((run) => [run.id, run]));
27
30
  for (const run of runs) {
31
+ if (isShadowRun(run.id))
32
+ continue;
28
33
  if (!agentArchived.has(run.agentId))
29
34
  agentArchived.set(run.agentId, (await store.agents.get(run.agentId))?.archivedAt ?? null);
30
35
  if (run.archivedAt !== null || agentArchived.get(run.agentId) !== null)
@@ -42,6 +47,8 @@ export async function analytics(store, filter = {}) {
42
47
  const isPending = running && pending[run.id] !== undefined;
43
48
  const metered = !running && metricsOf(run) !== null;
44
49
  const metrics = metered ? metricsOf(run) : null;
50
+ const shadow = shadows.get(shadowRunId(run.id));
51
+ const shadowUsd = shadow && runReadState(shadow, "agentic") !== "running" && shadow.costUsd !== null ? shadow.costUsd : 0;
45
52
  facts.push({
46
53
  startedMs: run.startedAt,
47
54
  endedMs: run.endedAt,
@@ -54,12 +61,15 @@ export async function analytics(store, filter = {}) {
54
61
  harness: harnessOf.get(run.revisionId),
55
62
  source: run.importedFrom?.source ?? "live",
56
63
  effort: metered ? (metrics?.effort ?? null) : null,
64
+ shadowUsd,
57
65
  });
58
66
  }
59
67
  const counted = (group) => {
60
68
  let unknownTokens = false;
61
69
  let runsN = 0, completed = 0, needsReview = 0, failed = 0, metered = 0, tokens = 0, costUsd = 0, known = 0, pend = 0;
70
+ let shadowUsd = 0;
62
71
  for (const f of group) {
72
+ shadowUsd += f.shadowUsd;
63
73
  runsN += 1;
64
74
  if (f.state === "completed" || f.state === "escalated")
65
75
  completed += 1;
@@ -78,7 +88,7 @@ export async function analytics(store, filter = {}) {
78
88
  if (f.pending)
79
89
  pend += 1;
80
90
  }
81
- return { runs: runsN, completed, needsReview, failed, runsWithMetrics: metered, tokens: unknownTokens ? null : tokens, costUsd: known > 0 ? costUsd : null, unknownCostRuns: runsN - known - pend };
91
+ return { runs: runsN, completed, needsReview, failed, runsWithMetrics: metered, tokens: unknownTokens ? null : tokens, costUsd: known > 0 || shadowUsd > 0 ? costUsd + shadowUsd : null, unknownCostRuns: runsN - known - pend };
82
92
  };
83
93
  // Totals over the whole scope: the group counts, the token sums, and the time figures.
84
94
  let input = 0, cacheRead = 0, cacheWrite = 0, output = 0, requests = 0, unmetered = 0;
@@ -1,7 +1,7 @@
1
1
  import { type ItemStatus, type Learning, type NoteUsed, type Shown } from "../learning.js";
2
2
  import { type RunLaunch } from "../run-launch.js";
3
3
  import { type Impact, type ImpactLearning } from "../learning-run.js";
4
- import { type CostReplay, type CostRun, type CostSummary, type RunPath, runCostOf } from "../learning-cost.js";
4
+ import { amortize, type Bill, type CostReplay, type CostRun, type CostSummary, type RunPath, runCostOf } from "../learning-cost.js";
5
5
  import { type PastRun, workflowCostsOf } from "../runner/workflow-first.js";
6
6
  import { type Reflect } from "../reflect-range.js";
7
7
  import type { NoteRuns } from "../learning.js";
@@ -24,6 +24,8 @@ type KeptRow = {
24
24
  readonly answered_at?: unknown;
25
25
  readonly job_cost_usd?: unknown;
26
26
  readonly look_back_usd?: unknown;
27
+ /** What of its look-back its compile turn spent, when it asked one. */
28
+ readonly compile_usd?: unknown;
27
29
  };
28
30
  /** What a kept row says of a run that looked back (learning-run.ts closeLearning's fields): none for one that did not. */
29
31
  declare function answeredOf(row: KeptRow): Pick<Learning, "answered_at" | "job_cost_usd" | "look_back_usd">;
@@ -104,7 +106,44 @@ export declare function agentCostOverStore(store: Store, agentId: string, limit?
104
106
  unknown_cost_runs: number;
105
107
  unknown_path_runs: number;
106
108
  workflows: ReturnType<typeof workflowCostsOf>;
109
+ bill: Bill;
107
110
  }>;
111
+ type LedgerRow = Pick<RunRecord, "id" | "metrics" | "startedAt" | "costUsd" | "costAtMostUsd">;
112
+ /** A compile turn a run's look-back asked (runner/reflect-hook.ts), as its kept round says it: the revision it drafted
113
+ * (`digest`, null when every draft failed its checks or the cap stopped the turn, so it drafted none; `workflow` null for
114
+ * the latter, which kept no draft's name) and what its turn spent (`usd`, the round's `compile_usd`: null when unknown;
115
+ * 0 for a round that kept no split, whose look-back holds its compile turn). */
116
+ export type CompileSpend = {
117
+ readonly workflow: string | null;
118
+ readonly digest: string | null;
119
+ readonly usd: number | null;
120
+ };
121
+ /** Each revision of the agent's learned workflows (one per workflow and digest its promotion records name, in the order
122
+ * they were first recorded) with its learning spend, and what its served runs carry of it (amortize), over `rows`: the
123
+ * agent's ended runs that do a job or check one (no shadow, no imported or archived run). A revision is its workflow and
124
+ * its digest, never the digest alone: two workflows of the same text share a digest, and each pays its own way. Its
125
+ * spend is the compile turns that drafted it (`compiles` of its workflow at its digest: a recompile drafts a revision of
126
+ * its own) and its check (the replay runs that ran it: metrics.path `replay` of its workflow at its digest); unknown
127
+ * once a part's cost is (null, or only a bound). A compile whose drafts all failed drafted none: no revision carries it
128
+ * (the bill's unattributed does). It is spread over its first K served runs (`workflow` or `handed_back` of its workflow
129
+ * at its digest), K its check's compile_after; `state` from its newest record. */
130
+ export declare function revisionLedgerOf(records: readonly PromotionRecord[], rows: readonly LedgerRow[], compiles?: readonly CompileSpend[]): ReturnType<typeof amortize>;
131
+ /** Run `runId`'s path and its costs as GET /runs/{id} shows them (A8): `path` its record's (metrics.path, RUN_PATHS:
132
+ * `agent` for a run that does not learn; null while it has not ended, for a workflow revision's run, and for a run that
133
+ * learns whose end named none); `usd` its own spend, the job's (runCostOf's `cost_usd`: its row's cost, `rowUsd` when
134
+ * given, less its look-back and compile turns; null while unknown); `learning_usd` what learning spent for it: its
135
+ * look-back less its compile turns, its grades, its audit shadow's cost, and its share of its revision's compile and
136
+ * check (revisionLedgerOf); `all_in_usd` the two. A replay or a shadow run carries none: its spend is on the runs it
137
+ * serves, so its `learning_usd` and `all_in_usd` are 0, and the sum of every run's `all_in_usd` and the bill's
138
+ * `unattributed_usd` is the booked total. While the run is at work `usd` is `rowUsd` and the rest null; null while
139
+ * unknown (its shadow still at work, a grade's, a compile's or a check's cost unknown), never $0. Undefined for an
140
+ * unknown run. */
141
+ export declare function runAllInOverStore(store: Store, runId: string, rowUsd?: number | null): Promise<{
142
+ path: RunPath | null;
143
+ usd: number | null;
144
+ learning_usd: number | null;
145
+ all_in_usd: number | null;
146
+ } | undefined>;
108
147
  /** The check the serving promotion was decided on, as the cost summary says it: the champion (championOf) of the learned
109
148
  * workflow the newest run a learned workflow ran first on ran (`workflow` or `handed_back`), its record's check numbers
110
149
  * (the share of the inputs it ran on that said what the agent said, against the agent's own 100%). `cleared`: it passed
@@ -320,7 +359,7 @@ export declare function runLearningOverStore(store: Store, runId: string, shown:
320
359
  feedback_status: "running" | "ended" | "not_run" | null;
321
360
  source: "feedback" | "eval";
322
361
  graded_at: string;
323
- path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
362
+ path: "agent" | "workflow" | "replay" | "handed_back" | "audit";
324
363
  workflow_digest: string | null;
325
364
  feedback: "look_back" | null;
326
365
  run_id: string;