@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
@@ -16,6 +16,10 @@ export type CostLooked = {
16
16
  job_cost_usd?: number | null;
17
17
  look_back_usd?: number | null;
18
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;
19
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
20
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
21
25
  * grade spent (`gradeUsd`: its learning run's cost once that run ended, stopped or failed, 0 while it runs or when there
@@ -112,6 +116,102 @@ export type CostSummary = {
112
116
  replay: CostReplay | null;
113
117
  };
114
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
+ };
115
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
116
216
  * a spreadsheet would read as a formula (one starting with =, +, -, @, a tab or a carriage return) starts with a `'`, so
117
217
  * it opens as the text it is. */
@@ -15,7 +15,12 @@ import { ApiError } from "./errors.js";
15
15
  * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
16
16
  * record at its end (metrics.path). */
17
17
  export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay", "audit"];
18
+ /** A mean, rounded to the millionth: a quotient, never a booked figure. */
18
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;
19
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
20
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
21
26
  * grade spent (`gradeUsd`: its learning run's cost once that run ended, stopped or failed, 0 while it runs or when there
@@ -33,7 +38,7 @@ export function runCostOf(rowUsd, looked, gradeUsd = 0) {
33
38
  // look-back's cost unknown the two can't be told apart, and the job is what it had cost when it answered.
34
39
  const job = !answered || asAnswered === null || back === null ? asAnswered : rowUsd === null ? null : Math.max(asAnswered, rowUsd - back);
35
40
  const spent = back === null || gradeUsd === null ? null : back + gradeUsd;
36
- 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) };
37
42
  }
38
43
  /** The fewest runs after the takeover a "times cheaper" figure needs: fewer say too little. */
39
44
  export const CHEAPER_AFTER_RUNS = 20;
@@ -71,6 +76,116 @@ export function costSummary(runs, replay = null) {
71
76
  const afterState = after ? "priced" : first < 0 ? "no_served_runs" : "cost_unknown";
72
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 };
73
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
+ }
74
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
75
190
  * a spreadsheet would read as a formula (one starting with =, +, -, @, a tab or a carriage return) starts with a `'`, so
76
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<{
@@ -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) {
@@ -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;
@@ -0,0 +1,115 @@
1
+ // The address first. The server's CLI binds its port here, before it loads the rest of the server: on a slow disk (a cold
2
+ // start, a loaded machine), loading the server's modules is most of a start, and the store, the harness probes and Docker
3
+ // come after it. Until the server takes this socket over (ServeOptions.listener), every request is answered here: the
4
+ // server is warming. GET /v2/health says so (503, status "warming", the store "opening"), the API answers 503
5
+ // `unavailable` with a Retry-After, and a browser gets a page that reloads itself. Only node's own modules load here.
6
+ import { randomBytes } from "node:crypto";
7
+ import { statfs } from "node:fs/promises";
8
+ import { createServer } from "node:http";
9
+ /** The port a server takes when none is named: the first free one from here (cli.ts). */
10
+ export const DEFAULT_PORT = 7340;
11
+ /** The address a server listens on when none is named: this machine only. */
12
+ export const DEFAULT_HOST = "127.0.0.1";
13
+ /** The free disk under the data directory below which GET /v2/health fails, in MiB, unless AGENTRUN_MIN_FREE_MB says. */
14
+ export const MIN_FREE_MIB = 64;
15
+ /** How long a warming answer asks its caller to wait before it asks again (Retry-After), and the page's reload. */
16
+ export const WARMING_RETRY_S = 2;
17
+ /** AGENTRUN_MIN_FREE_MB as MiB (MIN_FREE_MIB when unset), or undefined when it is no number of MiB, 0 or more. */
18
+ export function minFreeMibOf(env) {
19
+ const mib = env.AGENTRUN_MIN_FREE_MB ? Number(env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
20
+ return Number.isFinite(mib) && mib >= 0 ? mib : undefined;
21
+ }
22
+ /** `server` listening on `host`, from port `first`; with `nextFreePort`, a taken port passes to the next, up to 99 past
23
+ * `first`. Each attempt takes off both its handlers when it ends, so a taken port leaves no listener behind. */
24
+ export async function listenOn(server, host, first, nextFreePort) {
25
+ const last = nextFreePort && first !== 0 ? Math.min(first + 99, 65_535) : first;
26
+ for (let port = first;; port++) {
27
+ try {
28
+ await new Promise((done, reject) => {
29
+ const onError = (error) => (server.off("listening", onListening), reject(error));
30
+ const onListening = () => (server.off("error", onError), done());
31
+ server.once("error", onError);
32
+ server.once("listening", onListening);
33
+ server.listen(port, host);
34
+ });
35
+ return;
36
+ }
37
+ catch (error) {
38
+ if (error.code !== "EADDRINUSE")
39
+ throw error;
40
+ if (port < last)
41
+ continue;
42
+ throw last > first ? Object.assign(new Error(`every port from ${first} to ${last} on ${host} is taken`), { code: "EADDRINUSE" }) : error;
43
+ }
44
+ }
45
+ }
46
+ /** The URL a listening `server` on `host` is reached at on this machine: an address of every interface at its loopback one. */
47
+ export function urlOf(server, host) {
48
+ const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
49
+ return `http://${shown.includes(":") ? `[${shown}]` : shown}:${server.address().port}`;
50
+ }
51
+ const PAGE = `<!doctype html>
52
+ <html lang="en"><head><meta charset="utf-8"><meta http-equiv="refresh" content="${WARMING_RETRY_S}"><meta name="color-scheme" content="light dark"><title>AgentRun is starting</title></head>
53
+ <body style="font-family: ui-monospace, SFMono-Regular, Menlo, monospace; margin: 3rem"><p>AgentRun is starting. This page reloads until it is ready.</p></body></html>
54
+ `;
55
+ /** The warming answer to one request: health, a browser's page, or the API's 503. Nothing in it is the server's: no
56
+ * token, no data, so it needs no Host check. */
57
+ function warming(data, minFreeBytes) {
58
+ return (req, res) => {
59
+ res.setHeader("x-request-id", `req_${randomBytes(8).toString("hex")}`);
60
+ res.setHeader("retry-after", String(WARMING_RETRY_S));
61
+ res.setHeader("cache-control", "no-store");
62
+ const path = (req.url ?? "/").split("?")[0];
63
+ const json = (body) => {
64
+ res.writeHead(503, { "content-type": "application/json" });
65
+ res.end(JSON.stringify(body));
66
+ };
67
+ req.resume();
68
+ if (path === "/v2/health") {
69
+ void statfs(data).then((fs) => fs.bavail * fs.bsize, () => undefined).then((free) => {
70
+ const disk = free === undefined || minFreeBytes === undefined ? "cannot_check" : free >= minFreeBytes ? "ok" : "below_floor";
71
+ json({ status: "warming", checks: { store: "opening", disk } });
72
+ });
73
+ return;
74
+ }
75
+ if (req.method === "GET" && !path.startsWith("/v2/") && /\btext\/html\b/i.test(String(req.headers.accept ?? ""))) {
76
+ res.writeHead(503, { "content-type": "text/html; charset=utf-8" });
77
+ res.end(PAGE);
78
+ return;
79
+ }
80
+ json({ error: { code: "unavailable", message: `AgentRun is starting: its store is opening. Send the request again in ${WARMING_RETRY_S} s.`, retryable: true, request_id: res.getHeader("x-request-id") } });
81
+ };
82
+ }
83
+ /** A WebSocket asked for while warming: refused, to be asked again. */
84
+ function warmingUpgrade(_req, socket) {
85
+ socket.on("error", () => socket.destroy());
86
+ socket.end(`HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nRetry-After: ${WARMING_RETRY_S}\r\nContent-Length: 0\r\n\r\n`);
87
+ }
88
+ /** A server bound on `host` at `port`, answering warming (above) until `takeOver`. Undefined when that port is taken: the
89
+ * 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
90
+ * the data directory first, and only then takes the port, or passes to the next free one, as it always has. Any other
91
+ * failure to listen throws. */
92
+ export async function listenFirst(o) {
93
+ const mib = minFreeMibOf(o.env);
94
+ const server = createServer(warming(o.data, mib === undefined ? undefined : mib * 2 ** 20));
95
+ // A request's headers come within 10 s, as the server's own listener has them.
96
+ server.headersTimeout = 10_000;
97
+ server.on("upgrade", warmingUpgrade);
98
+ try {
99
+ await listenOn(server, o.host, o.port, false);
100
+ }
101
+ catch (error) {
102
+ if (error.code === "EADDRINUSE")
103
+ return undefined;
104
+ throw error;
105
+ }
106
+ return server;
107
+ }
108
+ /** The server's own handlers on `server` from now on, in place of the warming ones: a request already being answered
109
+ * finishes as it began. */
110
+ export function takeOver(server, onRequest, onUpgrade) {
111
+ server.removeAllListeners("request");
112
+ server.removeAllListeners("upgrade");
113
+ server.on("request", onRequest);
114
+ server.on("upgrade", onUpgrade);
115
+ }
package/dist/llms.txt CHANGED
@@ -17,7 +17,8 @@ Auth: the API's routes take `Authorization: Bearer <token>`, all but `GET /v2/he
17
17
  - `POST /v2/agents` with `{definition: {name, instructions, tools, harness?, model?, thinking?}}` makes an agent (a workflow one holds `workflow` in place of `instructions`). A refusal is `422 input_invalid` naming each field. `PUT /v2/agents/{id}/definition` makes its next revision.
18
18
  - `POST /v2/agents/{id}/runs` with `{input, file_ids?, effort?, revision?}` starts a run, answered at once, queued. An agentic run's input is `{content: "the first message"}`. An `Idempotency-Key` header makes a retry safe.
19
19
  - `POST /v2/files?path=notes.md` with the file's bytes as the body (`curl --data-binary @notes.md`) uploads a file, answered `201` with the file, ready, its `file_id` under `file`. Name it in a run's `file_ids`, and the run finds it at `inputs/notes.md`. `GET /v2/files` lists the uploads, `DELETE /v2/files/{id}` removes one.
20
- - `GET /v2/runs/{id}`: status (`queued`, `working`, `input_required`, `completed`, `failed`, `cancelled`, `paused`), `result` (`final_answer`, or a workflow's `output`), `error`, `cost` (`usd` is null while unknown, never $0).
20
+ - `GET /v2/runs/{id}`: status (`queued`, `working`, `input_required`, `completed`, `failed`, `cancelled`, `paused`), `result` (`final_answer`, or a workflow's `output`), `error`, `cost` (`usd` is null while unknown, never $0), `path` (`agent`, `workflow`, `handed_back`; null until it ends).
21
+ - An agent that learns: a run its learned workflow served (`path` `workflow`) has the workflow's answer as `result.final_answer`; one handed back (`handed_back`) has the agent's. Its timeline is its `user_message`, the learned_workflow `tool_use` and `tool_result` (its nodes in `learned_nodes`; they write no `decision` rows), then `final_answer` and `usage`; a hand-back puts a `phase` row and the agent's own rows before them. Learning spends on the agent's own model route, key and cap: on `GET /v2/runs/{id}`, `cost.usd` is the run's own spend, the job's; `cost.learning_usd` what learning spent for it (its look-back, its grade, its audit's shadow run, and its share of its workflow revision's compile turn and check, spread over the revision's first `compile_after` served runs; a compile whose drafts all failed is on no run, in the bill's `unattributed_usd`), `cost.all_in_usd` both. A shadow run is in no run list and sends no webhook. `GET /v2/agents/{id}/learning/cost` has the agent's whole bill (`bill`).
21
22
  - `GET /v2/runs/{id}/timeline?after=0&limit=100` pages its steps; follow `next_after` until a page is `final` with `has_more` false.
22
23
  - `GET /v2/runs/{id}/files`, then `GET /v2/runs/{id}/files/{path}`: what it wrote.
23
24
  - `POST /v2/runs/{id}/messages` with `{content}` answers a run that asked a question (`input_required`), or follows up; `POST /v2/runs/{id}/cancel` ends one.
@@ -148,11 +148,11 @@ export declare class McpServersOverStore {
148
148
  not_metered?: string[] | undefined;
149
149
  tools: {
150
150
  grant_problems?: Record<string, string>;
151
- default_permission: "allow" | "ask" | "deny";
152
- permissions: ("allow" | "ask" | "deny")[];
151
+ default_permission: "ask" | "allow" | "deny";
152
+ permissions: ("ask" | "allow" | "deny")[];
153
153
  fallback_allow_reads?: true | undefined;
154
154
  allow_reads?: true | undefined;
155
- permission: "allow" | "ask" | "deny";
155
+ permission: "ask" | "allow" | "deny";
156
156
  effect: import("./tool-gate.js").ToolEffect;
157
157
  name: string;
158
158
  title?: string;
@@ -189,11 +189,11 @@ export declare class McpServersOverStore {
189
189
  not_metered?: string[] | undefined;
190
190
  tools: {
191
191
  grant_problems?: Record<string, string>;
192
- default_permission: "allow" | "ask" | "deny";
193
- permissions: ("allow" | "ask" | "deny")[];
192
+ default_permission: "ask" | "allow" | "deny";
193
+ permissions: ("ask" | "allow" | "deny")[];
194
194
  fallback_allow_reads?: true | undefined;
195
195
  allow_reads?: true | undefined;
196
- permission: "allow" | "ask" | "deny";
196
+ permission: "ask" | "allow" | "deny";
197
197
  effect: import("./tool-gate.js").ToolEffect;
198
198
  name: string;
199
199
  title?: string;
@@ -259,11 +259,11 @@ export declare class McpServersOverStore {
259
259
  not_metered?: string[] | undefined;
260
260
  tools: {
261
261
  grant_problems?: Record<string, string>;
262
- default_permission: "allow" | "ask" | "deny";
263
- permissions: ("allow" | "ask" | "deny")[];
262
+ default_permission: "ask" | "allow" | "deny";
263
+ permissions: ("ask" | "allow" | "deny")[];
264
264
  fallback_allow_reads?: true | undefined;
265
265
  allow_reads?: true | undefined;
266
- permission: "allow" | "ask" | "deny";
266
+ permission: "ask" | "allow" | "deny";
267
267
  effect: import("./tool-gate.js").ToolEffect;
268
268
  name: string;
269
269
  title?: string;
@@ -304,11 +304,11 @@ export declare class McpServersOverStore {
304
304
  not_metered?: string[] | undefined;
305
305
  tools: {
306
306
  grant_problems?: Record<string, string>;
307
- default_permission: "allow" | "ask" | "deny";
308
- permissions: ("allow" | "ask" | "deny")[];
307
+ default_permission: "ask" | "allow" | "deny";
308
+ permissions: ("ask" | "allow" | "deny")[];
309
309
  fallback_allow_reads?: true | undefined;
310
310
  allow_reads?: true | undefined;
311
- permission: "allow" | "ask" | "deny";
311
+ permission: "ask" | "allow" | "deny";
312
312
  effect: import("./tool-gate.js").ToolEffect;
313
313
  name: string;
314
314
  title?: string;
package/dist/model.d.ts CHANGED
@@ -6,10 +6,12 @@ import type { Revision } from "./agent-rows.js";
6
6
  /** The child's environment names the faux module by absolute path. */
7
7
  export declare const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
8
8
  /** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_WEB, ...), but the harness table's
9
- * (harness-table.ts HARNESS_TABLE_ENV), which withoutFaux drops by name. */
9
+ * (harness-table.ts HARNESS_TABLE_ENV), which withoutFaux drops by name, as it drops the resolved harness modules list
10
+ * (HARNESS_MODULES_ENV). */
10
11
  export declare const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
11
- /** `env` without a test hook's name: serve sets those from startServe's options alone, so a name the server's own
12
- * environment holds (an operator's export, a leftover) never gives its runs fake answers or loads a module. */
12
+ /** `env` without a test hook's name or the resolved harness modules list: serve sets those from startServe's options
13
+ * alone, so a name the server's own environment holds (an operator's export, a leftover) never gives its runs fake
14
+ * answers or loads a module. */
13
15
  export declare const withoutFaux: (env: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
14
16
  /** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
15
17
  * tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
@@ -229,7 +231,9 @@ export declare function catalogPrices(): Promise<Map<string, Listed[]>>;
229
231
  * version form: the vendor's entry (the id's segment before it, else `named`); else each level every entry that says
230
232
  * agrees on (gpt-6.1-sol's entries differ on `minimal` alone: openai-codex's asks low), a level they differ on left to
231
233
  * pi-ai's default. None: undefined, pi-ai's defaults. So pi through a gateway at thinking off asks gpt-6.1-sol for no
232
- * effort, as its catalog entries say (off: null), not the "none" it refuses. */
234
+ * effort, as its catalog entries say (off: null), not the "none" it refuses. A model the catalog does not list (a local
235
+ * model, a gateway's own alias) is never asked to stop reasoning either (off: null): pi then thinks at its lowest level,
236
+ * so a model that reasons anyway has its reasoning split out of the answer, never written into it. */
233
237
  export declare function catalogThinking(catalog: ReadonlyMap<string, readonly Listed[]>, id: string, named: string | undefined): ThinkingLevelMap | undefined;
234
238
  /** A gateway model's price in `catalog` (catalogPrices'), by its id as the host or the revision names it: a ref that names
235
239
  * its provider (`named`), priced as that provider's entry, whether the id went whole or bare; a host model set whole