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

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 (346) hide show
  1. package/CHANGELOG.md +131 -5
  2. package/README.md +371 -300
  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 +52 -16
  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-3O2Yl6hZ.js +701 -0
  39. package/dist/console/assets/index-DaFsZuzQ.css +1 -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/key-check.js +3 -0
  64. package/dist/learn/audit.d.ts +6 -6
  65. package/dist/learn/audit.js +3 -7
  66. package/dist/learn/check.d.ts +23 -89
  67. package/dist/learn/check.js +57 -335
  68. package/dist/learn/commit.d.ts +63 -90
  69. package/dist/learn/commit.js +124 -316
  70. package/dist/learn/compile.d.ts +53 -50
  71. package/dist/learn/compile.js +87 -102
  72. package/dist/learn/corrections.d.ts +13 -0
  73. package/dist/learn/corrections.js +23 -0
  74. package/dist/learn/delete.d.ts +5 -5
  75. package/dist/learn/delete.js +8 -10
  76. package/dist/learn/folder.d.ts +35 -47
  77. package/dist/learn/folder.js +118 -134
  78. package/dist/learn/index.d.ts +3 -5
  79. package/dist/learn/index.js +6 -9
  80. package/dist/learn/learning.sh +45 -15
  81. package/dist/learn/promote.d.ts +13 -1
  82. package/dist/learn/promote.js +9 -0
  83. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  84. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  85. package/dist/learn/workflow-nodes.js +1 -1
  86. package/dist/learned-workflow.js +2 -2
  87. package/dist/learning-cost.d.ts +38 -24
  88. package/dist/learning-cost.js +41 -24
  89. package/dist/learning-routes.d.ts +91 -170
  90. package/dist/learning-routes.js +183 -421
  91. package/dist/learning-run.d.ts +19 -40
  92. package/dist/learning-run.js +23 -93
  93. package/dist/learning-setting.d.ts +4 -4
  94. package/dist/learning-setting.js +6 -6
  95. package/dist/learning-words.d.ts +28 -74
  96. package/dist/learning-words.js +64 -162
  97. package/dist/learning.d.ts +61 -392
  98. package/dist/learning.js +101 -651
  99. package/dist/live-reach.d.ts +25 -2
  100. package/dist/live-reach.js +46 -4
  101. package/dist/llms.txt +1 -1
  102. package/dist/local-models.d.ts +3 -11
  103. package/dist/local-models.js +5 -6
  104. package/dist/mcp-servers-store.d.ts +4 -4
  105. package/dist/model-form.js +6 -5
  106. package/dist/model.d.ts +4 -0
  107. package/dist/model.js +26 -9
  108. package/dist/native/binding.js +1 -1
  109. package/dist/native/connection.js +1 -1
  110. package/dist/native/discovery.js +1 -1
  111. package/dist/native/instructions.d.ts +3 -0
  112. package/dist/native/instructions.js +5 -3
  113. package/dist/native/remote-worker-bridge.js +9 -43
  114. package/dist/native/remote.d.ts +8 -15
  115. package/dist/native/remote.js +3 -3
  116. package/dist/native/schema.js +1 -1
  117. package/dist/native/types.d.ts +2 -2
  118. package/dist/openapi.js +268 -316
  119. package/dist/paid-calls.d.ts +8 -0
  120. package/dist/paid-calls.js +20 -0
  121. package/dist/particle-provider.d.ts +11 -0
  122. package/dist/particle-provider.js +135 -0
  123. package/dist/port-models.d.ts +12 -4
  124. package/dist/port-models.js +28 -11
  125. package/dist/print.d.ts +27 -0
  126. package/dist/print.js +21 -0
  127. package/dist/provider.d.ts +7 -0
  128. package/dist/provider.js +15 -1
  129. package/dist/reflect-range.js +2 -3
  130. package/dist/run-launch.d.ts +14 -28
  131. package/dist/run-launch.js +9 -12
  132. package/dist/run-learning-served.d.ts +15 -89
  133. package/dist/run-listing.d.ts +34 -0
  134. package/dist/run-listing.js +128 -0
  135. package/dist/run-model-key.js +1 -1
  136. package/dist/run-timeline-served.js +5 -3
  137. package/dist/run-trace.d.ts +97 -0
  138. package/dist/run-trace.js +253 -0
  139. package/dist/run-view.d.ts +15 -0
  140. package/dist/run-view.js +9 -0
  141. package/dist/runnable.js +2 -1
  142. package/dist/runner/adapter-loop.d.ts +8 -6
  143. package/dist/runner/adapter-loop.js +16 -12
  144. package/dist/runner/adapter-run-spec.d.ts +16 -4
  145. package/dist/runner/adapter-run-spec.js +64 -58
  146. package/dist/runner/adapters/index.js +22 -0
  147. package/dist/runner/adapters/pi.d.ts +4 -12
  148. package/dist/runner/adapters/pi.js +2 -2
  149. package/dist/runner/audit.d.ts +1 -1
  150. package/dist/runner/audit.js +16 -8
  151. package/dist/runner/beside.d.ts +6 -2
  152. package/dist/runner/beside.js +38 -9
  153. package/dist/runner/claim-secrets.d.ts +18 -2
  154. package/dist/runner/claim-secrets.js +42 -18
  155. package/dist/runner/cli-run-spec.js +55 -51
  156. package/dist/runner/conformance/harness.d.ts +6 -0
  157. package/dist/runner/conformance/harness.js +16 -5
  158. package/dist/runner/dispatch.d.ts +2 -2
  159. package/dist/runner/end-of-run.d.ts +6 -14
  160. package/dist/runner/end-of-run.js +8 -33
  161. package/dist/runner/feedback-round.d.ts +2 -2
  162. package/dist/runner/feedback-round.js +7 -7
  163. package/dist/runner/github-app.js +3 -1
  164. package/dist/runner/harness-loops.d.ts +0 -8
  165. package/dist/runner/harness-loops.js +11 -59
  166. package/dist/runner/held.d.ts +170 -0
  167. package/dist/runner/held.js +57 -0
  168. package/dist/runner/journal-kinds.d.ts +2 -3
  169. package/dist/runner/journal-kinds.js +2 -3
  170. package/dist/runner/learned-first.d.ts +40 -0
  171. package/dist/runner/learned-first.js +32 -0
  172. package/dist/runner/learning-end.d.ts +77 -69
  173. package/dist/runner/learning-end.js +250 -303
  174. package/dist/runner/learning-seed.d.ts +15 -33
  175. package/dist/runner/learning-seed.js +24 -45
  176. package/dist/runner/loop-contract.d.ts +2 -3
  177. package/dist/runner/main.d.ts +17 -9
  178. package/dist/runner/main.js +63 -20
  179. package/dist/runner/mcp-run.d.ts +11 -0
  180. package/dist/runner/mcp-run.js +67 -0
  181. package/dist/runner/memory-claim.d.ts +10 -5
  182. package/dist/runner/memory-claim.js +12 -6
  183. package/dist/runner/model-route.d.ts +7 -4
  184. package/dist/runner/model-route.js +22 -10
  185. package/dist/runner/native-loop.d.ts +0 -7
  186. package/dist/runner/native-loop.js +9 -101
  187. package/dist/runner/promotion.d.ts +8 -6
  188. package/dist/runner/promotion.js +19 -12
  189. package/dist/runner/reflect-hook.d.ts +64 -95
  190. package/dist/runner/reflect-hook.js +112 -225
  191. package/dist/runner/run-channel.d.ts +43 -0
  192. package/dist/runner/run-channel.js +467 -0
  193. package/dist/runner/run-child-host.d.ts +169 -0
  194. package/dist/runner/run-child-host.js +1222 -0
  195. package/dist/runner/run-child.d.ts +1 -0
  196. package/dist/runner/run-child.js +254 -0
  197. package/dist/runner/run-errors.d.ts +2 -0
  198. package/dist/runner/run-errors.js +20 -0
  199. package/dist/runner/runner.js +1 -5
  200. package/dist/runner/sdk-ask.d.ts +78 -0
  201. package/dist/runner/sdk-ask.js +158 -0
  202. package/dist/runner/sdk-loop.d.ts +2 -4
  203. package/dist/runner/sdk-loop.js +29 -49
  204. package/dist/runner/store-secrets.d.ts +5 -3
  205. package/dist/runner/store-secrets.js +5 -1
  206. package/dist/runner/workflow-first.d.ts +5 -0
  207. package/dist/runner/workflow-first.js +4 -0
  208. package/dist/runner/workflow-spec.js +7 -2
  209. package/dist/runs-over-store.d.ts +16 -28
  210. package/dist/runs-over-store.js +31 -38
  211. package/dist/sdk/runs.d.ts +6 -11
  212. package/dist/sdk/runs.js +20 -41
  213. package/dist/sdk/schema.js +3 -4
  214. package/dist/seal-key.d.ts +5 -0
  215. package/dist/seal-key.js +7 -0
  216. package/dist/secrets.d.ts +3 -0
  217. package/dist/secrets.js +16 -3
  218. package/dist/server.d.ts +55 -33
  219. package/dist/server.js +685 -320
  220. package/dist/sign-ins-store.d.ts +8 -0
  221. package/dist/sign-ins-store.js +36 -1
  222. package/dist/skills.js +1 -1
  223. package/dist/store/index.d.ts +2 -2
  224. package/dist/store/index.js +1 -1
  225. package/dist/store/journal/storage.js +3 -0
  226. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  227. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  228. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  229. package/dist/store/schema.d.ts +53 -4
  230. package/dist/store/schema.js +137 -6
  231. package/dist/store/sqlite/connection.d.ts +2 -0
  232. package/dist/store/sqlite/connection.js +3 -1
  233. package/dist/store/sqlite/run-patch.d.ts +0 -17
  234. package/dist/store/sqlite/run-patch.js +4 -33
  235. package/dist/store/sqlite/store.js +246 -63
  236. package/dist/store/sqlite/worker.js +25 -0
  237. package/dist/store/store.d.ts +193 -36
  238. package/dist/store/store.js +25 -3
  239. package/dist/store-reads/learning.d.ts +102 -204
  240. package/dist/store-reads/learning.js +159 -321
  241. package/dist/store-reads/loop.d.ts +0 -1
  242. package/dist/store-reads/loop.js +1 -1
  243. package/dist/store-view.d.ts +29 -1
  244. package/dist/store-view.js +97 -31
  245. package/dist/template-eval.d.ts +3 -6
  246. package/dist/template-eval.js +22 -36
  247. package/dist/templates.d.ts +2 -1
  248. package/dist/templates.js +6 -3
  249. package/dist/timeline/index.d.ts +1 -1
  250. package/dist/timeline/index.js +1 -1
  251. package/dist/timeline/timeline.d.ts +5 -1
  252. package/dist/timeline/timeline.js +16 -0
  253. package/dist/tool-gate.d.ts +0 -7
  254. package/dist/tool-gate.js +1 -15
  255. package/dist/tool-keys-store.d.ts +1 -1
  256. package/dist/tool-keys.d.ts +6 -4
  257. package/dist/tool-keys.js +12 -6
  258. package/dist/tools.d.ts +2 -2
  259. package/dist/tools.js +11 -4
  260. package/dist/triggers.d.ts +60 -5
  261. package/dist/triggers.js +123 -18
  262. package/dist/validate.js +1 -1
  263. package/dist/webhooks.d.ts +4 -1
  264. package/dist/webhooks.js +11 -4
  265. package/dist/workspace/agent-computer.d.ts +2 -0
  266. package/dist/workspace/agent-computer.js +2 -0
  267. package/dist/workspace/archil-claim.d.ts +7 -0
  268. package/dist/workspace/archil-claim.js +29 -0
  269. package/dist/workspace/archil.d.ts +9 -1
  270. package/dist/workspace/archil.js +165 -3
  271. package/dist/workspace/attach.d.ts +3 -1
  272. package/dist/workspace/attach.js +2 -0
  273. package/dist/workspace/attached-computers.d.ts +16 -5
  274. package/dist/workspace/attached-computers.js +25 -9
  275. package/dist/workspace/computer-deps.js +1 -1
  276. package/dist/workspace/computer-for-claim.d.ts +7 -3
  277. package/dist/workspace/computer-for-claim.js +119 -22
  278. package/dist/workspace/computer-hold.js +2 -1
  279. package/dist/workspace/computer-kept.d.ts +11 -1
  280. package/dist/workspace/computer-kept.js +24 -3
  281. package/dist/workspace/resolve-computer.d.ts +33 -19
  282. package/dist/workspace/resolve-computer.js +172 -64
  283. package/dist/workspace/revision-skills.d.ts +1 -2
  284. package/dist/workspace/revision-skills.js +3 -4
  285. package/dist/workspace/run-workspace.d.ts +1 -1
  286. package/dist/workspace/run-workspace.js +5 -0
  287. package/dist/workspace/synced-folder.d.ts +85 -0
  288. package/dist/workspace/synced-folder.js +230 -0
  289. package/dist/workspace/workspace.d.ts +4 -0
  290. package/launcher/agentrun-serve +1 -1
  291. package/package.json +10 -10
  292. package/templates/README.md +7 -7
  293. package/templates/inbound-lead/agent.md +3 -3
  294. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  295. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  296. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  297. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  298. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  299. package/templates/inbound-lead/lead.schema.json +6 -5
  300. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  301. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  302. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  303. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  304. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  305. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  306. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  307. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  308. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  309. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  310. package/dist/console/assets/index-BUktRvS-.css +0 -1
  311. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  312. package/dist/learn/grade.d.ts +0 -138
  313. package/dist/learn/grade.js +0 -682
  314. package/dist/learn/notes.d.ts +0 -81
  315. package/dist/learn/notes.js +0 -178
  316. package/dist/learn/reflect.d.ts +0 -77
  317. package/dist/learn/reflect.js +0 -228
  318. package/dist/learn/relevance.d.ts +0 -24
  319. package/dist/learn/relevance.js +0 -91
  320. package/dist/learn/seed-check.d.ts +0 -74
  321. package/dist/learn/seed-check.js +0 -103
  322. package/dist/learning-batch.d.ts +0 -291
  323. package/dist/learning-batch.js +0 -600
  324. package/dist/learning-evals.d.ts +0 -35
  325. package/dist/learning-evals.js +0 -99
  326. package/dist/native/context.d.ts +0 -6
  327. package/dist/native/context.js +0 -22
  328. package/dist/propose.d.ts +0 -52
  329. package/dist/propose.js +0 -224
  330. package/dist/runner/learning-ask.d.ts +0 -47
  331. package/dist/runner/learning-ask.js +0 -128
  332. package/dist/runner/learning-dispatch.d.ts +0 -45
  333. package/dist/runner/learning-dispatch.js +0 -99
  334. package/dist/runner/learning-factory.d.ts +0 -16
  335. package/dist/runner/learning-factory.js +0 -50
  336. package/dist/runner/learning-loop.d.ts +0 -273
  337. package/dist/runner/learning-loop.js +0 -521
  338. package/dist/usage.d.ts +0 -11
  339. package/dist/usage.js +0 -11
  340. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  341. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  342. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  343. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  344. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  345. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  346. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -2,65 +2,54 @@
2
2
  // run's store, driven by the learning start its launch records (run-launch.ts learningStartOf), which the server decided
3
3
  // once at the run's start. A spec builder gives the adapter loop `endOfRun: learningEndOfRun(launch, deps)`. Each of the
4
4
  // hook's reads is the server's own rule, over the store in place of the run's directory:
5
- // - whether it looks back (learning-run.ts reflectSkip): its cap and its spend so far, read as its view reads them;
6
- // - its prompt's facts: how many notes its seed held (launch seedNotes);
7
- // - the compile turn's facts (compileAskOf, learn/compile.ts): whether the job is due to be compiled (its notes, its
8
- // completed runs, no learned workflow yet), or a workflow its promotion holds wants a revision (once per hold); its
9
- // notes whole, its last runs' traces, the tools a workflow may name (draftTools) and the DSL's own language for
10
- // writing one;
11
- // - whether it looks back at all (ownerSaid): a run of a job that compiles workflows is asked its look-back only when
12
- // its owner gave feedback (a grade's words, or a message after its first); its compile turn, when due, is asked alone;
13
- // - what the person said in the run and a trigger's input (heard.ts Hearing over its entries, the end-of-run turn's
14
- // own left out), as learning-run.ts turnOf reads them;
15
- // - whether the job gave nothing new to look back on (onlyLearnedWorkflows over its timeline): a run whose only tool
16
- // work was its learned workflows, each answering, is not asked;
17
- // - the checks: propose.ts proposeRun against the seed it started from, the server's one rule, which keeps the
18
- // proposal the hook stores beside the run's end (learning_proposals);
19
- // - what the run must never learn (learning-run.ts refused, the server's serverSecrets as far as the runner reads
20
- // them): every secret the server keeps sealed (store-secrets.ts storeSecrets: the store's planes, and the API token,
21
- // session secret and outbound webhook secret beside it), the runner's secrets, the keys its claim handed it, and
22
- // the sign-in pointers its row says it was handed, read back from the store (handed-values.ts handedValuesOf). A run
23
- // whose pointers can't be read back learns nothing (the hook drops it, saying why), never over a shorter list. A
24
- // runner's run has no door token: its loop runs in the runner's process.
25
- // A proposal queues the learning run (learning_run), which the runner's dispatch runs on the learning loop
26
- // (harness-loops.ts: harness "learning"), to grade and merge it. A run whose seed could not be read keeps that drop.
5
+ // - its cap and its spend so far, read as its gates read them;
6
+ // - its owner's words (ownerWords): a grade's, and each message they sent after the job's first, one line of
7
+ // corrections.md, checked against main first (learn/commit.ts correctionRefused);
8
+ // - the compile turn's facts (compileAskOf, learn/compile.ts): whether the job is due to be compiled (its completed
9
+ // runs, no learned workflow yet), or a workflow its promotion holds wants a revision (once per hold); its last runs'
10
+ // traces, the tools a workflow may name (draftTools) and the DSL's own language for writing one;
11
+ // - whether the job gave nothing new (onlyLearnedWorkflows over its timeline): a run whose only tool work was its
12
+ // learned workflows, each answering;
13
+ // - each compile draft's checks (checkDraftOf): the workflow checks, its dry run, the secret and hidden-character
14
+ // refusals, against the commit the run started from (a revision's against the commit its text was read at);
15
+ // - the round's one merge (commitDirect): a passing draft and the owner's line, committed by the run;
16
+ // - what the run must never learn (the server's serverSecrets as far as the runner reads them): every secret the server
17
+ // keeps sealed (store-secrets.ts storeSecrets), the runner's secrets, the keys its claim handed it, and the sign-in
18
+ // pointers its row says it was handed, read back from the store (handed-values.ts handedValuesOf). A run whose
19
+ // pointers can't be read back learns nothing (the hook drops it, saying why), never over a shorter list.
20
+ // A run whose seed could not be read keeps that drop.
27
21
  import { createHash } from "node:crypto";
28
- import { mkdtemp, readFile, rm } from "node:fs/promises";
29
- import { tmpdir } from "node:os";
30
- import { join } from "node:path";
31
22
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
32
23
  import { isMessageRow } from "../timeline/index.js";
33
- import { Hearing } from "../heard.js";
34
- import { learningCommit } from "../learn/commit.js";
35
- import { readLearning, readSnapshot } from "../learn/folder.js";
24
+ import { correctionRefused, learningCommit } from "../learn/commit.js";
25
+ import { checkDraft, problemWords, unstorable } from "../learn/index.js";
26
+ import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
36
27
  import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
37
28
  import { loopOf } from "../learning-setting.js";
38
29
  import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
39
- import { draftDecisionProviders } from "../learn/skills.js";
30
+ import { draftDecisionProviders, draftDryRun, draftFiles, draftMcpTools, unpricedCalls, WORKFLOWS_DIR } from "../learn/workflow-draft.js";
40
31
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
41
32
  import { handedValuesOf } from "../handed-values.js";
42
33
  import { excerptShown, MIN_SECRET, redactSecrets } from "../learn/secrets.js";
43
34
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
44
35
  import { META_TOOLS } from "../meta-tool-names.js";
45
- import { holdsSecret, LEARNING_LABEL, PROPOSAL, secretsShown } from "../learning.js";
46
- import { reflects } from "../reflect-range.js";
36
+ import { holdsSecret, LEARNING_LABEL, secretsShown } from "../learning.js";
47
37
  import { said, STOPPED } from "../learning-words.js";
48
- import { proposeRun } from "../propose.js";
49
38
  import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
50
- import { costOf } from "../run-view.js";
51
39
  import { FINAL_STATES } from "../store/store.js";
52
40
  import { shadowRunId } from "../learn/audit.js";
53
41
  import { getMcpServer } from "../mcp-store.js";
54
42
  import { readApprovers } from "../server-approvers.js";
55
- import { runEntries, runReflect, runTimeline, withFeedback, withoutFeedbackRounds } from "../store-reads/journal.js";
56
- import { capNowOf } from "./journal-kinds.js";
57
- import { bookedCapSpend, bookedSpend } from "./metrics.js";
43
+ import { isCliRecord, runEntries, runTimeline, withoutFeedbackRounds } from "../store-reads/journal.js";
44
+ import { capNowOf, KINDS } from "./journal-kinds.js";
45
+ import { bookedCapSpend, cliModelWorked, runCostOf } from "./metrics.js";
58
46
  import { fits, workflowDigest } from "./workflow-first.js";
59
47
  import { pendingFeedbackOf } from "./feedback-round.js";
60
48
  import { createReflectHook } from "./reflect-hook.js";
61
49
  import { sdkDraftTools } from "../sdk/workflows.js";
62
50
  import { runnerSecrets } from "./redact.js";
63
51
  import { mcpNameOf } from "../tool-names.js";
52
+ import { held, heldEndOfRun } from "./held.js";
64
53
  /** The end-of-run step for a run launched with `launch`: undefined when its launch records no learning start (a run that
65
54
  * does not learn is asked nothing and keeps nothing), else the reflect hook over the run's store. */
66
55
  export function learningEndOfRun(launch, deps) {
@@ -68,71 +57,53 @@ export function learningEndOfRun(launch, deps) {
68
57
  // A run that only uses what its agent learned (`learning: "use"`) is asked nothing and keeps nothing, at every end.
69
58
  if (!start || start.use)
70
59
  return undefined;
60
+ // In a run's own process the step is its runner's (held.ts): what the run must never learn is every secret the runner
61
+ // holds, and a run's process is given none but its own keys.
62
+ if (held())
63
+ return heldEndOfRun();
71
64
  const env = deps.env ?? process.env;
72
- // The grade model the server named at the run's start (its learning start's), none: the agent's own grades it.
73
- const gradeModel = start.gradeModel;
74
- // The learning run's grade runs after the run's turn ended: never on a run's own key (erased with that end), and never
75
- // on none.
76
- const gradeOff = deps.spendOff ? () => deps.spendOff?.("The learning run's grade") : undefined;
77
- const hookFor = (runId, round, before) => createReflectHook({
65
+ const hookFor = (seed, round) => createReflectHook({
78
66
  round,
79
- ...(gradeOff ? { gradeOff } : {}),
80
- ...(before ? { before } : {}),
81
- // reflectSkip's facts: a run its cap stopped has no room left, and one whose spend is unknown under a cap cannot be
82
- // kept within it. The cap is the run's now (capNowOf: its newest raise's, else its launch's), the one its requests
83
- // were admitted under, never the launch's alone. A person's stop comes to the hook as its `cut`.
84
- // Its spend under that cap is what the run's own gates read (capSpendOf: a request with no price of its own at the
85
- // figure it was held at), never the cost a person is shown, which is unknown once one request's is. What its earlier
86
- // rounds' grades and its audit's shadow took beside it counts toward that cap as its own spend does (besideOf, the
87
- // figure its gates read). Either unknown: the spend is unknown, said so, never read as the whole cap.
67
+ // A run its cap stopped has no room left, and one whose spend is unknown under a cap cannot be kept within it. The cap
68
+ // is the run's now (capNowOf: its newest raise's, else its launch's), the one its requests were admitted under. Its
69
+ // spend under that cap is what the run's own gates read (capSpendOf: a request with no price of its own at the figure
70
+ // it was held at, and what an earlier end's audit shadow took beside it), never the cost a person is shown, which is
71
+ // unknown once one request's is. Either unknown: the spend is unknown, never read as the whole cap. A person's stop
72
+ // comes to the hook as its `cut`.
88
73
  facts: async (runId) => {
89
- const [rows, entries] = await Promise.all([
90
- runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false }),
91
- runEntries(deps.store, runId, BACKGROUND_CONTEXT),
92
- ]);
93
- // A pi retry's Timeline carries the answered requests alone. Its earlier cut request is still an unknown charge
94
- // in the booking: keep it unknown in the task snapshot too, as the run's end does, never just the retry's subtotal.
95
- // A request a crash cut booked at its hold (`bounded`) is an upper bound, not a spend: the job's and look-back's
96
- // figures say no "at most", so they stay unknown, as the run's stored cost reads once it ends (RunRow.costUsd null,
97
- // the bound apart in costAtMostUsd). This reads the booking before the run's row has a cost, hence its own check.
98
- const unknown = ["model", "paid", "decisions"].some((kind) => {
99
- const spend = bookedSpend(entries, kind);
100
- return spend.usd === null || spend.bounded > 0;
101
- });
102
- const costUsd = unknown ? null : costOf(rows);
74
+ const entries = await runEntries(deps.store, runId, BACKGROUND_CONTEXT);
75
+ // The run's spend so far by the one rule its end stores its cost by (metrics.ts runCostOf, as the store view reads
76
+ // an ended run's): its booking, so the job's cost kept here is the figure the end stores when no turn follows it, and
77
+ // what a turn after it spent is that figure less the job's. Never the Timeline's usage row: it reads pi's answers,
78
+ // and pi answers a compaction's summary with no answer of its own (its cost rides on the next answer), so each one
79
+ // read there as a request cut with no answer, unknown. A cut request still unknown in the booking (a pi retry's
80
+ // earlier one) keeps it unknown; one a crash cut booked at its hold is an upper bound, not a spend: the job's and the
81
+ // compile's figures say no "at most", so they stay unknown, as the run's stored cost reads once it ends.
82
+ const booked = runCostOf(entries, { unbooked: isCliRecord(entries) && cliModelWorked(entries) });
83
+ const costUsd = booked.atMost > 0 ? null : booked.usd;
103
84
  if (launch.maxCostUsd === undefined)
104
85
  return { learns: true, costUsd };
105
86
  const capUsd = capNowOf(launch.maxCostUsd, entries);
106
87
  const spentUsd = await capSpendOf(deps.store, runId, entries);
107
88
  return { learns: true, costUsd, capUsd, spentUsd, capReached: spentUsd !== null && spentUsd >= capUsd };
108
89
  },
109
- // A grade's feedback round always has something new, the grade's words (feedback-round.ts: heard, never "nothing
110
- // new"), whatever the job did: said here, never left to the words' row counting as a message of the job's.
90
+ // A grade's feedback round always has something new, the grade's words (feedback-round.ts), whatever the job did.
111
91
  nothingNew: async (runId) => !pendingFeedbackOf(await runEntries(deps.store, runId, BACKGROUND_CONTEXT)) && onlyLearnedWorkflows(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })),
112
- promptFacts: async () => ({ active: start.seedNotes ?? start.given.length }),
113
- // A notes run (`learning: "notes"`) compiles nothing, and looks back on every run. A run of a job that compiles
114
- // workflows looks back only on its owner's feedback (ownerSaid).
115
- ...(start.notesOnly ? {} : {
116
- compileFacts: (input) => compileAskOf(deps, { ...input, input: launch.input, seedWorkflows: start.workflows?.length ?? 0 }),
92
+ feedback: async (runId) => {
93
+ const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
94
+ return ownerWords(entries, rows);
95
+ },
96
+ // A round whose merge is on main already (a stop after its commit, before its end was saved) is not checked for room
97
+ // again: its merge gives back what it did.
98
+ correctionRefused: ({ runId, agentId, round: at, text, refuse }) => withFolder(deps, agentId, (folder) => correctionRefused(folder.workspace, text, refuse, { runId, round: at })),
99
+ // A run with no workflow binding (an SDK run's `noWorkflows`) compiles nothing.
100
+ ...(start.noWorkflows ? {} : {
101
+ compileFacts: (input) => compileAskOf(deps, { ...input, input: launch.input, seedWorkflows: start.workflows?.length ?? 0, corrections: start.section }),
117
102
  compileFailed: (input) => recordDraftFailed(deps, input),
118
- ownerSaid: async (runId) => {
119
- const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
120
- return ownerSaid(entries, rows);
121
- },
122
103
  }),
123
- asked: async (runId) => {
124
- const [entries, reflect] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runReflect(deps.store, runId, BACKGROUND_CONTEXT)]);
125
- const hearing = new Hearing();
126
- // A grade's feedback round's words (feedback-round.ts) are heard as the reviewer's, as its Timeline shows them.
127
- for (const entry of withFeedback(entries))
128
- hearing.note(entry);
129
- const heard = [...hearing.heard].filter(([id]) => !reflects(reflect, id)).sort(([a], [b]) => a - b).map(([, one]) => one);
130
- const triggered = heard.flatMap(({ text, source }) => (source === undefined ? [] : [{ source, text }]));
131
- return { asked: heard.filter((one) => one.source === undefined).map(({ text }) => text), ...(triggered.length ? { triggered } : {}) };
132
- },
133
- // learning-run.ts refused(run): the runner's secrets, what the claim handed the run, every secret the server keeps
134
- // sealed, and the sign-in pointers it was handed (each at least MIN_SECRET long, as every cut takes them);
135
- // `unreadable` when those can't be read back, or the server's secrets can't be read (never a check over a shorter list).
104
+ // The run's secrets, what the claim handed it, every secret the server keeps sealed, and the sign-in pointers it was
105
+ // handed (each at least MIN_SECRET long, as every cut takes them); `unreadable` when those can't be read back, or the
106
+ // server's secrets can't be read (never a check over a shorter list).
136
107
  refuse: async (runId) => {
137
108
  const pointers = await handedValuesOf(deps, deps.store, runId);
138
109
  if (pointers === "unreadable")
@@ -146,29 +117,24 @@ export function learningEndOfRun(launch, deps) {
146
117
  }
147
118
  return runnerSecrets(env, [...(deps.handed ?? []), ...stored, ...pointers.refs.filter((ref) => ref.length >= MIN_SECRET)]);
148
119
  },
149
- check: async ({ runId, agentId, turn, outcome, refuse, revised }) => {
150
- if (start.seed === null)
151
- throw new Error("the run's learning start names no commit of main to propose against");
152
- // A later round checks against the main the earlier rounds merged into, not the seed the run started from: a note
153
- // round 1 added and a reviewer corrected is a supersedes target round 2 may name.
154
- // The skills and workflows keep the seed the run was laid from as their conflict base (the merge refuses a file main
155
- // changed since), so only the notes are checked against that main; but a workflow the compile turn revised from
156
- // main's text (`revised`, in the compile turn's checks) has the commit its first ask read it at as its base (kept with
157
- // that ask, so a restart that replays its answer never reads main again), so a change to it before that read is what
158
- // the revision was written over, and only one after it is a conflict.
159
- const notesSeed = round > 1 ? await mainOf(deps, agentId) : undefined;
160
- return checkedOf(deps, { runId, agentId, seed: start.seed, ...(notesSeed ? { notesSeed } : {}), ...(revised ? { revised } : {}), turn, outcome, refuse, ...(start.notesOnly ? { workflows: false } : {}) });
120
+ // A draft is checked against the seed the run was laid from (its conflict base: the merge refuses a file main changed
121
+ // since); a workflow the compile turn revised from main's text (`revised`) against the commit its first ask read it
122
+ // at (kept with that ask, so a restart that replays its answer never reads main again).
123
+ checkDraft: ({ runId, agentId, draft, refuse, revised }) => checkDraftOf(deps, { runId, agentId, seed, draft, refuse, ...(revised ? { revised } : {}) }),
124
+ commit: async ({ runId, agentId, round: at, draft, correction, refuse }) => {
125
+ const reason = draft ? `Compiled the job as workflow ${draft.name}${correction !== undefined ? ", with its owner's correction" : ""}.` : "Its owner's correction.";
126
+ const done = await commitDirect({ folder: () => deps.learningFolder(agentId), log: deps.log ?? (() => undefined) }, {
127
+ runId, round: at, reason, seed, files: draft ? draft.files.map((file) => ({ ...file })) : [],
128
+ ...(draft?.held?.length ? { held: [...draft.held] } : {}), ...(draft?.bases ? { bases: draft.bases } : {}),
129
+ ...(correction !== undefined ? { correction, refuseValues: refuse } : {}),
130
+ });
131
+ return committedOf(done);
161
132
  },
162
- // The learning run's id, one per round of the run: a replayed end queues the same one (the store adds it once).
163
- newRunId: () => learningRunIdOf(runId, round),
164
- // The cap its grade runs under (none for an uncapped run): what the run's cap leaves now.
165
- ...(launch.maxCostUsd !== undefined ? { gradeCap: (runId) => gradeCapOf(deps.store, runId, round, launch.maxCostUsd) } : {}),
166
- ...(gradeModel ? { gradeModel } : {}),
167
133
  });
168
134
  return async (input) => {
169
- // No seed, no end-of-run turn (seedFailed): a run that started from no commit of main has nothing to propose against,
170
- // so it is never asked to look back (no model request). Why, as its start recorded it: a folder that could not be
171
- // read, or a start that could not be made from it; a start that records none names no reason.
135
+ // No seed, no end-of-run step (seedFailed): a run that started from no commit of main has nothing to commit over.
136
+ // Why, as its start recorded it: a folder that could not be read, or a start that could not be made from it; a
137
+ // start that records none names no reason.
172
138
  if (seedFailed(start)) {
173
139
  const failed = start.seedFailed;
174
140
  const why = failed === "unreadable" ? STOPPED.unreadable : failed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
@@ -178,31 +144,21 @@ export function learningEndOfRun(launch, deps) {
178
144
  // Which end of the run this is: the round after the newest it kept (a follow-up opened the run again after it), else
179
145
  // its first. A replayed end reads the same round: its rows are written only with the end that closes it.
180
146
  const prior = await deps.store.learning.proposal(input.runId);
181
- const round = prior ? prior.round + 1 : 1;
182
- const kept = prior?.proposal;
183
- const spent = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
184
- const before = prior ? { job_cost_usd: spent(kept?.job_cost_usd), look_back_usd: spent(kept?.look_back_usd), looked: prior.turn !== null } : undefined;
185
- return hookFor(input.runId, round, before)(input);
147
+ return hookFor(start.seed, prior ? prior.round + 1 : 1)(input);
186
148
  };
187
149
  }
188
150
  /** What every cap gate of run `runId` reads as spent beside it on its behalf (adapter-loop.ts RunCapConfig.beside): its
189
- * learning runs' grades and its audit's shadow run (besideOf), for a capped run with a learning start, the only run
190
- * whose ends queue them (one that only uses what its agent learned queues no grade, but may start a shadow); none for any
191
- * other, whose gates read only its own sessions. */
151
+ * audit's shadow run (shadowBesideOf), for a capped run with a learning start, the only run whose end may start one;
152
+ * none for any other, whose gates read only its own sessions. */
192
153
  export function spentBesideOf(launch, store, runId) {
193
154
  if (launch.maxCostUsd === undefined || !learningStartOf(launch))
194
155
  return undefined;
195
- return () => besideOf(store, runId);
196
- }
197
- /** What was spent beside run `runId` on its behalf, the one figure its cap gates and its grades' caps read: its learning
198
- * runs' grades (Store.learning.spentBeside; `beforeRound`: its earlier rounds' alone) and its audit's shadow run
199
- * (runner/audit.ts, started at its end with what its cap left): the shadow at its cost once it ended, at its own cap while
200
- * it has not (the most it may take) or when it ended at a cost not known, 0 when none was started. Null: unknown. */
201
- export async function besideOf(store, runId, options = {}) {
202
- const [grades, shadow] = await Promise.all([store.learning.spentBeside(runId, options), shadowBesideOf(store, runId)]);
203
- return grades === null || shadow === null ? null : grades + shadow;
156
+ return () => shadowBesideOf(store, runId);
204
157
  }
205
- async function shadowBesideOf(store, runId) {
158
+ /** What run `runId`'s audit's shadow run took beside it (runner/audit.ts, started at its end with what its cap left): at
159
+ * its cost once it ended, at its own cap while it has not (the most it may take) or when it ended at a cost not known,
160
+ * 0 when none was started. Null: unknown. */
161
+ export async function shadowBesideOf(store, runId) {
206
162
  const id = shadowRunId(runId);
207
163
  const shadow = await store.runs.get(id);
208
164
  if (!shadow)
@@ -215,17 +171,15 @@ async function shadowBesideOf(store, runId) {
215
171
  }
216
172
  /** What run `runId`'s cap leaves its audit's shadow run at its end (runner/audit.ts startAudit): the cap it is held to now
217
173
  * (capNowOf: its newest raise's, else `launchCapUsd`), less what it spent under it (capSpendOf over `entries`, its
218
- * journal: its job, its look-back, every grade an earlier round queued) and the cap of the grade this end queues
219
- * (`queued`, the end's rows: it is not in the store until the end commits). Null when that spend is unknown. */
220
- export async function auditRoomOf(store, runId, launchCapUsd, entries, queued) {
174
+ * journal: its job, its follow-ups, its compile turns). Null when that spend is unknown. */
175
+ export async function auditRoomOf(store, runId, launchCapUsd, entries) {
221
176
  const capUsd = capNowOf(launchCapUsd, entries);
222
177
  const spent = await capSpendOf(store, runId, entries);
223
- const grade = queued.find((row) => row.table === "learning_run")?.row.capUsd ?? 0;
224
- return spent === null ? null : capUsd - spent - grade;
178
+ return spent === null ? null : capUsd - spent;
225
179
  }
226
180
  /** What capped run `runId` has spent under its cap, as every gate of the run reads it: its sessions' booking as the kernel
227
- * cap counts it (metrics.ts bookedCapSpend over `entries`, its journal) and what was spent beside it on its behalf
228
- * (besideOf: its grades, `beforeRound` its earlier rounds' alone, and its audit's shadow). Null when either is unknown.
181
+ * cap counts it (metrics.ts bookedCapSpend over `entries`, its journal) and what its audit's shadow took beside it
182
+ * (shadowBesideOf). Null when either is unknown.
229
183
  *
230
184
  * The rule for a cost no one knows (a request answered with no price of its own, one cut short or lost): under a cap it
231
185
  * counts at the figure the cap held it at when it was admitted (its worst case at the model's price, and a lost one's
@@ -234,49 +188,57 @@ export async function auditRoomOf(store, runId, launchCapUsd, entries, queued) {
234
188
  * unknown (a held figure is the cap's, never a charge). Only a request held at no figure (none is, under a cap) leaves
235
189
  * the spend itself unknown: then nothing more is sent under the cap, and the words say the spend is unknown, as the
236
190
  * kernel's unknownSpend refusal does, never "no room". */
237
- export async function capSpendOf(store, runId, entries, beforeRound) {
191
+ export async function capSpendOf(store, runId, entries) {
238
192
  const spent = bookedCapSpend(entries);
239
193
  if (spent === null)
240
194
  return null;
241
- const beside = await besideOf(store, runId, beforeRound === undefined ? {} : { beforeRound });
195
+ const beside = await shadowBesideOf(store, runId);
242
196
  return beside === null ? null : spent + beside;
243
197
  }
244
- /** The cap the grade of round `round` of run `runId` runs under (its learning run's max_cost_usd), so the run's grades
245
- * never take it past its cap: the cap the run is held to now (capNowOf: its newest raise's, else `launchCapUsd`), less
246
- * what the run spent under it (its job, its follow-ups and every look-back) and what was spent beside it on its behalf by
247
- * its earlier rounds (capSpendOf: each earlier grade at its cost once it ended, at its own cap while it has not). Null
248
- * when that spend is unknown, or a read fails: the grade is then not run, said so (said.gradeUnknownSpend), never run
249
- * with a room nobody knows and never told it has none. */
250
- export async function gradeCapOf(store, runId, round, launchCapUsd) {
198
+ /** `read` over agent `agentId`'s learning folder, opened for it and always ended after. */
199
+ async function withFolder(deps, agentId, read) {
200
+ const folder = deps.learningFolder(agentId);
251
201
  try {
252
- const entries = await runEntries(store, runId, BACKGROUND_CONTEXT);
253
- const capUsd = capNowOf(launchCapUsd, entries);
254
- const spent = await capSpendOf(store, runId, entries, round);
255
- return spent === null ? null : Math.max(0, capUsd - spent);
202
+ return await read(folder);
256
203
  }
257
- catch {
258
- return null;
204
+ finally {
205
+ await folder.end().catch(() => undefined);
259
206
  }
260
207
  }
261
- /** A workflow text written straight onto the agent's learning folder as a merge by `runId`, from the claim's `seed`: the
262
- * one direct commit a runner makes outside a learning run (a compile turn's revision). A file changed on main since the
263
- * seed is a conflict, never written over. The learning commit it landed as, or null when it did not (the reason is
264
- * logged). The folder is always released. */
265
- export async function commitDirect(deps, files, reason, runId, seed) {
208
+ /**
209
+ * A run's merge on the agent's learning folder, written by the runner directly (learn/commit.ts learningCommit, one
210
+ * exec): its compiled draft's files and its owner's correction, committed by `change.runId` (its Run-Id trailer). A file
211
+ * changed on main since the run's seed (or a revision's `bases` commit) is a conflict, never written over; a correction
212
+ * that holds what must never be stored, or would take corrections.md past its cap, is refused (past the cap beside a
213
+ * draft, it is left out alone and the draft merges). Any failure is logged by its reason alone. The folder is always
214
+ * released.
215
+ */
216
+ export async function commitDirect(deps, change) {
266
217
  const folder = deps.folder();
267
218
  try {
268
- const done = await learningCommit(folder.workspace, { kind: "merge", runId, reason, files, graded: {}, ...(seed ? { seed } : {}) });
219
+ const done = await learningCommit(folder.workspace, change);
269
220
  if (!done.ok)
270
- deps.log(`learning: a direct commit could not be written (${done.reason})`);
271
- return done.ok ? done.commit : null;
221
+ deps.log(`learning: run ${change.runId}: its merge could not be written (${done.reason})`);
222
+ return done;
272
223
  }
273
224
  finally {
274
225
  await folder.end();
275
226
  }
276
227
  }
277
- /** The learning run of round `round` of run `runId`'s learning: `<runId>-learning` for its first, `<runId>-learning-<n>`
278
- * for each later one. */
279
- export const learningRunIdOf = (runId, round = 1) => (round > 1 ? `${runId}-learning-${round}` : `${runId}-learning`);
228
+ /** A merge's result as the hook reads it. */
229
+ const committedOf = (done) => done.ok ? { ok: true, commit: done.commit, ...(done.refusedCorrection ? { refusedCorrection: done.refusedCorrection } : {}) } : done.reason === "unavailable" ? { ok: false, reason: "unavailable", problems: [] } : { ok: false, reason: done.reason, problems: done.problems };
230
+ /** What a run's owner said of it, in order, each a line for corrections.md: the grade's words its end closes (a feedback
231
+ * round, feedback-round.ts pendingFeedbackOf over its root `entries`), and each message a person sent in this round of
232
+ * its timeline `rows`: after the job's first on its first round, after its previous end on a later one (a follow-up
233
+ * opened it again). A grade's round's rows, the end-of-run turn's and a subagent's (a child conversation's rows carry
234
+ * its spawning call, parent_tool_use_id: its task prompt is the job's, not the owner's) are left out. */
235
+ export function ownerWords(entries, rows) {
236
+ const graded = pendingFeedbackOf(entries)?.text;
237
+ const ended = entries.findLast((entry) => entry.kind === KINDS.end)?.id;
238
+ const messages = withoutFeedbackRounds(rows).filter((row) => row.agent_label !== LEARNING_LABEL && !row.parent_tool_use_id && isMessageRow(row));
239
+ const said = ended === undefined ? messages.slice(1) : messages.filter((row) => Number(row.id.split(":")[1]) > ended);
240
+ return [...(graded ? [graded] : []), ...said.filter((row) => row.kind === "user_message").map((row) => String(row.text ?? row.summary ?? ""))];
241
+ }
280
242
  /** learned_workflow by every name a harness calls it: its own, and claude-agent's host-tool alias (`mcp__hands__<name>`).
281
243
  * A harness that names it another way reads as another tool, so its run is asked as before. */
282
244
  export const LEARNED_NAMES = new Set([LEARNED_WORKFLOW_TOOL, `mcp__hands__${LEARNED_WORKFLOW_TOOL}`]);
@@ -288,10 +250,9 @@ export function modelsOwn(rows) {
288
250
  return (row) => !row.parent_tool_use_id || META_TOOLS.has((named.get(row.parent_tool_use_id) ?? "").replace(/^(?:mcp__hands__|hands_)/, ""));
289
251
  }
290
252
  /** Whether a run's job, by its timeline `rows` (the end-of-run turn's own, labelled LEARNING_LABEL, left out), gave
291
- * nothing new to look back on: it called tools, every one of them learned_workflow (a workflow's own nested calls are
292
- * its), each answering; no tool result failed or was refused; no error, approval or wait; and one message, its first,
293
- * came in. Anything else is asked its end-of-run turn. Read on the job's turns (withoutFeedbackRounds): a grade's
294
- * feedback round is no message of the job's. */
253
+ * nothing new: it called tools, every one of them learned_workflow (a workflow's own nested calls are its), each
254
+ * answering; no tool result failed or was refused; no error, approval or wait; and one message, its first, came in.
255
+ * Read on the job's turns (withoutFeedbackRounds): a grade's feedback round is no message of the job's. */
295
256
  export function onlyLearnedWorkflows(rows) {
296
257
  const own = withoutFeedbackRounds(rows).filter((row) => row.agent_label !== LEARNING_LABEL);
297
258
  if (own.some((row) => row.kind === "error" || row.kind === "tool_approval_requested" || row.kind === "waiting"))
@@ -308,21 +269,10 @@ export function onlyLearnedWorkflows(rows) {
308
269
  const answered = new Set(results.filter(models).map((row) => row.tool_use_id));
309
270
  return calls.every((row) => answered.has(row.tool_use_id));
310
271
  }
311
- /** Whether a run carries its owner's feedback, the only thing a run of a job that compiles workflows is looked back on
312
- * for: a grade's words its end closes (a feedback round, feedback-round.ts pendingFeedbackOf over its root `entries`),
313
- * or a person's message after its first in its timeline `rows` (a follow-up, or a word while it ran: traceFrom's
314
- * feedback), the end-of-run turn's own, a grade's round's and a subagent's (a child conversation's rows carry its
315
- * spawning call, parent_tool_use_id: its task prompt is the job's, not the owner's) rows left out. */
316
- export function ownerSaid(entries, rows) {
317
- if (pendingFeedbackOf(entries))
318
- return true;
319
- const messages = withoutFeedbackRounds(rows).filter((row) => row.agent_label !== LEARNING_LABEL && !row.parent_tool_use_id && isMessageRow(row));
320
- return messages.slice(1).some((row) => row.kind === "user_message");
321
- }
322
272
  /** The path a run took (learning-cost.ts RunPath), by its timeline `rows` as runTimeline labels them (its end-of-run
323
273
  * turn's rows, LEARNING_LABEL, are the learning's and left out): `workflow` when its job did only what
324
- * onlyLearnedWorkflows asks of a run with nothing new to look back on, `handed_back` when it called a learned workflow
325
- * otherwise, `agent` when it called none. */
274
+ * onlyLearnedWorkflows asks of a run with nothing new, `handed_back` when it called a learned workflow otherwise,
275
+ * `agent` when it called none. */
326
276
  export function runPathOf(rows) {
327
277
  const models = modelsOwn(rows);
328
278
  const ran = rows.some((row) => row.agent_label !== LEARNING_LABEL && row.kind === "tool_use" && models(row) && LEARNED_NAMES.has(row.tool_name ?? ""));
@@ -340,50 +290,102 @@ export function workflowNameOf(calls) {
340
290
  }
341
291
  return null;
342
292
  }
343
- /** Why each draft of `proposal` waits for its owner's OK whatever the grade: its steps calling an MCP tool with no
344
- * declared price (skills.ts unpricedCalls), by its workflow.json's path, from the prices each server's row keeps
345
- * (mcp-probe.ts McpPrices). A server the store can't read gives no price: held. */
346
- async function heldOf(store, proposal, manifest) {
347
- const files = (proposal?.files ?? []).filter((one) => typeof one?.file === "string" && one.file.endsWith("/workflow.json") && typeof one.text === "string");
348
- const { draftMcpTools, unpricedCalls, unpricedLine } = await import("../learn/skills.js");
293
+ /** Whether a draft's workflow.json (`json`) waits for its owner's OK whatever its checks say: a step of it calls an MCP
294
+ * tool with no declared price (workflow-draft.ts unpricedCalls), from the prices each server's row keeps (mcp-probe.ts
295
+ * McpPrices), or an SDK run's manifest gives. A server the store can't read gives no price: held. */
296
+ async function heldOf(store, json, manifest) {
297
+ let doc;
298
+ try {
299
+ doc = JSON.parse(json);
300
+ }
301
+ catch {
302
+ return false;
303
+ }
349
304
  const rows = new Map();
350
305
  const priced = new Map();
351
- const held = {};
352
- for (const { file, text } of files) {
353
- let doc;
354
- try {
355
- doc = JSON.parse(text);
356
- }
357
- catch {
306
+ // Every MCP tool its call nodes run, as the workflow's own read reads them (draftMcpTools over the parsed JSON: an
307
+ // escaped "\/" is a slash there), its price read first (unpricedCalls asks synchronously).
308
+ for (const name of draftMcpTools(doc)) {
309
+ if (manifest) {
310
+ priced.set(name, manifest.find((tool) => tool.name === name)?.price_usd);
358
311
  continue;
359
312
  }
360
- // Every MCP tool its call nodes run, as the workflow's own read reads them (draftMcpTools over the parsed JSON: an
361
- // escaped "\/" is a slash there), its price read first (unpricedCalls asks synchronously).
362
- for (const name of draftMcpTools(doc)) {
363
- if (manifest) {
364
- priced.set(name, manifest.find((tool) => tool.name === name)?.price_usd);
365
- continue;
366
- }
367
- const { server, tool } = mcpNameOf(name);
368
- if (!rows.has(server))
369
- rows.set(server, getMcpServer(store, server).catch(() => undefined));
370
- const price = (await rows.get(server))?.prices?.[tool];
371
- priced.set(name, typeof price === "number" && Number.isFinite(price) ? price : undefined);
372
- }
373
- const lines = unpricedCalls(doc, (tool) => priced.get(tool)).map(unpricedLine);
374
- if (lines.length)
375
- held[file] = lines;
313
+ const { server, tool } = mcpNameOf(name);
314
+ if (!rows.has(server))
315
+ rows.set(server, getMcpServer(store, server).catch(() => undefined));
316
+ const price = (await rows.get(server))?.prices?.[tool];
317
+ priced.set(name, typeof price === "number" && Number.isFinite(price) ? price : undefined);
376
318
  }
377
- return held;
319
+ return unpricedCalls(doc, (tool) => priced.get(tool)).length > 0;
320
+ }
321
+ /**
322
+ * One compile draft through the checks (the compile turn's `check`): its two files as the folder would hold them
323
+ * (workflow-draft.ts draftFiles: its workflow.json, and the README.md the host writes from its front matter), against
324
+ * `seed`, the commit the run started from (a revision of main's text, `revised`, against the commit it read that text
325
+ * at). In order: its example, the run's own input, refused for anything that must never be stored; the static checks
326
+ * (check.ts checkDraft: the DSL's validation, caps, the secret and hidden-character refusals, a file a person retired or
327
+ * holds for their OK); then its dry run (workflow-draft.ts draftDryRun: every model and tool answer synthesized, nothing
328
+ * sent, paid or run) and the checks again with it. Its errors, each naming its file; else what is committed: the files
329
+ * whole, the README held when a step calls an unpriced tool, the revision's base, and the workflow.json's digest. A
330
+ * draft that is the very text the commit holds passes nothing and keeps nothing.
331
+ */
332
+ export async function checkDraftOf(deps, input) {
333
+ const { name } = input.draft;
334
+ const { json, readme, example } = draftFiles(name, input.draft.text);
335
+ const jsonPath = `${WORKFLOWS_DIR}/${name}/workflow.json`;
336
+ const readmePath = `${WORKFLOWS_DIR}/${name}/README.md`;
337
+ const revised = input.revised && input.revised.workflow === name && input.revised.base !== input.seed ? input.revised : undefined;
338
+ const base = revised?.base ?? input.seed;
339
+ const at = await withFolder(deps, input.agentId, async (folder) => {
340
+ const now = await readSnapshot(folder.workspace);
341
+ const snapshot = now?.main === base ? now : await snapshotAt(folder.workspace, base);
342
+ if (!snapshot)
343
+ throw new Error(`the learning folder has no commit ${base}`);
344
+ return { snapshot, texts: (await textsAt(folder.workspace, base, [jsonPath, readmePath])) ?? {} };
345
+ });
346
+ if (at.texts[jsonPath] === json && at.texts[readmePath] === readme)
347
+ return { errors: [] };
348
+ const refused = (problems) => ({ errors: problems.map((problem) => problemWords([problem])), problems });
349
+ const held = new Set(at.snapshot.workflows.flatMap((item) => item.files.map(({ path }) => path)));
350
+ const changeOf = (path, text) => ({ path, status: held.has(path) ? "modified" : "added", mode: "100644", bytes: Buffer.from(text) });
351
+ // Its example is the run's own input, read as every text it gave is: one that holds what must never be stored refuses
352
+ // the draft, said at its README, though it is never written there.
353
+ if (example !== undefined) {
354
+ const leaky = unstorable([{ ...changeOf(readmePath, example), status: "added" }], input.refuse);
355
+ if (leaky.length)
356
+ return refused(leaky);
357
+ }
358
+ const { tools, gated, deniedBy, decisions, outputSchema, workflowAdapters, manifest } = await draftTools(deps, input.runId);
359
+ const dsl = await import("@parcha/agentrun-dsl");
360
+ // A draft whose text on main has a status is a person's call (retired, or waiting for their OK): never changed.
361
+ const kept = at.snapshot.workflows.filter((item) => item.status !== "active").map((item) => item.file);
362
+ const changes = [changeOf(jsonPath, json), changeOf(readmePath, readme)];
363
+ const check = (dryRuns) => checkDraft({
364
+ changes, refuseValues: input.refuse, tools, dsl,
365
+ ...(Object.keys(gated).length ? { gated } : {}), ...(Object.keys(deniedBy).length ? { deniedBy } : {}), ...(decisions ? { decisions } : {}),
366
+ ...(workflowAdapters !== undefined ? { workflowAdapters } : {}), ...(kept.length ? { kept } : {}), ...(dryRuns ? { dryRuns } : {}),
367
+ });
368
+ const statics = check();
369
+ if (statics.length)
370
+ return refused(statics);
371
+ const ran = check({ [jsonPath]: await draftDryRun(dsl, json, example, outputSchema) });
372
+ if (ran.length)
373
+ return refused(ran);
374
+ const files = [{ path: jsonPath, text: json }, { path: readmePath, text: readme }];
375
+ return {
376
+ errors: [],
377
+ kept: { name, files, ...((await heldOf(deps.store, json, manifest)) ? { held: [readmePath] } : {}), ...(revised ? { bases: { [jsonPath]: revised.base, [readmePath]: revised.base } } : {}) },
378
+ digest: workflowDigest({ workflow: json }),
379
+ };
378
380
  }
379
381
  /** The backend manifest is data describing existing callbacks, not a server MCP connection. */
380
382
  function sdkDescribed(manifest) {
381
383
  return manifest.map((tool) => ({ name: tool.name, does: `${tool.description}. Takes ${JSON.stringify(tool.input_schema)}.${tool.output_schema ? ` Gives ${JSON.stringify(tool.output_schema)}.` : ""}` }));
382
384
  }
383
385
  /** What each of `tools` takes and gives a workflow's call node, in the server's own words for it (tools.ts ToolEntry's
384
- * summary): the draft ask's `describe`. An MCP tool (`mcp:<server>/<tool>`, LS-07) is described by its server's listing
385
- * as the store keeps it: what it does, the schema it takes and, when it lists one, the one it gives (reflect.ts cuts
386
- * each line to its cap). A server or a tool the store does not list is described by none. */
386
+ * summary): the compile ask's `described`. An MCP tool (`mcp:<server>/<tool>`, LS-07) is described by its server's
387
+ * listing as the store keeps it: what it does, the schema it takes and, when it lists one, the one it gives. A server or
388
+ * a tool the store does not list is described by none. */
387
389
  async function describedOf(tools, store) {
388
390
  const { toolOf } = await import("../tools.js");
389
391
  const listed = new Map();
@@ -447,17 +449,6 @@ export async function recordDraftFailed(deps, input) {
447
449
  deps.log?.(`learning: run ${input.runId}: the compile's failed drafts were not recorded: ${error instanceof Error ? error.message : String(error)}`);
448
450
  }
449
451
  }
450
- /** Whether a new workflow's compile is waiting on its grade: a run's kept learning carries a draft that passed its
451
- * checks (a compiled digest) whose learning run, which grades and merges it, has not ended. It is the compile: none
452
- * is asked until it lands (a learned workflow then) or is dropped. Read from the agent's kept learning whose grade has
453
- * not ended (Learning.grading: every one, however many runs kept learning since, never a window of the newest); one
454
- * that can't be read waits. */
455
- async function draftAwaitingGrade(store, agentId) {
456
- const grading = await store.learning.grading(agentId).catch(() => undefined);
457
- if (!grading)
458
- return true;
459
- return grading.some((one) => typeof one.proposal?.compiled?.digest === "string");
460
- }
461
452
  /** The most tool calls of one run a trace keeps, and the most of a call's input or a message it holds, in characters. */
462
453
  const TRACE_CALLS = 20;
463
454
  const TRACE_TEXT = 600;
@@ -489,20 +480,18 @@ export function traceFrom(timeline, refuse) {
489
480
  * it, with the check's numbers and the inputs it disagreed on, once per hold (none when any run since the hold compiled
490
481
  * it, read from the agent's kept learning; a stopped check's none); else, when the job is due (compileDue: the run
491
482
  * completed, the agent has no learned workflow active or waiting, and it has its definition's compile_after completed
492
- * agent runs), a new one, compiled once: none while the last compile's passing draft waits on its grade
493
- * (draftAwaitingGrade), one more after a first compile whose drafts all failed their checks, and none after a
494
- * recompile's (recordDraftFailed). Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's
495
- * stop are single runs, which the hold reads among many. Either way the
496
- * agent's active notes whole, the traces of its last COMPILE_TRACES completed runs before this one, the tools a call node
497
- * may run (draftTools) with what each takes and gives, its decision providers, the run's input (`input`, its fields for
498
- * the workflow's input schema), the agent's output schema when it has one (its final output's shape) and the DSL's
499
- * language with this host's addendum. Undefined when it compiles nothing, or
500
- * when the folder can't be read. */
483
+ * agent runs), a new one, compiled once: one more after a first compile whose drafts all failed their checks, and none
484
+ * after a recompile's (recordDraftFailed). A draft that passes is on main at once (a learned workflow then), so nothing
485
+ * waits on it. Nothing else asks one: a hand-back, a wrong grade of a served answer and the money rule's stop are single
486
+ * runs, which the hold reads among many. Either way the traces of the agent's last COMPILE_TRACES completed runs before
487
+ * this one, the tools a call node may run (draftTools) with what each takes and gives, its decision providers, the
488
+ * run's input (`input`, its fields for the workflow's input schema), the agent's output schema when it has one (its
489
+ * final output's shape) and the DSL's language with this host's addendum. An SDK run's compile, asked outside its
490
+ * session, also carries the owner's standing corrections it was laid with (`corrections`, its # Learned section), as an
491
+ * in-session compile reads them in its session. Undefined when it compiles nothing, or when the folder can't be read. */
501
492
  export async function compileAskOf(deps, input) {
502
- // A revision is asked only of a workflow its promotion holds, once per hold. One run is one sample: a hand-back, a wrong
503
- // grade of a served answer or the money rule's stop asks for none; the hold, read over many runs, does.
504
- // The workflows whose newest revision other than their champion (learn/promote.ts championOf: it serves while that one
505
- // is held) is held: the run's own may be one (its champion served it, or it went by hand).
493
+ // A revision is asked only of a workflow its promotion holds, once per hold. The workflows whose newest revision other
494
+ // than their champion (learn/promote.ts championOf: it serves while that one is held) is held: the run's own may be one.
506
495
  const records = await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
507
496
  const heldNames = heldNamesOf(records);
508
497
  // The loop's numbers on the agent's definition (the revision this run runs): the first compile waits for compile_after
@@ -518,8 +507,8 @@ export async function compileAskOf(deps, input) {
518
507
  const compiledOf = (kept) => kept?.proposal?.compiled;
519
508
  // Compile once: a recompile whose drafts failed their checks stopped the agent's new compiles (recordDraftFailed).
520
509
  const stopped = compileStoppedOf(records);
521
- // First by what the run started from (its seed's notes and the workflows it was offered): a run not due by them
522
- // opens no folder, unless one of its workflows is held. Main is read below for the turn itself, and decides again.
510
+ // First by what the run started from (the workflows it was offered): a run not due by them opens no folder, unless one
511
+ // of its workflows is held. Main is read below for the turn itself, and decides again.
523
512
  if (!heldNames.size && (stopped || !dueWith(input.seedWorkflows ?? 0)))
524
513
  return undefined;
525
514
  const dsl = await import("@parcha/agentrun-dsl");
@@ -528,12 +517,12 @@ export async function compileAskOf(deps, input) {
528
517
  // cut, and logged by name and count only. A workflow the start left out is never revised from its text either.
529
518
  const shown = secretsShown(input.refuse);
530
519
  const holds = (value) => holdsSecret(typeof value === "string" ? value : (JSON.stringify(value) ?? ""), shown);
531
- const leftOut = { workflows: new Set(), notes: 0, traces: 0, input: false };
520
+ const leftOut = { workflows: new Set(), traces: 0, input: false };
532
521
  const folder = deps.learningFolder(input.agentId);
533
522
  // `main`: the commit the snapshot read is main's at, which `current` was read from.
534
523
  let read;
535
524
  try {
536
- read = await readLearning(folder.workspace, async ({ snapshot, body }) => {
525
+ const readFrom = async ({ snapshot, body }) => {
537
526
  const workflows = (snapshot?.workflows ?? []).filter(({ status }) => status === "active" || status === "pending");
538
527
  const textOf = async (name) => {
539
528
  const file = workflows.find((one) => one.name === name)?.files.find(({ path }) => path.endsWith("/workflow.json"));
@@ -559,21 +548,18 @@ export async function compileAskOf(deps, input) {
559
548
  if (record?.decided === "hold" && !record.check?.stopped && !record.audit?.stopped)
560
549
  [held, current] = [record, fitting[0].workflow];
561
550
  }
562
- // An agent with a learned workflow compiles nothing new: its notes' text is not read.
563
- if (!held && workflows.length)
564
- return { notes: [], workflows: workflows.length };
565
- const notes = [];
566
- for (const note of snapshot?.notes ?? []) {
567
- if (note.status !== "active")
568
- continue;
569
- const text = await body(note.file, note.oid);
570
- if (holds(note.file) || holds(text))
571
- leftOut.notes += 1;
572
- else
573
- notes.push({ file: note.file, text });
574
- }
575
- return { notes, workflows: workflows.length, ...(current !== undefined ? { current } : {}), ...(held ? { held } : {}), ...(snapshot?.main ? { main: snapshot.main } : {}) };
576
- });
551
+ return { workflows: workflows.length, ...(current !== undefined ? { current } : {}), ...(held ? { held } : {}), ...(snapshot?.main ? { main: snapshot.main } : {}) };
552
+ };
553
+ // A round that merged already (a crash between its commit and its end): main holds its own merge, so the turn is
554
+ // decided again on main as that merge read it (its parent), and the replayed answer lands on the merge it made
555
+ // (learn/commit.ts learningCommit: a round merges once), never a drop that leaves its commit unrecorded. A stop
556
+ // between the merge and its diff file is read back from the run's ref (runMergeOf).
557
+ const own = await runMergeOf(folder.workspace, input.runId, input.round);
558
+ const before = own ? await folderAt(folder.workspace, own.parent) : undefined;
559
+ read = before
560
+ ? await readFrom({ snapshot: before.snapshot, body: async (path, oid) => { const blob = before.blobs.get(oid); if (!blob)
561
+ throw new Error(`${path} is not in ${own.parent}`); return blob.toString("utf8"); } })
562
+ : await readLearning(folder.workspace, readFrom);
577
563
  }
578
564
  catch {
579
565
  return undefined;
@@ -583,15 +569,15 @@ export async function compileAskOf(deps, input) {
583
569
  }
584
570
  // What it left out, by name and count: said once the facts are gathered, or now when it asks nothing.
585
571
  const sayLeftOut = () => {
586
- const parts = [...[...leftOut.workflows].map((name) => `workflow \`${name}\``), ...(leftOut.notes ? [`${leftOut.notes} note${leftOut.notes === 1 ? "" : "s"}`] : []), ...(leftOut.traces ? [`${leftOut.traces} earlier run${leftOut.traces === 1 ? "" : "s"}`] : []), ...(leftOut.input ? ["the run's input"] : [])];
572
+ const parts = [...[...leftOut.workflows].map((name) => `workflow \`${name}\``), ...(leftOut.traces ? [`${leftOut.traces} earlier run${leftOut.traces === 1 ? "" : "s"}`] : []), ...(leftOut.input ? ["the run's input"] : [])];
587
573
  if (parts.length)
588
574
  deps.log?.(`learning: run ${input.runId}: the compile turn left out what holds a secret: ${parts.join(", ")}`);
589
575
  };
590
576
  let held;
591
577
  if (read.held) {
592
578
  // Once per hold: a run since it that compiled this workflow asked already, whatever came of it (its revision is on its
593
- // way to a replay, its draft failed its checks, or the grader dropped it), however many runs ago. Read from the
594
- // agent's kept learning since the hold, never a window of its last runs; one that can't be read asks nothing.
579
+ // way to a replay, or its draft failed its checks), however many runs ago. Read from the agent's kept learning since
580
+ // the hold, never a window of its last runs; one that can't be read asks nothing.
595
581
  const since = Date.parse(read.held.at);
596
582
  const kept = await deps.store.learning.proposals(input.agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
597
583
  if (!kept || kept.some((one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow))
@@ -606,9 +592,6 @@ export async function compileAskOf(deps, input) {
606
592
  }
607
593
  if (!held && (stopped || !dueWith(read.workflows)))
608
594
  return sayLeftOut(), undefined;
609
- // A new workflow is compiled once: not while the last compile's passing draft waits on its grade.
610
- if (!held && (await draftAwaitingGrade(deps.store, input.agentId)))
611
- return sayLeftOut(), undefined;
612
595
  // An earlier run's trace is cut of each value it held (traceFrom); one that still holds a secret (a value in a call's
613
596
  // input spelled in JSON escapes, a shape the cut does not take) is left out whole.
614
597
  const traces = (await Promise.all(done.slice(0, COMPILE_TRACES).reverse().map((run) => traceOf(deps.store, run.id, input.refuse).catch(() => undefined)))).filter((one) => {
@@ -626,8 +609,10 @@ export async function compileAskOf(deps, input) {
626
609
  const object = input.input !== null && typeof input.input === "object" && !Array.isArray(input.input);
627
610
  leftOut.input = object && holds(input.input);
628
611
  const fields = object && !leftOut.input ? { input: input.input } : {};
612
+ // An SDK compile is one request outside the run's session: it carries the corrections the session was laid with.
629
613
  const bridge = workflowAdapters !== undefined ? { workflowAdapters } : {};
630
- const base = { ...bridge, reference: compileReference(dsl, { tools, judges, ...bridge }), notes: read.notes, traces, tools, described, judges, ...fields, ...(outputSchema !== undefined ? { outputSchema } : {}) };
614
+ const corrections = workflowAdapters !== undefined && input.corrections?.trim() ? { corrections: input.corrections } : {};
615
+ const base = { ...bridge, ...corrections, reference: compileReference(dsl, { tools, judges, ...bridge }), traces, tools, described, judges, ...fields, ...(outputSchema !== undefined ? { outputSchema } : {}) };
631
616
  // A revision is of main's text as read here, whatever the run started from: that commit is its conflict base (`base`).
632
617
  const ask = !held ? { mode: "new", ...base } : { mode: "revise", workflow: held.workflow, current: read.current, ...(read.main ? { base: read.main } : {}), held, ...base };
633
618
  sayLeftOut();
@@ -639,8 +624,9 @@ export async function compileAskOf(deps, input) {
639
624
  }
640
625
  return ask;
641
626
  }
642
- /** The tools a workflow draft may name (learning-run.ts draftTools): the revision's own, as its run's gate reads them
643
- * with the server's settings (from the store) and the agent's; none for a workflow revision. */
627
+ /** The tools a workflow draft may name: the revision's own, as its run's gate reads them with the server's settings
628
+ * (from the store) and the agent's, or an SDK run's manifest (`manifest`, its prices with it); none for a workflow
629
+ * revision. */
644
630
  async function draftTools(deps, runId) {
645
631
  const run = await deps.store.runs.get(runId);
646
632
  const launch = run ? readLaunchBody((await deps.store.runs.launch(runId)).body) : undefined;
@@ -653,7 +639,7 @@ async function draftTools(deps, runId) {
653
639
  const shaped = body.outputSchema !== undefined ? { outputSchema: body.outputSchema } : {};
654
640
  if (launch?.sdk?.workflow_tools) {
655
641
  const catalog = sdkDraftTools(launch.sdk.workflow_tools);
656
- return { ...catalog, ...shaped, workflowAdapters: launch.sdk.workflow_adapters ?? [], described: sdkDescribed(launch.sdk.workflow_tools.filter(tool => catalog.tools.includes(tool.name))) };
642
+ return { ...catalog, ...shaped, workflowAdapters: launch.sdk.workflow_adapters ?? [], manifest: launch.sdk.workflow_tools, described: sdkDescribed(launch.sdk.workflow_tools.filter(tool => catalog.tools.includes(tool.name))) };
657
643
  }
658
644
  const [{ learnedDraftTools }, { permissionFrom }, { loadToolSettings }] = await Promise.all([import("../tools.js"), import("../tool-gate.js"), import("../tool-plane.js")]);
659
645
  // The server's settings from the one store, as the run's gate reads them: a stored row that does not read carries
@@ -661,7 +647,7 @@ async function draftTools(deps, runId) {
661
647
  const server = (await loadToolSettings(deps.store)).settings;
662
648
  const agent = (body.toolSettings ?? {});
663
649
  const approvals = body.approvals === "never" ? "never" : "ask";
664
- // `deniedBy`: where each deny was set (the agent's tool settings, the server's, a default), which a left-out draft's
650
+ // `deniedBy`: where each deny was set (the agent's tool settings, the server's, a default), which a refused draft's
665
651
  // words name.
666
652
  const { tools, gated, deniedBy } = learnedDraftTools(body.tools ?? [], (name) => permissionFrom(name, server, agent, approvals).permission, undefined, (name) => permissionFrom(name, server, agent, approvals).from, { mcp: true, approvers: await readApprovers(deps.store.settings) });
667
653
  // A draft's decision nodes (LS-07): the host's decision providers, each held to the gate by its bare id as the run's
@@ -681,42 +667,3 @@ async function draftTools(deps, runId) {
681
667
  }
682
668
  return { tools, gated, deniedBy, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy }, ...shaped };
683
669
  }
684
- /** The commit main of the agent's learning folder is at now; none for a folder with no main yet. */
685
- async function mainOf(deps, agentId) {
686
- const folder = deps.learningFolder(agentId);
687
- try {
688
- return (await readSnapshot(folder.workspace))?.main ?? undefined;
689
- }
690
- finally {
691
- await folder.end();
692
- }
693
- }
694
- /** proposeRun's checks over the turn, against seed `seed` (a revised workflow's files against the commit its compile ask
695
- * read it at: `revised`), in a directory of the step's own: the proposal it keeps there is read back for the hook to
696
- * store with the run's end, and the directory is removed. */
697
- async function checkedOf(deps, input) {
698
- const runDir = await mkdtemp(join(tmpdir(), "agentrun-learning-end-"));
699
- try {
700
- const { tools, gated, deniedBy, decisions, outputSchema } = await draftTools(deps, input.runId);
701
- const sdk = readLaunchBody((await deps.store.runs.launch(input.runId)).body)?.sdk;
702
- const turn = { answer: input.turn.answer, asked: [...input.turn.asked], ...(input.turn.triggered?.length ? { triggered: input.turn.triggered.map((one) => ({ ...one })) } : {}) };
703
- const folder = deps.learningFolder(input.agentId);
704
- let proposed;
705
- try {
706
- proposed = await proposeRun({ ...(sdk?.workflow_tools ? { workflowAdapters: sdk.workflow_adapters ?? [] } : {}), folder: folder.workspace, runDir, seed: input.seed, ...(input.notesSeed ? { notesSeed: input.notesSeed } : {}), ...(input.revised ? { revised: input.revised } : {}), turn, refuse: input.refuse, outcome: input.outcome, tools, ...(Object.keys(gated).length ? { gated } : {}), ...(Object.keys(deniedBy).length ? { deniedBy } : {}), ...(decisions ? { decisions } : {}), ...(input.workflows === false ? { workflows: false } : {}), ...(outputSchema !== undefined ? { outputSchema } : {}) });
707
- }
708
- finally {
709
- await folder.end();
710
- }
711
- if (proposed.state !== "proposed")
712
- return proposed;
713
- const proposal = JSON.parse(await readFile(join(runDir, PROPOSAL), "utf8"));
714
- // A draft calling an MCP tool with no declared price waits for its owner's OK whatever the grade (LS-07): held here,
715
- // from the prices the store keeps now, and said to the grader.
716
- const held = await heldOf(deps.store, proposal, sdk?.workflow_tools);
717
- return { ...proposed, proposal: Object.keys(held).length ? { ...proposal, held } : proposal };
718
- }
719
- finally {
720
- await rm(runDir, { recursive: true, force: true });
721
- }
722
- }