@parcha/agentrun-serve 0.1.0-beta.42 → 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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  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/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
@@ -3,9 +3,11 @@
3
3
  * rule for a run with nothing new to look back on, runner/learning-end.ts onlyLearnedWorkflows); `handed_back`, a
4
4
  * learned workflow ran and the agent went on (it handed back, failed, escalated, or the agent did more work after it);
5
5
  * `agent`, no learned workflow ran; `replay`, a replay run deciding whether a learned workflow's new revision serves
6
- * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
6
+ * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost); `audit`, a shadow run auditing a
7
+ * run a learned workflow served (runner/audit.ts: the agent on its input with learning off; its cost is that run's
8
+ * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
7
9
  * record at its end (metrics.path). */
8
- export declare const RUN_PATHS: readonly ["agent", "handed_back", "workflow", "replay"];
10
+ export declare const RUN_PATHS: readonly ["agent", "handed_back", "workflow", "replay", "audit"];
9
11
  export type RunPath = (typeof RUN_PATHS)[number];
10
12
  /** What a run that looked back kept of its costs as it answered (runner/reflect-hook.ts: store-reads/learning.ts
11
13
  * answeredOf): when the job answered, what it had cost by then and what looking back cost after it. */
@@ -14,6 +16,10 @@ export type CostLooked = {
14
16
  job_cost_usd?: number | null;
15
17
  look_back_usd?: number | null;
16
18
  };
19
+ /** A booked figure with its float noise rounded off, nothing more (runner/metrics.ts floatNoiseOff, the precision a run's
20
+ * own cost is kept at): a decision costs millionths of a dollar, so a figure rounded to the millionth would lose it, and
21
+ * the run's cost here would read other than its usage row (A8). `+ 0` makes a noise-sized negative a plain 0, never -0. */
22
+ export declare const noiseOff: (value: number) => number;
17
23
  /** A run's own cost and what learning added for it, from its row's cost (`rowUsd`: the job, its look-back and any turn a
18
24
  * person asked of it after), what it kept as it answered (`looked`, none for a run that did not look back) and what its
19
25
  * grade spent (`gradeUsd`: its learning run's cost once that run ended, stopped or failed, 0 while it runs or when there
@@ -53,13 +59,18 @@ export declare const COST_WINDOW = 10;
53
59
  /** The latest runs the route answers by default, and at most. */
54
60
  export declare const COST_RUNS_DEFAULT = 1000;
55
61
  export declare const COST_RUNS_MAX = 10000;
56
- /** The serving promotion's replay (store-reads/learning.ts servingReplayOf): on `n` inputs, the workflow's accuracy and the
57
- * agent's in percent to a tenth, and whether it `cleared` the bar promotion reads (learn/promote.ts withinBar). */
62
+ /** The serving promotion's check (store-reads/learning.ts servingReplayOf): on `n` inputs, the workflow's agreement and the
63
+ * agent's own in percent to a tenth, whether it `cleared` the bar (learn/promote.ts checkPasses), and the agreement check
64
+ * itself: `agreed` of the `alone` inputs it answered alone said what the agent said, against the bar `agree_min` (0-1).
65
+ * Passing that bar is all it says: never that the workflow is as accurate as the agent. */
58
66
  export type CostReplay = {
59
67
  n: number;
60
68
  workflow_pct: number;
61
69
  agent_pct: number;
62
70
  cleared: boolean;
71
+ agreed: number;
72
+ alone: number;
73
+ agree_min: number;
63
74
  };
64
75
  /** The paths a learned workflow served a run on: it ran first and answered alone (`workflow`) or handed back
65
76
  * (`handed_back`). A `replay` checks a new revision on a graded input and serves no one; an `agent` run is by hand. */
@@ -105,6 +116,102 @@ export type CostSummary = {
105
116
  replay: CostReplay | null;
106
117
  };
107
118
  export declare function costSummary(runs: readonly CostRun[], replay?: CostReplay | null): CostSummary;
119
+ /** The paths of the runs that do a job: the bill's run index counts these. A replay checks a revision and an audit's
120
+ * shadow audits a run: their spend is learning, booked where it falls (billOf) and carried by the runs they serve. */
121
+ export declare const JOB_PATHS: readonly RunPath[];
122
+ /** One run of the bill: `n` its place among the agent's runs that do a job (JOB_PATHS, 1 the first), `actual_usd` the
123
+ * booked $ to it, every run before it included, and `agent_usd` the agent for all of it: the baseline times the runs
124
+ * the bill shows to it (null with no baseline). */
125
+ export type BillPoint = {
126
+ n: number;
127
+ run_id: string;
128
+ actual_usd: number;
129
+ agent_usd: number | null;
130
+ };
131
+ /** A revision's learning spend and what its served runs carry of it (amortize): `compile_usd` the compile turns that
132
+ * drafted it (a recompile's turn is its recompiled revision's), `check_usd` its check's replay runs, `spend_usd` the
133
+ * two (each null when a part's cost is unknown), `k` the served runs it is spread over (its check's compile_after),
134
+ * `served` how many of those have run, `attributed_usd` what they carry, `unattributed_usd` the rest, and `state`:
135
+ * `checking` (its check is at work), `serving` (it is the champion) or `stopped` (held or replaced: nothing more will
136
+ * carry it). */
137
+ export type RevisionSpend = {
138
+ workflow: string;
139
+ digest: string;
140
+ compile_usd: number | null;
141
+ check_usd: number | null;
142
+ spend_usd: number | null;
143
+ k: number;
144
+ state: "checking" | "serving" | "stopped";
145
+ };
146
+ export type RevisionShare = RevisionSpend & {
147
+ served: number;
148
+ attributed_usd: number | null;
149
+ unattributed_usd: number | null;
150
+ };
151
+ /** A hold of a learned workflow, placed on the series by the server (agentCostOverStore): `n` the first run that does a
152
+ * job from it on (its number among them, as the points have it; null when none has run since), `by` what held it (its
153
+ * audits, a check of a new revision, or this release's workflow DSL refusing the serving revision: a hold with neither
154
+ * `audit` nor `check`, runner/promotion.ts holdRefused), and its record's `reason`. */
155
+ export type BillHold = {
156
+ n: number | null;
157
+ at: string;
158
+ workflow: string;
159
+ by: "audit" | "check" | "dsl";
160
+ reason: string;
161
+ };
162
+ /** The owner's bill over the series (GET /agents/{id}/learning/cost `bill`, billOf), booked $ only: `points`, one a run
163
+ * that does a job; `baseline` the mean own $ (learning left out) of the `agent` runs before the first served run (every
164
+ * one with none yet) known exactly; `promoted` the first run a learned workflow served (or an audit audited); `break_even`
165
+ * the first run from `promoted` on after which `actual_usd` never again exceeds `agent_usd`, the booked total past the
166
+ * last point included (null: not yet, or nothing served), and `gap_usd` the booked total less the line at the last point
167
+ * while there is none; `withheld` the runs (a replay among them) whose cost is unknown or only a bound, on neither line;
168
+ * `booked_usd` every priced run's $, spend booked after the last point included. With the v2 split (amortize):
169
+ * `revisions`, `unattributed_usd` (the booked total less every run's all-in: what no run carries) and `holds`. */
170
+ export type Bill = {
171
+ baseline: {
172
+ runs: number;
173
+ mean_usd: number;
174
+ } | null;
175
+ promoted: {
176
+ n: number;
177
+ run_id: string;
178
+ at: string;
179
+ } | null;
180
+ points: BillPoint[];
181
+ break_even: {
182
+ n: number;
183
+ run_id: string;
184
+ } | null;
185
+ gap_usd: number | null;
186
+ withheld: number;
187
+ booked_usd: number;
188
+ revisions: RevisionShare[];
189
+ unattributed_usd: number | null;
190
+ holds: BillHold[];
191
+ };
192
+ /** The bill over `runs` (the cost series, oldest first, replays among them) and `promotedAt` (when the agent's first
193
+ * run on a served path started, null for none): each run that does a job, all in (its own $, its look-back, grade and
194
+ * audit shadow), with each replay's $ joining the run that does a job it followed (the first one when none did),
195
+ * cumulative; against the baseline times the runs shown so far. Spend booked with no point to join (a replay after a
196
+ * job of unknown cost) is carried to the next point, and with none after it is still booked: in the gap, and no
197
+ * break-even while it puts the bill over the line. Every sum and difference has its float noise rounded off (noiseOff),
198
+ * so a tie reads as a tie and a decision's sub-micro-dollar cost is booked as the usage row books it. */
199
+ export declare function billOf(runs: readonly CostRun[], promotedAt: string | null): Omit<Bill, "revisions" | "unattributed_usd" | "holds">;
200
+ /** Each revision's spend split over its first `k` served runs (`served`: the runs a learned workflow served, oldest
201
+ * first, with the workflow and digest that served each: a revision is both, as two workflows of the same text share a
202
+ * digest), in whole micro-dollars: each carries spend/k, the first ones a micro-dollar more, and the k-th the
203
+ * sub-micro-dollar rest too, so the split is exact to what was booked; a run past the k-th carries none of it.
204
+ * `shares`: what each served run carries, by run id (null when its revision's spend is unknown); what a revision's
205
+ * runs have not carried is its `unattributed_usd`, and `unattributed_usd` their sum (null once one is unknown). */
206
+ export declare function amortize(revisions: readonly RevisionSpend[], served: readonly {
207
+ run_id: string;
208
+ workflow: string;
209
+ digest: string;
210
+ }[]): {
211
+ shares: Map<string, number | null>;
212
+ revisions: RevisionShare[];
213
+ unattributed_usd: number | null;
214
+ };
108
215
  /** The series as CSV (RFC 4180, a header line, `\r\n` line ends): one row a run, an unknown figure empty. A text cell that
109
216
  * a spreadsheet would read as a formula (one starting with =, +, -, @, a tab or a carriage return) starts with a `'`, so
110
217
  * it opens as the text it is. */
@@ -10,10 +10,17 @@ import { ApiError } from "./errors.js";
10
10
  * rule for a run with nothing new to look back on, runner/learning-end.ts onlyLearnedWorkflows); `handed_back`, a
11
11
  * learned workflow ran and the agent went on (it handed back, failed, escalated, or the agent did more work after it);
12
12
  * `agent`, no learned workflow ran; `replay`, a replay run deciding whether a learned workflow's new revision serves
13
- * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
13
+ * (runner/promotion.ts: the workflow alone on a graded run's input, at workflow cost); `audit`, a shadow run auditing a
14
+ * run a learned workflow served (runner/audit.ts: the agent on its input with learning off; its cost is that run's
15
+ * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
14
16
  * record at its end (metrics.path). */
15
- export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay"];
17
+ export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay", "audit"];
18
+ /** A mean, rounded to the millionth: a quotient, never a booked figure. */
16
19
  const usd = (value) => Math.round(value * 1e6) / 1e6;
20
+ /** A booked figure with its float noise rounded off, nothing more (runner/metrics.ts floatNoiseOff, the precision a run's
21
+ * own cost is kept at): a decision costs millionths of a dollar, so a figure rounded to the millionth would lose it, and
22
+ * the run's cost here would read other than its usage row (A8). `+ 0` makes a noise-sized negative a plain 0, never -0. */
23
+ export const noiseOff = (value) => Math.round(value * 1e12) / 1e12 + 0;
17
24
  /** A run's own cost and what learning added for it, from its row's cost (`rowUsd`: the job, its look-back and any turn a
18
25
  * person asked of it after), what it kept as it answered (`looked`, none for a run that did not look back) and what its
19
26
  * grade spent (`gradeUsd`: its learning run's cost once that run ended, stopped or failed, 0 while it runs or when there
@@ -31,7 +38,7 @@ export function runCostOf(rowUsd, looked, gradeUsd = 0) {
31
38
  // look-back's cost unknown the two can't be told apart, and the job is what it had cost when it answered.
32
39
  const job = !answered || asAnswered === null || back === null ? asAnswered : rowUsd === null ? null : Math.max(asAnswered, rowUsd - back);
33
40
  const spent = back === null || gradeUsd === null ? null : back + gradeUsd;
34
- return { cost_usd: job === null ? null : usd(job), learning_usd: spent === null ? null : usd(spent), total_usd: job === null || spent === null ? null : usd(job + spent) };
41
+ return { cost_usd: job === null ? null : noiseOff(job), learning_usd: spent === null ? null : noiseOff(spent), total_usd: job === null || spent === null ? null : noiseOff(job + spent) };
35
42
  }
36
43
  /** The fewest runs after the takeover a "times cheaper" figure needs: fewer say too little. */
37
44
  export const CHEAPER_AFTER_RUNS = 20;
@@ -69,6 +76,116 @@ export function costSummary(runs, replay = null) {
69
76
  const afterState = after ? "priced" : first < 0 ? "no_served_runs" : "cost_unknown";
70
77
  return { takeover: first < 0 ? null : { n: runs[first].n, run_id: runs[first].run_id }, before, after, after_state: afterState, times_cheaper: times, hand_backs: handBacks, withheld, replay };
71
78
  }
79
+ /** The paths of the runs that do a job: the bill's run index counts these. A replay checks a revision and an audit's
80
+ * shadow audits a run: their spend is learning, booked where it falls (billOf) and carried by the runs they serve. */
81
+ export const JOB_PATHS = ["agent", "workflow", "handed_back"];
82
+ /** The bill over `runs` (the cost series, oldest first, replays among them) and `promotedAt` (when the agent's first
83
+ * run on a served path started, null for none): each run that does a job, all in (its own $, its look-back, grade and
84
+ * audit shadow), with each replay's $ joining the run that does a job it followed (the first one when none did),
85
+ * cumulative; against the baseline times the runs shown so far. Spend booked with no point to join (a replay after a
86
+ * job of unknown cost) is carried to the next point, and with none after it is still booked: in the gap, and no
87
+ * break-even while it puts the bill over the line. Every sum and difference has its float noise rounded off (noiseOff),
88
+ * so a tie reads as a tie and a decision's sub-micro-dollar cost is booked as the usage row books it. */
89
+ export function billOf(runs, promotedAt) {
90
+ const jobs = runs.filter((run) => JOB_PATHS.includes(run.path));
91
+ const priced = (run) => run.total_usd !== null && !run.cost_upper_bound;
92
+ const before = jobs.filter((run) => run.path === "agent" && (promotedAt === null || run.started_at < promotedAt) && run.cost_usd !== null && !run.cost_upper_bound);
93
+ const baseline = before.length ? { runs: before.length, mean_usd: usd(before.reduce((sum, run) => sum + run.cost_usd, 0) / before.length) } : null;
94
+ // Each replay's $ joins the job it followed; one before every job joins the first.
95
+ const extra = new Map();
96
+ let withheld = 0;
97
+ let last;
98
+ const early = [];
99
+ for (const run of runs) {
100
+ if (JOB_PATHS.includes(run.path)) {
101
+ last = run.run_id;
102
+ if (early.length)
103
+ extra.set(last, noiseOff((extra.get(last) ?? 0) + early.splice(0).reduce((a, b) => noiseOff(a + b), 0)));
104
+ continue;
105
+ }
106
+ if (run.path !== "replay")
107
+ continue;
108
+ if (!priced(run)) {
109
+ withheld += 1;
110
+ continue;
111
+ }
112
+ if (last === undefined)
113
+ early.push(run.total_usd);
114
+ else
115
+ extra.set(last, noiseOff((extra.get(last) ?? 0) + run.total_usd));
116
+ }
117
+ const points = [];
118
+ let actual = 0;
119
+ let shown = 0;
120
+ const line = baseline ? baseline.mean_usd : null;
121
+ const diffs = [];
122
+ jobs.forEach((run, at) => {
123
+ if (!priced(run)) {
124
+ withheld += 1;
125
+ actual = noiseOff(actual + (extra.get(run.run_id) ?? 0));
126
+ return;
127
+ }
128
+ shown += 1;
129
+ actual = noiseOff(actual + run.total_usd + (extra.get(run.run_id) ?? 0));
130
+ const agent = line === null ? null : noiseOff(line * shown);
131
+ points.push({ n: at + 1, run_id: run.run_id, actual_usd: actual, agent_usd: agent });
132
+ diffs.push(agent === null ? Number.NaN : noiseOff(actual - agent));
133
+ });
134
+ // Replays with no job at all to join (every job run archived, say) are booked all the same.
135
+ actual = noiseOff(early.reduce((sum, one) => sum + one, actual));
136
+ const first = promotedAt === null ? -1 : jobs.findIndex((run) => run.started_at >= promotedAt);
137
+ const promoted = first < 0 ? null : { n: first + 1, run_id: jobs[first].run_id, at: promotedAt };
138
+ // The booked total against the line at the last point: spend after it (carried to no point) is in.
139
+ const tail = line === null ? Number.NaN : noiseOff(actual - noiseOff(line * shown));
140
+ let breakEven = null;
141
+ if (promoted && line !== null && !(tail > 0)) {
142
+ const from = points.findIndex((point) => point.n >= promoted.n);
143
+ if (from >= 0) {
144
+ const over = diffs.findLastIndex((diff, at) => at >= from && diff > 0);
145
+ const at = over < 0 ? from : over + 1;
146
+ if (at < points.length)
147
+ breakEven = { n: points[at].n, run_id: points[at].run_id };
148
+ }
149
+ }
150
+ const gap = !breakEven && line !== null && points.length ? tail : null;
151
+ return { baseline, promoted, points, break_even: breakEven, gap_usd: gap, withheld, booked_usd: actual };
152
+ }
153
+ /** Each revision's spend split over its first `k` served runs (`served`: the runs a learned workflow served, oldest
154
+ * first, with the workflow and digest that served each: a revision is both, as two workflows of the same text share a
155
+ * digest), in whole micro-dollars: each carries spend/k, the first ones a micro-dollar more, and the k-th the
156
+ * sub-micro-dollar rest too, so the split is exact to what was booked; a run past the k-th carries none of it.
157
+ * `shares`: what each served run carries, by run id (null when its revision's spend is unknown); what a revision's
158
+ * runs have not carried is its `unattributed_usd`, and `unattributed_usd` their sum (null once one is unknown). */
159
+ export function amortize(revisions, served) {
160
+ const shares = new Map();
161
+ let rest = 0;
162
+ const out = revisions.map((revision) => {
163
+ const runs = served.filter((one) => one.workflow === revision.workflow && one.digest === revision.digest).slice(0, revision.k);
164
+ if (revision.spend_usd === null) {
165
+ for (const run of runs)
166
+ shares.set(run.run_id, null);
167
+ rest = null;
168
+ return { ...revision, served: runs.length, attributed_usd: null, unattributed_usd: null };
169
+ }
170
+ // Its whole micro-dollars (read off its pico-dollars, so float noise never drops one), split in integers; the rest
171
+ // under a micro-dollar is the k-th run's.
172
+ const total = Math.floor(Math.round(revision.spend_usd * 1e12) / 1e6);
173
+ const fraction = noiseOff(revision.spend_usd - total / 1e6);
174
+ const each = Math.floor(total / revision.k);
175
+ const over = total - each * revision.k;
176
+ let carried = 0;
177
+ runs.forEach((run, at) => {
178
+ const share = noiseOff((each + (at < over ? 1 : 0)) / 1e6 + (at === revision.k - 1 ? fraction : 0));
179
+ carried = noiseOff(carried + share);
180
+ shares.set(run.run_id, share);
181
+ });
182
+ const left = noiseOff(revision.spend_usd - carried);
183
+ if (rest !== null)
184
+ rest = noiseOff(rest + left);
185
+ return { ...revision, served: runs.length, attributed_usd: carried, unattributed_usd: left };
186
+ });
187
+ return { shares, revisions: out, unattributed_usd: rest };
188
+ }
72
189
  /** The series as CSV (RFC 4180, a header line, `\r\n` line ends): one row a run, an unknown figure empty. A text cell that
73
190
  * a spreadsheet would read as a formula (one starting with =, +, -, @, a tab or a carriage return) starts with a `'`, so
74
191
  * it opens as the text it is. */
@@ -26,6 +26,8 @@ export declare function wilsonOf(n: number, correct: number): [number, number];
26
26
  /** A posted record, checked for its shape only: each field that is missing or wrong is 422 input_invalid by field, and
27
27
  * nothing is kept. */
28
28
  export declare function evalOf(body: unknown, now: Date): LearningEval;
29
+ /** Where agent `agentId`'s eval records are kept (a setting of the store). */
30
+ export declare const evalsKey: (agentId: string) => string;
29
31
  /** Agent `agentId`'s records, newest recorded first. */
30
32
  export declare function evalsOf(store: Store, agentId: string): Promise<LearningEval[]>;
31
33
  /** Appends `record` first in agent `agentId`'s records, the latest EVALS_KEPT kept: a compare-and-set, so of two posts at
@@ -76,16 +76,17 @@ export function evalOf(body, now) {
76
76
  recorded_at: now.toISOString(),
77
77
  };
78
78
  }
79
- const keyOf = (agentId) => `learning.evals.${agentId}`;
79
+ /** Where agent `agentId`'s eval records are kept (a setting of the store). */
80
+ export const evalsKey = (agentId) => `learning.evals.${agentId}`;
80
81
  const listOf = (value) => (Array.isArray(value) ? value : []);
81
82
  /** Agent `agentId`'s records, newest recorded first. */
82
83
  export async function evalsOf(store, agentId) {
83
- return listOf(await store.settings.get(keyOf(agentId)));
84
+ return listOf(await store.settings.get(evalsKey(agentId)));
84
85
  }
85
86
  /** Appends `record` first in agent `agentId`'s records, the latest EVALS_KEPT kept: a compare-and-set, so of two posts at
86
87
  * once neither is lost. */
87
88
  export async function recordEval(store, agentId, record) {
88
- const key = keyOf(agentId);
89
+ const key = evalsKey(agentId);
89
90
  for (;;) {
90
91
  const was = await store.settings.get(key);
91
92
  const next = [record, ...listOf(was)].slice(0, EVALS_KEPT);
@@ -133,6 +133,14 @@ export declare function workflowRevisions(data: string, agentId: string, name: s
133
133
  total: number;
134
134
  truncated: boolean;
135
135
  }>;
136
+ /** Learned workflow `name`'s text at `digest` (a champion's, as its promotion records name it), read by that digest and
137
+ * never by paging the workflow's history: at `commits` (the records' learning commits, newest first), then at main, the
138
+ * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
139
+ * main yet, or no commit read holds it). One read-only exec per commit tried (textsAt). */
140
+ export declare function workflowAtDigest(data: string, agentId: string, name: string, digest: string, commits: readonly string[]): Promise<{
141
+ text: string;
142
+ commit: string;
143
+ } | undefined>;
136
144
  /** GET /agents/{id}/learning/files/{file}: the file on main as text, its ETag, and its type (a draft's workflow.json is
137
145
  * JSON). */
138
146
  export declare function readNote(data: string, agentId: string, raw: string, shown: Shown): Promise<{
@@ -254,7 +254,7 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
254
254
  const texts = await textsAt(ws, change.commit, [path]).catch((error) => { throw routeFailure(error); });
255
255
  const raw = texts?.[path];
256
256
  // Its digest, read from the text as it is (workflow-first.ts workflowDigest's): the one a run's metrics and the
257
- // promotion records name, so a revision's runs, guards and promotion are found by it.
257
+ // promotion records name, so a revision's runs and promotion are found by it.
258
258
  revisions.push({ commit: change.commit, at: change.at, by: change.by, reason: shown.text(change.reason), text: raw === undefined ? null : shown.text(raw), digest: raw === undefined ? null : createHash("sha256").update(raw).digest("hex").slice(0, 16) });
259
259
  }
260
260
  return { revisions, total: touched.length, truncated: snapshot.log_more };
@@ -263,6 +263,23 @@ export async function workflowRevisions(data, agentId, name, query, shown) {
263
263
  throw new ApiError("not_found", "the agent's learning folder has no such workflow");
264
264
  return { name, ...found };
265
265
  }
266
+ /** Learned workflow `name`'s text at `digest` (a champion's, as its promotion records name it), read by that digest and
267
+ * never by paging the workflow's history: at `commits` (the records' learning commits, newest first), then at main, the
268
+ * first commit whose workflow.json is that digest's text, with the commit it was read at. Undefined when none is (no
269
+ * main yet, or no commit read holds it). One read-only exec per commit tried (textsAt). */
270
+ export async function workflowAtDigest(data, agentId, name, digest, commits) {
271
+ if (!learnedName("workflow", name))
272
+ return undefined;
273
+ const path = `${WORKFLOWS_DIR}/${name}/workflow.json`;
274
+ return reading(data, agentId, async ({ ws, snapshot }) => {
275
+ for (const commit of new Set([...commits, snapshot.main])) {
276
+ const raw = (await textsAt(ws, commit, [path]).catch(() => undefined))?.[path];
277
+ if (raw !== undefined && createHash("sha256").update(raw).digest("hex").slice(0, 16) === digest)
278
+ return { text: raw, commit };
279
+ }
280
+ return undefined;
281
+ }, () => undefined);
282
+ }
266
283
  /** The blob of `file` on the snapshot's main, as a route names it: the index, a note, a skill's SKILL.md, a draft's
267
284
  * README.md or workflow.json; undefined when main holds no such file the snapshot names. */
268
285
  function blobIn(snapshot, file) {
@@ -3,7 +3,17 @@ export interface LearningLoop {
3
3
  readonly compile_after?: number;
4
4
  readonly agree_min?: number;
5
5
  readonly alone_min?: number;
6
+ readonly audit_every?: number;
7
+ readonly audit_every_later?: number;
8
+ readonly audit_later_after?: number;
9
+ readonly hold_window?: number;
10
+ readonly hold_disagree?: number;
11
+ readonly stop_window?: number;
6
12
  }
13
+ /** The check's numbers (runner/promotion.ts): what a check record keeps of the loop. */
14
+ export type CheckLoop = Required<Pick<LearningLoop, "compile_after" | "agree_min" | "alone_min">>;
15
+ /** The audit's numbers (runner/audit.ts). */
16
+ export type AuditLoop = Required<Pick<LearningLoop, "audit_every" | "audit_every_later" | "audit_later_after" | "hold_window" | "hold_disagree" | "stop_window">>;
7
17
  /** A definition's `learning`, as kept on an agentic revision. */
8
18
  export type LearningSetting = boolean | "notes" | LearningLoop;
9
19
  export declare const COMPILE_AFTER_DEFAULT = 20;
@@ -11,10 +21,15 @@ export declare const AGREE_MIN_DEFAULT = 0.8;
11
21
  export declare const ALONE_MIN_DEFAULT = 0.7;
12
22
  /** The most completed runs a compile may wait for: the newest this many of an agent's runs are what it counts and checks. */
13
23
  export declare const COMPILE_AFTER_MAX = 200;
24
+ export declare const AUDIT_DEFAULTS: AuditLoop;
25
+ /** The most any audit number may be: 1 in 1,000 runs, a window of 1,000 (the ledger keeps more rows than that). */
26
+ export declare const AUDIT_MAX = 1000;
14
27
  /** Whether `learning` has the agent's runs learn workflows too (true, or an object): never "notes", false or absent. */
15
28
  export declare const learnsWorkflowsOf: (learning: unknown) => boolean;
16
29
  /** The loop's numbers for a revision's `learning`: its object's, each one it leaves out at its default. */
17
- export declare function loopOf(learning: unknown): Required<LearningLoop>;
30
+ export declare function loopOf(learning: unknown): CheckLoop;
31
+ /** The audit's numbers for a revision's `learning`: its object's, each one it leaves out at its default (AUDIT_DEFAULTS). */
32
+ export declare function auditLoopOf(learning: unknown): AuditLoop;
18
33
  /** What is wrong with a definition's `learning`, in words naming the field (`at` its path), or undefined when it is one
19
34
  * of true, false, "notes" or an object of the loop's numbers. */
20
35
  export declare function learningSettingIssue(value: unknown, at?: string): string | undefined;
@@ -5,12 +5,31 @@
5
5
  // it answered alone, at least this share say what the agent's own recorded answer said;
6
6
  // alone_min (S): ...and when it answered at least this share of them alone (no escalate, no failed step).
7
7
  // learn/compile.ts compileDue reads compile_after; runner/promotion.ts's check reads all three.
8
+ // Once a workflow serves, its shadow audit (runner/audit.ts) reads the other six:
9
+ // audit_every (k): a run it serves is audited at 1 in k, drawn from the run's id (learn/audit.ts auditDrawn);
10
+ // audit_every_later, audit_later_after: 1 in this many once the digest served audit_later_after runs;
11
+ // hold_window, hold_disagree: it stops serving (a hold) when its last hold_window audit rows hold at least
12
+ // hold_disagree disagreements;
13
+ // stop_window: a second hold within this many served runs of the first stops it for good.
8
14
  export const COMPILE_AFTER_DEFAULT = 20;
9
15
  export const AGREE_MIN_DEFAULT = 0.8;
10
16
  export const ALONE_MIN_DEFAULT = 0.7;
11
17
  /** The most completed runs a compile may wait for: the newest this many of an agent's runs are what it counts and checks. */
12
18
  export const COMPILE_AFTER_MAX = 200;
13
- const LOOP_KEYS = ["compile_after", "agree_min", "alone_min"];
19
+ export const AUDIT_DEFAULTS = { audit_every: 10, audit_every_later: 20, audit_later_after: 50, hold_window: 10, hold_disagree: 3, stop_window: 100 };
20
+ /** The most any audit number may be: 1 in 1,000 runs, a window of 1,000 (the ledger keeps more rows than that). */
21
+ export const AUDIT_MAX = 1_000;
22
+ const AUDIT_KEYS = ["audit_every", "audit_every_later", "audit_later_after", "hold_window", "hold_disagree", "stop_window"];
23
+ const LOOP_KEYS = ["compile_after", "agree_min", "alone_min", ...AUDIT_KEYS];
24
+ /** Each audit number's words, for its 422. */
25
+ const AUDIT_WORDS = {
26
+ audit_every: "audits 1 in this many served runs",
27
+ audit_every_later: "audits 1 in this many served runs once audit_later_after served",
28
+ audit_later_after: "is the served runs after which audit_every_later applies",
29
+ hold_window: "is the audit rows the hold rule reads",
30
+ hold_disagree: "is the disagreements in hold_window rows that hold the workflow",
31
+ stop_window: "is the served runs within which a second hold stops the workflow",
32
+ };
14
33
  const isLoop = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
15
34
  /** Whether `learning` has the agent's runs learn workflows too (true, or an object): never "notes", false or absent. */
16
35
  export const learnsWorkflowsOf = (learning) => learning === true || isLoop(learning);
@@ -23,13 +42,18 @@ export function loopOf(learning) {
23
42
  alone_min: set.alone_min ?? ALONE_MIN_DEFAULT,
24
43
  };
25
44
  }
45
+ /** The audit's numbers for a revision's `learning`: its object's, each one it leaves out at its default (AUDIT_DEFAULTS). */
46
+ export function auditLoopOf(learning) {
47
+ const set = isLoop(learning) ? learning : {};
48
+ return Object.fromEntries(AUDIT_KEYS.map((key) => [key, set[key] ?? AUDIT_DEFAULTS[key]]));
49
+ }
26
50
  /** What is wrong with a definition's `learning`, in words naming the field (`at` its path), or undefined when it is one
27
51
  * of true, false, "notes" or an object of the loop's numbers. */
28
52
  export function learningSettingIssue(value, at = "learning") {
29
53
  if (typeof value === "boolean" || value === "notes")
30
54
  return undefined;
31
55
  if (!isLoop(value))
32
- return `${at} is true, false, "notes" or an object of the loop's numbers ({compile_after?, agree_min?, alone_min?}, on with those set)`;
56
+ return `${at} is true, false, "notes" or an object of the loop's numbers ({${LOOP_KEYS.map((key) => `${key}?`).join(", ")}}, on with those set)`;
33
57
  const other = Object.keys(value).find((key) => !LOOP_KEYS.includes(key));
34
58
  if (other !== undefined)
35
59
  return `${at}.${other} is not one of the loop's numbers: ${LOOP_KEYS.join(", ")}`;
@@ -40,6 +64,14 @@ export function learningSettingIssue(value, at = "learning") {
40
64
  if (share !== undefined && !(typeof share === "number" && Number.isFinite(share) && share >= 0 && share <= 1))
41
65
  return `${at}.${key} is a share from 0 to 1`;
42
66
  }
67
+ for (const key of AUDIT_KEYS) {
68
+ const n = value[key];
69
+ if (n !== undefined && !(Number.isInteger(n) && n >= 1 && n <= AUDIT_MAX))
70
+ return `${at}.${key} ${AUDIT_WORDS[key]}: a whole number from 1 to ${AUDIT_MAX}`;
71
+ }
72
+ const audit = auditLoopOf(value);
73
+ if (audit.hold_disagree > audit.hold_window)
74
+ return `${at}.hold_disagree is at most hold_window (${audit.hold_window}): the disagreements are counted in that many rows`;
43
75
  return undefined;
44
76
  }
45
77
  /** A valid `learning` as a revision keeps it: an object's numbers in one order, so two definitions that say the same are
@@ -204,7 +204,7 @@ export declare function shortOf<T extends {
204
204
  state: "dropped" | "proposed" | "merged" | "seeded" | "reflecting";
205
205
  reason: "cancelled" | "use" | "empty" | "unparsed" | "seed_failed" | "no_budget" | "unknown_cost" | "crashed" | "reflect_timeout" | "reflect_failed" | "propose_failed" | "checker" | "grader" | "grade_failed" | null;
206
206
  detail: string | null;
207
- } & Omit<T, "at" | "reason" | "detail" | "state">;
207
+ } & Omit<T, "at" | "reason" | "state" | "detail">;
208
208
  /** The label of the end-of-run turn's timeline rows, and the kind and label of a run's learning row. */
209
209
  export declare const LEARNING_LABEL = "learning";
210
210
  /** A run's proposal, in its directory (propose.ts): the seed it was checked against, each new note's file and text, its
@@ -0,0 +1,30 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ /** The port a server takes when none is named: the first free one from here (cli.ts). */
4
+ export declare const DEFAULT_PORT = 7340;
5
+ /** The address a server listens on when none is named: this machine only. */
6
+ export declare const DEFAULT_HOST = "127.0.0.1";
7
+ /** The free disk under the data directory below which GET /v2/health fails, in MiB, unless AGENTRUN_MIN_FREE_MB says. */
8
+ export declare const MIN_FREE_MIB = 64;
9
+ /** How long a warming answer asks its caller to wait before it asks again (Retry-After), and the page's reload. */
10
+ export declare const WARMING_RETRY_S = 2;
11
+ /** AGENTRUN_MIN_FREE_MB as MiB (MIN_FREE_MIB when unset), or undefined when it is no number of MiB, 0 or more. */
12
+ export declare function minFreeMibOf(env: NodeJS.ProcessEnv): number | undefined;
13
+ /** `server` listening on `host`, from port `first`; with `nextFreePort`, a taken port passes to the next, up to 99 past
14
+ * `first`. Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind. */
15
+ export declare function listenOn(server: Server, host: string, first: number, nextFreePort: boolean): Promise<void>;
16
+ /** The URL a listening `server` on `host` is reached at on this machine: an address of every interface at its loopback one. */
17
+ export declare function urlOf(server: Server, host: string): string;
18
+ /** A server bound on `host` at `port`, answering warming (above) until `takeOver`. Undefined when that port is taken: the
19
+ * port is then left to the start's own listen, which waits for a server it replaces (a restart, a redeploy) to let go of
20
+ * the data directory first, and only then takes the port, or passes to the next free one, as it always has. Any other
21
+ * failure to listen throws. */
22
+ export declare function listenFirst(o: {
23
+ host: string;
24
+ port: number;
25
+ data: string;
26
+ env: NodeJS.ProcessEnv;
27
+ }): Promise<Server | undefined>;
28
+ /** The server's own handlers on `server` from now on, in place of the warming ones: a request already being answered
29
+ * finishes as it began. */
30
+ export declare function takeOver(server: Server, onRequest: (req: IncomingMessage, res: ServerResponse) => void, onUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => void): void;