@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
@@ -15,7 +15,8 @@ import { CAP_TOLERANCE, money } from "./cap.js";
15
15
  import { ApiError, invalid, unsupported } from "./errors.js";
16
16
  import { harnessOfBody } from "./harness.js";
17
17
  import { redacted, redactedOutput } from "./key-refusal.js";
18
- import { givenOf, LEARNING_BUDGET, learnedOf } from "./learning.js";
18
+ import { LEARNING_BUDGET, learnedParts } from "./learning.js";
19
+ import { thinkingLevel } from "./model.js";
19
20
  import { resolvePlace } from "./place.js";
20
21
  import { launchBody } from "./run-launch.js";
21
22
  import { sendCommand } from "./runner/commands.js";
@@ -210,6 +211,17 @@ async function sentAnswer(store, runId, id) {
210
211
  const row = (await store.commands(runId, 0)).find((command) => (command.kind === "approve" || command.kind === "deny") && command.refused === null && isObject(command.body) && command.body.approval === id);
211
212
  return row && { decision: row.kind === "approve" ? "allow" : "deny" };
212
213
  }
214
+ /** How a stop or cancel written to run `runId` before `before` (a command id; absent, any) answers every call still waiting:
215
+ * the runner reads commands in the order they were written, so it applies the stop first and withdraws (or, on a cancel,
216
+ * cancels) the call, and refuses every answer written after it. An answer written then is told so at once, the same 409
217
+ * the call's withdrawal gives, never 204 for a call that will not run. Read by the rows' order, so a stop that lands
218
+ * between this read and the answer's write is caught once the answer is written (approve). Untaken rows only, unless
219
+ * `taken` (a run already final: the end its runner applied). */
220
+ async function endBefore(store, runId, { before = Number.POSITIVE_INFINITY, taken = false } = {}) {
221
+ // The first: the runner applies the first stop or cancel it reads and stops reading there.
222
+ const row = (await store.commands(runId, 0)).find((command) => (command.kind === "stop" || command.kind === "cancel") && command.id < before && command.refused === null && (taken || command.takenAt === null));
223
+ return row && { decision: row.kind === "cancel" ? "canceled" : "withdrawn" };
224
+ }
213
225
  /** A person's answer to the tool call `id` that waits for approval (tool-gate.ts): an approve or deny command row the run's
214
226
  * runner reads and acts on. The first answer wins from the moment it is written, before the runner takes it — the same one
215
227
  * again changes nothing, another is 409 already-answered — and a run with no such waiting call is 404. Two answers at once
@@ -225,16 +237,31 @@ export async function approve(store, moment, id, decision, note) {
225
237
  return settle(given);
226
238
  if (!(moment.approvalIds?.has(id) ?? false))
227
239
  throw new ApiError("not_found", `The run ${moment.id} has no tool call ${id} waiting for approval.`);
240
+ const ending = await endBefore(store, moment.id);
241
+ if (ending)
242
+ throw alreadyAnswered(id, ending.decision);
228
243
  const body = { approval: id, ...(note !== undefined ? { note } : {}) };
244
+ let sent;
229
245
  try {
230
- await sendCommand(store, moment.id, { kind: decision === "allow" ? "approve" : "deny", body });
246
+ sent = await sendCommand(store, moment.id, { kind: decision === "allow" ? "approve" : "deny", body });
231
247
  }
232
248
  catch (error) {
249
+ // The run went final since it was read (its runner took a stop or a cancel, or it ended): its calls were answered by
250
+ // that end, so the answer is told how, never a 500.
251
+ if (error instanceof RunFinal) {
252
+ const end = await endBefore(store, moment.id, { taken: true });
253
+ throw alreadyAnswered(id, end?.decision ?? "withdrawn", end === undefined);
254
+ }
233
255
  const won = error instanceof StoreConstraint ? await sentAnswer(store, moment.id, id) : undefined;
234
256
  if (!won)
235
257
  throw error;
236
- settle(won);
258
+ return settle(won);
237
259
  }
260
+ // A stop or cancel written between the read above and this answer comes first in the runner's order: the answer will be
261
+ // refused at that end, so the person is told now.
262
+ const raced = await endBefore(store, moment.id, { before: sent.id });
263
+ if (raced)
264
+ throw alreadyAnswered(id, raced.decision);
238
265
  }
239
266
  // ---- start -----------------------------------------------------------------------------------------------------------
240
267
  /** A UUIDv7 run id: time-ordered, so a listing by start time is stable, and unique per run. */
@@ -250,21 +277,35 @@ function uuidv7(now = Date.now()) {
250
277
  const noShown = { text: (text) => text, name: (name) => name, holds: () => false };
251
278
  /** The run's learning start as the old start decided it (learning-run.ts onStart): undefined when the run does not learn (the
252
279
  * server's learning off, a workflow revision, or its revision does not say learning), else the notes its # Learned section
253
- * names (givenOf, the one decision the runner puts in the prompt), the # Learned text (learnedOf), the seed sha it starts
280
+ * names and the # Learned text (learnedParts, the one decision the runner puts in the prompt), the seed sha it starts
254
281
  * from and the count of all the seed's notes before the budget picked `given` (seedNotes) — or given empty, seed null and no
255
282
  * seedNotes when its seed cannot be read (a learning fault never refuses a run). */
256
- async function learningStartFor(deps, entry, revision, rbody) {
283
+ async function learningStartFor(deps, entry, revision, rbody, input) {
257
284
  const learns = deps.learning !== undefined && deps.learning !== "off" && revision.kind === "agentic" && rbody.learning === true;
258
285
  if (!learns || !deps.seedFor)
259
286
  return undefined;
287
+ const grade = deps.gradeModel ? { gradeModel: deps.gradeModel } : {};
260
288
  const seeded = await deps.seedFor(entry.agent.id);
289
+ // The folder could not be read (main's STOPPED.unreadable), or what it read could not be made into the start (main's
290
+ // copy that threw, STOPPED.notCopied): the run starts with nothing learned, and its learning end says which.
261
291
  if (!("seed" in seeded))
262
- return { given: [], seed: null, section: "" };
263
- const options = { budget: deps.learningBudget ?? LEARNING_BUDGET, read: Array.isArray(rbody.tools) && rbody.tools.includes("read"), shown: deps.shown ? deps.shown() : noShown };
264
- // The notes and the # Learned text are the old start's one decision (learnedParts): givenOf and learnedOf over the same
265
- // seed and options, so the runner lays exactly this section for exactly these notes and reads no learning folder. seedNotes
266
- // is the whole seed's note count, before the budget narrowed `given` (as the old seed_notes was).
267
- return { given: givenOf(seeded.seed, options), seed: seeded.seed.sha, section: learnedOf(seeded.seed, options) ?? "", seedNotes: Object.keys(seeded.seed.notes).length };
292
+ return { given: [], seed: null, section: "", seedFailed: "unreadable", ...grade };
293
+ try {
294
+ // The run's input goes to the note selector (learning.ts NoteSelector; byRelevance, the default, scores the notes by it).
295
+ const options = { budget: deps.learningBudget ?? LEARNING_BUDGET, read: Array.isArray(rbody.tools) && rbody.tools.includes("read"), shown: deps.shown ? deps.shown() : noShown, run: { input } };
296
+ // The notes and the # Learned text are the old start's one decision (learnedParts: one choice of the note selector), so
297
+ // the runner lays exactly this section for exactly these notes and reads no learning folder. seedNotes is the whole
298
+ // seed's note count, before the budget narrowed `given` (as the old seed_notes was).
299
+ const { section, given } = learnedParts(seeded.seed, options);
300
+ // The learned skills the seed offers the run, by name: each with its files (one over a run's skill budget at all is held
301
+ // by its size and never laid) and no host secret in it, as chooseSkills leaves them out. The claim lays them; the
302
+ // end-of-run turn counts the runs each served (runner/learning-end.ts draftForOf).
303
+ const skills = (seeded.seed.skills ?? []).flatMap(({ name, files }) => (files && !options.shown.holds(name) && !Object.entries(files).some(([path, text]) => options.shown.holds(path) || options.shown.holds(text)) ? [name] : []));
304
+ return { given: given.map(({ file, name }) => ({ file, name })), seed: seeded.seed.sha, section: section ?? "", seedNotes: Object.keys(seeded.seed.notes).length, ...(skills.length ? { skills } : {}), ...grade };
305
+ }
306
+ catch {
307
+ return { given: [], seed: null, section: "", seedFailed: "not_copied", ...grade };
308
+ }
268
309
  }
269
310
  /** Starts a run of `entry`'s agent from a create body, as POST /agents/{id}/runs starts it: every check the old start made
270
311
  * before a run started (prepareLaunch), then an INSERT — a queued run and its launch body in one transaction
@@ -381,22 +422,27 @@ export async function prepareLaunch(deps, entry, body, { trigger, capped = false
381
422
  // The run's model, resolved once, at start (the runner reads launch.model only).
382
423
  const model = await deps.modelOf(entry, revision);
383
424
  // The run's learning start, decided here as the old start did (learning-run.ts onStart): a run learns when the server's
384
- // learning is on and its revision says so; then its seed is read now and the notes its # Learned section names (givenOf,
425
+ // learning is on and its revision says so; then its seed is read now and the notes its # Learned section names (learnedParts,
385
426
  // the one decision) are pinned in the launch for the runner to put in the prompt. A seed that cannot be read starts it with
386
427
  // nothing (given empty, seed null); the end state is the runner's.
387
- const learning = await learningStartFor(deps, entry, revision, rbody);
428
+ const learning = await learningStartFor(deps, entry, revision, rbody, input);
429
+ // The run's effort: its own, else its revision's saved thinking, else the host's AGENT_THINKING (each a thinking level,
430
+ // else none). Nothing set: none, so the run gets no effort note and its harness's own default. Kept in its launch, so
431
+ // its harness's thinking, its guidance and its metrics all read the one value.
432
+ const effort = typeof body.effort === "string" ? body.effort : (thinkingLevel(rbody.thinking) ?? thinkingLevel(deps.planeEnv().AGENT_THINKING));
388
433
  const launch = {
389
434
  input,
390
435
  title: clip(redacted(title.trim().replace(/\s+/g, " "), deps.serverSecrets()), 80),
391
436
  place,
392
437
  harness: harnessOfBody(revision.body),
393
- ...(typeof body.effort === "string" ? { effort: body.effort } : {}),
438
+ ...(effort !== undefined ? { effort } : {}),
394
439
  ...(cap !== undefined ? { maxCostUsd: cap } : {}),
395
440
  ...(capMode !== undefined ? { capMode } : {}),
396
441
  ...(Object.keys(plane).length ? { plane } : {}),
397
442
  ...(deps.approvers !== undefined ? { approvers: deps.approvers } : {}),
398
443
  ...(deps.documents !== undefined ? { documents: deps.documents } : {}),
399
444
  ...(deps.boxAllow !== undefined ? { boxAllow: deps.boxAllow } : {}),
445
+ ...(deps.boxAllowSet ? { boxAllowSet: true } : {}),
400
446
  ...(fileIds.length ? { files: fileIds } : {}),
401
447
  ...(learning ? { learning } : {}),
402
448
  ...(trigger ? { trigger } : {}),
package/dist/seal-key.js CHANGED
@@ -16,12 +16,11 @@
16
16
  // start makes a key and records it (and the import's, which sets a data directory up as the server does); a runner reads
17
17
  // one and checks it, and never makes or records one. Several data directories in one process each keep their own key.
18
18
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
19
- import { chmodSync, closeSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, writeSync } from "node:fs";
19
+ import { chmodSync, closeSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
20
20
  import { join } from "node:path";
21
- import { unseal } from "@parcha/pi-durable-agent";
21
+ import { unseal } from "./sealing.js";
22
22
  import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
23
23
  import { handedSecret, holdSealKey } from "./secrets.js";
24
- import { webhookSecretIn } from "./webhooks.js";
25
24
  /** The seal key's own directory in the data directory, and its file there. */
26
25
  export const SEAL_KEY_DIR = "seal";
27
26
  export const SEAL_KEY_FILE = "seal.key";
@@ -173,49 +172,12 @@ function opensUnder(key, sealed, aad) {
173
172
  return false;
174
173
  }
175
174
  }
176
- /** The values data directory `dataDir` keeps sealed beside the store, under the same key: the outbound webhook's signing
177
- * secret (webhooks.ts) and any trigger settings file (sealed-settings.ts), each a check of whether a key opens it. */
178
- function sealedBeside(dataDir) {
179
- const checks = [];
180
- if (webhookSecretIn(dataDir, {}) !== undefined)
181
- checks.push((key) => "secret" in (webhookSecretIn(dataDir, { [SEAL_KEY_ENV]: key.toString("base64") }) ?? {}));
182
- let names = [];
183
- try {
184
- names = readdirSync(dataDir);
185
- }
186
- catch {
187
- // No data directory yet: nothing kept beside the store.
188
- }
189
- for (const name of names) {
190
- const adapter = /^trigger-settings-(.+)\.json$/.exec(name)?.[1];
191
- if (adapter === undefined)
192
- continue;
193
- let values;
194
- try {
195
- values = JSON.parse(readFileSync(join(dataDir, name), "utf8")).values;
196
- }
197
- catch {
198
- continue;
199
- }
200
- if (!values || typeof values !== "object")
201
- continue;
202
- for (const [scope, fields] of Object.entries(values)) {
203
- if (!fields || typeof fields !== "object")
204
- continue;
205
- for (const [field, sealed] of Object.entries(fields)) {
206
- if (typeof sealed === "string")
207
- checks.push((key) => opensUnder(key, Buffer.from(sealed, "base64"), `trigger-settings|${adapter}|${scope}|${field}`));
208
- }
209
- }
210
- }
211
- return checks;
212
- }
213
- async function storeSealOf(store, dataDir) {
175
+ async function storeSealOf(store) {
214
176
  const fingerprint = recordedIn(await store.settings.get(SEAL_KEY_SETTING));
215
177
  if (fingerprint !== undefined)
216
178
  return { fingerprint, sealed: [] };
217
179
  const rows = (await store.sealedSecrets.all()).map((row) => (key) => opensUnder(key, row.sealed, row.aad));
218
- return { fingerprint, sealed: [...rows, ...sealedBeside(dataDir)] };
180
+ return { fingerprint, sealed: rows };
219
181
  }
220
182
  const holdsSecrets = (seal) => seal.fingerprint !== undefined || seal.sealed.length > 0;
221
183
  /** Whether `key` is the store's, or why not: the one its fingerprint records; with none recorded, one that opens every
@@ -234,7 +196,7 @@ function notTheStoresWhy(seal, key) {
234
196
  const notTheStores = (why) => new SealKeyNotTheStores(`${SEALED_ELSEWHERE}. ${why}`);
235
197
  const PUT_BACK = `put the original there (mode 0600, in a 0700 directory), or hand it as ${SEAL_KEY_ENV}`;
236
198
  async function sealKeyFor(store, dataDir, given, role, write) {
237
- const kept = await storeSealOf(store, dataDir);
199
+ const kept = await storeSealOf(store);
238
200
  const dir = join(dataDir, SEAL_KEY_DIR);
239
201
  const file = join(dir, SEAL_KEY_FILE);
240
202
  let seal;
@@ -1,6 +1,21 @@
1
- import type { SettingsSpec } from "./sealed-settings.js";
2
1
  import type { TriggerSettings } from "./store/index.js";
3
- export { SERVER_SCOPE, type SettingsSpec } from "./sealed-settings.js";
2
+ /** What an adapter keeps sealed, and where: `server`, one set for the server; `trigger`, one set per trigger, by its id.
3
+ * A field with `mint` is a Standard Webhooks secret this server makes (standard-webhooks.ts), shown once; any other is
4
+ * given (set). `minBytes`: the fewest bytes its value may hold (standard-webhooks.ts keyBytes), MIN_KEY_BYTES for a key
5
+ * a request is verified with. `public`: a value that is no secret (an app's id, its name), kept with the rest but never
6
+ * in the list of the server's secrets, so no run's text is cut of it, and of any length. `format: "pem"`: a PEM private
7
+ * key, whose lines each are listed as secrets. */
8
+ export type SettingsSpec = {
9
+ scope: "server" | "trigger";
10
+ fields: Record<string, {
11
+ mint?: true;
12
+ minBytes?: number;
13
+ public?: true;
14
+ format?: "pem";
15
+ }>;
16
+ };
17
+ /** The scope of a server-scoped adapter's settings. */
18
+ export declare const SERVER_SCOPE = "server";
4
19
  /** The store slice this layer reads and writes. */
5
20
  type SealedSettingsStore = {
6
21
  readonly triggerSettings: Pick<TriggerSettings, "get" | "put" | "removeScope">;
@@ -66,6 +81,6 @@ declare class SealedSettingsOverStore {
66
81
  private remember;
67
82
  }
68
83
  export type { SealedSettingsOverStore };
69
- /** The SealedSettings surface over the one store: the switch swaps `new SealedSettings(data, id, spec, key, say)` for this,
70
- * then awaits load() once at start before the first get()/values(). */
84
+ /** An adapter's sealed settings over the one store; the server awaits load() once at start before the first
85
+ * get()/values(). */
71
86
  export declare function sealedSettingsOverStore(store: SealedSettingsStore, adapterId: string, spec: SettingsSpec, key: Buffer, say: (fields: Record<string, string>) => void): SealedSettingsOverStore;
@@ -1,15 +1,15 @@
1
- // A trigger source's sealed settings over the one store (store.triggerSettings), the store-backed replacement for the
2
- // SealedSettings file class (sealed-settings.ts). Each (scope, field) is a sealed row, bound to its adapter, scope and
3
- // field by the store's documented AAD trigger_settings|<adapter>|<scope>|<field>; the store holds base64 ciphertext and
4
- // never opens it. With no seal key none is kept, never in the clear. The surface is SealedSettings', so the switch swaps
5
- // `new SealedSettings(data, ...)` for `sealedSettingsOverStore(store, ...)` then awaits load() once: get()/values() are
1
+ // A trigger source's sealed settings over the one store (store.triggerSettings): the trigger kernel's one store of them.
2
+ // Each (scope, field) is a sealed row, bound to its adapter, scope and field by the store's documented AAD
3
+ // trigger_settings|<adapter>|<scope>|<field>; the store holds base64 ciphertext and never opens it, and none is kept in
4
+ // the clear (the server always has its seal key: seal-key.ts). The server awaits load() once: get()/values() are
6
5
  // synchronous off a snapshot the server (the one writer) loads once and keeps in step with every write; set/mint/remove
7
6
  // are durable before they resolve.
8
- import { seal, unseal } from "@parcha/pi-durable-agent";
7
+ import { seal, unseal } from "./sealing.js";
9
8
  import { invalid } from "./errors.js";
10
9
  import { keyBytes, MIN_KEY_BYTES, mintSecret, SECRET_PREFIX } from "./standard-webhooks.js";
11
10
  import { SEAL_KEY_ENV } from "./tool-keys.js";
12
- export { SERVER_SCOPE } from "./sealed-settings.js";
11
+ /** The scope of a server-scoped adapter's settings. */
12
+ export const SERVER_SCOPE = "server";
13
13
  /** The store's documented AAD for a trigger setting (store schema `trigger_settings`): the composite row key is in the
14
14
  * AAD, not store/seal.ts's single-row aadOf, which refuses a key holding the separator. */
15
15
  const aad = (adapterId, scope, field) => `trigger_settings|${adapterId}|${scope}|${field}`;
@@ -198,8 +198,8 @@ class SealedSettingsOverStore {
198
198
  this.retired.add(secret);
199
199
  }
200
200
  }
201
- /** The SealedSettings surface over the one store: the switch swaps `new SealedSettings(data, id, spec, key, say)` for this,
202
- * then awaits load() once at start before the first get()/values(). */
201
+ /** An adapter's sealed settings over the one store; the server awaits load() once at start before the first
202
+ * get()/values(). */
203
203
  export function sealedSettingsOverStore(store, adapterId, spec, key, say) {
204
204
  return new SealedSettingsOverStore(store, adapterId, spec, key, say);
205
205
  }
@@ -0,0 +1,4 @@
1
+ /** AES-256-GCM over `plain`, bound to `aad`: the IV, the ciphertext and the tag, in that order. */
2
+ export declare function seal(key: Buffer, plain: Buffer, aad: string): Buffer;
3
+ /** `seal`'s inverse; it throws when the bytes, the key or the `aad` differ from the sealing's. */
4
+ export declare function unseal(key: Buffer, sealed: Buffer, aad: string): Buffer;
@@ -0,0 +1,20 @@
1
+ // AES-256-GCM sealing, the one primitive every secret this server keeps at rest is sealed with (copied from
2
+ // @parcha/pi-durable-agent's vault.ts): the store's sealed columns (store/seal.ts), the
3
+ // trigger settings, the outbound webhook's secret, and what a runner opens under the server's seal key.
4
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
5
+ const IV_BYTES = 12;
6
+ const TAG_BYTES = 16;
7
+ /** AES-256-GCM over `plain`, bound to `aad`: the IV, the ciphertext and the tag, in that order. */
8
+ export function seal(key, plain, aad) {
9
+ const iv = randomBytes(IV_BYTES);
10
+ const cipher = createCipheriv("aes-256-gcm", key, iv).setAAD(Buffer.from(aad, "utf8"));
11
+ return Buffer.concat([iv, cipher.update(plain), cipher.final(), cipher.getAuthTag()]);
12
+ }
13
+ /** `seal`'s inverse; it throws when the bytes, the key or the `aad` differ from the sealing's. */
14
+ export function unseal(key, sealed, aad) {
15
+ if (sealed.length < IV_BYTES + TAG_BYTES)
16
+ throw new Error("too short");
17
+ const decipher = createDecipheriv("aes-256-gcm", key, sealed.subarray(0, IV_BYTES)).setAAD(Buffer.from(aad, "utf8"));
18
+ decipher.setAuthTag(sealed.subarray(sealed.length - TAG_BYTES));
19
+ return Buffer.concat([decipher.update(sealed.subarray(IV_BYTES, sealed.length - TAG_BYTES)), decipher.final()]);
20
+ }
@@ -1,4 +1,4 @@
1
- import { keyShaped } from "@parcha/pi-durable-disk/secret-name";
1
+ import { keyShaped } from "./secret-name.js";
2
2
  /** Whether a name is a secret's, whatever list names it or none does: one of its `_`-separated segments, in any case, is
3
3
  * KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN, or its last is PWD after another.
4
4
  * The one rule, pi-durable-disk's own: this cut, the harness log's and a run's environment (secrets.ts' withoutSecrets)
@@ -6,7 +6,7 @@ import { secretLintProfiler } from "@secretlint/profiler";
6
6
  import { rules as recommended } from "@secretlint/secretlint-rule-preset-recommend";
7
7
  // No performance marks: the profiler would leave about 14 a call in the process's global buffer.
8
8
  secretLintProfiler.setEnabled(false);
9
- import { keyShaped } from "@parcha/pi-durable-disk/secret-name";
9
+ import { keyShaped } from "./secret-name.js";
10
10
  /** Whether a name is a secret's, whatever list names it or none does: one of its `_`-separated segments, in any case, is
11
11
  * KEY, TOKEN, SECRET, PASSWORD, PASSWD, PASS, PAT, CREDENTIAL, CREDENTIALS or DSN, or its last is PWD after another.
12
12
  * The one rule, pi-durable-disk's own: this cut, the harness log's and a run's environment (secrets.ts' withoutSecrets)
@@ -0,0 +1,9 @@
1
+ /** The `_`-separated segments, in any case, that make a name a secret's. */
2
+ export declare const SECRET_SEGMENTS: readonly string[];
3
+ /**
4
+ * Whether `name` is a secret's name: one of its `_`-separated segments, in any case, is one of SECRET_SEGMENTS, or its last
5
+ * segment is PWD after another (DB_PWD). Segments, not suffixes, so MODAL_TOKEN_ID, FOO_TOKEN_BAR and MY_TOKEN_FILE are
6
+ * secrets' names, and CACHE_KEY_PREFIX too, which is the cheaper error; KEYBOARD, TOKENIZER, SECRETARY and PATTERN are
7
+ * not. PWD alone and OLDPWD are the shell's working directories, never a secret's.
8
+ */
9
+ export declare function keyShaped(name: string): boolean;
@@ -0,0 +1,15 @@
1
+ // The one rule for whether a variable's name is a secret's, by its name alone: what serve keeps out of a run's
2
+ // environment, cuts out of what an import keeps and out of a harness's log (secret-cut.ts).
3
+ /** The `_`-separated segments, in any case, that make a name a secret's. */
4
+ export const SECRET_SEGMENTS = Object.freeze(["KEY", "TOKEN", "SECRET", "PASSWORD", "PASSWD", "PASS", "PAT", "CREDENTIAL", "CREDENTIALS", "DSN"]);
5
+ const SEGMENTS = new Set(SECRET_SEGMENTS);
6
+ /**
7
+ * Whether `name` is a secret's name: one of its `_`-separated segments, in any case, is one of SECRET_SEGMENTS, or its last
8
+ * segment is PWD after another (DB_PWD). Segments, not suffixes, so MODAL_TOKEN_ID, FOO_TOKEN_BAR and MY_TOKEN_FILE are
9
+ * secrets' names, and CACHE_KEY_PREFIX too, which is the cheaper error; KEYBOARD, TOKENIZER, SECRETARY and PATTERN are
10
+ * not. PWD alone and OLDPWD are the shell's working directories, never a secret's.
11
+ */
12
+ export function keyShaped(name) {
13
+ const segments = name.toUpperCase().split("_");
14
+ return segments.some((segment) => SEGMENTS.has(segment)) || (segments.length > 1 && segments.at(-1) === "PWD");
15
+ }
@@ -26,7 +26,6 @@ export type SecretWriterFacts = {
26
26
  * off on a loopback-bound server, open the console from the launch link); no_accounts, accounts are off and the server is
27
27
  * reachable off loopback, where no one writes one until accounts are on. */
28
28
  export type SecretsReason = "token" | "sign_in" | "no_accounts";
29
- export declare const SECRETS_REASONS: readonly SecretsReason[];
30
29
  /** The one decision: whether a caller with these facts may write a secret, and if not, why. The owner's password session
31
30
  * always may; the accounts-off console on a loopback-bound server may where `loopbackConsoleIsOwner`
32
31
  * (LOOPBACK_CONSOLE_IS_OWNER); the API token never may, anywhere. */
@@ -11,7 +11,6 @@ export const SECRET_WRITE_REFUSAL = "Saving, replacing or removing a secret take
11
11
  * secrets_writable) follows it.
12
12
  */
13
13
  export const LOOPBACK_CONSOLE_IS_OWNER = true;
14
- export const SECRETS_REASONS = ["token", "sign_in", "no_accounts"];
15
14
  /** The one decision: whether a caller with these facts may write a secret, and if not, why. The owner's password session
16
15
  * always may; the accounts-off console on a loopback-bound server may where `loopbackConsoleIsOwner`
17
16
  * (LOOPBACK_CONSOLE_IS_OWNER); the API token never may, anywhere. */
@@ -16,6 +16,10 @@ export declare const defaultData: (env?: NodeJS.ProcessEnv) => string;
16
16
  * npxLine). */
17
17
  export declare const DATA_ENV = "AGENTRUN_SERVE_DATA";
18
18
  /** Agent `agentId`'s folder on the disk, which holds its learning folder (learning.ts) and its runs: `<data>/disk/agents/<agent>`. */
19
+ /** The folder of a data directory that holds each agent's disk: its runs and its learning. */
20
+ export declare const DISK_DIR = "disk";
21
+ /** Agent `agentId`'s folder on the disk of data directory `data`: `<data>/disk/agents/<name>`. */
22
+ export declare const agentDiskDir: (data: string, agentId: string) => string;
19
23
  export declare const agentFolderOf: (data: string, agentId: string) => string;
20
24
  /** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
21
25
  export declare const readJson: (path: string) => Promise<Json | null>;
package/dist/server-fs.js CHANGED
@@ -3,12 +3,11 @@
3
3
  // runner cutover deletes) can go on their own. Nothing here knows a run: it is whole-file writes made durable, a directory
4
4
  // sync, a JSON read that fails to null, a per-key work queue, the data-directory location and the names of the two files
5
5
  // the owner's CLI reads (the API token and the server record).
6
- import { randomBytes } from "node:crypto";
6
+ import { createHash, randomBytes } from "node:crypto";
7
7
  import { closeSync, constants, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
8
8
  import { open, readFile, rename, unlink, writeFile } from "node:fs/promises";
9
9
  import { homedir } from "node:os";
10
10
  import { dirname, join } from "node:path";
11
- import { agentDiskDir } from "@parcha/pi-durable-agent";
12
11
  /** The server's API token (`ar_local_...`), in the data directory, made at its first start when it is given none. */
13
12
  export const TOKEN_FILE = ".token";
14
13
  /** Where a running server is, for the launcher's CLI (`npx @parcha/agentrun agents list`), in the data directory: its
@@ -33,6 +32,13 @@ export const defaultData = (env = process.env) => join(env.XDG_DATA_HOME || join
33
32
  * npxLine). */
34
33
  export const DATA_ENV = "AGENTRUN_SERVE_DATA";
35
34
  /** Agent `agentId`'s folder on the disk, which holds its learning folder (learning.ts) and its runs: `<data>/disk/agents/<agent>`. */
35
+ /** The folder of a data directory that holds each agent's disk: its runs and its learning. */
36
+ export const DISK_DIR = "disk";
37
+ /** An agent's folder's name on the disk: its id in lower case, then 16 hex digits of the id's SHA-256, so ids that differ
38
+ * only in case never share one on a disk that folds case. */
39
+ const agentDirName = (agentId) => `${agentId.toLowerCase()}-${createHash("sha256").update(agentId, "utf8").digest("hex").slice(0, 16)}`;
40
+ /** Agent `agentId`'s folder on the disk of data directory `data`: `<data>/disk/agents/<name>`. */
41
+ export const agentDiskDir = (data, agentId) => join(data, DISK_DIR, "agents", agentDirName(agentId));
36
42
  export const agentFolderOf = (data, agentId) => agentDiskDir(data, agentId);
37
43
  /** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
38
44
  export const readJson = (path) => readFile(path, "utf8")
@@ -1,6 +1,4 @@
1
1
  export declare const SERVER_LOCK = "server.lock";
2
- /** The data root's server, as it last said: `{ pid, until }`, `until` (epoch ms) when it stops, null while it runs. */
3
- export declare const SERVER_STATE = "server.state";
4
2
  /** Another server holds the data root. Its message is the one line the CLI prints before it exits 1. */
5
3
  export declare class ServerLockHeldError extends Error {
6
4
  readonly code = "SERVER_LOCK_HELD";
@@ -20,25 +18,3 @@ export interface ServerLock {
20
18
  export declare function takeServerLock(dataRoot: string, options?: {
21
19
  chmod?: (file: string, mode: number) => void;
22
20
  }): ServerLock;
23
- /** A server that is stopping, by its mark: its process, and when its stop is over at the latest (epoch ms). */
24
- export type Stopping = {
25
- pid: number;
26
- until: number;
27
- };
28
- /** Records the data root's server as this process, running: once, as it starts, right after it takes the lock. */
29
- export declare function markRunning(dataRoot: string): void;
30
- /** Records the data root's server as stopping until `until`, as its close begins: the same file, rewritten in place in one
31
- * write of the same length, never made again (a record that is gone is left gone), so the stop adds no entry. */
32
- export declare function markStopping(dataRoot: string, until: number): void;
33
- /** The data root's server, when its record says it is stopping, its process lives and its time is still ahead; none
34
- * otherwise (no record, one that can't be read, a server that runs, or one that died as it stopped). */
35
- export declare function stoppingOf(dataRoot: string, now?: number): Stopping | undefined;
36
- /** Takes the data root's server lock, as takeServerLock. When another server holds it and is stopping (its record),
37
- * waits for that server as long as its process lives, under one cap, its record's `until` (the server's whole close:
38
- * its runs' drain, their carry backs and their boxes' cleanup), retrying every `everyMs`, and tells `waiting` once as it
39
- * starts to. A server that is not stopping is refused at once with ServerLockHeldError, as is one that still holds the
40
- * lock at its `until`, or a holder that is not the stopping server (its process gone, the lock still held). */
41
- export declare function takeServerLockAfterStop(dataRoot: string, options?: {
42
- waiting?: (stopping: Stopping) => void;
43
- everyMs?: number;
44
- }): Promise<ServerLock>;
@@ -9,24 +9,11 @@
9
9
  //
10
10
  // pi-durable-disk forgets a command record written in another pid namespace only under the precondition this lock
11
11
  // keeps: two servers never hold one data root at once.
12
- //
13
- // A server that stops keeps the lock until its runs' processes have drained and exited, which takes up to their drain
14
- // and a second. It says so in <data>/server.state: written once as the server starts, right after it takes the lock
15
- // (its pid, not stopping), and rewritten in place as its close begins (when its stop is over at the latest). A stop never
16
- // adds an entry to the data root, so a caller that removes the directory as soon as it signals the stop meets nothing
17
- // new there. A start that finds the lock held reads that file only then, and waits for a server that is stopping instead
18
- // of refusing it; a record whose pid is gone or whose time has passed is no stop.
19
- import { chmodSync, closeSync, openSync, readFileSync, writeFileSync, writeSync } from "node:fs";
12
+ import { chmodSync } from "node:fs";
20
13
  import { join } from "node:path";
21
14
  import { DatabaseSync } from "node:sqlite";
22
- import { processAlive } from "@parcha/agentrun-kernel/host";
23
15
  import { sqliteBusy } from "./agents.js";
24
16
  export const SERVER_LOCK = "server.lock";
25
- /** The data root's server, as it last said: `{ pid, until }`, `until` (epoch ms) when it stops, null while it runs. */
26
- export const SERVER_STATE = "server.state";
27
- /** The record's length on disk: its JSON padded with spaces, so a rewrite in place leaves no tail of an earlier one. */
28
- const STATE_BYTES = 128;
29
- const stateOf = (until) => Buffer.from(JSON.stringify({ pid: process.pid, until }).padEnd(STATE_BYTES - 1) + "\n");
30
17
  /** Another server holds the data root. Its message is the one line the CLI prints before it exits 1. */
31
18
  export class ServerLockHeldError extends Error {
32
19
  code = "SERVER_LOCK_HELD";
@@ -72,69 +59,3 @@ export function takeServerLock(dataRoot, options = {}) {
72
59
  },
73
60
  };
74
61
  }
75
- /** Records the data root's server as this process, running: once, as it starts, right after it takes the lock. */
76
- export function markRunning(dataRoot) {
77
- writeFileSync(join(dataRoot, SERVER_STATE), stateOf(null), { mode: 0o600 });
78
- }
79
- /** Records the data root's server as stopping until `until`, as its close begins: the same file, rewritten in place in one
80
- * write of the same length, never made again (a record that is gone is left gone), so the stop adds no entry. */
81
- export function markStopping(dataRoot, until) {
82
- let fd;
83
- try {
84
- fd = openSync(join(dataRoot, SERVER_STATE), "r+");
85
- }
86
- catch (error) {
87
- if (error.code === "ENOENT")
88
- return;
89
- throw error;
90
- }
91
- try {
92
- writeSync(fd, stateOf(until), 0, STATE_BYTES, 0);
93
- }
94
- finally {
95
- closeSync(fd);
96
- }
97
- }
98
- /** The data root's server, when its record says it is stopping, its process lives and its time is still ahead; none
99
- * otherwise (no record, one that can't be read, a server that runs, or one that died as it stopped). */
100
- export function stoppingOf(dataRoot, now = Date.now()) {
101
- let mark;
102
- try {
103
- mark = JSON.parse(readFileSync(join(dataRoot, SERVER_STATE), "utf8"));
104
- }
105
- catch {
106
- return undefined;
107
- }
108
- const { pid, until } = (mark ?? {});
109
- if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || typeof until !== "number" || !(until > now))
110
- return undefined;
111
- return processAlive(pid) ? { pid, until } : undefined;
112
- }
113
- /** Takes the data root's server lock, as takeServerLock. When another server holds it and is stopping (its record),
114
- * waits for that server as long as its process lives, under one cap, its record's `until` (the server's whole close:
115
- * its runs' drain, their carry backs and their boxes' cleanup), retrying every `everyMs`, and tells `waiting` once as it
116
- * starts to. A server that is not stopping is refused at once with ServerLockHeldError, as is one that still holds the
117
- * lock at its `until`, or a holder that is not the stopping server (its process gone, the lock still held). */
118
- export async function takeServerLockAfterStop(dataRoot, options = {}) {
119
- try {
120
- return takeServerLock(dataRoot);
121
- }
122
- catch (error) {
123
- if (!(error instanceof ServerLockHeldError))
124
- throw error;
125
- const stopping = stoppingOf(dataRoot);
126
- if (!stopping)
127
- throw error;
128
- options.waiting?.(stopping);
129
- for (;;) {
130
- await new Promise((resolve) => setTimeout(resolve, options.everyMs ?? 250));
131
- try {
132
- return takeServerLock(dataRoot);
133
- }
134
- catch (again) {
135
- if (!(again instanceof ServerLockHeldError) || Date.now() >= stopping.until || !processAlive(stopping.pid))
136
- throw again;
137
- }
138
- }
139
- }
140
- }
@@ -1,5 +1,5 @@
1
1
  import { type SealedSettingsOverStore } from "./sealed-settings-store.js";
2
- import { ServerSecrets } from "./server-secrets.js";
2
+ import { type ServerSecrets } from "./server-secrets.js";
3
3
  import type { TriggerAdapter } from "./trigger-adapter.js";
4
4
  import type { TriggerSettings } from "./store/index.js";
5
5
  /** The store slice this layer needs (handed to each adapter's sealed settings). */
@@ -7,11 +7,11 @@ type ServerSecretsStore = {
7
7
  readonly triggerSettings: Pick<TriggerSettings, "get" | "put" | "removeScope">;
8
8
  flush(): Promise<void>;
9
9
  };
10
- /** The server's own secrets over the store: the owner's token and the session secret (still files beside the store), the
11
- * outbound webhook's secret, and every adapter's sealed settings (now store rows), which are returned too, by adapter id,
10
+ /** The server's own secrets over the store: what it keeps beside the store (besideTheStore), every adapter's sealed
11
+ * settings and the outbound webhook's (OUTBOUND_WEBHOOK, its signing secret), store rows, which are returned too, by id,
12
12
  * for the server to keep using. Loads each adapter's settings before it answers (awaited once at start), so the redaction
13
13
  * list is whole from the first use. A value that does not open is said to `say`. */
14
- export declare function openServerSecretsOverStore(store: ServerSecretsStore, data: string, env: NodeJS.ProcessEnv, adapters: readonly TriggerAdapter[], say?: (fields: Record<string, string>) => void): Promise<{
14
+ export declare function openServerSecretsOverStore(store: ServerSecretsStore, data: string, env: NodeJS.ProcessEnv, adapters: readonly Pick<TriggerAdapter, "id" | "settings">[], say?: (fields: Record<string, string>) => void): Promise<{
15
15
  secrets: ServerSecrets;
16
16
  settings: Map<string, SealedSettingsOverStore>;
17
17
  }>;