@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.34

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 (381) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +266 -201
  3. package/dist/adapters.d.ts +0 -4
  4. package/dist/adapters.js +11 -15
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/bash-read-only.d.ts +22 -0
  16. package/dist/bash-read-only.js +701 -0
  17. package/dist/box-settings.d.ts +3 -23
  18. package/dist/box-settings.js +7 -51
  19. package/dist/boxes.d.ts +17 -0
  20. package/dist/boxes.js +27 -20
  21. package/dist/browser-commands.d.ts +5 -2
  22. package/dist/browser-commands.js +4 -4
  23. package/dist/browser-computer.d.ts +5 -0
  24. package/dist/browser-computer.js +21 -0
  25. package/dist/browser-cost.d.ts +9 -6
  26. package/dist/browser-cost.js +92 -50
  27. package/dist/browser-live.d.ts +7 -20
  28. package/dist/browser-live.js +15 -93
  29. package/dist/browser-person.d.ts +18 -51
  30. package/dist/browser-person.js +94 -277
  31. package/dist/cap.d.ts +8 -5
  32. package/dist/cap.js +12 -5
  33. package/dist/cli.js +39 -13
  34. package/dist/closed-pipes.d.ts +2 -0
  35. package/dist/closed-pipes.js +13 -0
  36. package/dist/computer-commands.d.ts +2 -0
  37. package/dist/computer-commands.js +2 -0
  38. package/dist/computer-keys.js +5 -2
  39. package/dist/computer-setting.d.ts +20 -4
  40. package/dist/computer-setting.js +25 -5
  41. package/dist/computers.d.ts +30 -2
  42. package/dist/computers.js +70 -11
  43. package/dist/confine.d.ts +120 -0
  44. package/dist/confine.js +436 -0
  45. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  46. package/dist/console/assets/index-opTN5Naq.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decision-rows.d.ts +1 -1
  49. package/dist/decision-rows.js +1 -1
  50. package/dist/docker-daemon.d.ts +31 -0
  51. package/dist/docker-daemon.js +56 -0
  52. package/dist/effort-guidance.js +4 -3
  53. package/dist/environment.d.ts +0 -3
  54. package/dist/environment.js +3 -5
  55. package/dist/errors.d.ts +0 -2
  56. package/dist/errors.js +6 -9
  57. package/dist/filed-answer.d.ts +32 -0
  58. package/dist/filed-answer.js +160 -0
  59. package/dist/files.d.ts +1 -3
  60. package/dist/files.js +2 -4
  61. package/dist/github-connection.d.ts +1 -1
  62. package/dist/graph-view.d.ts +3 -5
  63. package/dist/graph-view.js +4 -14
  64. package/dist/handed-values.d.ts +9 -0
  65. package/dist/handed-values.js +26 -0
  66. package/dist/harness-install.d.ts +1 -7
  67. package/dist/harness-install.js +1 -18
  68. package/dist/harness-opencode/adapter.d.ts +7 -0
  69. package/dist/harness-opencode/adapter.js +23 -6
  70. package/dist/harness-opencode/index.d.ts +1 -1
  71. package/dist/harness-opencode/index.js +1 -1
  72. package/dist/harness-opencode/verify.d.ts +17 -0
  73. package/dist/harness-opencode/verify.js +30 -10
  74. package/dist/harness-table.js +6 -1
  75. package/dist/heard.js +1 -1
  76. package/dist/held-fd.d.ts +5 -0
  77. package/dist/held-fd.js +14 -0
  78. package/dist/host-calls.d.ts +20 -0
  79. package/dist/host-calls.js +12 -0
  80. package/dist/host-tools.d.ts +4 -21
  81. package/dist/host-tools.js +4 -61
  82. package/dist/host.d.ts +2 -4
  83. package/dist/host.js +2 -7
  84. package/dist/import-summary.d.ts +1 -5
  85. package/dist/import-summary.js +0 -21
  86. package/dist/import.d.ts +6 -6
  87. package/dist/import.js +14 -15
  88. package/dist/key-refusal.d.ts +5 -1
  89. package/dist/key-refusal.js +19 -4
  90. package/dist/learn/check.d.ts +6 -2
  91. package/dist/learn/check.js +83 -29
  92. package/dist/learn/folder.d.ts +5 -1
  93. package/dist/learn/folder.js +10 -3
  94. package/dist/learn/grade.d.ts +14 -0
  95. package/dist/learn/grade.js +68 -12
  96. package/dist/learn/index.d.ts +4 -4
  97. package/dist/learn/index.js +4 -4
  98. package/dist/learn/reflect.d.ts +31 -2
  99. package/dist/learn/reflect.js +79 -4
  100. package/dist/learn/relevance.d.ts +24 -0
  101. package/dist/learn/relevance.js +91 -0
  102. package/dist/learn/secrets.d.ts +7 -1
  103. package/dist/learn/secrets.js +86 -19
  104. package/dist/learn/skills.d.ts +112 -14
  105. package/dist/learn/skills.js +556 -52
  106. package/dist/learned-workflow.d.ts +32 -1
  107. package/dist/learned-workflow.js +100 -9
  108. package/dist/learning-routes.d.ts +8 -4
  109. package/dist/learning-routes.js +23 -9
  110. package/dist/learning-run.d.ts +9 -26
  111. package/dist/learning-run.js +22 -32
  112. package/dist/learning-words.d.ts +12 -5
  113. package/dist/learning-words.js +18 -9
  114. package/dist/learning.d.ts +93 -77
  115. package/dist/learning.js +176 -304
  116. package/dist/live/stream.js +1 -1
  117. package/dist/live/translate.js +12 -2
  118. package/dist/local-models.d.ts +11 -5
  119. package/dist/local-models.js +13 -8
  120. package/dist/mcp-gateway.d.ts +11 -49
  121. package/dist/mcp-gateway.js +44 -135
  122. package/dist/mcp-oauth.d.ts +10 -14
  123. package/dist/mcp-oauth.js +14 -32
  124. package/dist/mcp-probe.d.ts +0 -7
  125. package/dist/mcp-probe.js +4 -10
  126. package/dist/mcp-servers-store.d.ts +6 -6
  127. package/dist/mcp-servers-store.js +12 -14
  128. package/dist/mcp-store.js +3 -4
  129. package/dist/mcp.js +4 -3
  130. package/dist/model.d.ts +6 -7
  131. package/dist/model.js +43 -27
  132. package/dist/monid.d.ts +0 -2
  133. package/dist/monid.js +3 -6
  134. package/dist/openapi.d.ts +8 -1
  135. package/dist/openapi.js +121 -47
  136. package/dist/page.d.ts +1 -3
  137. package/dist/page.js +6 -18
  138. package/dist/paid-calls.d.ts +21 -27
  139. package/dist/paid-calls.js +25 -60
  140. package/dist/propose.js +83 -39
  141. package/dist/push-handler.d.ts +1 -1
  142. package/dist/reflect-range.d.ts +25 -0
  143. package/dist/reflect-range.js +30 -0
  144. package/dist/refusal-words.d.ts +5 -1
  145. package/dist/refusal-words.js +5 -1
  146. package/dist/rows.d.ts +1 -1
  147. package/dist/run-cut.d.ts +0 -6
  148. package/dist/run-cut.js +0 -6
  149. package/dist/run-db.d.ts +2 -11
  150. package/dist/run-db.js +2 -37
  151. package/dist/run-launch.d.ts +19 -2
  152. package/dist/run-launch.js +13 -5
  153. package/dist/run-learning-served.d.ts +10 -4
  154. package/dist/run-learning-served.js +23 -13
  155. package/dist/run-reads-over-store.d.ts +1 -1
  156. package/dist/run-reads-over-store.js +15 -6
  157. package/dist/run-secrets.d.ts +1 -1
  158. package/dist/run-timeline-served.d.ts +5 -1
  159. package/dist/run-timeline-served.js +15 -4
  160. package/dist/run-view.d.ts +7 -8
  161. package/dist/run-view.js +26 -7
  162. package/dist/runnable.d.ts +18 -10
  163. package/dist/runnable.js +21 -10
  164. package/dist/runner/adapter-loop.d.ts +6 -1
  165. package/dist/runner/adapter-loop.js +423 -53
  166. package/dist/runner/adapter-run-spec.d.ts +21 -8
  167. package/dist/runner/adapter-run-spec.js +90 -32
  168. package/dist/runner/adapters/index.js +11 -1
  169. package/dist/runner/adapters/pi.d.ts +12 -2
  170. package/dist/runner/adapters/pi.js +16 -5
  171. package/dist/runner/beside.d.ts +30 -3
  172. package/dist/runner/beside.js +36 -5
  173. package/dist/runner/claim-secrets.d.ts +10 -1
  174. package/dist/runner/claim-secrets.js +48 -14
  175. package/dist/runner/cli-run-spec.d.ts +2 -0
  176. package/dist/runner/cli-run-spec.js +45 -16
  177. package/dist/runner/commands.js +1 -1
  178. package/dist/runner/computer-journal.d.ts +15 -2
  179. package/dist/runner/computer-journal.js +41 -5
  180. package/dist/runner/conformance/harness.js +118 -8
  181. package/dist/runner/conformance/subject.d.ts +4 -1
  182. package/dist/runner/dispatch.d.ts +8 -1
  183. package/dist/runner/dispatch.js +81 -7
  184. package/dist/runner/end-of-run.d.ts +8 -2
  185. package/dist/runner/end-of-run.js +10 -4
  186. package/dist/runner/github-app.js +1 -1
  187. package/dist/runner/harness-loops.d.ts +9 -1
  188. package/dist/runner/harness-loops.js +15 -2
  189. package/dist/runner/journal-kinds.d.ts +24 -6
  190. package/dist/runner/journal-kinds.js +20 -5
  191. package/dist/runner/journal-reader.d.ts +1 -1
  192. package/dist/runner/journal-reader.js +2 -2
  193. package/dist/runner/learning-ask.d.ts +4 -0
  194. package/dist/runner/learning-ask.js +15 -1
  195. package/dist/runner/learning-end.d.ts +18 -3
  196. package/dist/runner/learning-end.js +113 -11
  197. package/dist/runner/learning-loop.d.ts +5 -0
  198. package/dist/runner/learning-loop.js +26 -6
  199. package/dist/runner/main.d.ts +56 -9
  200. package/dist/runner/main.js +127 -18
  201. package/dist/runner/mcp-claim.js +1 -2
  202. package/dist/runner/mcp-run.d.ts +2 -0
  203. package/dist/runner/mcp-run.js +15 -5
  204. package/dist/runner/memory-claim.d.ts +9 -0
  205. package/dist/runner/memory-claim.js +25 -0
  206. package/dist/runner/metrics.d.ts +33 -1
  207. package/dist/runner/metrics.js +85 -1
  208. package/dist/runner/model-route.d.ts +13 -0
  209. package/dist/runner/model-route.js +133 -9
  210. package/dist/runner/reflect-hook.d.ts +12 -1
  211. package/dist/runner/reflect-hook.js +33 -3
  212. package/dist/runner/runner.d.ts +20 -0
  213. package/dist/runner/runner.js +56 -10
  214. package/dist/runner/store-port.d.ts +1 -1
  215. package/dist/runner/store-secrets.d.ts +3 -3
  216. package/dist/runner/store-secrets.js +8 -12
  217. package/dist/runner/text-tools.d.ts +44 -0
  218. package/dist/runner/text-tools.js +237 -0
  219. package/dist/runner/workflow-loop.d.ts +6 -0
  220. package/dist/runner/workflow-loop.js +6 -4
  221. package/dist/runner/workflow-spec.d.ts +18 -0
  222. package/dist/runner/workflow-spec.js +63 -17
  223. package/dist/runs-over-store.d.ts +7 -2
  224. package/dist/runs-over-store.js +60 -14
  225. package/dist/seal-key.js +5 -43
  226. package/dist/sealed-settings-store.d.ts +19 -4
  227. package/dist/sealed-settings-store.js +9 -9
  228. package/dist/sealing.d.ts +4 -0
  229. package/dist/sealing.js +20 -0
  230. package/dist/secret-cut.d.ts +1 -1
  231. package/dist/secret-cut.js +1 -1
  232. package/dist/secret-name.d.ts +9 -0
  233. package/dist/secret-name.js +15 -0
  234. package/dist/secret-writes.d.ts +0 -1
  235. package/dist/secret-writes.js +0 -1
  236. package/dist/server-fs.d.ts +4 -0
  237. package/dist/server-fs.js +8 -2
  238. package/dist/server-lock.d.ts +0 -24
  239. package/dist/server-lock.js +1 -80
  240. package/dist/server-secrets-store.d.ts +4 -4
  241. package/dist/server-secrets-store.js +9 -31
  242. package/dist/server-secrets.d.ts +4 -9
  243. package/dist/server-secrets.js +12 -36
  244. package/dist/server.d.ts +16 -38
  245. package/dist/server.js +145 -106
  246. package/dist/sign-ins-store.d.ts +34 -36
  247. package/dist/sign-ins-store.js +27 -38
  248. package/dist/sign-ins.d.ts +2 -119
  249. package/dist/sign-ins.js +5 -311
  250. package/dist/standard-webhooks.d.ts +1 -1
  251. package/dist/standard-webhooks.js +1 -1
  252. package/dist/stats.d.ts +3 -2
  253. package/dist/stats.js +1 -1
  254. package/dist/store/agent-body.d.ts +8 -2
  255. package/dist/store/agent-body.js +16 -4
  256. package/dist/store/index.d.ts +2 -2
  257. package/dist/store/index.js +2 -2
  258. package/dist/store/open.d.ts +6 -3
  259. package/dist/store/open.js +2 -2
  260. package/dist/store/postgres/connection.d.ts +18 -2
  261. package/dist/store/postgres/connection.js +156 -32
  262. package/dist/store/postgres/migrate.d.ts +4 -0
  263. package/dist/store/postgres/migrate.js +9 -2
  264. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  265. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  266. package/dist/store/postgres/store.d.ts +9 -2
  267. package/dist/store/postgres/store.js +9 -0
  268. package/dist/store/schema.js +1 -1
  269. package/dist/store/seal.js +2 -2
  270. package/dist/store/sqlite/connection.js +49 -5
  271. package/dist/store/sqlite/run-patch.d.ts +3 -0
  272. package/dist/store/sqlite/run-patch.js +3 -0
  273. package/dist/store/sqlite/store.js +41 -12
  274. package/dist/store/store.d.ts +35 -6
  275. package/dist/store/store.js +12 -2
  276. package/dist/store-reads/cap.d.ts +1 -1
  277. package/dist/store-reads/cap.js +22 -4
  278. package/dist/store-reads/journal.d.ts +9 -6
  279. package/dist/store-reads/journal.js +93 -17
  280. package/dist/store-reads/learning.d.ts +26 -8
  281. package/dist/store-reads/learning.js +12 -4
  282. package/dist/store-reads/workflow.d.ts +1 -1
  283. package/dist/store-reads/workflow.js +1 -1
  284. package/dist/store-view.d.ts +5 -1
  285. package/dist/store-view.js +53 -18
  286. package/dist/template-eval.d.ts +60 -4
  287. package/dist/template-eval.js +120 -54
  288. package/dist/templates.d.ts +24 -10
  289. package/dist/templates.js +69 -38
  290. package/dist/timeline/group.d.ts +33 -0
  291. package/dist/timeline/group.js +77 -0
  292. package/dist/timeline/index.d.ts +7 -0
  293. package/dist/timeline/index.js +7 -0
  294. package/dist/timeline/labels.d.ts +79 -0
  295. package/dist/timeline/labels.js +150 -0
  296. package/dist/timeline/origin.d.ts +56 -0
  297. package/dist/timeline/origin.js +92 -0
  298. package/dist/timeline/render-text.d.ts +11 -0
  299. package/dist/timeline/render-text.js +62 -0
  300. package/dist/timeline/timeline.d.ts +274 -0
  301. package/dist/timeline/timeline.js +1308 -0
  302. package/dist/timeline/util.d.ts +17 -0
  303. package/dist/timeline/util.js +49 -0
  304. package/dist/tool-gate.d.ts +41 -216
  305. package/dist/tool-gate.js +79 -540
  306. package/dist/tool-keys-store.d.ts +11 -12
  307. package/dist/tool-keys-store.js +24 -31
  308. package/dist/tool-keys.d.ts +5 -101
  309. package/dist/tool-keys.js +8 -267
  310. package/dist/tool-plane.d.ts +14 -42
  311. package/dist/tool-plane.js +23 -81
  312. package/dist/tool-settings-store.d.ts +1 -2
  313. package/dist/tool-settings-store.js +5 -8
  314. package/dist/tools.d.ts +30 -18
  315. package/dist/tools.js +97 -107
  316. package/dist/trigger-adapter.d.ts +2 -2
  317. package/dist/trigger-targets.d.ts +13 -1
  318. package/dist/trigger-targets.js +31 -1
  319. package/dist/triggers.d.ts +2 -2
  320. package/dist/triggers.js +3 -3
  321. package/dist/turn-end.d.ts +1 -1
  322. package/dist/turn-end.js +1 -1
  323. package/dist/turns.d.ts +0 -6
  324. package/dist/turns.js +0 -19
  325. package/dist/uploads.js +1 -1
  326. package/dist/usage.d.ts +0 -2
  327. package/dist/usage.js +0 -2
  328. package/dist/validate.d.ts +2 -0
  329. package/dist/validate.js +23 -14
  330. package/dist/webhooks.d.ts +102 -76
  331. package/dist/webhooks.js +266 -233
  332. package/dist/workflow-run.d.ts +114 -0
  333. package/dist/workflow-run.js +144 -0
  334. package/dist/workspace/beneath.d.ts +19 -0
  335. package/dist/workspace/beneath.js +106 -0
  336. package/dist/workspace/computer-deps.d.ts +24 -6
  337. package/dist/workspace/computer-deps.js +108 -20
  338. package/dist/workspace/computer-for-claim.d.ts +12 -11
  339. package/dist/workspace/computer-for-claim.js +76 -15
  340. package/dist/workspace/computer-hold.d.ts +6 -1
  341. package/dist/workspace/computer-hold.js +6 -1
  342. package/dist/workspace/computer-janitor.d.ts +47 -0
  343. package/dist/workspace/computer-janitor.js +182 -0
  344. package/dist/workspace/grep-worker.d.ts +5 -0
  345. package/dist/workspace/grep-worker.js +9 -6
  346. package/dist/workspace/index.d.ts +3 -2
  347. package/dist/workspace/index.js +3 -3
  348. package/dist/workspace/local.d.ts +11 -2
  349. package/dist/workspace/local.js +161 -43
  350. package/dist/workspace/resolve-computer.d.ts +50 -10
  351. package/dist/workspace/resolve-computer.js +46 -11
  352. package/dist/workspace/run-tools.d.ts +13 -31
  353. package/dist/workspace/run-tools.js +10 -27
  354. package/dist/workspace-paths.d.ts +0 -17
  355. package/dist/workspace-paths.js +1 -41
  356. package/dist/workspace.d.ts +0 -14
  357. package/dist/workspace.js +3 -96
  358. package/package.json +13 -13
  359. package/templates/README.md +9 -3
  360. package/templates/market-monitor/agent.md +2 -2
  361. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  362. package/dist/bound-files.d.ts +0 -4
  363. package/dist/bound-files.js +0 -164
  364. package/dist/coding-tools.d.ts +0 -47
  365. package/dist/coding-tools.js +0 -189
  366. package/dist/computer-adb.d.ts +0 -12
  367. package/dist/computer-adb.js +0 -14
  368. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  369. package/dist/console/assets/index-DvW6Aled.css +0 -1
  370. package/dist/grade.d.ts +0 -63
  371. package/dist/grade.js +0 -150
  372. package/dist/mcp-servers.d.ts +0 -269
  373. package/dist/mcp-servers.js +0 -456
  374. package/dist/packs.d.ts +0 -71
  375. package/dist/packs.js +0 -180
  376. package/dist/sealed-settings.d.ts +0 -60
  377. package/dist/sealed-settings.js +0 -171
  378. package/dist/sessions.d.ts +0 -6
  379. package/dist/sessions.js +0 -109
  380. package/dist/workspace/computer-serves.d.ts +0 -12
  381. package/dist/workspace/computer-serves.js +0 -15
@@ -2,11 +2,12 @@
2
2
  // key), never from this process's environment or a pipe (the old per-run process read its own over a pipe; the runner is
3
3
  // one process for many runs). Scoped to the run as the old per-run environment was: the keys its revision's tools unlock
4
4
  // and its model needs (runs.ts keysFor/needsOf), and its decision provider keys (decisions.ts decisionKeysFor, Parallel's
5
- // where a web tool resolves there), and no other. So a run that names no monid never gets the monid key, and two runs on
5
+ // where a web tool resolves there), and no other; an agentic run's learned workflows add the keys of the decision
6
+ // providers they name, read once the claim's seed lay chose them (learnedDecisionKeys). So a run that names no monid never gets the monid key, and two runs on
6
7
  // one runner never see each other's keys: each claim reads its own, into its own environment. (MCP credentials are the
7
8
  // other per-claim secret; they come through mcp-claim.ts, which already opens them from the store under the claim.)
8
- import { decisionKeysFor } from "../decisions.js";
9
- import { GATEWAY_KEY_ENV, PROVIDER_KEYS } from "../model.js";
9
+ import { decisionKeysFor, providersNamed } from "../decisions.js";
10
+ import { GATEWAY_KEY_ENV, PROVIDER_KEYS, workflowNodes } from "../model.js";
10
11
  import { keysFor, needsOf, RUN_SECRETS } from "../run-secrets.js";
11
12
  import { DECISION_KEYS, withoutSecrets } from "../secrets.js";
12
13
  import { getSealedKey } from "../server-keys.js";
@@ -19,17 +20,7 @@ const CANDIDATES = [...new Set([...RUN_SECRETS, ...DECISION_KEYS])];
19
20
  * decision provider keys. A fresh object per claim, so no run's keys reach another's. */
20
21
  export async function claimSecrets(deps, revision, launch) {
21
22
  const base = withoutSecrets(deps.env ?? {});
22
- // Every candidate secret into a working environment, then scoped to the run below so a key the run does not need is never
23
- // put on the environment its tools run under. The server process's own environment value wins over the store's by the same
24
- // name (the secrets rule 4: env always overrides a pasted value), so a key set where the server starts is not shadowed by a
25
- // stale one saved in the store.
26
- const working = { ...base };
27
- // A name present with no value (`-e NAME`, an empty optional secret) is not a key: the store's saved one stands.
28
- for (const name of CANDIDATES) {
29
- const value = deps.env?.[name] || (deps.sealKey ? await getSealedKey(deps.store, deps.sealKey, name) : undefined);
30
- if (value !== undefined)
31
- working[name] = value;
32
- }
23
+ const working = await workingEnv(deps);
33
24
  const needs = await needsOf(revision);
34
25
  // An agentic run's model keys are its PINNED model's (the launch's, chosen at its start), the one its route sends, never
35
26
  // the host's default now: a key saved since the run started (another provider's, now first) would otherwise be opened
@@ -44,6 +35,49 @@ export async function claimSecrets(deps, revision, launch) {
44
35
  env[name] = value;
45
36
  return env;
46
37
  }
38
+ /** Every candidate secret in a working environment over the runner's base, read for one claim and scoped by its caller, so
39
+ * a key the run does not need is never put on the environment its tools run under. The server process's own environment
40
+ * value wins over the store's by the same name (the secrets rule 4: env always overrides a pasted value), so a key set
41
+ * where the server starts is not shadowed by a stale one saved in the store. */
42
+ async function workingEnv(deps) {
43
+ const working = { ...withoutSecrets(deps.env ?? {}) };
44
+ // A name present with no value (`-e NAME`, an empty optional secret) is not a key: the store's saved one stands.
45
+ for (const name of CANDIDATES) {
46
+ const value = deps.env?.[name] || (deps.sealKey ? await getSealedKey(deps.store, deps.sealKey, name) : undefined);
47
+ if (value !== undefined)
48
+ working[name] = value;
49
+ }
50
+ return working;
51
+ }
52
+ /** The decision keys a run's learned workflows need, beside those claimSecrets scoped to its revision (whose own nodes
53
+ * are all needsOf reads, so an agentic run gets none there): the keys of the providers the chosen workflows' typed
54
+ * questions name (decisions.ts providersNamed, Jev for a node that names none), but any provider `allowed` refuses (the
55
+ * run's gate), read as claimSecrets reads its keys and scoped by decisionKeysFor. `workflows`: those the claim's seed
56
+ * lay chose for the run's learned_workflow tool (runner/learning-seed.ts), so this read comes after the lay. A
57
+ * workflow that does not parse or inspect names no provider: the tool refuses it before any node runs. No workflow, or
58
+ * no provider left, reads nothing. A fresh object per call, so no run's keys reach another's. */
59
+ export async function learnedDecisionKeys(deps, workflows, allowed) {
60
+ if (!workflows.length)
61
+ return {};
62
+ const { inspectWorkflow } = await import("@parcha/agentrun-dsl");
63
+ const named = new Set();
64
+ for (const { workflow } of workflows) {
65
+ let nodes;
66
+ try {
67
+ const doc = JSON.parse(workflow);
68
+ nodes = workflowNodes(doc, inspectWorkflow(doc));
69
+ }
70
+ catch {
71
+ continue;
72
+ }
73
+ for (const id of providersNamed(nodes))
74
+ named.add(id);
75
+ }
76
+ const providers = [...named].filter((id) => allowed(id));
77
+ if (!providers.length)
78
+ return {};
79
+ return decisionKeysFor(await workingEnv(deps), { providers, parallelWeb: false });
80
+ }
47
81
  /** Every model key a model route reads by name: each of pi-ai's providers' (model.ts PROVIDER_KEYS) and the gateway's. */
48
82
  export const MODEL_KEY_NAMES = [...new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV])];
49
83
  /** `env` for a model route (model-route.ts routeOf, a CLI's providerFor): the runner's own environment, its secrets kept
@@ -7,6 +7,8 @@ export type { ClaimComputer, ClaimDeps, ClaimLaunch, ComputerForClaim } from "./
7
7
  /** What the runner hands the CLI spec builder: the same deps the pi spec takes (computerForClaim, computerDeps and
8
8
  * makeArchilDisk are on AdapterSpecDeps, shared by both). One per runner. */
9
9
  export type CliSpecDeps = AdapterSpecDeps;
10
+ /** What a CLI harness refuses of an agent's computer, in words: a browser, which only pi's browser tool drives. */
11
+ export declare const cliRefusesKind: (kind: string) => string | undefined;
10
12
  /**
11
13
  * One claimed CLI run's AdapterRunSpec, built from its launch record and its revision.
12
14
  *
@@ -30,7 +30,7 @@ import { learningWorkspace } from "../learn/folder.js";
30
30
  import { learningEndOfRun } from "./learning-end.js";
31
31
  import { providerModels, runModels } from "../model.js";
32
32
  import { firstMessage } from "../run-manifest.js";
33
- import { learningStartOf } from "../run-launch.js";
33
+ import { learningStartOf, seedFailed } from "../run-launch.js";
34
34
  import { readsFiles, systemOf } from "../skills.js";
35
35
  import { DATA_ENV } from "../server-fs.js";
36
36
  import { INPUTS_DIR, UPLOADS_DIR, Uploads } from "../uploads.js";
@@ -45,16 +45,19 @@ import { imageWaitWords } from "../workspace/computer-deps.js";
45
45
  import { hostLifecycle } from "./adapter-loop.js";
46
46
  import { adapterRunGate, answersCut, buildToolHost, hostToolCtxOf, learnedWorkflowHostTool, learnsWorkflows, modelAskOf, webHostTools, webToolNames } from "./adapter-run-spec.js";
47
47
  import { signInReads } from "../sign-ins-store.js";
48
- import { claimSecrets, withModelKeys } from "./claim-secrets.js";
48
+ import { claimSecrets, learnedDecisionKeys, withModelKeys } from "./claim-secrets.js";
49
49
  import { mcpForClaim } from "./mcp-run.js";
50
50
  import { TOOL_PLANE_ENV } from "../tool-plane.js";
51
51
  import { resolveHarness } from "./adapters/index.js";
52
52
  import { entriesOf } from "./loop.js";
53
- import { runMetrics } from "./metrics.js";
53
+ import { bookedSpend, runMetrics } from "./metrics.js";
54
+ import { journalEntries } from "./journal-reader.js";
54
55
  import { specBuilt } from "./spec-holds.js";
55
56
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
56
57
  import { githubAppAccess } from "./github-app.js";
57
58
  import { holdStored, storeSecrets } from "./store-secrets.js";
59
+ /** What a CLI harness refuses of an agent's computer, in words: a browser, which only pi's browser tool drives. */
60
+ export const cliRefusesKind = (kind) => kind === "browser" ? "This agent's computer is a browser, which only the pi harness drives here: pick pi for this agent, or another kind of computer in Settings → Computers." : undefined;
58
61
  /** The run's model and the catalog that prices it, as main chooses a CLI run's (app.ts wireModels and runModels): on the
59
62
  * harness's own wire where its entry says its model is chosen there (a pin there is its own provider/model-id, never a
60
63
  * gateway's), else as the run's usual models, a pin sent as pinned (modelAskOf). */
@@ -146,6 +149,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
146
149
  if (!name || !entry?.facts || !entry.adapter || !runner)
147
150
  throw new Error(`run ${claim.runId}: ${JSON.stringify(name)} is not a CLI harness this runner runs`);
148
151
  const facts = entry.facts;
152
+ // The level the harness thinks at: the run's effort, else above its highest (codex stops at xhigh) its highest. The
153
+ // run's metrics name this level, the one it ran at, never a level the harness has not.
154
+ const thinking = launch.effort ? thinkingFor(facts, launch.effort) : undefined;
149
155
  // The run's mode is the server's: Mode 2 where its Archil settings are saved (archil-settings.ts), the run's folder then
150
156
  // on the claim's Archil disk (archil-claim.ts: its keys from the store's sealed rows, under the runner's seal key, in
151
157
  // this claim's memory only, dropped at the release); else Mode 1, the run's local folder.
@@ -178,7 +184,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
178
184
  const computer = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, revisionId: runRow.revisionId, place: launch.place, ...(launch.computer !== undefined ? { computer: launch.computer } : {}) }, deps.store,
179
185
  // revokeMount removes the run's Archil mount credential at the computer's release (and if a start fails after a mint); the
180
186
  // run's end revokes it too, so it goes on every outcome even with no computer. Idempotent. As the pi spec does.
181
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, ...(archil ? { revokeMount: () => archil.revoke() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)) } : {}) });
187
+ // A browser computer is driven by the browser tool, which runs on pi's native route alone: a CLI's run of an agent
188
+ // whose computer is a browser is refused in words at its claim, before anything is made.
189
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, ...(archil ? { revokeMount: () => archil.revoke() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)) } : {}) });
182
190
  holds.hold({ computer });
183
191
  // The CLI works in the run's scratch folder on this machine (its working directory, swept at the run's end), its own
184
192
  // files (home, state) in a private folder inside it, never on the run's disk. The scratch is an alias of the run's
@@ -197,19 +205,20 @@ async function cliSpec(launch, run, deps, claim, holds) {
197
205
  // own skills through systemOf with the harness's own check (a harness that loads skills itself keeps in the prompt only
198
206
  // those it would refuse, and is handed the rest), then the effort guidance.
199
207
  const start = learningStartOf(launch);
200
- const laid = start ? laidLearned(body.instructions ?? "", start.section) : (body.instructions ?? "");
208
+ // A start whose seed failed tells the run nothing: it is never asked what to keep (learning-end.ts drops it).
209
+ const laid = start && !seedFailed(start) ? laidLearned(body.instructions ?? "", start.section) : (body.instructions ?? "");
201
210
  const check = await entry.skillCheck?.();
202
211
  // The revision's own skills laid before they are read, as the pi spec lays them (adapter-run-spec.ts).
203
212
  await layOwnSkills(ws.workspace, (revisionRow.skills ?? {}), { computer: launch.computer?.kind });
204
213
  // A learning run's seed laid as the pi spec lays it (runner/learning-seed.ts), its learned skills then in the skill list
205
214
  // the harness is handed (its native skills, or the prompt's), its learned workflows the ones learned_workflow runs.
206
- const seedLaid = start
215
+ const seedLaid = start && !seedFailed(start)
207
216
  ? await layLearningSeed({
208
217
  work: ws.workspace,
209
218
  seed: start.seed,
210
219
  folder: () => (archil === undefined ? learningFolderOf(deps.data, runRow.agentId) : learningWorkspace({ mode: "archil", agentId: runRow.agentId, archil })),
211
220
  own: Object.keys(revisionRow.skills ?? {}),
212
- shown: async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data))),
221
+ shown: async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true }),
213
222
  log,
214
223
  })
215
224
  : undefined;
@@ -279,9 +288,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
279
288
  followUpOf: (raised) => followUpOf(raised),
280
289
  };
281
290
  // The gate before a call's intent, the same as the pi spec: the revision's tool settings over the store's, read from the
282
- // store at each decide, and the turn's origin read through the run's Workspace (Mode 2: on the run's disk) — adapterRunGate
283
- // (RunGate.decide: the reflect-turn .learning refusal, deny with its words, a pin, allow, ask).
284
- const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace);
291
+ // store at each decide — adapterRunGate (RunGate.decide: deny with its words, a pin, allow, ask). The end-of-run turn's
292
+ // refusal of writes under .learning/ is the adapter loop's own (it knows the turn), never a file's.
293
+ const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace, tools.shell);
285
294
  // The run's tools: the kernel registry's hands on its Workspace (and computer); the web host tools it is granted
286
295
  // (web_fetch, web_search, monid), bound by the binding the pi spec uses (webHostTools) on the ToolHost the pi spec builds
287
296
  // (buildToolHost); and the learned_workflow tool when the run has it (learnsWorkflows: its revision is agentic and the
@@ -308,6 +317,15 @@ async function cliSpec(launch, run, deps, claim, holds) {
308
317
  if (webNames.length || learns) {
309
318
  // The claim's keys (above, already held by the redactors), a copy of its own for the tools' plane below.
310
319
  const toolEnv = { ...claimed };
320
+ // The decision keys its learned workflows' typed questions need, as the pi spec reads them (claim-secrets.ts
321
+ // learnedDecisionKeys): onto this copy alone, never the CLI's own environment or its model's (cliRunEnv, above), and
322
+ // held by the redactors as the claim's keys are.
323
+ if (learns) {
324
+ const learnedKeys = await learnedDecisionKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, workflows, (provider) => gate.permissions.policy(provider) !== "deny");
325
+ for (const redact of new Set([held, cut]))
326
+ holdClaimed(redact, learnedKeys);
327
+ Object.assign(toolEnv, learnedKeys);
328
+ }
311
329
  handedKeys = runnerSecrets(toolEnv);
312
330
  // The run's resolved tool plane (its web tools' providers), as the pi spec hands it its web tools.
313
331
  delete toolEnv[TOOL_PLANE_ENV];
@@ -318,8 +336,12 @@ async function cliSpec(launch, run, deps, claim, holds) {
318
336
  const host = buildToolHost({ root, workspace: ws.workspace, claim, env: toolEnv, run, store: deps.store, sealKey: deps.sealKey, life, redact: held });
319
337
  webTools = await webHostTools(host, granted, ctx);
320
338
  }
321
- if (learns)
322
- learnedTool = await learnedWorkflowHostTool({ run, kind: revision.kind, granted, plane: launch.plane, env: toolEnv, work: root, workflows, permissions: gate.permissions, ctx });
339
+ if (learns) {
340
+ // The gate asks a learned_workflow call about its workflow's MCP nodes (adapterRunGate); they run through the run's
341
+ // own MCP as the loop wraps it.
342
+ gate.learn(workflows);
343
+ learnedTool = await learnedWorkflowHostTool({ run, kind: revision.kind, granted, plane: launch.plane, env: toolEnv, work: root, workflows, permissions: gate.permissions, ctx, ...(mcp ? { mcp } : {}) });
344
+ }
323
345
  }
324
346
  const session = {
325
347
  key: `run:${claim.runId}`,
@@ -327,9 +349,9 @@ async function cliSpec(launch, run, deps, claim, holds) {
327
349
  system: [environmentLine(), instructions, guidance].filter((line) => Boolean(line)),
328
350
  // The web tools and the learned workflow's call nodes run on the claim's keys: their answers pass the runner's one
329
351
  // redactor, as pi's do.
330
- tools: [...tools.hostTools(withKindTools(granted, tools), undefined, results), ...[...webTools, ...(learnedTool ? [learnedTool] : [])].map((tool) => answersCut(tool, held))],
352
+ tools: [...tools.hostTools(withKindTools(granted, tools), results), ...[...webTools, ...(learnedTool ? [learnedTool] : [])].map((tool) => answersCut(tool, held))],
331
353
  context: "fresh",
332
- ...(launch.effort ? { thinking: thinkingFor(facts, launch.effort) } : {}),
354
+ ...(thinking ? { thinking } : {}),
333
355
  };
334
356
  const content = isObject(launch.input) && typeof launch.input.content === "string" ? launch.input.content : "";
335
357
  const input = await firstMessage(content, ws.workspace);
@@ -368,10 +390,17 @@ async function cliSpec(launch, run, deps, claim, holds) {
368
390
  ...(life ? { lifecycle: life } : {}),
369
391
  agentId: runRow.agentId,
370
392
  workRoot: root,
371
- // The end's metrics and cost from the run's journal; a CLI run's carry its model.
393
+ // The end's metrics from the run's record; a CLI run's carry its model. Its cost is its booking's: the harness's own
394
+ // record carries no per-request cost, so its model requests are counted at what the run's model proxy booked them at
395
+ // (metrics.ts bookedSpend over every session of its journal), as a pi run's are at its answers' costs.
372
396
  endPatch: async () => {
373
397
  const entries = await entriesOf(deps.journal(claim), ROOT_CONVERSATION_ID, context);
374
- const { metrics, costUsd } = runMetrics(entries, { ...(launch.effort !== undefined ? { effort: launch.effort } : {}), model: `${chosen.model.provider}/${chosen.model.modelId}` });
398
+ const { metrics } = runMetrics(entries, { ...(thinking ? { effort: thinking } : {}), model: `${chosen.model.provider}/${chosen.model.modelId}` });
399
+ // Its model requests and its decisions (a learned workflow's) at what they were booked at (bookedSpend).
400
+ const all = (await journalEntries(deps.journal(claim), context));
401
+ const model = bookedSpend(all, "model").usd;
402
+ const decisions = bookedSpend(all, "decisions").usd;
403
+ const costUsd = model === null || decisions === null ? null : model + decisions;
375
404
  // Its paid tool calls (a Parallel extract or search, a monid call), booked on the run's one ledger in their own
376
405
  // session, are the run's cost too, as the pi spec's.
377
406
  const paid = run.ledger?.paid ? run.ledger.paid.spentUsd() : 0;
@@ -1,7 +1,7 @@
1
1
  // Commands as rows (design: "Commands from the console are rows, not files or doors"). The server inserts one through
2
2
  // sendCommand; a runner reads them with store.commands(run, after) and hands each to the run's loop. A command's
3
3
  // taken_at is set once: by the loop's journal commit that applies it, or by the runner's refusal with a reason.
4
- import { originOf } from "@parcha/pi-durable-agent/timeline";
4
+ import { originOf } from "../timeline/index.js";
5
5
  /** stop and cancel both end the run, stopped: a cancel's end says it was cancelled, as main's cancel ends a run for good.
6
6
  * browser_hand_back is a person's answer to the agent's browser hand-over (runner/hand-back.ts). computer_take_over and
7
7
  * computer_hand_back are a person's turn with the run's desktop or phone (computer-commands.ts, runner/computer-journal.ts).
@@ -23,11 +23,24 @@ export declare const isComputerCommand: (command: Pick<Command, "kind">) => bool
23
23
  /** The journal's side of run `runId`'s hold, for the pass whose Harness `commit` writes root entries (in one commit, in
24
24
  * order). `now` is the clock the up entry is stamped with. */
25
25
  export declare function journalHold(runId: string, computer: RunComputerHold, commit: (entries: readonly RootEntry[]) => Promise<void>, now?: () => number): {
26
- /** The run's computer is up for this pass: the server shows it live, the agent driving. */
27
- up: () => Promise<void>;
26
+ /** The run's computer is up for this pass: the server shows it live, the agent driving. `prior`, the run's root
27
+ * entries before this pass: a take they still hold in force was on the computer of an earlier claim, whose runner
28
+ * lost the run (a crash, a lapsed lease: its own end of the take, if it wrote one, was refused by the fence) and
29
+ * whose computer this claim's start let go (releaseOlder deletes a lower epoch's computers). That take ends here,
30
+ * `released`, once, with its row when it had reached the person, so they read why the desktop is the agent's again.
31
+ * Only a hold that has had no take yet (a new claim's computer) ends one so: a restart within the claim keeps its own. */
32
+ up: (prior?: readonly {
33
+ readonly kind: string;
34
+ readonly data?: unknown;
35
+ }[]) => Promise<void>;
28
36
  /** Applies a take-over or hand-back row to the hold: `taken` when it changed the hold (the change's commit takes the
29
37
  * row: its entries carry the row's id as `by`), else refused in words. */
30
38
  apply(command: Command): CommandOutcome;
39
+ /** The run's end (#2134). From here nothing new is taken (hold.finish), so no take begins after this wait and is cut
40
+ * by the release. While a person holds the computer, the Timeline says the run waits for the hand-back, and this
41
+ * resolves once the agent drives again (a hand-back, the hold's idle bound, the viewer gone) or `cut` settles first
42
+ * (a stop, a lost claim). With the agent driving, it resolves at once and writes nothing. */
43
+ heldAtEnd(cut: Promise<unknown>): Promise<void>;
31
44
  /** Whether `data`, a computer entry's, is the change row `id` made: the commit that writes it takes the row. */
32
45
  madeBy: (data: Record<string, unknown>, id: number) => boolean;
33
46
  /** Every commit asked for so far is done. */
@@ -8,8 +8,8 @@
8
8
  //
9
9
  // onComputerHold is the change signal for whoever else in the runner's process shows the hold (tl-browser's run-side
10
10
  // viewer and its bar): it fires after each computer.hold change entry is committed, with that change's Timeline words.
11
- import { HOST_PHASE } from "@parcha/pi-durable-agent/timeline";
12
- import { COMPUTER_HAND_BACK, COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND, COMPUTER_TAKE_OVER, holdWords, takeEndedWords, } from "../computer-commands.js";
11
+ import { HOST_PHASE } from "../timeline/index.js";
12
+ import { COMPUTER_HAND_BACK, COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND, COMPUTER_TAKE_OVER, holdIn, holdWords, takeEndedWords, } from "../computer-commands.js";
13
13
  const listeners = new Map();
14
14
  /** Calls `listener` after each change of run `runId`'s hold is committed to its journal, in order, in this process.
15
15
  * Returns the unsubscribe. */
@@ -84,8 +84,19 @@ export function journalHold(runId, computer, commit, now = Date.now) {
84
84
  void write(entries).then(() => change && signal(runId, change), () => undefined);
85
85
  });
86
86
  return {
87
- /** The run's computer is up for this pass: the server shows it live, the agent driving. */
88
- up: () => {
87
+ /** The run's computer is up for this pass: the server shows it live, the agent driving. `prior`, the run's root
88
+ * entries before this pass: a take they still hold in force was on the computer of an earlier claim, whose runner
89
+ * lost the run (a crash, a lapsed lease: its own end of the take, if it wrote one, was refused by the fence) and
90
+ * whose computer this claim's start let go (releaseOlder deletes a lower epoch's computers). That take ends here,
91
+ * `released`, once, with its row when it had reached the person, so they read why the desktop is the agent's again.
92
+ * Only a hold that has had no take yet (a new claim's computer) ends one so: a restart within the claim keeps its own. */
93
+ up: async (prior = []) => {
94
+ const before = holdIn(prior.map((entry) => ({ kind: entry.kind, data: entry.data })));
95
+ if (before.up && before.state !== "agent" && before.take !== undefined && hold.epoch() === 0) {
96
+ const at = now();
97
+ const ended = { kind: COMPUTER_HOLD_KIND, data: { state: "agent", take: before.take, computer: kind, at, ended: "released" } };
98
+ await write(before.state === "person" ? [ended, phase(words.ended.released, at)] : [ended]);
99
+ }
89
100
  const at = now();
90
101
  const take = hold.current();
91
102
  // A pass that starts while a take is in force (a restart within the claim) says so after the up entry.
@@ -99,7 +110,9 @@ export function journalHold(runId, computer, commit, now = Date.now) {
99
110
  apply(command) {
100
111
  const body = (command.body ?? {});
101
112
  if (command.kind === COMPUTER_TAKE_OVER) {
102
- return hold.take({ by: command.id }) ? { taken: true } : { refused: `The ${kind} is already taken over, or not up now.` };
113
+ if (hold.take({ by: command.id }))
114
+ return { taken: true };
115
+ return { refused: hold.finishing() ? `The agent is done and the run is ending, so its ${kind} can't be taken over now.` : `The ${kind} is already taken over, or not up now.` };
103
116
  }
104
117
  if (typeof body.ask === "string") {
105
118
  const outcome = body.outcome === "cancelled" ? "cancelled" : "done";
@@ -110,6 +123,29 @@ export function journalHold(runId, computer, commit, now = Date.now) {
110
123
  return { refused: takeEndedWords(kind, "given") };
111
124
  return hold.give("given", { by: command.id }) ? { taken: true } : { refused: takeEndedWords(kind, "given") };
112
125
  },
126
+ /** The run's end (#2134). From here nothing new is taken (hold.finish), so no take begins after this wait and is cut
127
+ * by the release. While a person holds the computer, the Timeline says the run waits for the hand-back, and this
128
+ * resolves once the agent drives again (a hand-back, the hold's idle bound, the viewer gone) or `cut` settles first
129
+ * (a stop, a lost claim). With the agent driving, it resolves at once and writes nothing. */
130
+ async heldAtEnd(cut) {
131
+ hold.finish();
132
+ let off = () => { };
133
+ const back = new Promise((resolve) => {
134
+ off = hold.on(() => void (hold.state() === "agent" && resolve()));
135
+ if (hold.state() === "agent")
136
+ resolve();
137
+ });
138
+ try {
139
+ if (hold.state() === "agent")
140
+ return;
141
+ // A row the journal refuses (a lost claim's fence) is the cut's to answer, not this wait's.
142
+ await write([phase(words.ending, now())]).catch(() => undefined);
143
+ await Promise.race([back, cut]);
144
+ }
145
+ finally {
146
+ off();
147
+ }
148
+ },
113
149
  /** Whether `data`, a computer entry's, is the change row `id` made: the commit that writes it takes the row. */
114
150
  madeBy: (data, id) => data.by === id,
115
151
  /** Every commit asked for so far is done. */
@@ -19,8 +19,8 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
19
19
  import { dropPostgresSchema, openPostgresStore, openStore, RunFinal, StoreConstraint, storeTarget } from "../../store/index.js";
20
20
  import { sendCommand } from "../commands.js";
21
21
  import { callsOf, journalRecords, messagesOf } from "../journal-reader.js";
22
- import { KINDS } from "../journal-kinds.js";
23
- import { timelineReducer } from "@parcha/pi-durable-agent/timeline";
22
+ import { KINDS, MESSAGE_SENT_AGAIN } from "../journal-kinds.js";
23
+ import { timelineReducer } from "../../timeline/index.js";
24
24
  import { emptyState, translate } from "../../live/translate.js";
25
25
  /** The one row a person's stop gives on the live timeline (live/translate.ts STOPPED_BY_YOU), the same on every harness. */
26
26
  const STOPPED_BY_YOU = "Stopped by you";
@@ -119,15 +119,15 @@ function crashAt(point, holder) {
119
119
  return {
120
120
  beforeIntent: async () => (point === "beforeIntent" ? crash() : undefined),
121
121
  beforeResult: async () => (point === "beforeResult" ? crash() : undefined),
122
+ afterMessageSent: async () => (point === "afterMessageSent" ? crash() : undefined),
122
123
  };
123
124
  }
124
125
  /** The Postgres store each registered subject's worlds open (registerHarnessConformance's `storeUrl`), by the subject
125
126
  * object the suite's cases are handed: none for the data directory's SQLite store. */
126
127
  const STORE_URLS = new WeakMap();
127
- /** Cases a Postgres store can't pass yet, each with what it waits on: they run on SQLite and are skipped on Postgres. */
128
- const POSTGRES_PENDING = {
129
- "approval-double-click": "waits on the Postgres commands_one_answer migration (pgstore-1): the one-answer index is SQLite's today",
130
- };
128
+ /** Cases a Postgres store can't pass yet, each with what it waits on: they run on SQLite and are skipped on Postgres. None
129
+ * today. */
130
+ const POSTGRES_PENDING = {};
131
131
  /** A store in a data directory of its own, one queued run, and runners started on it (each its own connection). */
132
132
  /** The suite's short lease, for the crash cases: a crashed runner's claim must run out for the second runner to take
133
133
  * the run over. */
@@ -630,6 +630,88 @@ const CASES = [
630
630
  assert.ok((await w.commandRow(steer.id)).takenAt !== null, "the steer row is taken");
631
631
  },
632
632
  },
633
+ {
634
+ id: "message-mid-turn-kept",
635
+ title: "messages sent mid-turn are never dropped: each is taken, in order, and the model answers each",
636
+ async body(subject, t) {
637
+ const w = await world(subject, t);
638
+ const { tools, letSlowGo, slowStarted } = suiteTools();
639
+ // A harness that steers places a message in the turn in flight (steer-mid-turn); one that does not (a CLI's: its
640
+ // adapter's facts say steer false) sends each as a turn of its own once the turn ends, in the order they came. Either
641
+ // way the model reads it, and its row is taken, never refused after the API accepted it (#2174).
642
+ const steers = subject.facts?.steer !== false;
643
+ const texts = steers ? ["check the totals"] : ["check the totals", "and the dates"];
644
+ // The model's steps: the call, then what it says after it (the steer it read, when it steers), then, for each message
645
+ // sent as a turn of its own, that message (the last the person sent).
646
+ const script = [{ call: "slow" }, { sayLastSteer: true }, ...(steers ? [] : texts.map(() => ({ sayLastSteer: true })))];
647
+ await w.start("runner-a", { script, tools, hooks: quiet });
648
+ await slowStarted;
649
+ const rows = [];
650
+ for (const text of texts)
651
+ rows.push(await sendCommand(w.server, RUN, { kind: "steer", body: { text } }));
652
+ // The tool goes on once every message is with the loop: the turn in flight has them, never a timer.
653
+ await until(() => rows.every((row) => w.handedOver(row.id)), "the messages handed to the loop mid-turn");
654
+ letSlowGo();
655
+ await w.ended("ended");
656
+ const { calls, messages } = await w.read();
657
+ const slow = calls.find((call) => call.tool === "slow");
658
+ assert.ok(slow?.endEntry !== undefined && slow.status === "done", `slow ran to its end: ${JSON.stringify(calls)}`);
659
+ const sent = texts.map((text) => messages.find((message) => message.role !== "model" && message.text === text));
660
+ assert.ok(sent.every((message) => message !== undefined), `each message is in the journal: ${JSON.stringify(messages)}`);
661
+ for (const [i, message] of sent.entries()) {
662
+ assert.ok(message.entry > slow.endEntry, `"${texts[i]}" comes after the call it was sent during: ${JSON.stringify(messages)}`);
663
+ if (i > 0)
664
+ assert.ok(message.entry > sent[i - 1].entry, `in the order they came: ${JSON.stringify(messages)}`);
665
+ const answered = messages.find((one) => one.role === "model" && one.entry > message.entry && one.text.includes(texts[i]));
666
+ assert.ok(answered, `the model answered "${texts[i]}": ${JSON.stringify(messages)}`);
667
+ }
668
+ for (const row of rows) {
669
+ const taken = await w.commandRow(row.id);
670
+ assert.ok(taken.takenAt !== null && taken.refused === null, `its row is taken, not refused: ${JSON.stringify(taken)}`);
671
+ }
672
+ },
673
+ },
674
+ {
675
+ id: "message-resent-after-crash",
676
+ title: "a message sent as its own turn by a runner lost before its row was taken is sent again by the next, and the timeline says so",
677
+ async body(subject, t) {
678
+ const w = await world(subject, t);
679
+ const { tools, letSlowGo, slowStarted } = suiteTools();
680
+ const text = "check the totals";
681
+ // The call, then the turn's words, then the message's turn (sent once by runner-a, again by runner-b), each saying
682
+ // the message it was given.
683
+ const script = [{ call: "slow" }, { sayLastSteer: true }, { sayLastSteer: true }, { sayLastSteer: true }];
684
+ const holder = {};
685
+ await w.start("runner-a", { script, tools, hooks: crashAt("afterMessageSent", holder) }, holder);
686
+ await slowStarted;
687
+ const row = await sendCommand(w.server, RUN, { kind: "steer", body: { text } });
688
+ await until(() => w.handedOver(row.id), "the message handed to the loop mid-turn");
689
+ letSlowGo();
690
+ // runner-a dies once the session holds the message, before the commit that records it and takes its row.
691
+ await until(() => holder.crashed, "the crash after the message was sent", EVENT_WAIT_MS);
692
+ assert.equal((await w.commandRow(row.id)).takenAt, null, "the row is untaken when runner-a is lost");
693
+ await w.claimsSettled("runner-a");
694
+ w.runOut();
695
+ await w.start("runner-b", { script, tools, hooks: quiet });
696
+ await w.ended("ended", EVENT_WAIT_MS);
697
+ const { messages } = await w.read();
698
+ const sent = messages.filter((message) => message.role !== "model" && message.text === text);
699
+ assert.ok(sent.length >= 1, `the message is on the record: ${JSON.stringify(messages)}`);
700
+ assert.ok(messages.some((message) => message.role === "model" && message.text.includes(text) && message.entry > sent[0].entry), `the model answered it: ${JSON.stringify(messages)}`);
701
+ const taken = await w.commandRow(row.id);
702
+ assert.ok(taken.takenAt !== null && taken.refused === null, `its row is taken once runner-b sent it: ${JSON.stringify(taken)}`);
703
+ // Never silent: the timeline says the message went again, once, before it.
704
+ const rows = await w.liveRows();
705
+ const again = rows.filter((one) => one.summary === MESSAGE_SENT_AGAIN);
706
+ const shown = JSON.stringify(rows.map((one) => [one.kind, one.summary]));
707
+ assert.deepEqual(again.map((one) => one.kind), ["phase"], `one row says it was sent again: ${shown}`);
708
+ // Just before the message it was said of: the person's row of it is the next message row.
709
+ const at = rows.indexOf(again[0]);
710
+ const message = rows.findIndex((one, i) => i > at && one.kind === "user_message");
711
+ assert.ok(message > at && rows[message].text === text, `the notice comes right before the message it was sent again: ${shown}`);
712
+ assert.ok(!rows.slice(0, at).some((one) => one.kind === "user_message" && one.text === text), `no row of the message before the notice: ${shown}`);
713
+ },
714
+ },
633
715
  {
634
716
  id: "stop-ends-turn",
635
717
  title: "stop ends the turn; the run says why",
@@ -798,6 +880,31 @@ const CASES = [
798
880
  assert.deepEqual(calls.map((call) => [call.tool, call.status]), [["asked", "done"]]);
799
881
  },
800
882
  },
883
+ {
884
+ id: "approval-race",
885
+ title: "an approve and a deny sent at once write one answer: the store refuses the other (one answer per approval), and the run acts on the one written",
886
+ async body(subject, t) {
887
+ const w = await world(subject, t);
888
+ const { tools, ran } = suiteTools();
889
+ await w.start("runner-a", { script: [{ call: "asked" }, { say: "done" }], tools, hooks: quiet });
890
+ await w.ended("parked");
891
+ const callId = await w.askedCall();
892
+ // Both sent before either is awaited (on Postgres, each on its own pooled connection). Whichever is written first, the
893
+ // store's one-answer index refuses the other: no order is imposed, so the case holds for either winner.
894
+ const settled = await Promise.allSettled([
895
+ sendCommand(w.server, RUN, { kind: "approve", body: { approval: callId } }),
896
+ sendCommand(w.server, RUN, { kind: "deny", body: { approval: callId } }),
897
+ ]);
898
+ const won = settled.filter((r) => r.status === "fulfilled");
899
+ const lost = settled.filter((r) => r.status === "rejected");
900
+ assert.equal(won.length, 1, `one answer is written, not both: ${JSON.stringify(settled.map((r) => r.status))}`);
901
+ assert.ok(lost[0]?.reason instanceof StoreConstraint, `the other is refused by the store: ${String(lost[0]?.reason)}`);
902
+ await w.ended("ended");
903
+ const winner = won[0].value;
904
+ assert.equal(ran.asked, winner.kind === "approve" ? 1 : 0, "the run acted on the answer written, never the other");
905
+ assert.equal((await w.commandRow(winner.id)).refused, null, "the answer written stands");
906
+ },
907
+ },
801
908
  {
802
909
  id: "message-never-answers",
803
910
  title: "a message that answers nothing (a trigger's, answers: false) never answers a waiting call, whatever its words",
@@ -879,12 +986,13 @@ const CASES = [
879
986
  },
880
987
  },
881
988
  ];
989
+ const STEERS_IN_TURN = "it places a message sent mid-turn in the turn in flight, its row taken in its submission's commit, so it never sends one as a turn of its own (message-resent-after-crash)";
882
990
  const CLI_NEVER_RERUNS = "a CLI never reruns a call that started; only the model calls again (its adapter's facts: rerunsStarted false)";
883
991
  /** The cases a harness's declared facts rule out, each with why: what it does by design, not what it cannot model yet. */
884
992
  export function factsRuleOut(facts) {
885
993
  if (!facts)
886
994
  return {};
887
- const noSteer = `${facts.id} takes no message mid-turn (its adapter's facts: steer false), so the loop refuses a steer for it in words`;
995
+ const noSteer = `${facts.id} takes no message mid-turn (its adapter's facts: steer false), so a message sent while it works is never placed in the turn in flight: it is the run's next turn (message-mid-turn-kept)`;
888
996
  return {
889
997
  // steer-origin steers the turn in flight too: its message is taken mid-turn, or never.
890
998
  ...(facts.steer ? {} : { "steer-mid-turn": noSteer, "steer-origin": noSteer }),
@@ -918,7 +1026,9 @@ export function registerHarnessConformance(given, { test, storeUrl }) {
918
1026
  const ruledOut = factsRuleOut(subject.facts);
919
1027
  for (const entry of CASES) {
920
1028
  const processCase = entry.id.endsWith("-process");
921
- const byFacts = ruledOut[entry.id];
1029
+ // A harness that steers (any whose facts do not say steer false, as message-mid-turn-kept reads them) places a message
1030
+ // in the turn in flight, its row taken in the commit of its submission: it never sends one as a turn of its own.
1031
+ const byFacts = ruledOut[entry.id] ?? (entry.id === "message-resent-after-crash" && subject.facts?.steer !== false ? STEERS_IN_TURN : undefined);
922
1032
  const notYet = subject.unsupported?.[entry.id] ?? (processCase && !subject.process ? "it names no module a runner process can load (subject.process)" : undefined);
923
1033
  const onPostgres = storeUrl ? POSTGRES_PENDING[entry.id] : undefined;
924
1034
  const skip = byFacts ? `${subject.name} does not do this by design: ${byFacts}` : notYet ? `${subject.name} cannot model this yet: ${notYet}` : onPostgres ? `on Postgres, ${onPostgres}` : undefined;
@@ -46,6 +46,9 @@ export interface KernelHooks {
46
46
  beforeBooking?(): Promise<void>;
47
47
  /** The adapter loop waits for its session's paid requests to be booked (bookingsSettled, with one still unbooked). */
48
48
  awaitingBookings?(): void;
49
+ /** A message taken mid-turn was sent as a turn of its own (the adapter loop's sendAfterTurn): the session holds it, and
50
+ * the commit that records it and takes its row has not run yet. */
51
+ afterMessageSent?(): Promise<void>;
49
52
  }
50
53
  export interface ConformanceSetup {
51
54
  readonly script: readonly ScriptStep[];
@@ -54,7 +57,7 @@ export interface ConformanceSetup {
54
57
  /** The run's agent, for the subject's spec to name (AdapterRunSpec.agentId): the end-of-run step is asked with it. */
55
58
  readonly agentId?: string;
56
59
  }
57
- export type ConformanceCase = "crash-before-intent" | "crash-after-intent" | "crash-before-intent-process" | "crash-after-intent-process" | "stalled-past-lease-process" | "replay-safe-rerun" | "steer-mid-turn" | "cancel-ends-for-good" | "cancel-parked" | "deny-note" | "steer-origin" | "stop-ends-turn" | "park-on-ask" | "approval-names-its-call" | "approval-double-click" | "message-never-answers" | "end-of-run-answer" | "fault-effects-once" | "fault-restarts-bounded" | "length-ends-failed" | "length-mid-run";
60
+ export type ConformanceCase = "crash-before-intent" | "crash-after-intent" | "crash-before-intent-process" | "crash-after-intent-process" | "stalled-past-lease-process" | "replay-safe-rerun" | "steer-mid-turn" | "message-mid-turn-kept" | "message-resent-after-crash" | "cancel-ends-for-good" | "cancel-parked" | "deny-note" | "steer-origin" | "stop-ends-turn" | "park-on-ask" | "approval-names-its-call" | "approval-double-click" | "approval-race" | "message-never-answers" | "end-of-run-answer" | "fault-effects-once" | "fault-restarts-bounded" | "length-ends-failed" | "length-mid-run";
58
61
  export interface ConformanceSubject {
59
62
  /** The harness's name, as the suite's tests are titled. */
60
63
  readonly name: string;
@@ -7,7 +7,7 @@ export interface DispatchDeps {
7
7
  launchOf(runId: string): Promise<{
8
8
  readonly body: unknown;
9
9
  }>;
10
- /** The loop factory for a run launched with `harness`, built from its `launch` record and its run id (so the switch may
10
+ /** The loop factory for a run launched with `harness`, built from its `launch` record and its run id (so the resolver may
11
11
  * read the run's revision — a workflow revision runs on the workflow loop whatever its harness name), or undefined when
12
12
  * this runner does not run it (the run fails in words). pi is the adapter loop with adapterRunSpecFromLaunch; a built-in
13
13
  * learning run names "learning"; the CLI harnesses name their own. May be async (the revision read). */
@@ -24,6 +24,13 @@ export declare class LaunchUnreadable extends Error {
24
24
  name: string;
25
25
  constructor(runId: string);
26
26
  }
27
+ /** The first wait before a buffered row whose delivery threw is tried again, and the most any later wait (doubling)
28
+ * grows to. */
29
+ export declare const REPLAY_RETRY_FIRST_MS = 250;
30
+ export declare const REPLAY_RETRY_MAX_MS = 5000;
31
+ /** How many times in all a buffered row's delivery is tried before the dispatch stops trying it on this claim: a row that
32
+ * fails for a lasting reason is said once and left untaken for the run's next claim, never tried for the whole run. */
33
+ export declare const REPLAY_TRIES = 5;
27
34
  /** The loop factory the runner holds for every run: `createDispatchLoop(deps)` picks each run's harness loop at its
28
35
  * claim. The inner loop gets the same LoopDeps the dispatch does, so the runner's fence, flush, live and end-of-run
29
36
  * channels reach it unchanged. */