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