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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -2,11 +2,16 @@ import type { Store } from "../store/store.js";
2
2
  import type { RunnerMemory } from "./runner.js";
3
3
  /** What a run launched on `harness` weighs: its entry's run size on the owner's table of `env` (harness-table.ts
4
4
  * ownerHarness: a built-in's, or what a harness module declares; a test's stand-in weighs as the built-in it stands in
5
- * for), or a pi run's for a run on no harness of that table (a learning run, which runs in the runner's own process as a
6
- * pi run does). */
5
+ * for), or a pi run's for a run on no harness of that table (a learning run, whose loop is a pi run's). */
7
6
  export declare function claimMibOf(harness: string, env?: NodeJS.ProcessEnv): number;
7
+ /** What a run's own process weighs beside its harness's run (run-child-host.ts: a runner whose runs are each a process of
8
+ * their own): a Node with the server's modules loaded, which a run in the runner's own process shared with every other.
9
+ * As measured: a run's process at its first turn, its resident set (224 MiB on the faux model, test/run-isolation.test.mjs
10
+ * says it) less the harness's own (pi's 128). */
11
+ export declare const RUN_PROCESS_MIB = 96;
8
12
  /** The runner's memory budget over `store`: `memory` bytes (default the host's, hostMemory) less the server's own, each
9
13
  * waiting run weighed by the harness its launch names (store.runs.launch) on the owner's table of `env` (the runner's run
10
- * environment, which names its harness modules). A run whose launch cannot be read weighs a pi run: its claim fails it at
11
- * once (dispatch.ts), holding nothing for long. */
12
- export declare function runnerMemory(store: Pick<Store, "runs">, memory?: number, env?: NodeJS.ProcessEnv): RunnerMemory;
14
+ * environment, which names its harness modules), and `processMib` more for a run that is a process of its own
15
+ * (RUN_PROCESS_MIB; 0 for a runner whose runs share its process). A run whose launch cannot be read weighs a pi run: its
16
+ * claim fails it at once (dispatch.ts), holding nothing for long. */
17
+ export declare function runnerMemory(store: Pick<Store, "runs">, memory?: number, env?: NodeJS.ProcessEnv, processMib?: number): RunnerMemory;
@@ -8,21 +8,27 @@ import { builtinHarness, ownerHarness } from "../harness-table.js";
8
8
  import { hostMemory, runsMemoryMib } from "../host.js";
9
9
  /** What a run launched on `harness` weighs: its entry's run size on the owner's table of `env` (harness-table.ts
10
10
  * ownerHarness: a built-in's, or what a harness module declares; a test's stand-in weighs as the built-in it stands in
11
- * for), or a pi run's for a run on no harness of that table (a learning run, which runs in the runner's own process as a
12
- * pi run does). */
11
+ * for), or a pi run's for a run on no harness of that table (a learning run, whose loop is a pi run's). */
13
12
  export function claimMibOf(harness, env = {}) {
14
13
  return (ownerHarness(env, harness) ?? builtinHarness(DEFAULT_HARNESS)).runMib;
15
14
  }
15
+ /** What a run's own process weighs beside its harness's run (run-child-host.ts: a runner whose runs are each a process of
16
+ * their own): a Node with the server's modules loaded, which a run in the runner's own process shared with every other.
17
+ * As measured: a run's process at its first turn, its resident set (224 MiB on the faux model, test/run-isolation.test.mjs
18
+ * says it) less the harness's own (pi's 128). */
19
+ export const RUN_PROCESS_MIB = 96;
16
20
  /** The runner's memory budget over `store`: `memory` bytes (default the host's, hostMemory) less the server's own, each
17
21
  * waiting run weighed by the harness its launch names (store.runs.launch) on the owner's table of `env` (the runner's run
18
- * environment, which names its harness modules). A run whose launch cannot be read weighs a pi run: its claim fails it at
19
- * once (dispatch.ts), holding nothing for long. */
20
- export function runnerMemory(store, memory = hostMemory(), env = {}) {
22
+ * environment, which names its harness modules), and `processMib` more for a run that is a process of its own
23
+ * (RUN_PROCESS_MIB; 0 for a runner whose runs share its process). A run whose launch cannot be read weighs a pi run: its
24
+ * claim fails it at once (dispatch.ts), holding nothing for long. */
25
+ export function runnerMemory(store, memory = hostMemory(), env = {}, processMib = 0) {
21
26
  return {
22
27
  budgetMib: runsMemoryMib(memory),
23
28
  weigh: async (runIds) => new Map(await Promise.all(runIds.map(async (runId) => {
24
29
  const harness = await store.runs.launch(runId).then((row) => harnessOfBody((row.body ?? {})), () => DEFAULT_HARNESS);
25
- return [runId, claimMibOf(harness, env)];
30
+ // A learning run stays in the runner's process (run-child-host.ts childLoops): no process of its own.
31
+ return [runId, claimMibOf(harness, env) + (harness === "learning" ? 0 : processMib)];
26
32
  }))),
27
33
  };
28
34
  }
@@ -26,8 +26,7 @@ export type RouteUsage = {
26
26
  };
27
27
  /** Where a model's requests go: the API `provider.api` names at `origin` (the shape the kernel's model proxy forwards), its
28
28
  * credential sent as `auth` says, for `model` (its id on that wire), priced by `price`; `fetch`, the route's own upstream
29
- * when its model speaks no wire of the caller's. The fields of the learning grader's route (learning-ask.ts GraderRoute),
30
- * and `cost` beside them. */
29
+ * when its model speaks no wire of the caller's, and `cost` beside them. */
31
30
  export interface ModelRoute {
32
31
  /** `plan`: a ChatGPT plan's route (provider.ts billing "plan"), billed to the plan: no price, its rules on the wire.
33
32
  * Whether its answers state what they cost is the proxy's to read from `origin` (statesUsageCost): OpenRouter's, or
@@ -50,7 +49,8 @@ export interface ModelRoute {
50
49
  * wire that carries its reasoning (Responses), also whether it reasons, its window, its output ceiling, and the effort
51
50
  * each thinking level asks for (`thinkingLevelMap`: a level mapped to null sends no effort, so pi's thinking off asks
52
51
  * a model that takes no "none" for none, gpt-6.1-sol's case). On the route's own translation, a model that reasons
53
- * asks its level by name (LEVELS_BY_NAME: `adaptiveThinking`), so the run's effort reaches it. */
52
+ * asks its level by name (LEVELS_BY_NAME: `adaptiveThinking`), so the run's effort reaches it; Particle's also keeps
53
+ * its window and ceiling, and marks its Messages hop as carrying Chat Completions (`translatedChatCompletions`). */
54
54
  readonly like?: {
55
55
  readonly reasoning?: boolean;
56
56
  readonly contextWindow?: number;
@@ -60,6 +60,7 @@ export interface ModelRoute {
60
60
  readonly developerRole?: boolean;
61
61
  readonly adaptiveThinking?: boolean;
62
62
  readonly thinkingLevelMap?: ThinkingLevelMap;
63
+ readonly translatedChatCompletions?: boolean;
63
64
  };
64
65
  /** A request's price from its usage (the proxy's booking reads it): pi-ai's calculateCost, tiers included. */
65
66
  readonly price?: (model: string, usage: RouteUsage) => number | null;
@@ -112,7 +113,9 @@ type PiEvent = {
112
113
  error?: PiMessage;
113
114
  };
114
115
  type PiMessage = {
115
- usage?: RouteUsage;
116
+ usage?: RouteUsage & {
117
+ reasoning?: number;
118
+ };
116
119
  stopReason?: string;
117
120
  errorMessage?: string;
118
121
  content?: {
@@ -1,7 +1,7 @@
1
1
  // The runner's model route: where a model's requests go, on which id, at what price. A model is resolved as main
2
2
  // resolves a run's (model.ts chooseModel and runModels: the faux module under --faux, the gateway, or each provider on
3
3
  // its own key), and a route speaks a wire its caller speaks (`wires`: the pi adapter speaks both of main's, provider.ts,
4
- // and so do the learning grader and a workflow's model nodes, which take the route's wire as pi does):
4
+ // and so do a workflow's model nodes, which take the route's wire as pi does):
5
5
  // - an Anthropic model goes to Anthropic itself (its catalog origin, ANTHROPIC_BASE_URL's when set), its key read by
6
6
  // name when a request goes, never held by the route; a Claude model of serve's gateway goes to the gateway on Messages;
7
7
  // - a model pi-ai speaks OpenAI's Responses to (OpenAI's own on its key, serve's gateway), for a caller that speaks
@@ -75,8 +75,10 @@ export async function routeOf(model, env = process.env, tier = "default", wires
75
75
  // The translation writes an answer's cost in its usage only where pi-ai read the provider's own (OpenRouter's): the
76
76
  // proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
77
77
  // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
78
- // model, mapped and clamped by its own catalog entry.
79
- return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
78
+ // model, mapped and clamped by its own catalog entry. Direct Particle states no cost (its usage is priced from the
79
+ // catalog), and its session also takes the model's window and ceiling and replays unsigned reasoning.
80
+ const like = target.provider === "particle" ? { ...settings, ...LEVELS_BY_NAME, translatedChatCompletions: true } : target.reasoning ? { ...sees, ...LEVELS_BY_NAME } : undefined;
81
+ return { ...route, ...(like ? { like } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
80
82
  }
81
83
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
82
84
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
@@ -111,6 +113,9 @@ function tapped(upstream) {
111
113
  * as one the model proxy sends there does; a request to any other provider carries none. */
112
114
  export function messagesFetch(models, target, redact = keepText, upstream, env = process.env) {
113
115
  const attribution = piOnOpenRouter(target) ? openRouterAttribution(env) : {};
116
+ const particle = target.provider === "particle";
117
+ // Side requests without a Pi session id retain affinity for this route's lifetime.
118
+ const cacheSession = particle ? randomUUID() : undefined;
114
119
  // A tool call's id as Messages carries it (letters, digits, _ and -), and back to the provider's own on its result.
115
120
  const providerIds = new Map();
116
121
  const messagesId = (id) => {
@@ -125,11 +130,14 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
125
130
  // result of its history as text, and its calls read from its reply. A request with no tools goes as it is.
126
131
  const asText = target.toolsAs === "text" && (built.tools?.length ?? 0) > 0;
127
132
  const context = asText ? toolsAsText(built) : built;
128
- // On OpenRouter, each answer's end is kept as it streams by, for a rate limit it ends in (limitedWords).
129
- const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
133
+ // Keep each OpenRouter or Particle answer's end for structured failures inside a successful HTTP stream.
134
+ const tap = piOnOpenRouter(target) || particle ? tapped(upstream) : undefined;
130
135
  const sendWith = tap?.fetch ?? upstream;
131
136
  const level = levelOf(body);
132
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
137
+ // Particle's cache affinity: the session's id (the Messages hop's metadata.user_id), else this route's own; an
138
+ // empty id is a caller that asked for no cache hint.
139
+ const affinity = !particle ? {} : body.metadata?.user_id === "" ? { cacheRetention: "none" } : { sessionId: body.metadata?.user_id || cacheSession };
140
+ const streamOptions = { ...affinity, ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
133
141
  const events = models.streamSimple(target, context, streamOptions);
134
142
  const encoder = new TextEncoder();
135
143
  const stream = new ReadableStream({
@@ -157,7 +165,7 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
157
165
  const failed = tap ? streamErrorOf(tap.kept()) : undefined;
158
166
  if (failed === undefined)
159
167
  return sendWords(words);
160
- const tokens = used ? { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead ?? 0, cache_creation_input_tokens: used.cacheWrite ?? 0 } : undefined;
168
+ const tokens = used ? { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead ?? 0, cache_creation_input_tokens: used.cacheWrite ?? 0, ...(used.reasoning === undefined ? {} : { output_tokens_details: { thinking_tokens: used.reasoning } }) } : undefined;
161
169
  if ((tokens && tokens.input_tokens + tokens.output_tokens + tokens.cache_read_input_tokens + tokens.cache_creation_input_tokens > 0) || cost !== undefined) {
162
170
  send({ type: "message_delta", delta: { stop_reason: null, stop_sequence: null }, usage: { ...(tokens ?? { input_tokens: 0, output_tokens: 0 }), ...(cost === undefined ? {} : { cost }) } });
163
171
  }
@@ -166,8 +174,8 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
166
174
  send({ type: "message_start", message: { id: `msg_${Date.now().toString(36)}`, type: "message", role: "assistant", model: body.model ?? target.id, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
167
175
  // Messages blocks are numbered as sent. A thinking block is sent too, so the model's reasoning reaches the run's
168
176
  // record as a Timeline row; its text goes through the run's one redactor, so a held key the model quoted in its
169
- // thinking is cut before pi's session journals it, not only at read. It carries no signature here, which the bridge
170
- // back (contextOf) drops from a later turn's request, so none is needed and the cut thinking is never read as context.
177
+ // thinking is cut before pi's session journals it, not only at read. It carries no signature here. Particle
178
+ // preserves this redacted text for its native tool continuation; other translated providers drop it.
171
179
  const blockOf = new Map();
172
180
  const sentJson = new Set();
173
181
  let blocks = 0;
@@ -269,7 +277,7 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
269
277
  }
270
278
  const used = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
271
279
  const cost = reportedOf(message.usage);
272
- send({ type: "message_delta", delta: { stop_reason: stopReasonOf(event.reason ?? message.stopReason), stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(cost === undefined ? {} : { cost }) } });
280
+ send({ type: "message_delta", delta: { stop_reason: stopReasonOf(event.reason ?? message.stopReason), stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(used.reasoning === undefined ? {} : { output_tokens_details: { thinking_tokens: used.reasoning } }), ...(cost === undefined ? {} : { cost }) } });
273
281
  send({ type: "message_stop" });
274
282
  }
275
283
  }
@@ -424,6 +432,10 @@ function contextOf(body, target, providerId) {
424
432
  const content = blocks.flatMap((block) => {
425
433
  if (block.type === "text")
426
434
  return [{ type: "text", text: block.text ?? "" }];
435
+ // Retain Particle's native reasoning alongside the assistant tool call on continuation. The Messages
436
+ // hop has already redacted this text; restore only the field name, never a foreign provider's signature.
437
+ if (target.provider === "particle" && block.type === "thinking")
438
+ return [{ type: "thinking", thinking: block.thinking ?? "", thinkingSignature: "reasoning_content" }];
427
439
  if (block.type === "tool_use") {
428
440
  named.set(block.id ?? "", block.name ?? "");
429
441
  return [{ type: "toolCall", id: providerId(block.id ?? ""), name: block.name ?? "", arguments: (block.input ?? {}) }];
@@ -1,11 +1,4 @@
1
- import type { NativeBinding } from '../native/types.js';
2
1
  import type { RunLaunch } from '../run-launch.js';
3
- import type { Store } from '../store/store.js';
4
2
  import { type LoopFactory } from './loop-contract.js';
5
3
  import type { AdapterSpecDeps } from './adapter-run-spec.js';
6
4
  export declare function createNativeLoop(launch: RunLaunch, host: AdapterSpecDeps): LoopFactory;
7
- /** The ordinary checked/graded/atomic learning lane, using a distinct native signed-in session for its policy model.
8
- * A separate empty directory prevents the source project's answer-format instructions from becoming grader policy. */
9
- export declare function nativeLearningLoop(host: AdapterSpecDeps, target: NativeBinding): LoopFactory;
10
- /** Reuse the last policy snapshot before durable task dispatch, never an abandoned attempt or mutable source files. */
11
- export declare function nativeSourceInstructions(store: Store, runId: string): Promise<string>;
@@ -1,6 +1,4 @@
1
- import { RemoteConnectors, checkedPrepared, openRemoteSession, remoteResult } from '../native/remote.js';
2
- import { execFile } from "node:child_process";
3
- import { promisify } from "node:util";
1
+ import { RemoteConnectors, checkedPrepared, openRemoteSession } from '../native/remote.js';
4
2
  import { nativeEnvironment } from "../native/environment.js";
5
3
  // A native job participates in the existing claim/journal/end-of-run contract. Native side effects are never replayed
6
4
  // after an uncertain send. The original directory/configuration is untouched; pinned saved instructions and learned context are additive.
@@ -9,19 +7,15 @@ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
9
7
  import { join } from 'node:path';
10
8
  import { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';
11
9
  import { ROOT_CONVERSATION_ID } from '@earendil-works/pi-durable';
12
- import { learningFolderOf, readerOf, seedFrom, secretsShown, chooseSkills } from '../learning.js';
10
+ import { learningFolderOf } from '../learning.js';
13
11
  import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED } from '../native/binding.js';
14
12
  import { launchNative } from '../native/connection.js';
15
13
  import { openNativeSession } from '../native/runtime.js';
16
- import { discoverNative } from '../native/discovery.js';
17
- import { nativeSkillContext } from '../native/context.js';
18
14
  import { snapshotNativeInstructions, withSavedNativeInstructions } from '../native/instructions.js';
19
- import { isNativeRuntime, NATIVE_RUNTIME_FACTS } from '../native/runtimes.js';
20
15
  import { inputMessage } from '../run-manifest.js';
21
16
  import { outputContract, outputMiss, outputRetryWords } from '../answer-json.js';
22
17
  import { cutStrings, redactedOutput } from '../key-refusal.js';
23
18
  import { learningEndOfRun } from './learning-end.js';
24
- import { learningLoopFactory } from './learning-factory.js';
25
19
  import { pathMetrics } from './workflow-first.js';
26
20
  import { reflectRequestId } from './end-of-run.js';
27
21
  import { journalEntries } from './journal-reader.js';
@@ -69,37 +63,6 @@ async function lockProject(data, target, runId) {
69
63
  }
70
64
  return async () => { pendingProjects.delete(key); await rm(path, { recursive: true, force: true }); };
71
65
  }
72
- async function contextFor(data, agentId, runId, launch, refuse, nativeSkills) {
73
- if (!launch.learning)
74
- return { skills: [] };
75
- const folder = learningFolderOf(data, agentId);
76
- try {
77
- const seed = await seedFrom(launch.learning.seed, readerOf(folder.workspace));
78
- // Use the same budgets/checks as the managed seed. Reads only; no files in the source project are laid or replaced.
79
- const selected = await chooseSkills(folder.workspace, { ...seed, skills: seed.skills?.filter(skill => !nativeSkills.includes(skill.name)) }, [], secretsShown(refuse, { local: true }));
80
- if (launch.native?.remote) {
81
- const taken = [], left = [];
82
- for (const skill of selected.taken) {
83
- if (Object.keys(skill.files ?? {}).length > 128) {
84
- left.push(`${skill.name} (more than 128 remote skill files)`);
85
- continue;
86
- }
87
- if (taken.length >= 64) {
88
- left.push(`${skill.name} (64 remote skills already selected)`);
89
- continue;
90
- }
91
- taken.push(skill);
92
- }
93
- return { text: launch.learning.section, skills: taken.map(skill => skill.name), remoteSkills: taken, left };
94
- }
95
- const skills = selected.taken.map(s => s.name);
96
- const offered = await nativeSkillContext(join(data, 'native-context', runId, 'skills'), selected.taken);
97
- return { text: [launch.learning.section, offered].filter(Boolean).join('\n\n'), skills };
98
- }
99
- finally {
100
- await folder.end();
101
- }
102
- }
103
66
  export function createNativeLoop(launch, host) {
104
67
  return deps => {
105
68
  const held = heldRedactor(deps.redact ?? processSecretRedactor());
@@ -272,9 +235,9 @@ export function createNativeLoop(launch, host) {
272
235
  // Preparation can withdraw learning after this launch was queued. The final
273
236
  // saved-policy snapshot can also newly exceed the evidence limit. Keep task
274
237
  // context/use intact, but refuse the reflection before it reaches the source.
275
- if (launch.learning && !launch.learning.use && (instructions.incomplete || instructions.truncated || !target.capabilities.notes && !target.capabilities.skills)) {
238
+ if (launch.learning && !launch.learning.use && (instructions.incomplete || instructions.truncated || !target.capabilities.learning)) {
276
239
  automaticLearningUnavailable = true;
277
- const why = instructions.incomplete || (instructions.truncated ? 'the combined source and saved policy exceeds the grading evidence limit.' : 'the prepared source does not support notes or skills.');
240
+ const why = instructions.incomplete || (instructions.truncated ? 'the combined source and saved policy exceeds the grading evidence limit.' : 'the prepared source does not support learning.');
278
241
  const detail = redact(`Self-improvement skipped: ${why} A new run must capture complete policy evidence before automatic learning.`);
279
242
  // An unasked drop settles both learning views atomically with the task end;
280
243
  // it queues no learning run and keeps an unavailable run from staying seeded.
@@ -283,18 +246,18 @@ export function createNativeLoop(launch, host) {
283
246
  }
284
247
  // A reclaimed claim before the durable dispatch marker can safely replace only its own additive files.
285
248
  await rm(join(host.data, 'native-context', claim.runId), { recursive: true, force: true });
286
- const learned = await contextFor(host.data, agentId, claim.runId, launch, refuse, target.skills);
287
- if (learned.left?.length)
288
- await append(HOST_PHASE, { summary: redact(`Learned skills left out of this remote run: ${learned.left.join('; ')}.`) });
249
+ // What the agent learned reaches a native run as its # Learned section alone (its corrections): read only, nothing
250
+ // in the source project is laid or replaced.
251
+ const learned = { text: launch.learning?.section };
289
252
  await append(`${MARK}.configuration`, { ...target, learning_revision: launch.learning?.seed ?? null });
290
253
  if (launch.learning)
291
- await append(KINDS.learningLaid, { skills: learned.skills, workflows: [] });
254
+ await append(KINDS.learningLaid, { workflows: [] });
292
255
  const content = inputMessage(launch.input);
293
256
  await append(KINDS.message, { role: 'person', text: content, at: Date.now(), ...(launch.inputOrigin ? { origin: launch.inputOrigin } : {}) });
294
257
  await append(`${MARK}.sending`, { phase: 'task' });
295
258
  await deps.flush();
296
259
  const context = [savedInstructions, learned.text, outputContract(outputSchema)].filter(Boolean).join('\n\n');
297
- session = broker ? await openRemoteSession(broker, target, { context: context || undefined, skills: learned.remoteSkills, runId: claim.runId, signal, onEvent }) : await openNativeSession({ target, context: context || undefined, signal, onEvent, env: nativeEnvironment() });
260
+ session = broker ? await openRemoteSession(broker, target, { context: context || undefined, runId: claim.runId, signal, onEvent }) : await openNativeSession({ target, context: context || undefined, signal, onEvent, env: nativeEnvironment() });
298
261
  const task = async (prompt) => {
299
262
  const result = await send(prompt, 'task');
300
263
  await append(KINDS.message, { role: 'model', text: redact(result.answer), at: Date.now() });
@@ -381,58 +344,3 @@ function nativeMetrics(launch, entries, spend, model, turns, runtime) {
381
344
  // Native tasks always run their agent: this lane never serves or calls an AgentRun learned workflow.
382
345
  return { ...counted, ...pathMetrics(launch, { path: 'agent', workflow: null }, entries), input: usage.some(u => nativeInput(u, runtime) === null) ? null : count('input_tokens', 'input'), output: count('output_tokens', 'output'), cacheRead: count('cache_read_tokens', 'cacheRead'), cacheWrite: count('cache_write_tokens', 'cacheWrite'), requests: null, unmetered: null, models: {}, native_model_requests: null, native_turns: turns };
383
346
  }
384
- /** The ordinary checked/graded/atomic learning lane, using a distinct native signed-in session for its policy model.
385
- * A separate empty directory prevents the source project's answer-format instructions from becoming grader policy. */
386
- export function nativeLearningLoop(host, target) {
387
- return learningLoopFactory({ store: host.store, data: host.data, sourceInstructions: runId => nativeSourceInstructions(host.store, runId), ask: async (request, signal) => {
388
- if (target.remote) {
389
- const result = remoteResult(await new RemoteConnectors(host.store).request(target, 'grade', { prompt: request.prompt, timeout_ms: 180_000 }, { signal, timeoutMs: 185_000 }));
390
- const u = result.usage;
391
- return { text: result.answer, usd: u.cost_usd, tokens: u.input_tokens === null || u.output_tokens === null || u.cache_read_tokens === null || u.cache_write_tokens === null ? null : { input: nativeInput(u, target.runtime), output: u.output_tokens, cache_read: u.cache_read_tokens, cache_write: u.cache_write_tokens } };
392
- }
393
- const dir = join(host.data, 'native-grader');
394
- await mkdir(dir, { recursive: true });
395
- await promisify(execFile)('git', ['init', '--quiet', dir], { timeout: 10_000 });
396
- const graderTarget = (await discoverNative({ project: dir, runtime: target.runtime, env: nativeEnvironment() })).targets.find(value => value.selector.kind === 'project');
397
- if (!graderTarget)
398
- throw new Error('The native grading runtime is unavailable.');
399
- const grader = await openNativeSession({ target: graderTarget, signal, env: nativeEnvironment() });
400
- try {
401
- const result = await grader.send(request.prompt, { signal, reflection: true, timeoutMs: 180_000 });
402
- const u = result.usage;
403
- return { text: result.answer, usd: u.cost_usd, tokens: u.input_tokens === null || u.output_tokens === null || u.cache_read_tokens === null || u.cache_write_tokens === null ? null : { input: nativeInput(u, target.runtime), output: u.output_tokens, cache_read: u.cache_read_tokens, cache_write: u.cache_write_tokens } };
404
- }
405
- finally {
406
- await grader.close();
407
- }
408
- } });
409
- }
410
- /** Reuse the last policy snapshot before durable task dispatch, never an abandoned attempt or mutable source files. */
411
- export async function nativeSourceInstructions(store, runId) {
412
- const entries = await journalEntries(store.readJournal(runId), BACKGROUND_CONTEXT);
413
- const sent = entries.findIndex(entry => entry.kind === `${MARK}.sending` && entry.data?.phase === 'task');
414
- // A reclaimed pre-dispatch attempt can leave a snapshot behind. Only the last snapshot before the durable task
415
- // dispatch belongs to the native session whose work is being graded; later unbound evidence cannot replace it.
416
- const row = sent < 0 ? undefined : entries.slice(0, sent).findLast(entry => entry.kind === `${MARK}.instructions`);
417
- const configuration = sent < 0 ? undefined : entries.slice(0, sent).findLast(entry => entry.kind === `${MARK}.configuration`);
418
- const runtime = configuration?.data?.runtime;
419
- const protocol = isNativeRuntime(runtime) ? NATIVE_RUNTIME_FACTS[runtime].protocol : undefined;
420
- if (!row)
421
- throw new Error('Native learning lacks its immutable source instruction snapshot; no proposal was promoted.');
422
- if (!protocol)
423
- throw new Error('Native standing instruction evidence is incomplete: the dispatched native runtime was not recorded. No proposal was promoted; a new source run must capture complete policy evidence before automatic learning.');
424
- if (protocol === 'codex-json' && row?.data?.codexConfigurationChecked !== true)
425
- throw new Error('Native standing instruction evidence is incomplete: this older Codex snapshot did not inspect custom policy configuration. No proposal was promoted; a new source run must capture complete policy evidence before automatic learning.');
426
- if (protocol === 'claude-json' && row?.data?.claudeConfigurationChecked !== true)
427
- throw new Error('Native standing instruction evidence is incomplete: this older Claude snapshot did not preserve source settings precedence. No proposal was promoted; a new source run must capture complete policy evidence before automatic learning.');
428
- if (protocol === 'claude-json' && row?.data?.claudePolicySourcesChecked !== true)
429
- throw new Error('Native standing instruction evidence is incomplete: this older Claude snapshot did not check imported or additional policy files. No proposal was promoted; a new source run must capture complete policy evidence before automatic learning.');
430
- if (row?.data?.incomplete)
431
- throw new Error(`Native standing instruction evidence is incomplete: ${row.data.incomplete} No proposal was promoted; automatic learning requires a complete source policy snapshot.`);
432
- if (row?.data?.truncated)
433
- throw new Error('Native standing instructions exceed the grading evidence limit; no proposal was promoted. Reduce or explicitly configure the grading context before enabling automatic learning.');
434
- const text = row?.data?.text;
435
- if (typeof text !== 'string')
436
- throw new Error('Native learning lacks its immutable source instruction snapshot; no proposal was promoted.');
437
- return text;
438
- }
@@ -2,7 +2,7 @@ import type { Context } from "@earendil-works/chord/context";
2
2
  import type { LearnedWorkflow } from "../learning.js";
3
3
  import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
- import { type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
5
+ import { type Recorded, type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
7
  import { type CheckBar, type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
8
  import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
@@ -85,6 +85,8 @@ export declare const promotionGate: (deps: PromotionDeps) => Promoted;
85
85
  export declare const DSL_REFUSES = "this release's workflow DSL refuses it";
86
86
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
87
87
  export declare const NOTHING_TO_CHECK = "nothing to check it on";
88
+ /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none. */
89
+ export declare const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word; name the fields that carry the decision (learning.agree_on)";
88
90
  /** One input a check ran its draft on: the agent's run (`of`) and its input, the agent's recorded answer, and what the
89
91
  * draft did: its answer when it answered alone, why it handed the input back, or failed (or skipped a write). A
90
92
  * reserved input whose replay run was never created, or never ended, by the check's deadline failed (`unstarted` for
@@ -100,8 +102,8 @@ type CheckRow = {
100
102
  readonly unstarted?: true;
101
103
  };
102
104
  /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
103
- * with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate and no
104
- * failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
105
+ * with the agent's recorded answer (learn/promote.ts sameAnswer, on the bar's agree_on when it names fields), alone
106
+ * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
105
107
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
106
108
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
107
109
  * (the one write: of two claims at once, one decides). */
@@ -179,9 +181,11 @@ type ReplayView = {
179
181
  * older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
180
182
  * (missing) when the agent has no such replay. */
181
183
  export declare function replayView(ask: ReplayAsk, name: string, digest: string, id: string): Promise<ReplayView>;
182
- /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
183
- * (a CLI's record shaped as pi's), and each tool classed by the claim's MCP pin (`runId`'s, its servers' annotations as
184
- * they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one:
185
- * every write is then skipped, never run. */
186
- export declare function replayCallsFor(store: Store, runId: string, launch: RunLaunch, context: Context): Promise<ReplayCalls | undefined>;
184
+ /** A replay run's recording (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
185
+ * (a CLI's record shaped as pi's; another run's, which only a runner reads: learned-first.ts). Undefined for any other
186
+ * run. A recording that cannot be read is an empty one: every write is then skipped, never run. */
187
+ export declare function replayRecordedFor(store: Store, launch: RunLaunch, context: Context): Promise<Map<string, Recorded> | undefined>;
188
+ /** The replay's call nodes over `recorded`, each tool classed by run `runId`'s own MCP pin (its servers' annotations as
189
+ * they listed them) or the built-in list. */
190
+ export declare function replayCallsOver(store: Pick<Store, "mcp">, runId: string, recorded: ReadonlyMap<string, Recorded>): Promise<ReplayCalls>;
187
191
  export {};
@@ -9,14 +9,15 @@ import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/j
9
9
  import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
10
10
  import { isObject } from "../validate.js";
11
11
  import { agentRun, lastOwnRuns, newCompileAttempt } from "../learn/compile.js";
12
- import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, promotionOf, promotionsOf, recordPromotion, replayingOf, sameAnswer, skippedToolsOf } from "../learn/promote.js";
12
+ import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, fieldsWords, promotionOf, promotionsOf, recordPromotion, replayingOf, sameAnswer, skippedToolsOf } from "../learn/promote.js";
13
13
  import { sendCommand } from "./commands.js";
14
14
  import { ClaimRefused } from "./loop-contract.js";
15
15
  import { readSnapshot } from "../learn/folder.js";
16
16
  import { fits, laidFor, servedOf, workflowDigest } from "./workflow-first.js";
17
17
  import { excerptShown } from "../learn/secrets.js";
18
- import { dslRefusalOf } from "../learn/skills.js";
18
+ import { dslRefusalOf } from "../learn/workflow-draft.js";
19
19
  import { workflowsAt } from "./learning-seed.js";
20
+ import { held } from "./held.js";
20
21
  /** A replay run still not ended this long after its replay started counts as failed (no evidence), and is cancelled once
21
22
  * the replay is decided without it. */
22
23
  export const REPLAY_DEADLINE_MS = 60 * 60 * 1000;
@@ -182,7 +183,7 @@ async function servingNow(deps, workflow, digest, laid) {
182
183
  /** The words a hold of a serving revision this release's workflow DSL refuses starts with (holdRefused). */
183
184
  export const DSL_REFUSES = "this release's workflow DSL refuses it";
184
185
  /** `serving` as it serves this run, once a serving revision this release's workflow DSL refuses is held. The refusal is of
185
- * the text alone (learn/skills.ts dslRefusalOf: the DSL's own validation, no tool list), never of a host setting (a tool
186
+ * the text alone (learn/workflow-draft.ts dslRefusalOf: the DSL's own validation, no tool list), never of a host setting (a tool
186
187
  * gated, denied or missing, no adapter), which the run's own check still refuses as before. The hold is a promotion
187
188
  * record of its digest, `hold` by its reason alone ("this release's workflow DSL refuses it: <code> at <path>: <its
188
189
  * words>", cut of the host's secrets as a check's texts are), written only while the digest's newest record is still the
@@ -249,15 +250,12 @@ async function decide(deps, workflow, digest) {
249
250
  return startCheck(deps, workflow, digest);
250
251
  }
251
252
  /** The loop's numbers (learning-setting.ts) of the revision the claim runs: its definition's `learning`, each one it
252
- * leaves out at its default (a revision that cannot be read: every default). */
253
+ * leaves out at its default, and the answer paths its check compares on (its agree_on; none, the whole answer). A read
254
+ * that fails throws: no check is saved on defaults (a bar with no agree_on would compare the whole answer for the
255
+ * check's life); the claim's gate leaves the run to its agent and the next claim reads it again (#3182 review). */
253
256
  async function loopOfRevision(deps) {
254
- try {
255
- const revision = await deps.store.agents.revision(deps.revisionId);
256
- return loopOf(revision?.body?.learning);
257
- }
258
- catch {
259
- return loopOf(undefined);
260
- }
257
+ const revision = await deps.store.agents.revision(deps.revisionId);
258
+ return loopOf(revision?.body?.learning);
261
259
  }
262
260
  /** Which check of a compile a new revision's is: 2 when the workflow's newest record of another revision is a first
263
261
  * check's hold, an audit's hold or a hold by its reason alone (holdRefused: the DSL refuses a serving revision), or a
@@ -345,7 +343,7 @@ async function startCheck(deps, workflow, digest) {
345
343
  return;
346
344
  }
347
345
  const loop = await loopOfRevision(deps);
348
- const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, workflow.name, digest) };
346
+ const bar = { ...loop, attempt: attemptOf(records, workflow.name, digest) };
349
347
  const { inputs, looked, unfit, files } = await checkInputs(deps, workflow, { of: [], n: loop.compile_after }, auditInputsOf(records, workflow.name, digest));
350
348
  if (!inputs.length) {
351
349
  // Nothing of the agent's to check it on (a workflow landed before any run it fits): never promoted unchecked. It
@@ -367,6 +365,8 @@ async function startCheck(deps, workflow, digest) {
367
365
  }
368
366
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
369
367
  export const NOTHING_TO_CHECK = "nothing to check it on";
368
+ /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none. */
369
+ export const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word; name the fields that carry the decision (learning.agree_on)";
370
370
  /** Stops a draft its check had nothing to run on (`why`: no input of the agent's it takes, or every input skipped at a
371
371
  * write): held, never promoted unchecked, its record `stopped` (nothing compiles again until a hold or its owner acts)
372
372
  * and naming the cause, which the compile's draft errors show (store-reads/loop.ts). It asks no recompile: a revision
@@ -459,8 +459,8 @@ async function settleCheck(deps, workflow, digest, record) {
459
459
  return decided.record?.decided === "replaying" ? undefined : decided.record;
460
460
  }
461
461
  /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
462
- * with the agent's recorded answer (learn/promote.ts sameAnswer), alone when it answered it with no escalate and no
463
- * failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
462
+ * with the agent's recorded answer (learn/promote.ts sameAnswer, on the bar's agree_on when it names fields), alone
463
+ * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
464
464
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
465
465
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
466
466
  * (the one write: of two claims at once, one decides). */
@@ -468,7 +468,8 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
468
468
  const now = deps.now ?? Date.now;
469
469
  const ran = read.rows.filter((row) => row.outcome !== "skipped_write");
470
470
  const alone = (row) => row.outcome === "answered";
471
- const agrees = (row) => alone(row) && sameAnswer(row.answer, row.agent);
471
+ // Compared on the bar's agree_on when it names paths (the definition's), else the whole answer.
472
+ const agrees = (row) => alone(row) && sameAnswer(row.answer, row.agent, bar.agree_on);
472
473
  const score = { n: ran.length, agreed: ran.filter(agrees).length, alone: ran.filter(alone).length };
473
474
  const ok = checkPasses(score, bar);
474
475
  // Each text is cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown).
@@ -500,8 +501,10 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
500
501
  // and the words say none ran.
501
502
  const said = read.unstarted === score.n
502
503
  ? `none of its ${plural(score.n, "check run")} started by the check's deadline (its launch was interrupted: the server stopped after reserving it, say): nothing was checked`
503
- : `checked on ${score.n} of the agent's inputs: answered ${score.alone} alone (${pct(shares.alone)}, the bar ${pct(bar.alone_min)}), and ${score.agreed} of those said what the agent said (${pct(shares.agreement)}, the bar ${pct(bar.agree_min)})${aside ? ` (${aside})` : ""}`;
504
- const reason = ok ? `${said}: promoted` : stopped ? `${said}: held, and this was the recompile's check, so it stops: nothing compiles again until a hold or its owner acts` : `${said}: held; the agent's next run recompiles it once with the inputs it did not agree on`;
504
+ : `checked on ${score.n} of the agent's inputs: answered ${score.alone} alone (${pct(shares.alone)}, the bar ${pct(bar.alone_min)}), and ${score.agreed} of those said what the agent said${bar.agree_on?.length ? ` on ${fieldsWords(bar.agree_on)}` : ""} (${pct(shares.agreement)}, the bar ${pct(bar.agree_min)})${aside ? ` (${aside})` : ""}`;
505
+ // Compared whole and never once the same: free text two runs never repeat, most likely, so the owner is told what to set.
506
+ const verbatim = !ok && !bar.agree_on?.length && score.alone > 0 && score.agreed === 0 ? `; ${NEVER_WORD_FOR_WORD}` : "";
507
+ const reason = ok ? `${said}: promoted` : stopped ? `${said}: held${verbatim}, and this was the recompile's check, so it stops: nothing compiles again until a hold or its owner acts` : `${said}: held${verbatim}; the agent's next run recompiles it once with the inputs it did not agree on`;
505
508
  const check = { ...bar, ...score, ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}) };
506
509
  const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold", reason, check, ...seedOf(deps), ...extra }, still);
507
510
  if (decided.won)
@@ -545,7 +548,7 @@ function replayLaunchOf(deps) {
545
548
  ...(launch.learning ? { learning: launch.learning } : {}),
546
549
  ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
547
550
  };
548
- return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
551
+ return { revision: deps.revisionId, body: launchBody(base), ...((deps.sealKey || held()) && deps.runId ? { handed_from: deps.runId } : {}) };
549
552
  }
550
553
  /** Whether `was`, a digest's newest record now, is still the replay `record` reserved: replaying, under the same replay
551
554
  * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
@@ -580,8 +583,11 @@ async function cancelUnended(deps, record) {
580
583
  * logged. */
581
584
  async function handedTo(deps, launch, id) {
582
585
  const from = launch.handed_from;
583
- if (!deps.sealKey || !from)
586
+ if (!from)
584
587
  return undefined;
588
+ // A run's own process holds no seal key: its runner seals them again, from its own run alone (held.ts handOn).
589
+ if (!deps.sealKey)
590
+ return held()?.handOn(from, id);
585
591
  const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
586
592
  const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
587
593
  return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
@@ -760,10 +766,10 @@ export async function askReplay(ask, name, digest, inputs) {
760
766
  if (!picked.length)
761
767
  throw new ReplayRefused("conflict", `${name} at ${digest} has no input to replay on: none of ${typeof inputs === "number" ? `the agent's newest ${plural(inputs, "completed run")}` : last ? "the runs it was last checked on" : "the agent's last completed runs"} has an input it fits. Nothing was started.`);
762
768
  const { launch, revisionId } = await ask.launchOf(picked[0].launch.input);
763
- if (!launch.learning || launch.learning.notesOnly)
764
- throw new ReplayRefused("conflict", `A replay runs ${name} as a run of the agent that learns does, and the agent's runs do not take learned workflows here (its learning is off, notes only, or this server's is off).`);
769
+ if (!launch.learning || launch.learning.noWorkflows)
770
+ throw new ReplayRefused("conflict", `A replay runs ${name} as a run of the agent that learns does, and the agent's runs do not take learned workflows here (its learning is off, it takes no workflows, or this server's is off).`);
765
771
  const deps = { store: ask.store, agentId: ask.agentId, revisionId, launch: { ...launch, learning: { ...launch.learning, seed: found.commit } }, context: ask.context, log: ask.log, shown: ask.shown, ...(ask.now ? { now: ask.now } : {}) };
766
- const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, name, digest) };
772
+ const bar = { ...loop, attempt: attemptOf(records, name, digest) };
767
773
  const said = `checking it on ${plural(picked.length, "input")} of the agent's own runs, as its owner asked`;
768
774
  // Kept only while the revision's newest record is still the one read here: each record write stamps a new `at`.
769
775
  const reserved = await reserve(deps, found.workflow, digest, picked, said, (was) => was?.at === own?.at && was?.decided === own?.decided, bar);
@@ -818,15 +824,18 @@ export async function replayView(ask, name, digest, id) {
818
824
  }
819
825
  return checkView(ask, record, id, name, digest);
820
826
  }
821
- /** A replay run's call nodes (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
822
- * (a CLI's record shaped as pi's), and each tool classed by the claim's MCP pin (`runId`'s, its servers' annotations as
823
- * they listed them) or the built-in list. Undefined for any other run. A recording that cannot be read is an empty one:
824
- * every write is then skipped, never run. */
825
- export async function replayCallsFor(store, runId, launch, context) {
827
+ /** A replay run's recording (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
828
+ * (a CLI's record shaped as pi's; another run's, which only a runner reads: learned-first.ts). Undefined for any other
829
+ * run. A recording that cannot be read is an empty one: every write is then skipped, never run. */
830
+ export async function replayRecordedFor(store, launch, context) {
826
831
  if (!launch.replay)
827
832
  return undefined;
828
833
  const entries = await runEntries(store, launch.replay.of, context).catch(() => []);
829
- const recorded = recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
834
+ return recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
835
+ }
836
+ /** The replay's call nodes over `recorded`, each tool classed by run `runId`'s own MCP pin (its servers' annotations as
837
+ * they listed them) or the built-in list. */
838
+ export async function replayCallsOver(store, runId, recorded) {
830
839
  const pin = (await store.mcp.pin(runId).catch(() => undefined))?.body;
831
840
  const annotations = pinAnnotations(pin);
832
841
  return replayCalls(recorded, (tool) => toolClassOf(tool, annotations));