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

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 (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -1,99 +0,0 @@
1
- // An agent's eval records (POST and GET /agents/{id}/learning/evals): the counts of a held-out test of what the agent
2
- // learned, posted by whoever ran it (a bench, a script, a person): `n` jobs it never learned from, `correct` of them right,
3
- // the cost a task with learning and by hand, where the labels came from and the learned revision it tested. The server
4
- // computes the accuracy and its 95% Wilson interval from the counts (a caller never sends either), so the console's
5
- // Learning tab can say how accurate and how cheap the learned agent is, with how many jobs and how sure. A record is only
6
- // ever what was posted: the server never computes one from the agent's own runs (the jobs it learned from, never held
7
- // out). Append-only, the latest first and the one shown, the latest EVALS_KEPT kept in the store's settings under the
8
- // agent's key. Aggregates only: no rows, no inputs.
9
- import { randomUUID } from "node:crypto";
10
- import { invalid } from "./errors.js";
11
- /** How many records an agent keeps, newest first. */
12
- export const EVALS_KEPT = 20;
13
- /** The most jobs one test may count. */
14
- export const EVAL_JOBS_MAX = 10_000_000;
15
- /** The longest `name` and `label_source`. */
16
- export const EVAL_TEXT_MAX = 200;
17
- const FIELDS = ["name", "label_source", "n", "correct", "cost_per_task_usd", "baseline_cost_per_task_usd", "learned_revision"];
18
- /** z for a two-sided 95% interval. */
19
- const Z95 = 1.959963984540054;
20
- const places = (value) => Math.round(value * 1e4) / 1e4;
21
- /** The 95% Wilson score interval of `correct` right of `n`, [low, high], each from 0 to 1, to four places: unlike the
22
- * normal approximation it holds at 0 and at n right and with few jobs. */
23
- export function wilsonOf(n, correct) {
24
- const p = correct / n;
25
- const z2 = Z95 * Z95;
26
- const over = 1 + z2 / n;
27
- const centre = (p + z2 / (2 * n)) / over;
28
- const half = (Z95 * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / over;
29
- return [places(Math.max(0, centre - half)), places(Math.min(1, centre + half))];
30
- }
31
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
32
- const oneLine = (value) => typeof value === "string" && !!value.trim() && value.length <= EVAL_TEXT_MAX && !/[\u0000-\u001f\u007f]/.test(value);
33
- const whole = (value, least, most) => Number.isInteger(value) && value >= least && value <= most;
34
- const dollars = (value) => value === null || (typeof value === "number" && Number.isFinite(value) && value >= 0);
35
- /** A posted record, checked for its shape only: each field that is missing or wrong is 422 input_invalid by field, and
36
- * nothing is kept. */
37
- export function evalOf(body, now) {
38
- if (!isObject(body))
39
- throw invalid([{ field: "body", reason: "invalid", message: "the body is a JSON object" }]);
40
- const issues = [];
41
- for (const key of Object.keys(body)) {
42
- const why = key === "accuracy" || key === "ci" ? "the server computes accuracy and ci from n and correct" : `the body takes ${FIELDS.join(", ")}`;
43
- if (!FIELDS.includes(key))
44
- issues.push({ field: key, reason: "unknown", message: why });
45
- }
46
- const { name, label_source: source = null, n, correct, cost_per_task_usd: cost = null, baseline_cost_per_task_usd: baseline = null, learned_revision: revision = null } = body;
47
- if (!oneLine(name))
48
- issues.push({ field: "name", reason: "invalid", message: `name says what ran the test, in one line of at most ${EVAL_TEXT_MAX} characters`, example: "invoice bench, sealed test" });
49
- if (!(source === null || oneLine(source)))
50
- issues.push({ field: "label_source", reason: "invalid", message: `label_source says where the right answers came from, in one line of at most ${EVAL_TEXT_MAX} characters, or null`, example: "teacher labels, 87% strict vs people" });
51
- const jobs = whole(n, 1, EVAL_JOBS_MAX);
52
- if (!jobs)
53
- issues.push({ field: "n", reason: "invalid", message: `n is the held-out jobs counted, a whole number from 1 to ${EVAL_JOBS_MAX}`, example: 200 });
54
- if (!whole(correct, 0, jobs ? n : EVAL_JOBS_MAX))
55
- issues.push({ field: "correct", reason: "invalid", message: "correct is how many of the n jobs it got right, a whole number from 0 to n", example: 188 });
56
- if (!dollars(cost))
57
- issues.push({ field: "cost_per_task_usd", reason: "invalid", message: "cost_per_task_usd is the mean cost a task with learning, in dollars, 0 or more, or null" });
58
- if (!dollars(baseline))
59
- issues.push({ field: "baseline_cost_per_task_usd", reason: "invalid", message: "baseline_cost_per_task_usd is the mean cost a task by hand, in dollars, 0 or more, or null" });
60
- if (!(revision === null || (typeof revision === "string" && /^[0-9a-f]{7,64}$/.test(revision))))
61
- issues.push({ field: "learned_revision", reason: "invalid", message: "learned_revision is the learning folder's commit it tested (7 to 64 hex characters), or null" });
62
- if (issues.length)
63
- throw invalid(issues);
64
- const [jobsN, right] = [n, correct];
65
- return {
66
- id: `eval_${randomUUID()}`,
67
- name: name.trim(),
68
- label_source: source === null ? null : source.trim(),
69
- n: jobsN,
70
- correct: right,
71
- accuracy: places(right / jobsN),
72
- ci: wilsonOf(jobsN, right),
73
- cost_per_task_usd: cost,
74
- baseline_cost_per_task_usd: baseline,
75
- learned_revision: revision,
76
- recorded_at: now.toISOString(),
77
- };
78
- }
79
- /** Where agent `agentId`'s eval records are kept (a setting of the store). */
80
- export const evalsKey = (agentId) => `learning.evals.${agentId}`;
81
- const listOf = (value) => (Array.isArray(value) ? value : []);
82
- /** Agent `agentId`'s records, newest recorded first. */
83
- export async function evalsOf(store, agentId) {
84
- return listOf(await store.settings.get(evalsKey(agentId)));
85
- }
86
- /** Appends `record` first in agent `agentId`'s records, the latest EVALS_KEPT kept: a compare-and-set, so of two posts at
87
- * once neither is lost. */
88
- export async function recordEval(store, agentId, record) {
89
- const key = evalsKey(agentId);
90
- for (;;) {
91
- const was = await store.settings.get(key);
92
- const next = [record, ...listOf(was)].slice(0, EVALS_KEPT);
93
- // putIfAbsent answers what the key holds after: ours, or ours under a post that raced in between (Postgres inserts and reads
94
- // back in separate calls), so ours is kept when its id is in the list, never when the list merely differs from ours.
95
- const kept = was === undefined ? listOf(await store.settings.putIfAbsent(key, next)).some((e) => e.id === record.id) : await store.settings.replaceIf(key, was, next);
96
- if (kept)
97
- return;
98
- }
99
- }
@@ -1,6 +0,0 @@
1
- /** Additive files under AgentRun's private per-run directory. Native settings and project files are never changed.
2
- * Relative skill resources stay beside SKILL.md. Reading/executing them still requires native tool permission. */
3
- export declare function nativeSkillContext(root: string, skills: readonly {
4
- name: string;
5
- files?: Record<string, string>;
6
- }[]): Promise<string>;
@@ -1,22 +0,0 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import { dirname, resolve, sep } from 'node:path';
3
- /** Additive files under AgentRun's private per-run directory. Native settings and project files are never changed.
4
- * Relative skill resources stay beside SKILL.md. Reading/executing them still requires native tool permission. */
5
- export async function nativeSkillContext(root, skills) {
6
- const sections = [];
7
- for (const skill of skills) {
8
- if (!/^[a-z0-9][a-z0-9-]*$/.test(skill.name))
9
- throw new Error('Unsafe learned skill name.');
10
- const base = resolve(root, skill.name);
11
- await mkdir(base, { recursive: true, mode: 0o700 });
12
- for (const [path, content] of Object.entries(skill.files ?? {})) {
13
- const target = resolve(base, path);
14
- if (!target.startsWith(base + sep) || path.includes('\\'))
15
- throw new Error('Unsafe learned skill resource path.');
16
- await mkdir(dirname(target), { recursive: true, mode: 0o700 });
17
- await writeFile(target, content, { mode: 0o600, flag: 'wx' });
18
- }
19
- sections.push(`## AgentRun learned skill: ${skill.name}\nSkill directory: ${base}\nResolve this skill's relative references from that directory, not the project. Use absolute paths for its resources. Native permissions still apply; if unavailable, report that limitation.\n\n${skill.files?.['SKILL.md'] ?? ''}`);
20
- }
21
- return sections.join('\n\n');
22
- }
package/dist/propose.d.ts DELETED
@@ -1,52 +0,0 @@
1
- import { type Problem } from "./learn/index.js";
2
- import type { DraftDecisions } from "./learn/skills.js";
3
- import { type Turn } from "./learning.js";
4
- import type { Workspace } from "./workspace/index.js";
5
- export type Proposed = {
6
- state: "proposed";
7
- notes: number;
8
- skills: number;
9
- workflows: number;
10
- left?: Problem[];
11
- } | {
12
- state: "dropped";
13
- reason: "empty";
14
- } | {
15
- state: "dropped";
16
- reason: "unparsed";
17
- detail: string;
18
- } | {
19
- state: "dropped";
20
- reason: "checker";
21
- problems: Problem[];
22
- };
23
- /** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
24
- * pin) in the agent's learning folder `folder` (learningWorkspace; the caller ends it) and kept in `runDir` as its
25
- * proposal, with what the user said in the run as the grader reads it (each message cut of the host's secrets, then
26
- * shortened to its head and tail by shortMessage); or `empty` when it gave nothing, `unparsed` when its answer is out of
27
- * format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the very text the
28
- * seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
29
- * `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
30
- * description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
31
- * `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets; `outputSchema`: the
32
- * agent's, which a draft's dry run holds its answer to (learn/skills.ts draftDryRun). */
33
- export declare const proposeRun: (input: {
34
- folder: Workspace;
35
- runDir: string;
36
- seed: string;
37
- notesSeed?: string;
38
- revised?: {
39
- workflow: string;
40
- base: string;
41
- };
42
- turn: Turn;
43
- refuse: readonly string[];
44
- outcome?: string;
45
- tools?: readonly string[];
46
- gated?: Readonly<Record<string, string>>;
47
- deniedBy?: Readonly<Record<string, "agent" | "server" | "default">>;
48
- decisions?: DraftDecisions;
49
- workflowAdapters?: readonly ("runNode" | "runJudge")[];
50
- workflows?: false;
51
- outputSchema?: unknown;
52
- }) => Promise<Proposed>;
package/dist/propose.js DELETED
@@ -1,224 +0,0 @@
1
- // Learning, after a run: the notes its end-of-run turn answered with, and a skill or a workflow draft beside them, are read
2
- // by the host (learn/reflect.ts parseReflection), checked against the commit the run started from (learn/check.ts
3
- // checkProposal), and kept as its proposal (`learning-proposal.json`, in the directory the caller gives), or dropped. The
4
- // answer is what the runner's end-of-run turn read from the run's store (runner/learning-end.ts), never the run's work;
5
- // and no file the run wrote is read at all, in `.learning/` or anywhere. The seed is
6
- // read from the agent's learning folder through its Workspace, as the reflect hook's check reads it (learn/seed-check.ts):
7
- // the snapshot and its bodies when main is the seed (no exec), else one read-only exec of the learning script at that
8
- // commit. Nothing is written to git here, and nothing is written at all before the checks pass: what they refuse (a
9
- // note holding a secret among them) is never kept anywhere.
10
- import { join } from "node:path";
11
- import { checkProposal, draftDryRun, draftFiles, NOTE_BLOCK, unstorable, parseReflection, redactSecrets, shortMessage, SKILL_BLOCK, SKILLS_DIR, WORKFLOW_BLOCK, WORKFLOWS_DIR } from "./learn/index.js";
12
- import { folderAt, readLearning, readSnapshot } from "./learn/folder.js";
13
- import { baseOf } from "./learn/seed-check.js";
14
- import { parseNoteFile, ruleOf } from "./learn/notes.js";
15
- import { writeDurable } from "./files.js";
16
- import { PROPOSAL } from "./learning.js";
17
- /** The rules that refuse a proposal whole, whatever item they name: a path outside what a run may write, a deletion,
18
- * anything that must never be stored (a secret, a character a reader does not see), which says the run's answer is
19
- * not to be trusted for any item, and text that is not UTF-8, which cannot be read for one. Every other problem is its
20
- * item's alone: a count cap names the items past it (learn/check.ts), a size cap the item over it, the index's lines
21
- * the notes that add lines from the answer's end, and they are left out and the rest kept; unstorable reads every
22
- * item's text whole first. */
23
- const WHOLE = new Set(["outside", "deleted", "secret_value", "secret_shape", "invisible_unicode", "encoding"]);
24
- /** The item a changed file belongs to: a draft's two files are one item (its folder), every other file is itself. */
25
- const itemOf = (path) => (path.startsWith(`${WORKFLOWS_DIR}/`) ? path.split("/").slice(0, 2).join("/") : path);
26
- const utf8 = new TextDecoder("utf-8", { fatal: true });
27
- /** The text of `bytes`, or undefined when they are not UTF-8 (no text an answer can give again). */
28
- const textOf = (bytes) => {
29
- try {
30
- return utf8.decode(bytes);
31
- }
32
- catch {
33
- return undefined;
34
- }
35
- };
36
- /** Each file of a snapshot by path, with its blob id: the notes, and the learned items' regular files. */
37
- const oidsOf = (snapshot) => new Map([
38
- ...snapshot.notes.map((note) => [note.file, note.oid]),
39
- ...[...snapshot.skills, ...snapshot.workflows].flatMap((item) => item.files.map(({ path, oid }) => [path, oid])),
40
- ]);
41
- /** The seed `seed` of the folder `lw`, and the texts of the files of it `wanted` names (one it does not hold, or that is
42
- * not UTF-8, is left out): from the snapshot and its bodies when its main is the seed (no exec); else ONE read-only
43
- * exec of the learning script's `read` at that commit. Throws when the folder has no such commit. */
44
- async function seedAt(lw, seed, wanted) {
45
- const now = await readSnapshot(lw);
46
- if (now?.main === seed) {
47
- const read = await readLearning(lw, async ({ snapshot, bytes }) => {
48
- // The folder moved on as it was read: read at the seed below.
49
- if (snapshot?.main !== seed)
50
- return undefined;
51
- const oids = oidsOf(snapshot);
52
- const texts = new Map();
53
- for (const path of wanted(snapshot)) {
54
- const oid = oids.get(path);
55
- const text = oid === undefined ? undefined : textOf(await bytes(path, oid));
56
- if (text !== undefined)
57
- texts.set(path, text);
58
- }
59
- return { snapshot, texts };
60
- });
61
- if (read)
62
- return read;
63
- }
64
- const at = await folderAt(lw, seed);
65
- if (!at)
66
- throw new Error(`the learning folder has no commit ${seed}`);
67
- const oids = oidsOf(at.snapshot);
68
- const texts = new Map();
69
- for (const path of wanted(at.snapshot)) {
70
- const blob = oids.has(path) ? at.blobs.get(oids.get(path)) : undefined;
71
- const text = blob === undefined ? undefined : textOf(blob);
72
- if (text !== undefined)
73
- texts.set(path, text);
74
- }
75
- return { snapshot: at.snapshot, texts };
76
- }
77
- /** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
78
- * pin) in the agent's learning folder `folder` (learningWorkspace; the caller ends it) and kept in `runDir` as its
79
- * proposal, with what the user said in the run as the grader reads it (each message cut of the host's secrets, then
80
- * shortened to its head and tail by shortMessage); or `empty` when it gave nothing, `unparsed` when its answer is out of
81
- * format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the very text the
82
- * seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
83
- * `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
84
- * description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
85
- * `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets; `outputSchema`: the
86
- * agent's, which a draft's dry run holds its answer to (learn/skills.ts draftDryRun). */
87
- export const proposeRun = async (input) => {
88
- const parsed = parseReflection(input.turn.answer);
89
- // Each skill and draft as the folder would hold it, keyed by its block (kind and name) so the changes keep the
90
- // answer's order; a draft is its two files, given together or not at all. A draft's `example:` line, by its
91
- // workflow.json's path: the input its dry run runs on, never a file's (draftFiles leaves it out of the README).
92
- const fileGroups = new Map();
93
- const examples = new Map();
94
- const keyOf = (kind, name) => `${kind}\u0000${name}`;
95
- for (const { name, text } of parsed.ok ? (parsed.skills ?? []) : [])
96
- fileGroups.set(keyOf(SKILL_BLOCK, name), [{ file: `${SKILLS_DIR}/${name}/SKILL.md`, text }]);
97
- for (const { name, text } of parsed.ok ? (parsed.workflows ?? []) : []) {
98
- const { json, readme, example } = draftFiles(name, text);
99
- if (example !== undefined)
100
- examples.set(`${WORKFLOWS_DIR}/${name}/workflow.json`, example);
101
- fileGroups.set(keyOf(WORKFLOW_BLOCK, name), [{ file: `${WORKFLOWS_DIR}/${name}/workflow.json`, text: json }, { file: `${WORKFLOWS_DIR}/${name}/README.md`, text: readme }]);
102
- }
103
- const given = [...fileGroups.values()];
104
- // The seed is read whatever the answer: a seed the folder does not hold fails the check.
105
- // The seed's active notes are read too: a new note of the same rule as one (notes.ts ruleOf) is a duplicate.
106
- const activeOf = (seedSnapshot) => seedSnapshot.notes.filter((note) => note.status === "active").map((note) => note.file);
107
- // And the skill of each draft's name, as the folder holds it: what the draft keeps as a workflow, for the grader.
108
- const skillOf = (draft) => `${SKILLS_DIR}/${draft.split("/")[1]}/SKILL.md`;
109
- const draftSkills = given.flat().filter(({ file }) => file.endsWith("/workflow.json")).map(({ file }) => skillOf(file));
110
- const { snapshot, texts } = await seedAt(input.folder, input.seed, (seedSnapshot) => (parsed.ok ? [...parsed.notes.map(({ file }) => file), ...given.flat().map(({ file }) => file), ...draftSkills, ...activeOf(seedSnapshot)] : []));
111
- if (!parsed.ok)
112
- return parsed.reason === "empty" ? { state: "dropped", reason: "empty" } : { state: "dropped", reason: "unparsed", detail: parsed.detail };
113
- const { base: seedBase, kept: seedKept } = baseOf(snapshot);
114
- // A workflow the compile turn revised from main's text (`revised`) is checked against the commit it read that text at,
115
- // not the seed: a change made to it on main before that read is what the revision was written over, and only one after
116
- // it is a conflict (its files' `bases` in the proposal, which the merge checks main against). Every other item keeps
117
- // the seed.
118
- const revisedDir = input.revised && input.revised.base !== input.seed ? `${WORKFLOWS_DIR}/${input.revised.workflow}/` : undefined;
119
- const isRevised = (path) => revisedDir !== undefined && path.startsWith(revisedDir);
120
- const revisedAt = revisedDir ? await seedAt(input.folder, input.revised.base, () => given.flat().map(({ file }) => file).filter(isRevised)) : undefined;
121
- const revisedBase = revisedAt ? baseOf(revisedAt.snapshot) : undefined;
122
- const textAt = (file) => (revisedAt && isRevised(file) ? revisedAt.texts.get(file) : texts.get(file));
123
- const kept = revisedBase ? [...seedKept.filter((file) => !isRevised(file)), ...revisedBase.kept.filter(isRevised)] : seedKept;
124
- // A later round's notes are checked against the main the earlier rounds merged into (`notesSeed`: a note round 1 added
125
- // is a supersedes target and a duplicate rule), while a skill's or a draft's files keep `seed` as their conflict base:
126
- // the run was laid from it, so a file changed on main since is a conflict, never written over.
127
- const noted = input.notesSeed && input.notesSeed !== input.seed
128
- ? await seedAt(input.folder, input.notesSeed, (seedSnapshot) => (parsed.ok ? [...parsed.notes.map(({ file }) => file), ...activeOf(seedSnapshot)] : []))
129
- : { snapshot, texts };
130
- const rules = new Map(activeOf(noted.snapshot).flatMap((file) => {
131
- const note = noted.texts.has(file) ? parseNoteFile(file, noted.texts.get(file)) : undefined;
132
- return note && !Array.isArray(note) ? [[ruleOf(note.body), file]] : [];
133
- }));
134
- const learnedPath = (path) => path.startsWith(`${SKILLS_DIR}/`) || path.startsWith(`${WORKFLOWS_DIR}/`);
135
- const notedBase = baseOf(noted.snapshot).base;
136
- const base = { files: [...[...notedBase.files].filter((path) => !learnedPath(path)), ...[...seedBase.files].filter((path) => learnedPath(path) && !isRevised(path)), ...[...(revisedBase?.base.files ?? [])].filter(isRevised)], active: notedBase.active, rules };
137
- const held = new Set(base.files);
138
- const files = given.filter((group) => group.some(({ file, text }) => textAt(file) !== text)).flat();
139
- const changeOf = ({ file, text }) => ({ path: file, status: held.has(file) ? "modified" : "added", mode: "100644", bytes: Buffer.from(text) });
140
- // Each changed item in the order the answer gave its block, whatever its kind: a count cap names the items past it in
141
- // that order (learn/check.ts), so a skill the answer led with is never the one past the changed-path cap.
142
- const noteTexts = new Map(parsed.notes.map(({ file, text }) => [file, text]));
143
- const changed = new Set(files.map(({ file }) => file));
144
- const changes = parsed.order.flatMap(({ kind, name }) => {
145
- if (kind === NOTE_BLOCK) {
146
- const text = noteTexts.get(name);
147
- return noted.texts.get(name) !== text ? [changeOf({ file: name, text })] : [];
148
- }
149
- return (fileGroups.get(keyOf(kind, name)) ?? []).filter(({ file }) => changed.has(file)).map(changeOf);
150
- });
151
- // The workflow DSL reads a draft, and is loaded only when there is one to read.
152
- const dsl = files.some(({ file }) => file.endsWith("/workflow.json")) ? await import("@parcha/agentrun-dsl") : undefined;
153
- // A draft's example: the run's own input, so read as every text the run gave is, for what must never be stored (a
154
- // held secret, a secret's shape): one that holds any refuses the whole answer, said at the draft's README, though it
155
- // is never written there.
156
- const exampled = files.filter(({ file }) => examples.has(file)).map(({ file }) => ({ path: file.replace(/workflow\.json$/, "README.md"), status: "added", mode: "100644", bytes: Buffer.from(examples.get(file)) }));
157
- const leaky = unstorable(exampled, input.refuse);
158
- if (leaky.length)
159
- return { state: "dropped", reason: "checker", problems: leaky };
160
- // A skill or a draft whose seed text has a status is a person's call (retired, or waiting for their OK): never changed.
161
- const dryRuns = {};
162
- const check = (some) => checkProposal({ workflowAdapters: input.workflowAdapters, base, changes: some, refuseValues: input.refuse, ...(input.workflows === false ? { workflows: false } : {}), ...(kept.length ? { kept } : {}), ...(input.outcome === undefined ? {} : { outcome: input.outcome }), ...(input.tools ? { tools: input.tools } : {}), ...(input.gated ? { gated: input.gated } : {}), ...(input.deniedBy ? { deniedBy: input.deniedBy } : {}), ...(input.decisions ? { decisions: input.decisions } : {}), ...(dsl ? { dsl, dryRuns } : {}) });
163
- // The static checks first, every one (validateWorkflow with executeCode: false, draftProblems' refusal of code nodes,
164
- // caps, secrets): a draft they refuse is never dry-run, nor is any when they refuse the answer whole. Then each draft
165
- // left is dry-run on its example, else on a synthesized input (learn/skills.ts draftDryRun): every model and tool
166
- // answer synthesized, nothing sent, paid or run, and no code it holds run in this process.
167
- if (dsl) {
168
- const statics = check(changes).problems;
169
- const whole = statics.some((problem) => WHOLE.has(problem.rule) || problem.path === undefined);
170
- const refused = new Set(statics.flatMap((problem) => (problem.path === undefined ? [] : [itemOf(problem.path)])));
171
- if (!whole)
172
- for (const { file, text } of files)
173
- if (file.endsWith("/workflow.json") && !refused.has(itemOf(file)))
174
- dryRuns[file] = await draftDryRun(dsl, text, examples.get(file), input.outputSchema);
175
- }
176
- // A verdict per item from the checks too: the items a problem names are left out (a draft's two files together),
177
- // and the rest is checked again, until it passes; a problem that names no item, or one that refuses the whole (WHOLE),
178
- // drops it all, as does a rest with nothing left. A later pass can name what an earlier one did not reach (the
179
- // supersedes count, asked only of a rest with no other problem); each pass leaves out at least one item, so it ends.
180
- let checked = check(changes);
181
- let left = [];
182
- const out = new Set();
183
- if (checked.problems.length) {
184
- const named = new Set(changes.map(({ path }) => itemOf(path)));
185
- // Before any item is kept from an answer the checks refuse: every name and text it gave, read whole. Something
186
- // that must never be stored anywhere in it (in an item the checks refused unread, too) refuses it all.
187
- const never = unstorable(changes, input.refuse);
188
- for (;;) {
189
- if (checked.problems.some((problem) => WHOLE.has(problem.rule) || problem.path === undefined || !named.has(itemOf(problem.path))))
190
- return { state: "dropped", reason: "checker", problems: [...left, ...checked.problems] };
191
- if (never.length)
192
- return { state: "dropped", reason: "checker", problems: [...left, ...checked.problems, ...never] };
193
- left = [...left, ...checked.problems];
194
- for (const problem of checked.problems)
195
- out.add(itemOf(problem.path));
196
- const rest = changes.filter(({ path }) => !out.has(itemOf(path)));
197
- if (!rest.length)
198
- return { state: "dropped", reason: "checker", problems: left };
199
- checked = check(rest);
200
- if (!checked.problems.length)
201
- break;
202
- }
203
- }
204
- const passing = files.filter(({ file }) => !out.has(itemOf(file)));
205
- if (!checked.notes.length && !passing.length)
206
- return { state: "dropped", reason: "empty" };
207
- // Each message cut of the host's secrets whole first, and only then shortened: a secret the cut fell inside would
208
- // leave a part of itself that no longer matches. The whole message is read, however long (a message is bounded by
209
- // the run's own request limits), so a long one is not lost to the grader as one "[redacted]".
210
- const asked = input.turn.asked.map((message) => shortMessage(redactSecrets(message, input.refuse, Number.POSITIVE_INFINITY)));
211
- // A trigger's input, apart from what the user said, cut and shortened the same way.
212
- const triggered = (input.turn.triggered ?? []).map(({ source, text }) => ({ source, text: shortMessage(redactSecrets(text, input.refuse, Number.POSITIVE_INFINITY)) }));
213
- // How each kept draft's dry run went, for the grader: passed, or not run and why.
214
- const ran = Object.fromEntries(passing.filter(({ file }) => dryRuns[file]).map(({ file }) => [file, dryRuns[file]]));
215
- // Each kept draft's skill as the folder holds it at the seed, unless the proposal gives that skill itself (the grader
216
- // reads it there): the format the draft's answer keeps (#2412). Cut of the host's secrets, as what was said is.
217
- const proposing = new Set(passing.map(({ file }) => file));
218
- const drafted = passing.filter(({ file }) => file.endsWith("/workflow.json")).map(({ file }) => skillOf(file)).filter((file) => !proposing.has(file) && texts.has(file)).map((file) => ({ file, text: redactSecrets(texts.get(file), input.refuse, Number.POSITIVE_INFINITY) }));
219
- const bases = Object.fromEntries(passing.filter(({ file }) => isRevised(file)).map(({ file }) => [file, input.revised.base]));
220
- const proposal = { seed: input.seed, ...(Object.keys(bases).length ? { bases } : {}), notes: checked.notes.map(({ file, text }) => ({ file, text })), ...(passing.length ? { files: passing } : {}), ...(Object.keys(ran).length ? { dryRuns: ran } : {}), ...(drafted.length ? { drafted } : {}), asked, ...(triggered.length ? { triggered } : {}) };
221
- await writeDurable(join(input.runDir, PROPOSAL), `${JSON.stringify(proposal)}\n`);
222
- const count = (suffix) => passing.filter(({ file }) => file.endsWith(suffix)).length;
223
- return { state: "proposed", notes: proposal.notes.length, skills: count("/SKILL.md"), workflows: count("/workflow.json"), ...(left.length ? { left } : {}) };
224
- };
@@ -1,47 +0,0 @@
1
- import { type BeforeRequest, type Wire } from "@parcha/agentrun-kernel";
2
- import { type LearningLoopDeps } from "./learning-loop.js";
3
- import type { RouteCost } from "./model-route.js";
4
- /** How long the ask waits, once the grade answered, for the proxy to book its request: the proxy books a request after its
5
- * client has the whole answer (when the provider's stream ends, which can come later), so the spend is read once it is
6
- * booked. One booked later than this reads unknown (null), never $0. */
7
- export declare const GRADE_BOOKING_WAIT_MS = 10000;
8
- /** The session the grader's requests are booked under, in the learning run's journal. */
9
- export declare const GRADE_SESSION = "learning.grade";
10
- /** Where the grader's request goes: the route's wire (`api`, Anthropic's Messages or OpenAI's Responses) at `origin`, for
11
- * `model`, priced by `price`. A model on neither wire comes as the route's Messages translation (model-route.ts
12
- * messagesFetch, its `fetch`). */
13
- export interface GraderRoute {
14
- readonly provider: {
15
- readonly api: Wire;
16
- readonly origin: string;
17
- readonly credential: () => string | Promise<string>;
18
- readonly headers?: Readonly<Record<string, string>>;
19
- readonly auth?: "bearer" | "x-api-key";
20
- };
21
- readonly model: string;
22
- /** The catalog's entry for the model (whether it reasons, its window), as pi's session takes it (model-route.ts). */
23
- readonly like?: {
24
- readonly reasoning?: boolean;
25
- readonly contextWindow?: number;
26
- readonly maxTokens?: number;
27
- };
28
- /** A request's price from its usage (the proxy's booking reads it). */
29
- readonly price?: (model: string, usage: {
30
- input: number;
31
- output: number;
32
- cacheRead: number;
33
- cacheWrite: number;
34
- }) => number | null;
35
- /** The upstream fetch (a test's scripted origin). */
36
- readonly fetch?: typeof fetch;
37
- /** The catalog's cost of the model, tiers included, whether serve has a price for it at all, and its output ceiling:
38
- * what a capped grade is judged at before it leaves (model-route.ts ModelRoute; adapter-run-spec.ts capModelOf). */
39
- readonly cost?: RouteCost;
40
- readonly unpriced?: boolean;
41
- readonly outputCeiling?: number | null;
42
- }
43
- export interface BookedAskOptions extends GraderRoute {
44
- /** The learning run's cap: the host's check before each paid request (the kernel cap's beforeRequestOf). */
45
- readonly beforeRequest?: BeforeRequest;
46
- }
47
- export declare function bookedAsk(options: BookedAskOptions): LearningLoopDeps["ask"];
@@ -1,128 +0,0 @@
1
- // The learning run's grader call (learning-loop.ts LearningLoopDeps.ask): a paid model request like a pi turn, on the
2
- // same path. Its session ("learning.grade") lives in the learning run's own journal (journalSessions); the host's check
3
- // before it leaves is the learning run's cap, asked with the run's totals (runBooking, the run's one booking), and a
4
- // request it refuses is never sent (the ask throws GradeOverCap, and the loop skips the grade); its record
5
- // is written and made durable before it leaves, and its cost booked when it answers (modelPortFor); and it reaches the
6
- // provider only through the kernel's model proxy, which admits and books it (startModelProxy with the booking's port).
7
- // What it spent is that booking's, and its tokens the answer's usage: the grade's cost_usd and tokens. Each answer, and
8
- // each refusal, carries the booking's whole spend (`booked`): an earlier attempt's requests are the grade's too.
9
- import { randomBytes } from "node:crypto";
10
- import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
11
- import { createModels } from "@earendil-works/pi-ai/models";
12
- import { createRegistry, Harness } from "@earendil-works/pi-durable";
13
- import { modelPortFor, runBooking } from "@parcha/agentrun-kernel";
14
- import { startModelProxy } from "@parcha/agentrun-kernel/host";
15
- import { sessionProvider } from "../port-models.js";
16
- import { policyFor } from "./adapters/pi.js";
17
- import { GradeOverCap } from "./learning-loop.js";
18
- import { journalSessions } from "./sessions.js";
19
- /** How long the ask waits, once the grade answered, for the proxy to book its request: the proxy books a request after its
20
- * client has the whole answer (when the provider's stream ends, which can come later), so the spend is read once it is
21
- * booked. One booked later than this reads unknown (null), never $0. */
22
- export const GRADE_BOOKING_WAIT_MS = 10_000;
23
- /** The session the grader's requests are booked under, in the learning run's journal. */
24
- export const GRADE_SESSION = "learning.grade";
25
- const PROVIDER = "agentrun-grade";
26
- /** `journal` as its Harness sees it: every method its own, but close, which is the claim's to do, not the ask's. */
27
- function unclosed(journal) {
28
- return new Proxy(journal, {
29
- get(target, key) {
30
- if (key === "close")
31
- return async () => undefined;
32
- const value = Reflect.get(target, key, target);
33
- return typeof value === "function" ? value.bind(target) : value;
34
- },
35
- });
36
- }
37
- export function bookedAsk(options) {
38
- const { model } = options;
39
- return async (request, signal, run) => {
40
- const context = withAbortSignal(signal, BACKGROUND_CONTEXT);
41
- // The claim's journal (a store hands one storage per claim, the loop's too) under a Harness of the ask's own, whose
42
- // close leaves the storage open: the loop goes on writing its entries there after the grade.
43
- const harness = await Harness.open(unclosed(run.journal()), { models: createModels(), registry: createRegistry(), onReport: () => { } }, context);
44
- try {
45
- const sessions = journalSessions(harness, context, { flush: () => run.flush() });
46
- const writer = await sessions.open(GRADE_SESSION);
47
- // The cap is the learning run's: asked with every session of the run summed, never this one's alone.
48
- const hostCheck = options.beforeRequest ? runBooking(sessions, options.beforeRequest) : undefined;
49
- let refused;
50
- // Told once the grade's own request is booked (its request_end), never by a cut request booked before it.
51
- let booked;
52
- const booking = await modelPortFor(writer, {
53
- key: GRADE_SESSION,
54
- label: "grade",
55
- ...(hostCheck ? { beforeRequest: async (asked) => {
56
- const answer = await hostCheck(asked);
57
- if (answer && "refuse" in answer)
58
- refused = answer;
59
- return answer;
60
- } } : {}),
61
- // The rule before a side effect: the request's record is durable before the request leaves.
62
- onEvent: async (event) => {
63
- if (event.type === "request_start")
64
- await run.flush();
65
- if (event.type === "request_end")
66
- booked?.();
67
- },
68
- });
69
- // A grade request an earlier attempt sent and a crash cut is booked first, at its held figure.
70
- await booking.bookCut();
71
- const before = booking.spentUsd();
72
- const bookedOnce = new Promise((resolve) => (booked = () => resolve(true)));
73
- // The policy of the route's wire, as pi's session takes it (pi.ts policyFor: claude-agent's on Messages, codex's on
74
- // Responses, no fork); the grade offers no tool.
75
- const proxy = await startModelProxy({
76
- policy: await policyFor(options.provider, model, []),
77
- hooks: booking.models,
78
- model,
79
- origin: options.provider.origin,
80
- credential: async () => (await options.provider.credential()) ?? "",
81
- ...(options.price ? { price: options.price } : {}),
82
- ...(options.provider.headers ? { headers: options.provider.headers } : {}),
83
- ...(options.fetch ? { fetch: options.fetch } : {}),
84
- }, randomBytes(32).toString("base64url"));
85
- try {
86
- // pi-ai's client of the route's wire at the proxy (port-models.ts sessionProvider), as pi's session reaches its own.
87
- const models = createModels();
88
- models.setProvider(sessionProvider(options.provider.api, proxy, model, { provider: PROVIDER, keyName: "AGENTRUN_GRADE_KEY", like: { ...options.like, maxTokens: request.maxTokens }, reasoning: false }));
89
- const target = models.getModel(PROVIDER, model);
90
- // Refused by the cap before it left: nothing of it was sent or spent, and the grade is not run (GradeOverCap),
91
- // however its client came back.
92
- // What the grade spent before it is its records' (every attempt's requests), never $0 for an earlier attempt's.
93
- const overCap = () => (refused ? new GradeOverCap(refused.refuse, refused.forGood === true, { usd: booking.spentUsd(), turns: booking.turns() }) : undefined);
94
- let answer;
95
- try {
96
- answer = (await models.completeSimple(target, { messages: [{ role: "user", content: request.prompt, timestamp: Date.now() }] }, { signal, maxTokens: request.maxTokens }));
97
- }
98
- catch (error) {
99
- throw overCap() ?? error;
100
- }
101
- const over = overCap();
102
- if (over)
103
- throw over;
104
- if (answer.stopReason === "error" || answer.stopReason === "aborted")
105
- throw new Error(`the grade's request failed: ${answer.errorMessage ?? answer.stopReason}`);
106
- const text = answer.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
107
- // The spend once the proxy booked this request: read before, it is the spend without it ($0 for the grade). Not
108
- // booked within the wait: unknown.
109
- let timer;
110
- const inTime = await Promise.race([bookedOnce, new Promise((resolve) => (timer = setTimeout(() => resolve(false), GRADE_BOOKING_WAIT_MS)))]);
111
- clearTimeout(timer);
112
- const after = inTime ? booking.spentUsd() : null;
113
- const usd = before === null || after === null ? null : after - before;
114
- // pi-ai counts cache reads and writes apart from input, as the grade's tokens do.
115
- const used = answer.usage;
116
- const tokens = used ? { input: used.input, cache_read: used.cacheRead ?? 0, cache_write: used.cacheWrite ?? 0, output: used.output } : null;
117
- // The grade's records after it: every grade request of the learning run, an earlier attempt's included.
118
- return { text, usd, tokens, booked: { usd: after, turns: booking.turns() } };
119
- }
120
- finally {
121
- await proxy.close().catch(() => undefined);
122
- }
123
- }
124
- finally {
125
- await harness.close(context).catch(() => undefined);
126
- }
127
- };
128
- }
@@ -1,45 +0,0 @@
1
- import type { BeforeRequest } from "@parcha/agentrun-kernel";
2
- import { type GraderRoute } from "./learning-ask.js";
3
- import type { LoopFactory } from "./loop-contract.js";
4
- import type { Store } from "../store/store.js";
5
- /** What a grade asks the runner's route for: the grade model the launch names (`model`), the model of the run that
6
- * learned, as its revision names it (`own`: main grades on it when no grade model is named), and the agent. */
7
- export interface GradeRouteAsk {
8
- readonly model?: string;
9
- readonly own?: string;
10
- readonly agentId: string;
11
- }
12
- /** The model a grade runs on, main's order: the grade model the server names, else the agent's own (the model its
13
- * revision names), else none (the host's default, which the route picks). */
14
- export declare const gradeModelFor: (grade: Pick<GradeRouteAsk, "model" | "own">) => string | undefined;
15
- export interface LearningDispatchDeps {
16
- readonly store: Pick<Store, "runs" | "agents" | "learning">;
17
- /** The server's data directory: each agent's learning folder. */
18
- readonly data: string;
19
- readonly sourceInstructions?: (runId: string) => Promise<string>;
20
- /** The runner's one model route (its pi runs take the same): where a grade goes, on which model, at what price; under
21
- * --faux, the faux model's. GraderRoute moves to runner/model-route.ts with the route. */
22
- readonly routeOf: (grade: GradeRouteAsk) => GraderRoute | Promise<GraderRoute>;
23
- readonly log?: (line: string) => void;
24
- readonly now?: () => number;
25
- /** For tests: the grade's bound, as a signal. Default: GRADE_TIMEOUT_MS from the ask. */
26
- readonly gradeBound?: () => AbortSignal;
27
- }
28
- /** The grade's route for `model` (the grade model the server names; undefined, the agent's own), from the runner's one
29
- * route (`routeOf`), but where this host reaches the model's vendor only through OpenRouter (provider.ts
30
- * openRouterOnly: its one key for that wire is OpenRouter's, no gateway), as main's grade reaches it there:
31
- * - an Anthropic model, at OpenRouter's Messages endpoint as a claude-agent run's requests go (providerFor: Anthropic's
32
- * own id on the wire, OpenRouter's key as a bearer token, its one credential), priced at OpenRouter's catalog price of
33
- * the model (its priceModel, through the runner's route);
34
- * - an OpenAI model, the same model on OpenRouter (`openrouter/openai/<id>`, the route's own translation).
35
- * A faux host (FAUX_ENV) and a gateway take the model as named: a faux grade never reaches a real provider, whatever
36
- * key the host inherited. Every other Anthropic model goes by Anthropic's own id (anthropicModelId: OpenRouter's
37
- * dotted name dashed), as its harness's model selection names it (provider.ts modelOn), so the catalog finds it. */
38
- export declare function gradeRouteOf(model: string | undefined, env: NodeJS.ProcessEnv, routeOf: (model: string | undefined) => GraderRoute | Promise<GraderRoute>): Promise<GraderRoute>;
39
- /** The learning run's cap on its grade (`capUsd`), the kernel's one rule over its booking (bookedAsk's runBooking): each
40
- * grader call on `route` judged at its worst case before it leaves, every input token uncached and its whole
41
- * output bound as the least it may be sent with, so a grade never runs on a cut answer. Another model than the route's is
42
- * priced by nothing here: refused. */
43
- export declare function gradeCap(capUsd: number, route: GraderRoute): BeforeRequest;
44
- /** The loop for a launch of harness "learning": the runner's dispatch calls it for each such run it claims. */
45
- export declare function learningLoopOf(deps: LearningDispatchDeps): LoopFactory;