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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +131 -5
  2. package/README.md +371 -300
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +52 -16
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  39. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/key-check.js +3 -0
  64. package/dist/learn/audit.d.ts +6 -6
  65. package/dist/learn/audit.js +3 -7
  66. package/dist/learn/check.d.ts +23 -89
  67. package/dist/learn/check.js +57 -335
  68. package/dist/learn/commit.d.ts +63 -90
  69. package/dist/learn/commit.js +124 -316
  70. package/dist/learn/compile.d.ts +53 -50
  71. package/dist/learn/compile.js +87 -102
  72. package/dist/learn/corrections.d.ts +13 -0
  73. package/dist/learn/corrections.js +23 -0
  74. package/dist/learn/delete.d.ts +5 -5
  75. package/dist/learn/delete.js +8 -10
  76. package/dist/learn/folder.d.ts +35 -47
  77. package/dist/learn/folder.js +118 -134
  78. package/dist/learn/index.d.ts +3 -5
  79. package/dist/learn/index.js +6 -9
  80. package/dist/learn/learning.sh +45 -15
  81. package/dist/learn/promote.d.ts +13 -1
  82. package/dist/learn/promote.js +9 -0
  83. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  84. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  85. package/dist/learn/workflow-nodes.js +1 -1
  86. package/dist/learned-workflow.js +2 -2
  87. package/dist/learning-cost.d.ts +38 -24
  88. package/dist/learning-cost.js +41 -24
  89. package/dist/learning-routes.d.ts +91 -170
  90. package/dist/learning-routes.js +183 -421
  91. package/dist/learning-run.d.ts +19 -40
  92. package/dist/learning-run.js +23 -93
  93. package/dist/learning-setting.d.ts +4 -4
  94. package/dist/learning-setting.js +6 -6
  95. package/dist/learning-words.d.ts +28 -74
  96. package/dist/learning-words.js +64 -162
  97. package/dist/learning.d.ts +61 -392
  98. package/dist/learning.js +101 -651
  99. package/dist/live-reach.d.ts +25 -2
  100. package/dist/live-reach.js +46 -4
  101. package/dist/llms.txt +1 -1
  102. package/dist/local-models.d.ts +3 -11
  103. package/dist/local-models.js +5 -6
  104. package/dist/mcp-servers-store.d.ts +4 -4
  105. package/dist/model-form.js +6 -5
  106. package/dist/model.d.ts +4 -0
  107. package/dist/model.js +26 -9
  108. package/dist/native/binding.js +1 -1
  109. package/dist/native/connection.js +1 -1
  110. package/dist/native/discovery.js +1 -1
  111. package/dist/native/instructions.d.ts +3 -0
  112. package/dist/native/instructions.js +5 -3
  113. package/dist/native/remote-worker-bridge.js +9 -43
  114. package/dist/native/remote.d.ts +8 -15
  115. package/dist/native/remote.js +3 -3
  116. package/dist/native/schema.js +1 -1
  117. package/dist/native/types.d.ts +2 -2
  118. package/dist/openapi.js +268 -316
  119. package/dist/paid-calls.d.ts +8 -0
  120. package/dist/paid-calls.js +20 -0
  121. package/dist/particle-provider.d.ts +11 -0
  122. package/dist/particle-provider.js +135 -0
  123. package/dist/port-models.d.ts +12 -4
  124. package/dist/port-models.js +28 -11
  125. package/dist/print.d.ts +27 -0
  126. package/dist/print.js +21 -0
  127. package/dist/provider.d.ts +7 -0
  128. package/dist/provider.js +15 -1
  129. package/dist/reflect-range.js +2 -3
  130. package/dist/run-launch.d.ts +14 -28
  131. package/dist/run-launch.js +9 -12
  132. package/dist/run-learning-served.d.ts +15 -89
  133. package/dist/run-listing.d.ts +34 -0
  134. package/dist/run-listing.js +128 -0
  135. package/dist/run-model-key.js +1 -1
  136. package/dist/run-timeline-served.js +5 -3
  137. package/dist/run-trace.d.ts +97 -0
  138. package/dist/run-trace.js +253 -0
  139. package/dist/run-view.d.ts +15 -0
  140. package/dist/run-view.js +9 -0
  141. package/dist/runnable.js +2 -1
  142. package/dist/runner/adapter-loop.d.ts +8 -6
  143. package/dist/runner/adapter-loop.js +16 -12
  144. package/dist/runner/adapter-run-spec.d.ts +16 -4
  145. package/dist/runner/adapter-run-spec.js +64 -58
  146. package/dist/runner/adapters/index.js +22 -0
  147. package/dist/runner/adapters/pi.d.ts +4 -12
  148. package/dist/runner/adapters/pi.js +2 -2
  149. package/dist/runner/audit.d.ts +1 -1
  150. package/dist/runner/audit.js +16 -8
  151. package/dist/runner/beside.d.ts +6 -2
  152. package/dist/runner/beside.js +38 -9
  153. package/dist/runner/claim-secrets.d.ts +18 -2
  154. package/dist/runner/claim-secrets.js +42 -18
  155. package/dist/runner/cli-run-spec.js +55 -51
  156. package/dist/runner/conformance/harness.d.ts +6 -0
  157. package/dist/runner/conformance/harness.js +16 -5
  158. package/dist/runner/dispatch.d.ts +2 -2
  159. package/dist/runner/end-of-run.d.ts +6 -14
  160. package/dist/runner/end-of-run.js +8 -33
  161. package/dist/runner/feedback-round.d.ts +2 -2
  162. package/dist/runner/feedback-round.js +7 -7
  163. package/dist/runner/github-app.js +3 -1
  164. package/dist/runner/harness-loops.d.ts +0 -8
  165. package/dist/runner/harness-loops.js +11 -59
  166. package/dist/runner/held.d.ts +170 -0
  167. package/dist/runner/held.js +57 -0
  168. package/dist/runner/journal-kinds.d.ts +2 -3
  169. package/dist/runner/journal-kinds.js +2 -3
  170. package/dist/runner/learned-first.d.ts +40 -0
  171. package/dist/runner/learned-first.js +32 -0
  172. package/dist/runner/learning-end.d.ts +77 -69
  173. package/dist/runner/learning-end.js +250 -303
  174. package/dist/runner/learning-seed.d.ts +15 -33
  175. package/dist/runner/learning-seed.js +24 -45
  176. package/dist/runner/loop-contract.d.ts +2 -3
  177. package/dist/runner/main.d.ts +17 -9
  178. package/dist/runner/main.js +63 -20
  179. package/dist/runner/mcp-run.d.ts +11 -0
  180. package/dist/runner/mcp-run.js +67 -0
  181. package/dist/runner/memory-claim.d.ts +10 -5
  182. package/dist/runner/memory-claim.js +12 -6
  183. package/dist/runner/model-route.d.ts +7 -4
  184. package/dist/runner/model-route.js +22 -10
  185. package/dist/runner/native-loop.d.ts +0 -7
  186. package/dist/runner/native-loop.js +9 -101
  187. package/dist/runner/promotion.d.ts +8 -6
  188. package/dist/runner/promotion.js +19 -12
  189. package/dist/runner/reflect-hook.d.ts +64 -95
  190. package/dist/runner/reflect-hook.js +112 -225
  191. package/dist/runner/run-channel.d.ts +43 -0
  192. package/dist/runner/run-channel.js +467 -0
  193. package/dist/runner/run-child-host.d.ts +169 -0
  194. package/dist/runner/run-child-host.js +1222 -0
  195. package/dist/runner/run-child.d.ts +1 -0
  196. package/dist/runner/run-child.js +254 -0
  197. package/dist/runner/run-errors.d.ts +2 -0
  198. package/dist/runner/run-errors.js +20 -0
  199. package/dist/runner/runner.js +1 -5
  200. package/dist/runner/sdk-ask.d.ts +78 -0
  201. package/dist/runner/sdk-ask.js +158 -0
  202. package/dist/runner/sdk-loop.d.ts +2 -4
  203. package/dist/runner/sdk-loop.js +29 -49
  204. package/dist/runner/store-secrets.d.ts +5 -3
  205. package/dist/runner/store-secrets.js +5 -1
  206. package/dist/runner/workflow-first.d.ts +5 -0
  207. package/dist/runner/workflow-first.js +4 -0
  208. package/dist/runner/workflow-spec.js +7 -2
  209. package/dist/runs-over-store.d.ts +16 -28
  210. package/dist/runs-over-store.js +31 -38
  211. package/dist/sdk/runs.d.ts +6 -11
  212. package/dist/sdk/runs.js +20 -41
  213. package/dist/sdk/schema.js +3 -4
  214. package/dist/seal-key.d.ts +5 -0
  215. package/dist/seal-key.js +7 -0
  216. package/dist/secrets.d.ts +3 -0
  217. package/dist/secrets.js +16 -3
  218. package/dist/server.d.ts +55 -33
  219. package/dist/server.js +685 -320
  220. package/dist/sign-ins-store.d.ts +8 -0
  221. package/dist/sign-ins-store.js +36 -1
  222. package/dist/skills.js +1 -1
  223. package/dist/store/index.d.ts +2 -2
  224. package/dist/store/index.js +1 -1
  225. package/dist/store/journal/storage.js +3 -0
  226. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  227. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  228. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  229. package/dist/store/schema.d.ts +53 -4
  230. package/dist/store/schema.js +137 -6
  231. package/dist/store/sqlite/connection.d.ts +2 -0
  232. package/dist/store/sqlite/connection.js +3 -1
  233. package/dist/store/sqlite/run-patch.d.ts +0 -17
  234. package/dist/store/sqlite/run-patch.js +4 -33
  235. package/dist/store/sqlite/store.js +246 -63
  236. package/dist/store/sqlite/worker.js +25 -0
  237. package/dist/store/store.d.ts +193 -36
  238. package/dist/store/store.js +25 -3
  239. package/dist/store-reads/learning.d.ts +102 -204
  240. package/dist/store-reads/learning.js +159 -321
  241. package/dist/store-reads/loop.d.ts +0 -1
  242. package/dist/store-reads/loop.js +1 -1
  243. package/dist/store-view.d.ts +29 -1
  244. package/dist/store-view.js +97 -31
  245. package/dist/template-eval.d.ts +3 -6
  246. package/dist/template-eval.js +22 -36
  247. package/dist/templates.d.ts +2 -1
  248. package/dist/templates.js +6 -3
  249. package/dist/timeline/index.d.ts +1 -1
  250. package/dist/timeline/index.js +1 -1
  251. package/dist/timeline/timeline.d.ts +5 -1
  252. package/dist/timeline/timeline.js +16 -0
  253. package/dist/tool-gate.d.ts +0 -7
  254. package/dist/tool-gate.js +1 -15
  255. package/dist/tool-keys-store.d.ts +1 -1
  256. package/dist/tool-keys.d.ts +6 -4
  257. package/dist/tool-keys.js +12 -6
  258. package/dist/tools.d.ts +2 -2
  259. package/dist/tools.js +11 -4
  260. package/dist/triggers.d.ts +60 -5
  261. package/dist/triggers.js +123 -18
  262. package/dist/validate.js +1 -1
  263. package/dist/webhooks.d.ts +4 -1
  264. package/dist/webhooks.js +11 -4
  265. package/dist/workspace/agent-computer.d.ts +2 -0
  266. package/dist/workspace/agent-computer.js +2 -0
  267. package/dist/workspace/archil-claim.d.ts +7 -0
  268. package/dist/workspace/archil-claim.js +29 -0
  269. package/dist/workspace/archil.d.ts +9 -1
  270. package/dist/workspace/archil.js +165 -3
  271. package/dist/workspace/attach.d.ts +3 -1
  272. package/dist/workspace/attach.js +2 -0
  273. package/dist/workspace/attached-computers.d.ts +16 -5
  274. package/dist/workspace/attached-computers.js +25 -9
  275. package/dist/workspace/computer-deps.js +1 -1
  276. package/dist/workspace/computer-for-claim.d.ts +7 -3
  277. package/dist/workspace/computer-for-claim.js +119 -22
  278. package/dist/workspace/computer-hold.js +2 -1
  279. package/dist/workspace/computer-kept.d.ts +11 -1
  280. package/dist/workspace/computer-kept.js +24 -3
  281. package/dist/workspace/resolve-computer.d.ts +33 -19
  282. package/dist/workspace/resolve-computer.js +172 -64
  283. package/dist/workspace/revision-skills.d.ts +1 -2
  284. package/dist/workspace/revision-skills.js +3 -4
  285. package/dist/workspace/run-workspace.d.ts +1 -1
  286. package/dist/workspace/run-workspace.js +5 -0
  287. package/dist/workspace/synced-folder.d.ts +85 -0
  288. package/dist/workspace/synced-folder.js +230 -0
  289. package/dist/workspace/workspace.d.ts +4 -0
  290. package/launcher/agentrun-serve +1 -1
  291. package/package.json +10 -10
  292. package/templates/README.md +7 -7
  293. package/templates/inbound-lead/agent.md +3 -3
  294. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  295. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  296. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  297. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  298. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  299. package/templates/inbound-lead/lead.schema.json +6 -5
  300. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  301. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  302. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  303. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  304. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  305. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  306. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  307. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  308. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  309. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  310. package/dist/console/assets/index-BUktRvS-.css +0 -1
  311. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  312. package/dist/learn/grade.d.ts +0 -138
  313. package/dist/learn/grade.js +0 -682
  314. package/dist/learn/notes.d.ts +0 -81
  315. package/dist/learn/notes.js +0 -178
  316. package/dist/learn/reflect.d.ts +0 -77
  317. package/dist/learn/reflect.js +0 -228
  318. package/dist/learn/relevance.d.ts +0 -24
  319. package/dist/learn/relevance.js +0 -91
  320. package/dist/learn/seed-check.d.ts +0 -74
  321. package/dist/learn/seed-check.js +0 -103
  322. package/dist/learning-batch.d.ts +0 -291
  323. package/dist/learning-batch.js +0 -600
  324. package/dist/learning-evals.d.ts +0 -35
  325. package/dist/learning-evals.js +0 -99
  326. package/dist/native/context.d.ts +0 -6
  327. package/dist/native/context.js +0 -22
  328. package/dist/propose.d.ts +0 -52
  329. package/dist/propose.js +0 -224
  330. package/dist/runner/learning-ask.d.ts +0 -47
  331. package/dist/runner/learning-ask.js +0 -128
  332. package/dist/runner/learning-dispatch.d.ts +0 -45
  333. package/dist/runner/learning-dispatch.js +0 -99
  334. package/dist/runner/learning-factory.d.ts +0 -16
  335. package/dist/runner/learning-factory.js +0 -50
  336. package/dist/runner/learning-loop.d.ts +0 -273
  337. package/dist/runner/learning-loop.js +0 -521
  338. package/dist/usage.d.ts +0 -11
  339. package/dist/usage.js +0 -11
  340. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  341. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  342. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  343. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  344. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  345. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  346. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -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";
@@ -179,9 +179,11 @@ type ReplayView = {
179
179
  * older, held one) is decided too, and never running forever. Once decided, it reads only its record. Refused
180
180
  * (missing) when the agent has no such replay. */
181
181
  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>;
182
+ /** A replay run's recording (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; another run's, which only a runner reads: learned-first.ts). Undefined for any other
184
+ * run. A recording that cannot be read is an empty one: every write is then skipped, never run. */
185
+ export declare function replayRecordedFor(store: Store, launch: RunLaunch, context: Context): Promise<Map<string, Recorded> | undefined>;
186
+ /** The replay's call nodes over `recorded`, each tool classed by run `runId`'s own MCP pin (its servers' annotations as
187
+ * they listed them) or the built-in list. */
188
+ export declare function replayCallsOver(store: Pick<Store, "mcp">, runId: string, recorded: ReadonlyMap<string, Recorded>): Promise<ReplayCalls>;
187
189
  export {};
@@ -15,8 +15,9 @@ 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
@@ -545,7 +546,7 @@ function replayLaunchOf(deps) {
545
546
  ...(launch.learning ? { learning: launch.learning } : {}),
546
547
  ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
547
548
  };
548
- return { revision: deps.revisionId, body: launchBody(base), ...(deps.sealKey && deps.runId ? { handed_from: deps.runId } : {}) };
549
+ return { revision: deps.revisionId, body: launchBody(base), ...((deps.sealKey || held()) && deps.runId ? { handed_from: deps.runId } : {}) };
549
550
  }
550
551
  /** Whether `was`, a digest's newest record now, is still the replay `record` reserved: replaying, under the same replay
551
552
  * id. A replay settled meanwhile, and a newer replay of the same revision its owner started since (a held revision may
@@ -580,8 +581,11 @@ async function cancelUnended(deps, record) {
580
581
  * logged. */
581
582
  async function handedTo(deps, launch, id) {
582
583
  const from = launch.handed_from;
583
- if (!deps.sealKey || !from)
584
+ if (!from)
584
585
  return undefined;
586
+ // A run's own process holds no seal key: its runner seals them again, from its own run alone (held.ts handOn).
587
+ if (!deps.sealKey)
588
+ return held()?.handOn(from, id);
585
589
  const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
586
590
  const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
587
591
  return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
@@ -760,8 +764,8 @@ export async function askReplay(ask, name, digest, inputs) {
760
764
  if (!picked.length)
761
765
  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
766
  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).`);
767
+ if (!launch.learning || launch.learning.noWorkflows)
768
+ 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
769
  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
770
  const bar = { compile_after: loop.compile_after, agree_min: loop.agree_min, alone_min: loop.alone_min, attempt: attemptOf(records, name, digest) };
767
771
  const said = `checking it on ${plural(picked.length, "input")} of the agent's own runs, as its owner asked`;
@@ -818,15 +822,18 @@ export async function replayView(ask, name, digest, id) {
818
822
  }
819
823
  return checkView(ask, record, id, name, digest);
820
824
  }
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) {
825
+ /** A replay run's recording (launch.replay; learn/replay-calls.ts): the agent run's recorded calls, read from its journal
826
+ * (a CLI's record shaped as pi's; another run's, which only a runner reads: learned-first.ts). Undefined for any other
827
+ * run. A recording that cannot be read is an empty one: every write is then skipped, never run. */
828
+ export async function replayRecordedFor(store, launch, context) {
826
829
  if (!launch.replay)
827
830
  return undefined;
828
831
  const entries = await runEntries(store, launch.replay.of, context).catch(() => []);
829
- const recorded = recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
832
+ return recordedCalls(isCliRecord(entries) ? piShaped(entries) : entries);
833
+ }
834
+ /** The replay's call nodes over `recorded`, each tool classed by run `runId`'s own MCP pin (its servers' annotations as
835
+ * they listed them) or the built-in list. */
836
+ export async function replayCallsOver(store, runId, recorded) {
830
837
  const pin = (await store.mcp.pin(runId).catch(() => undefined))?.body;
831
838
  const annotations = pinAnnotations(pin);
832
839
  return replayCalls(recorded, (tool) => toolClassOf(tool, annotations));