@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.59

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 (404) hide show
  1. package/CHANGELOG.md +376 -0
  2. package/README.md +393 -118
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agents-store.js +1 -1
  8. package/dist/answer-text.d.ts +3 -0
  9. package/dist/answer-text.js +22 -0
  10. package/dist/api-only.d.ts +2 -4
  11. package/dist/api-only.js +2 -4
  12. package/dist/attach-conformance.js +5 -4
  13. package/dist/box-paths.d.ts +7 -5
  14. package/dist/box-paths.js +12 -8
  15. package/dist/browser-computer.d.ts +3 -8
  16. package/dist/browser-computer.js +12 -35
  17. package/dist/browser-cost.js +94 -20
  18. package/dist/capacity.d.ts +1 -1
  19. package/dist/capacity.js +3 -3
  20. package/dist/chatgpt-plan.d.ts +5 -0
  21. package/dist/chatgpt-plan.js +25 -11
  22. package/dist/claude-login-token.d.ts +121 -0
  23. package/dist/claude-login-token.js +797 -0
  24. package/dist/claude-login.d.ts +119 -34
  25. package/dist/claude-login.js +551 -79
  26. package/dist/claude-sign-in.d.ts +3 -0
  27. package/dist/claude-sign-in.js +10 -1
  28. package/dist/cli.js +325 -328
  29. package/dist/composio-made.d.ts +1 -6
  30. package/dist/composio-made.js +1 -6
  31. package/dist/composio-owners.d.ts +26 -0
  32. package/dist/composio-owners.js +36 -0
  33. package/dist/composio-preset.d.ts +56 -23
  34. package/dist/composio-preset.js +173 -77
  35. package/dist/composio-triggers.d.ts +4 -4
  36. package/dist/composio-triggers.js +6 -7
  37. package/dist/compute-cost.js +11 -2
  38. package/dist/computer-attach.d.ts +40 -19
  39. package/dist/computer-attach.js +326 -62
  40. package/dist/computer-held-routes.d.ts +1 -1
  41. package/dist/computer-held-routes.js +9 -4
  42. package/dist/computer-keys.d.ts +11 -1
  43. package/dist/computer-keys.js +26 -1
  44. package/dist/computer-record.js +3 -1
  45. package/dist/computer-view.d.ts +5 -3
  46. package/dist/computer-view.js +10 -6
  47. package/dist/computer-viewer.js +36 -7
  48. package/dist/computers.d.ts +12 -11
  49. package/dist/computers.js +11 -8
  50. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  51. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  52. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  53. package/dist/console/assets/share-L84tlUDW.js +6 -0
  54. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  55. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  56. package/dist/console/index.html +4 -3
  57. package/dist/console/share.html +17 -0
  58. package/dist/decisions.d.ts +17 -7
  59. package/dist/decisions.js +41 -15
  60. package/dist/dial-relay.d.ts +25 -4
  61. package/dist/dial-relay.js +139 -5
  62. package/dist/docker-daemon.js +4 -5
  63. package/dist/docker-host-addresses.js +29 -11
  64. package/dist/email/account.d.ts +6 -0
  65. package/dist/email/account.js +6 -0
  66. package/dist/email/authentication.d.ts +21 -0
  67. package/dist/email/authentication.js +106 -0
  68. package/dist/email/email-faux.d.ts +11 -2
  69. package/dist/email/email-faux.js +21 -5
  70. package/dist/email/mail.d.ts +25 -0
  71. package/dist/email/mail.js +58 -2
  72. package/dist/email/names.js +2 -2
  73. package/dist/email/tools.d.ts +9 -4
  74. package/dist/email/tools.js +95 -13
  75. package/dist/env-switch.d.ts +13 -5
  76. package/dist/env-switch.js +24 -6
  77. package/dist/errors.d.ts +1 -0
  78. package/dist/errors.js +2 -0
  79. package/dist/fal-price.d.ts +12 -4
  80. package/dist/fal-price.js +110 -26
  81. package/dist/faux-computers.js +1 -1
  82. package/dist/filed-answer.d.ts +2 -2
  83. package/dist/filed-answer.js +2 -2
  84. package/dist/graph-served.d.ts +10 -5
  85. package/dist/graph-served.js +40 -10
  86. package/dist/handed-values.js +1 -2
  87. package/dist/harness-check.d.ts +2 -1
  88. package/dist/harness-check.js +45 -12
  89. package/dist/harness-keys.js +9 -6
  90. package/dist/harness-opencode/facts.js +2 -0
  91. package/dist/harness-recipe-entry.d.ts +9 -3
  92. package/dist/harness-recipe-entry.js +18 -9
  93. package/dist/harness-recipe.d.ts +21 -0
  94. package/dist/harness-recipe.js +25 -3
  95. package/dist/harness-table.d.ts +8 -0
  96. package/dist/harness-table.js +17 -6
  97. package/dist/helper-env.d.ts +4 -1
  98. package/dist/helper-env.js +4 -1
  99. package/dist/host-check.d.ts +2 -3
  100. package/dist/host-check.js +13 -7
  101. package/dist/hosted-search.js +1 -1
  102. package/dist/import.d.ts +11 -8
  103. package/dist/import.js +437 -186
  104. package/dist/key-refusal.d.ts +9 -2
  105. package/dist/key-refusal.js +86 -32
  106. package/dist/learn/audit.d.ts +8 -5
  107. package/dist/learn/audit.js +15 -7
  108. package/dist/learn/compile.d.ts +5 -2
  109. package/dist/learn/compile.js +45 -21
  110. package/dist/learn/field-check.d.ts +111 -0
  111. package/dist/learn/field-check.js +174 -0
  112. package/dist/learn/ledger.d.ts +173 -0
  113. package/dist/learn/ledger.js +225 -0
  114. package/dist/learn/promote.d.ts +82 -39
  115. package/dist/learn/promote.js +61 -66
  116. package/dist/learn/secrets.d.ts +4 -0
  117. package/dist/learn/secrets.js +12 -0
  118. package/dist/learned-nodes.d.ts +8 -5
  119. package/dist/learned-nodes.js +8 -5
  120. package/dist/learned-workflow.d.ts +2 -1
  121. package/dist/learned-workflow.js +13 -10
  122. package/dist/learning-cost.d.ts +40 -21
  123. package/dist/learning-cost.js +30 -21
  124. package/dist/learning-setting.d.ts +6 -0
  125. package/dist/learning-setting.js +11 -1
  126. package/dist/listen-first.d.ts +5 -4
  127. package/dist/listen-first.js +4 -5
  128. package/dist/live-reach.d.ts +9 -0
  129. package/dist/live-reach.js +9 -0
  130. package/dist/mcp-api-only-origins.d.ts +23 -3
  131. package/dist/mcp-api-only-origins.js +57 -17
  132. package/dist/mcp-gateway.d.ts +16 -2
  133. package/dist/mcp-gateway.js +41 -3
  134. package/dist/mcp-oauth.d.ts +1 -1
  135. package/dist/mcp-oauth.js +3 -2
  136. package/dist/mcp-probe.d.ts +3 -0
  137. package/dist/mcp-probe.js +3 -0
  138. package/dist/mcp-secret-writes.d.ts +24 -2
  139. package/dist/mcp-secret-writes.js +30 -2
  140. package/dist/mcp-servers-store.d.ts +52 -14
  141. package/dist/mcp-servers-store.js +165 -61
  142. package/dist/mcp-sources.d.ts +1 -2
  143. package/dist/mcp-sources.js +1 -2
  144. package/dist/mcp-store.d.ts +5 -5
  145. package/dist/mcp-store.js +3 -3
  146. package/dist/mcp.js +1 -1
  147. package/dist/micro.d.ts +2 -0
  148. package/dist/micro.js +2 -0
  149. package/dist/model-gateway.d.ts +1 -1
  150. package/dist/model-gateway.js +20 -36
  151. package/dist/model.d.ts +5 -4
  152. package/dist/model.js +7 -6
  153. package/dist/monid.d.ts +14 -1
  154. package/dist/monid.js +103 -26
  155. package/dist/ollama-provider.d.ts +23 -9
  156. package/dist/ollama-provider.js +49 -20
  157. package/dist/openapi.js +234 -61
  158. package/dist/otel/genai.d.ts +83 -7
  159. package/dist/otel/genai.js +69 -9
  160. package/dist/otel/tracer.d.ts +42 -13
  161. package/dist/otel/tracer.js +241 -56
  162. package/dist/page.d.ts +7 -1
  163. package/dist/page.js +76 -22
  164. package/dist/paid-calls.d.ts +6 -4
  165. package/dist/paid-calls.js +15 -7
  166. package/dist/place-offers.d.ts +59 -34
  167. package/dist/place-offers.js +100 -58
  168. package/dist/place.d.ts +13 -14
  169. package/dist/place.js +56 -41
  170. package/dist/print.js +1 -1
  171. package/dist/provider.d.ts +5 -4
  172. package/dist/provider.js +26 -13
  173. package/dist/redact/match.d.ts +27 -9
  174. package/dist/redact/match.js +266 -57
  175. package/dist/run-census.d.ts +1 -1
  176. package/dist/run-census.js +4 -5
  177. package/dist/run-cut.js +4 -5
  178. package/dist/run-export-store.d.ts +15 -0
  179. package/dist/run-export-store.js +30 -0
  180. package/dist/run-export.d.ts +139 -0
  181. package/dist/run-export.js +379 -0
  182. package/dist/run-file-cut.d.ts +5 -0
  183. package/dist/run-file-cut.js +13 -0
  184. package/dist/run-launch.js +16 -3
  185. package/dist/run-learning-served.d.ts +2 -2
  186. package/dist/run-model-key.d.ts +15 -6
  187. package/dist/run-model-key.js +30 -31
  188. package/dist/run-reads-over-store.js +4 -4
  189. package/dist/run-secrets.js +3 -5
  190. package/dist/run-timeline-served.js +3 -1
  191. package/dist/run-view.d.ts +1 -2
  192. package/dist/run-view.js +2 -1
  193. package/dist/runnable.js +2 -2
  194. package/dist/runner/adapter-loop.d.ts +35 -18
  195. package/dist/runner/adapter-loop.js +97 -63
  196. package/dist/runner/adapter-run-spec.d.ts +34 -14
  197. package/dist/runner/adapter-run-spec.js +120 -75
  198. package/dist/runner/adapters/pi.js +4 -2
  199. package/dist/runner/audit.d.ts +8 -5
  200. package/dist/runner/audit.js +37 -17
  201. package/dist/runner/beside.d.ts +9 -2
  202. package/dist/runner/beside.js +29 -13
  203. package/dist/runner/claim-secrets.d.ts +27 -18
  204. package/dist/runner/claim-secrets.js +61 -47
  205. package/dist/runner/cli-run-spec.d.ts +18 -0
  206. package/dist/runner/cli-run-spec.js +93 -46
  207. package/dist/runner/compare-end.d.ts +2 -1
  208. package/dist/runner/compare-end.js +25 -10
  209. package/dist/runner/conformance/harness.js +2 -3
  210. package/dist/runner/conformance/subject.d.ts +4 -1
  211. package/dist/runner/harness-loops.js +3 -3
  212. package/dist/runner/held.d.ts +19 -4
  213. package/dist/runner/journal-kinds.d.ts +4 -1
  214. package/dist/runner/journal-kinds.js +22 -4
  215. package/dist/runner/learned-first.js +20 -4
  216. package/dist/runner/learning-end.d.ts +2 -8
  217. package/dist/runner/learning-end.js +11 -19
  218. package/dist/runner/live-ticker.js +7 -5
  219. package/dist/runner/loop-contract.d.ts +0 -2
  220. package/dist/runner/loop.d.ts +7 -0
  221. package/dist/runner/loop.js +1 -0
  222. package/dist/runner/main.d.ts +11 -6
  223. package/dist/runner/main.js +24 -18
  224. package/dist/runner/mcp-claim.js +24 -7
  225. package/dist/runner/mcp-run.d.ts +3 -6
  226. package/dist/runner/mcp-run.js +3 -4
  227. package/dist/runner/meta-tools.js +3 -2
  228. package/dist/runner/metrics.d.ts +7 -0
  229. package/dist/runner/metrics.js +19 -0
  230. package/dist/runner/model-route.d.ts +10 -7
  231. package/dist/runner/model-route.js +79 -15
  232. package/dist/runner/native-loop.js +10 -8
  233. package/dist/runner/presence.d.ts +11 -4
  234. package/dist/runner/presence.js +11 -6
  235. package/dist/runner/promotion.d.ts +25 -13
  236. package/dist/runner/promotion.js +125 -50
  237. package/dist/runner/redact.d.ts +3 -1
  238. package/dist/runner/redact.js +5 -3
  239. package/dist/runner/reflect-hook.js +1 -1
  240. package/dist/runner/responses-fetch.d.ts +36 -0
  241. package/dist/runner/responses-fetch.js +511 -0
  242. package/dist/runner/run-child-host.d.ts +38 -12
  243. package/dist/runner/run-child-host.js +231 -83
  244. package/dist/runner/run-child.js +11 -4
  245. package/dist/runner/runner-check.js +5 -1
  246. package/dist/runner/runner.d.ts +5 -3
  247. package/dist/runner/runner.js +14 -10
  248. package/dist/runner/save-slots.js +2 -1
  249. package/dist/runner/sdk-loop.js +8 -8
  250. package/dist/runner/spec-holds.d.ts +8 -1
  251. package/dist/runner/spec-holds.js +9 -4
  252. package/dist/runner/subagent.d.ts +11 -0
  253. package/dist/runner/subagent.js +17 -3
  254. package/dist/runner/workflow-calls.d.ts +9 -0
  255. package/dist/runner/workflow-calls.js +150 -0
  256. package/dist/runner/workflow-first.d.ts +138 -37
  257. package/dist/runner/workflow-first.js +230 -99
  258. package/dist/runner/workflow-spec.js +2 -2
  259. package/dist/runs-over-store.js +8 -7
  260. package/dist/save-once.d.ts +14 -0
  261. package/dist/save-once.js +31 -0
  262. package/dist/scrub-command.d.ts +34 -31
  263. package/dist/scrub-command.js +116 -147
  264. package/dist/sdk/runs.d.ts +6 -0
  265. package/dist/sdk/runs.js +89 -10
  266. package/dist/seal-key.js +4 -4
  267. package/dist/secret-cut.d.ts +3 -0
  268. package/dist/secret-cut.js +7 -1
  269. package/dist/secret-rules.d.ts +8 -1
  270. package/dist/secret-rules.js +482 -53
  271. package/dist/secrets.d.ts +51 -9
  272. package/dist/secrets.js +311 -21
  273. package/dist/server-keys.d.ts +4 -3
  274. package/dist/server-keys.js +4 -3
  275. package/dist/server-secrets-store.js +2 -4
  276. package/dist/server.d.ts +33 -10
  277. package/dist/server.js +454 -136
  278. package/dist/share-context.d.ts +22 -0
  279. package/dist/share-context.js +76 -0
  280. package/dist/shell-lex.d.ts +105 -0
  281. package/dist/shell-lex.js +646 -0
  282. package/dist/sign-ins-store.d.ts +5 -7
  283. package/dist/sign-ins-store.js +12 -16
  284. package/dist/sign-ins.d.ts +7 -11
  285. package/dist/sign-ins.js +40 -41
  286. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  287. package/dist/slots.d.ts +9 -0
  288. package/dist/slots.js +45 -0
  289. package/dist/start-switches.d.ts +6 -5
  290. package/dist/start-switches.js +8 -4
  291. package/dist/stats.d.ts +5 -1
  292. package/dist/stats.js +1 -1
  293. package/dist/store/agent-body.js +2 -2
  294. package/dist/store/dialect.d.ts +4 -0
  295. package/dist/store/dialect.js +1 -0
  296. package/dist/store/index.d.ts +2 -2
  297. package/dist/store/index.js +1 -1
  298. package/dist/store/mcp-record-keys.d.ts +10 -0
  299. package/dist/store/mcp-record-keys.js +13 -0
  300. package/dist/store/postgres/dialect.js +2 -0
  301. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  302. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  303. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  304. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  305. package/dist/store/postgres/store.js +4 -0
  306. package/dist/store/schema.d.ts +44 -4
  307. package/dist/store/schema.js +111 -11
  308. package/dist/store/seal.d.ts +4 -1
  309. package/dist/store/sqlite/run-launch.d.ts +3 -10
  310. package/dist/store/sqlite/run-launch.js +12 -23
  311. package/dist/store/sqlite/run-patch.d.ts +19 -2
  312. package/dist/store/sqlite/run-patch.js +67 -2
  313. package/dist/store/sqlite/store.d.ts +3 -0
  314. package/dist/store/sqlite/store.js +177 -32
  315. package/dist/store/store-schema.js +3 -4
  316. package/dist/store/store.d.ts +74 -25
  317. package/dist/store/store.js +14 -11
  318. package/dist/store-reads/analytics.d.ts +2 -1
  319. package/dist/store-reads/analytics.js +7 -5
  320. package/dist/store-reads/learning.d.ts +102 -136
  321. package/dist/store-reads/learning.js +251 -302
  322. package/dist/store-reads/stats.d.ts +2 -2
  323. package/dist/store-reads/stats.js +13 -7
  324. package/dist/store-view.js +10 -7
  325. package/dist/suggestions.d.ts +1 -1
  326. package/dist/suggestions.js +29 -13
  327. package/dist/template-eval.d.ts +91 -9
  328. package/dist/template-eval.js +448 -105
  329. package/dist/template-import.d.ts +0 -10
  330. package/dist/template-import.js +5 -10
  331. package/dist/timeline/labels.d.ts +1 -1
  332. package/dist/timeline/labels.js +4 -3
  333. package/dist/timeline/timeline.d.ts +23 -11
  334. package/dist/timeline/timeline.js +115 -31
  335. package/dist/timeline/web-calls.d.ts +14 -14
  336. package/dist/timeline/web-calls.js +18 -30
  337. package/dist/tool-gate.d.ts +13 -1
  338. package/dist/tool-gate.js +43 -3
  339. package/dist/tool-keys-store.js +2 -4
  340. package/dist/tool-keys.d.ts +11 -0
  341. package/dist/tool-keys.js +16 -0
  342. package/dist/tool-plane.d.ts +50 -11
  343. package/dist/tool-plane.js +94 -30
  344. package/dist/tools.d.ts +5 -1
  345. package/dist/tools.js +7 -7
  346. package/dist/trigger-email.js +12 -6
  347. package/dist/triggers.d.ts +15 -34
  348. package/dist/triggers.js +119 -126
  349. package/dist/validate.d.ts +8 -1
  350. package/dist/validate.js +163 -23
  351. package/dist/web-fake.d.ts +2 -1
  352. package/dist/web-fake.js +8 -6
  353. package/dist/web-fetch.d.ts +8 -6
  354. package/dist/web-fetch.js +13 -11
  355. package/dist/web-holds.d.ts +32 -0
  356. package/dist/web-holds.js +86 -0
  357. package/dist/web-run.d.ts +32 -5
  358. package/dist/web-run.js +75 -28
  359. package/dist/web-save.d.ts +4 -9
  360. package/dist/web-save.js +27 -55
  361. package/dist/web-search.js +14 -25
  362. package/dist/wires.d.ts +4 -3
  363. package/dist/wires.js +5 -4
  364. package/dist/workspace/archil-claim.d.ts +12 -5
  365. package/dist/workspace/archil-claim.js +45 -5
  366. package/dist/workspace/attach.js +52 -19
  367. package/dist/workspace/attached-computers.d.ts +38 -11
  368. package/dist/workspace/attached-computers.js +81 -16
  369. package/dist/workspace/computer-deps.d.ts +29 -7
  370. package/dist/workspace/computer-deps.js +36 -18
  371. package/dist/workspace/computer-for-claim.d.ts +21 -4
  372. package/dist/workspace/computer-for-claim.js +166 -57
  373. package/dist/workspace/computer-intervals.d.ts +2 -0
  374. package/dist/workspace/computer-intervals.js +1 -1
  375. package/dist/workspace/computer-janitor.d.ts +48 -14
  376. package/dist/workspace/computer-janitor.js +153 -44
  377. package/dist/workspace/computer-kept.d.ts +158 -32
  378. package/dist/workspace/computer-kept.js +288 -63
  379. package/dist/workspace/computer-providers.d.ts +8 -3
  380. package/dist/workspace/computer-providers.js +12 -5
  381. package/dist/workspace/index.d.ts +1 -1
  382. package/dist/workspace/index.js +1 -1
  383. package/dist/workspace/local.js +41 -1
  384. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  385. package/dist/workspace/mount-revoke-left.js +72 -0
  386. package/dist/workspace/paired-route.d.ts +91 -0
  387. package/dist/workspace/paired-route.js +152 -0
  388. package/dist/workspace/resolve-computer.d.ts +5 -2
  389. package/dist/workspace/resolve-computer.js +9 -3
  390. package/dist/workspace/run-end-computers.d.ts +11 -5
  391. package/dist/workspace/run-end-computers.js +153 -28
  392. package/dist/workspace/run-tools.d.ts +22 -3
  393. package/dist/workspace/run-tools.js +17 -5
  394. package/dist/workspace/run-workspace.d.ts +14 -1
  395. package/dist/workspace/run-workspace.js +34 -1
  396. package/dist/workspace/workspace.d.ts +6 -0
  397. package/dist/wrapped.d.ts +8 -2
  398. package/dist/wrapped.js +21 -6
  399. package/package.json +12 -13
  400. package/skills/agentrun-serve/SKILL.md +5 -2
  401. package/templates/README.md +25 -9
  402. package/dist/console/assets/backend-DVhHzJX2.js +0 -166
  403. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  404. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -12,21 +12,142 @@
12
12
  // runner's listener (computer-attach.ts relayDial) with the proxy's proof under the seal key (live-reach.ts relayProof).
13
13
  // The listener answers nothing without a good, fresh proof it has not taken before, for this token, this runner and
14
14
  // this incarnation, on loopback too, and its attach routes take only a token whose row names this runner and
15
- // incarnation. The daemon fetch stays the server's; nothing changes on the machine.
15
+ // incarnation. A paired box's token, which never expires, reaches it as its SHA-256 alone (live-reach.ts
16
+ // RELAY_TOKEN_HEADER), never as itself; a minted machine's, of one run, as its bearer. The daemon fetch stays the
17
+ // server's; nothing changes on the machine.
16
18
  //
17
19
  // A runner with no public address keeps no relay: its dial providers still refuse (hosted/provider.ts), and the server's
18
20
  // Settings → Computers still says so (computers.ts runs_refused).
21
+ //
22
+ // A paired computer reaches a run on this runner the same way (`paired`): the run's claim routes the box here
23
+ // (workspace/paired-route.ts takeRoute, under the run's claim) and waits until the server has moved its socket onto this
24
+ // hub (bring), and the run's release lets it go (letGo) once its hold ended, every remove or KILL it sent answered. The
25
+ // listener takes a paired computer's token only while its route names this runner and incarnation. A route this runner
26
+ // brought whose hold ended (released, or at its deadline) with no bring in flight is dropped at the next sweep
27
+ // (PRESENCE_RENEW_MS); and when the box's socket leaves this hub for a route that names another runner (the run resumed
28
+ // there), this runner's hold of it ends.
29
+ //
30
+ // The runner beside a server, in its process, brings and lets go of a paired box the same way (pairedRelayOn over the
31
+ // server's own hub, runner/beside.ts): its run's claim takes the box's route under that runner's name and incarnation,
32
+ // so a runner apart's take for another run is refused while the hold lasts, and the server's tick, which knows that
33
+ // runner (Serve.beside), keeps the box in its own hub.
19
34
  import { createServer } from "node:http";
35
+ import { setTimeout as sleep } from "node:timers/promises";
20
36
  import { ATTACH_PATH, AttachHub } from "@parcha/agentrun-computer";
21
37
  import { bearerOf, createAttachRoutes, sha256Hex } from "./computer-attach.js";
22
- import { LOOPBACK, relayKeyOf, relayProofs, runnerLiveOf } from "./live-reach.js";
38
+ import { isTokenSha256, LOOPBACK, RELAY_TOKEN_HEADER, relayKeyOf, relayProofs, runnerLiveOf } from "./live-reach.js";
23
39
  import { logLine } from "./print.js";
40
+ import { PRESENCE_RENEW_MS } from "./runner/presence.js";
41
+ import { PAIRED_ID_PREFIX } from "./workspace/attached-computers.js";
42
+ import { dropRoute, lateWords, PAIRED_BRING_MS, PAIRED_BRING_POLL_MS, readRoute, takeRoute } from "./workspace/paired-route.js";
43
+ /** A claim's failure to have its paired computer here, in words: the claim fails computer_unavailable with them. */
44
+ const unavailable = (words) => Object.assign(new Error(words), { code: "computer_unavailable" });
45
+ /** A bring whose claim was cancelled (its create's signal aborted) before the box reached runner `runner`. */
46
+ const cancelledWords = (name, runner) => `${name} was not brought to runner ${runner}: this run's claim was cancelled while it waited for the box, and its route was let go`;
24
47
  /** The server's public address as this runner's environment names it (cli.ts reads the same two), or undefined. */
25
48
  export function publicUrlOf(env) {
26
49
  const given = env.AGENTRUN_PUBLIC_URL || env.RENDER_EXTERNAL_URL;
27
50
  const parsed = given && URL.canParse(given) ? new URL(given) : undefined;
28
51
  return parsed && /^https?:$/.test(parsed.protocol) ? parsed.href.replace(/\/+$/, "") : undefined;
29
52
  }
53
+ /** The paired computers' bring and let-go over `hub` for runner `runner` of incarnation `incarnation`: a runner apart's
54
+ * own hub (startRunnerRelay), or the server's for the runner beside it in its process (runner/beside.ts). `left` is
55
+ * told when a box's socket leaves the hub; `stop` ends the sweep of the routes it brought. */
56
+ export function pairedRelayOn(options) {
57
+ const { store, hub, runner, incarnation, now = Date.now } = options;
58
+ const log = options.log ?? (() => { });
59
+ const mine = { runner, incarnation };
60
+ /** The routes this process brought, by computer: the run, when it was taken, and whether a hold was seen on it. */
61
+ const held = new Map();
62
+ /** The bring in flight per computer, by its run. */
63
+ const bringing = new Map();
64
+ /** When the box's socket leaves this hub: a route that now names another runner (or another process of this one)
65
+ * ends this runner's hold of it (the run resumed there); a route still here keeps it, for the box's redial. */
66
+ const left = async (id) => {
67
+ const route = await readRoute(store.settings, id);
68
+ if (route.runner === runner && route.incarnation === incarnation)
69
+ return;
70
+ const hold = hub.hold(id);
71
+ if (hold !== undefined)
72
+ await hub.unclaim(id, hold);
73
+ held.delete(id);
74
+ };
75
+ const paired = {
76
+ hub,
77
+ async bring(row, { run, until, claim, signal }) {
78
+ // A claim cancelled before its bring takes nothing.
79
+ if (signal?.aborted)
80
+ throw unavailable(cancelledWords(row.name, runner));
81
+ bringing.set(row.id, run);
82
+ try {
83
+ const took = await takeRoute({ settings: store.settings, runners: store.runners, runs: store.runs }, row.id, { ...mine, run, until }, { ...(claim ? { claim } : {}), name: row.name });
84
+ if (!took.taken)
85
+ throw unavailable(took.why);
86
+ held.set(row.id, { run, since: now(), seenHold: false });
87
+ const end = now() + PAIRED_BRING_MS;
88
+ for (;;) {
89
+ // The claim was cancelled while it waited: its route goes (the row removed while it is still this run's), and
90
+ // the claim fails in words at once, never waiting out PAIRED_BRING_MS.
91
+ if (signal?.aborted) {
92
+ await dropRoute(store.settings, row.id, { ...mine, run }).catch(() => undefined);
93
+ held.delete(row.id);
94
+ throw unavailable(cancelledWords(row.name, runner));
95
+ }
96
+ if (hub.online(row.id))
97
+ return;
98
+ const route = await readRoute(store.settings, row.id);
99
+ const ours = route.runner === runner && route.incarnation === incarnation && route.run === run;
100
+ // The server noted why the box can't come (not attached now, its relay refused), or the time is up: the route
101
+ // goes, its words kept on the row, and the claim fails in them. Never a hang.
102
+ const why = !ours ? (route.refused ?? `${row.name}'s route went to another run while this run waited for it: its next claim tries again`) : (route.refused ?? (now() >= end ? lateWords(row.name, runner) : undefined));
103
+ if (why !== undefined) {
104
+ if (ours)
105
+ await dropRoute(store.settings, row.id, { ...mine, run }, why).catch(() => undefined);
106
+ held.delete(row.id);
107
+ throw unavailable(why);
108
+ }
109
+ // A cancel wakes the wait at once; the loop's top answers it.
110
+ await sleep(PAIRED_BRING_POLL_MS, undefined, signal ? { signal } : undefined).catch(() => undefined);
111
+ }
112
+ }
113
+ finally {
114
+ if (bringing.get(row.id) === run)
115
+ bringing.delete(row.id);
116
+ }
117
+ },
118
+ async letGo(computer, hold, run) {
119
+ // Its hold ends first: unclaim waits for every remove or KILL it sent. A route stays while a hold is left here, or
120
+ // while another run's bring is in flight here.
121
+ if (hold !== undefined)
122
+ await hub.unclaim(computer, hold);
123
+ if (hub.hold(computer) !== undefined)
124
+ return;
125
+ const bring = bringing.get(computer);
126
+ if (bring !== undefined && bring !== run)
127
+ return;
128
+ held.delete(computer);
129
+ await dropRoute(store.settings, computer, { ...mine, ...(run !== undefined ? { run } : {}) });
130
+ },
131
+ };
132
+ // The sweep of the routes this process brought: one whose hold ended (released, or at its deadline), or that no hold
133
+ // took within PAIRED_BRING_MS, with no bring in flight, goes.
134
+ const sweep = setInterval(() => {
135
+ for (const [id, at] of held) {
136
+ if (bringing.has(id))
137
+ continue;
138
+ if (hub.hold(id) !== undefined) {
139
+ at.seenHold = true;
140
+ continue;
141
+ }
142
+ if (!at.seenHold && now() - at.since < PAIRED_BRING_MS)
143
+ continue;
144
+ held.delete(id);
145
+ void dropRoute(store.settings, id, { ...mine, run: at.run }).catch((error) => log(logLine("computer_route_undropped", { computer: id, run: at.run, error: error instanceof Error ? error.message : String(error) })));
146
+ }
147
+ }, PRESENCE_RENEW_MS);
148
+ sweep.unref();
149
+ return { paired, left, stop: () => clearInterval(sweep) };
150
+ }
30
151
  /** The runner's relay, started: undefined where its environment names no public address of the server's. */
31
152
  export async function startRunnerRelay(options) {
32
153
  const url = publicUrlOf(options.env);
@@ -38,9 +159,16 @@ export async function startRunnerRelay(options) {
38
159
  const live = runnerLiveOf(options.env, options.sealKey);
39
160
  const host = live?.host ?? LOOPBACK;
40
161
  const hub = new AttachHub();
162
+ const mine = { runner, incarnation };
163
+ const relayed = pairedRelayOn({ store, hub, runner, incarnation, log, now });
164
+ const { paired } = relayed;
41
165
  const routes = createAttachRoutes({
42
- store, hub, machinesOnly: true, owner: { runner, incarnation }, now,
166
+ store, hub, owner: mine, now,
43
167
  log: (event, fields) => log(logLine(event, fields)),
168
+ onSocket: (computer, ws) => {
169
+ if (computer.startsWith(PAIRED_ID_PREFIX))
170
+ ws.once("close", () => void relayed.left(computer).catch(() => undefined));
171
+ },
44
172
  ...(options.timing ? { timing: options.timing } : {}),
45
173
  });
46
174
  const proven = relayProofs(relayKeyOf(options.sealKey), now);
@@ -54,10 +182,14 @@ export async function startRunnerRelay(options) {
54
182
  socket.on("error", () => socket.destroy());
55
183
  if ((req.url ?? "/").split("?")[0] !== ATTACH_PATH)
56
184
  return deny(socket, "404 Not Found");
185
+ // A token named one way: a minted machine's as its bearer, a paired box's by its SHA-256 alone (RELAY_TOKEN_HEADER),
186
+ // never both.
57
187
  const bearer = bearerOf(req.headers.authorization);
58
- if (bearer === undefined || !proven(req, { tokenSha256: sha256Hex(bearer), runner, incarnation }))
188
+ const hashed = req.headers[RELAY_TOKEN_HEADER];
189
+ const tokenSha256 = hashed === undefined ? (bearer === undefined ? undefined : sha256Hex(bearer)) : bearer === undefined && isTokenSha256(hashed) ? hashed : undefined;
190
+ if (tokenSha256 === undefined || !proven(req, { tokenSha256, runner, incarnation }))
59
191
  return deny(socket, "401 Unauthorized");
60
- routes.upgrade(req, socket, head, (status, words, headers) => deny(socket, status, words, headers));
192
+ routes.upgrade(req, socket, head, (status, words, headers) => deny(socket, status, words, headers), hashed === undefined ? undefined : { tokenSha256 });
61
193
  });
62
194
  await new Promise((resolve, reject) => {
63
195
  server.once("error", reject);
@@ -65,6 +197,7 @@ export async function startRunnerRelay(options) {
65
197
  });
66
198
  const port = server.address().port;
67
199
  const shut = async () => {
200
+ relayed.stop();
68
201
  await routes.close();
69
202
  server.closeAllConnections();
70
203
  await new Promise((resolve) => server.close(() => resolve()));
@@ -80,6 +213,7 @@ export async function startRunnerRelay(options) {
80
213
  let closing;
81
214
  return {
82
215
  dial: { url, tokens: routes.machineTokens, hub },
216
+ paired,
83
217
  incarnation,
84
218
  host,
85
219
  port,
@@ -2,7 +2,7 @@
2
2
  // within a short bound, the answer kept for a while and asked again after it, so a daemon that comes up after the start
3
3
  // is seen. Settings → Computers' view, a run's start check and the claim's launch read it, and say one thing when no
4
4
  // daemon answers (noDockerWords): a hosted server (Render and the like) runs none, so a vendor's computer is the way.
5
- import { askDockerDaemon } from "./place-offers.js";
5
+ import { askDockerDaemon, NO_DOCKER_HERE } from "./place-offers.js";
6
6
  /** How long one ask of the daemon may take: a daemon that does not answer within it is taken as none. */
7
7
  export const DAEMON_ASK_MS = 3_000;
8
8
  /** How long an answer is kept before the next read asks again. */
@@ -46,11 +46,10 @@ const either = (names) => (names.length < 2 ? names.join("") : `${names.slice(0,
46
46
  * daemon: a sandbox holds the run's folder, so it is one that mounts Archil, and in Mode 1 those need Archil turned on
47
47
  * first; a desktop, phone or browser holds none, so any that takes no folder of this machine (no bind) does. */
48
48
  export function noDockerWords(kind, providers, mode) {
49
- const NO_DOCKER = "No Docker on this server: Render and most hosted services run none.";
50
49
  const vendors = providers.filter((one) => one.kinds.includes(kind) && (kind === "sandbox" ? one.mounts.includes("archil") : !one.mounts.includes("bind"))).map((one) => one.label);
51
50
  if (vendors.length === 0)
52
- return `${NO_DOCKER} Pick another kind of computer, or none.`;
51
+ return `${NO_DOCKER_HERE} Pick another kind of computer, or none.`;
53
52
  if (kind === "sandbox" && mode === 1)
54
- return `${NO_DOCKER} A vendor sandbox (${either(vendors)}) needs Archil turned on in Settings → Workspace.`;
55
- return `${NO_DOCKER} Use a vendor computer, e.g. ${either(vendors)} for a ${kind}.`;
53
+ return `${NO_DOCKER_HERE} A vendor sandbox (${either(vendors)}) needs Archil turned on in Settings → Workspace.`;
54
+ return `${NO_DOCKER_HERE} Use a vendor computer, e.g. ${either(vendors)} for a ${kind}.`;
56
55
  }
@@ -140,20 +140,38 @@ export function unionOf(read, named) {
140
140
  return "why" in read ? { addresses, why: read.why } : { addresses };
141
141
  }
142
142
  /** One read per process, for each environment's docker (the binary PATH finds and the daemon it reaches), kept once it
143
- * succeeds: a server and the runner beside it share it, and a failed read is tried again at the next ask. A read this
144
- * call starts ends at `signal` (readHostAddresses). */
143
+ * succeeds: a server and the runner beside it share it, and a failed read is tried again at the next ask. A read in
144
+ * flight ends when any caller's `signal` aborts, whoever started it (the runner beside the server starts one with no
145
+ * signal): the server's stop then waits for the read's removal by name, not for the read's own bound. */
145
146
  const reads = new Map();
147
+ const cuts = new Map();
146
148
  export function hostAddressesOnce(env, signal) {
147
149
  const key = envKey(env);
148
- const known = reads.get(key);
149
- if (known)
150
- return known;
151
- const read = readHostAddresses(env, undefined, undefined, undefined, signal).then((result) => {
152
- if ("why" in result)
153
- reads.delete(key);
154
- return result;
155
- });
156
- reads.set(key, read);
150
+ let read = reads.get(key);
151
+ if (!read) {
152
+ const cut = new AbortController();
153
+ cuts.set(key, cut);
154
+ read = readHostAddresses(env, undefined, undefined, undefined, cut.signal).then((result) => {
155
+ if ("why" in result)
156
+ reads.delete(key);
157
+ cuts.delete(key);
158
+ return result;
159
+ });
160
+ reads.set(key, read);
161
+ }
162
+ const cut = cuts.get(key);
163
+ if (signal && cut) {
164
+ if (signal.aborted)
165
+ cut.abort();
166
+ else {
167
+ // The server's retry asks again on its one stop signal for every read while Docker stays down: the handler goes
168
+ // when this read settles, or a long outage piles one up per read.
169
+ const onAbort = () => cut.abort();
170
+ signal.addEventListener("abort", onAbort, { once: true });
171
+ const drop = () => signal.removeEventListener("abort", onAbort);
172
+ void read.then(drop, drop);
173
+ }
174
+ }
157
175
  return read;
158
176
  }
159
177
  /** The waits before each read again after a read failed at the start, the last one repeated: soon at first, as a busy
@@ -50,6 +50,12 @@ export declare const accountRowSecrets: (plain: string) => string[];
50
50
  /** Whether the saved account is Gmail's, by its preset or its IMAP host: what a tool's description says before any
51
51
  * connection (a call itself goes by the server's X-GM-EXT-1). */
52
52
  export declare const isGmailAccount: (account: Pick<EmailAccount, "preset" | "imap">) => boolean;
53
+ /** The authserv-id Gmail's receiving servers write on the Authentication-Results they put on every message they take in. */
54
+ export declare const GMAIL_AUTHSERV_ID = "mx.google.com";
55
+ /** The authserv-id (RFC 8601) the account's provider's receiving servers write on their own Authentication-Results, the
56
+ * only ones a starter's DMARC pass is read from (authentication.ts dmarcPassed): Gmail's (isGmailAccount). Undefined for
57
+ * any other provider, whose id isn't known here, so no message there carries a verdict (fail closed). */
58
+ export declare const authservIdOf: (account: Pick<EmailAccount, "preset" | "imap">) => string | undefined;
53
59
  /** The account's public part as kept now, never its password; undefined when none is kept or it does not open. */
54
60
  export declare function keptAccount(store: AccountStore, sealKey: Buffer, account?: string): Promise<EmailAccount | undefined>;
55
61
  /** The account kept now, opened with `sealKey`; undefined when none is kept, or its row does not open (sealed under
@@ -118,6 +118,12 @@ export const accountRowSecrets = (plain) => {
118
118
  /** Whether the saved account is Gmail's, by its preset or its IMAP host: what a tool's description says before any
119
119
  * connection (a call itself goes by the server's X-GM-EXT-1). */
120
120
  export const isGmailAccount = (account) => account.preset === "gmail" || /(^|\.)gmail\.com$/i.test(account.imap.host);
121
+ /** The authserv-id Gmail's receiving servers write on the Authentication-Results they put on every message they take in. */
122
+ export const GMAIL_AUTHSERV_ID = "mx.google.com";
123
+ /** The authserv-id (RFC 8601) the account's provider's receiving servers write on their own Authentication-Results, the
124
+ * only ones a starter's DMARC pass is read from (authentication.ts dmarcPassed): Gmail's (isGmailAccount). Undefined for
125
+ * any other provider, whose id isn't known here, so no message there carries a verdict (fail closed). */
126
+ export const authservIdOf = (account) => (isGmailAccount(account) ? GMAIL_AUTHSERV_ID : undefined);
121
127
  /** The account's public part as kept now, never its password; undefined when none is kept or it does not open. */
122
128
  export async function keptAccount(store, sealKey, account = DEFAULT_ACCOUNT) {
123
129
  const opened = await openAccount(store, sealKey, account);
@@ -0,0 +1,21 @@
1
+ /** One method's result, as an Authentication-Results header says it. */
2
+ type Result = {
3
+ method: string;
4
+ result: string;
5
+ properties: Map<string, string>;
6
+ };
7
+ /** An Authentication-Results header's value read: its authserv-id and each method's result. Undefined when it doesn't
8
+ * read: no authserv-id, a comment or quoted string that never ends, or a part that is no `method=result`. A part that
9
+ * says `none` holds no result. */
10
+ export declare function resultsOf(value: string): {
11
+ authservId: string;
12
+ results: Result[];
13
+ } | undefined;
14
+ /** Whether the receiving server said DMARC passed for a message's From: `results`, the message's Authentication-Results
15
+ * values, topmost first; `from`, every address of its From header (exactly one, or no verdict); `authservId`, the
16
+ * account's provider's (undefined: none known, no verdict). Only the topmost header is read, and only when its
17
+ * authserv-id is the provider's: one lower down may be the sender's own. It passes when that header has a dmarc result,
18
+ * every dmarc result it has is `pass`, and each one's header.from is the From's domain (ASCII case-blind). dkim=pass or
19
+ * spf=pass alone is no pass. */
20
+ export declare function dmarcPassed(results: readonly string[], from: readonly string[], authservId: string | undefined): boolean;
21
+ export {};
@@ -0,0 +1,106 @@
1
+ // The receiving mail server's word on who sent a message: its Authentication-Results header (RFC 8601), read for one
2
+ // thing only, whether DMARC passed for the domain of the message's one From. A message's sender can write any header,
3
+ // that one included, so only the receiving server's own counts: the topmost Authentication-Results (a server adds its
4
+ // own above what it was handed), and only when it carries the account's provider's authserv-id (account.ts
5
+ // authservIdOf). An account whose provider's authserv-id isn't known has no verdict read at all (fail closed).
6
+ /** `value` with its comments (RFC 5322 CFWS: parentheses, nested, `\` quoting inside) made one space each, its quoted
7
+ * strings kept whole. Empty when a comment or quoted string never ends: such a header reads as nothing. */
8
+ function uncommented(value) {
9
+ let out = "";
10
+ let depth = 0;
11
+ let quoted = false;
12
+ for (let i = 0; i < value.length; i++) {
13
+ const c = value[i];
14
+ if (depth > 0) {
15
+ if (c === "\\")
16
+ i++;
17
+ else if (c === "(")
18
+ depth++;
19
+ else if (c === ")" && --depth === 0)
20
+ out += " ";
21
+ continue;
22
+ }
23
+ if (quoted) {
24
+ out += c;
25
+ if (c === "\\" && i + 1 < value.length)
26
+ out += value[++i];
27
+ else if (c === '"')
28
+ quoted = false;
29
+ continue;
30
+ }
31
+ if (c === "(")
32
+ depth = 1;
33
+ else {
34
+ out += c;
35
+ if (c === '"')
36
+ quoted = true;
37
+ }
38
+ }
39
+ return depth > 0 || quoted ? "" : out;
40
+ }
41
+ /** `text` split at each `;` outside a quoted string, each part trimmed. */
42
+ function partsOf(text) {
43
+ const parts = [""];
44
+ let quoted = false;
45
+ for (let i = 0; i < text.length; i++) {
46
+ const c = text[i];
47
+ if (!quoted && c === ";") {
48
+ parts.push("");
49
+ continue;
50
+ }
51
+ parts[parts.length - 1] += c;
52
+ if (quoted && c === "\\" && i + 1 < text.length)
53
+ parts[parts.length - 1] += text[++i];
54
+ else if (c === '"')
55
+ quoted = !quoted;
56
+ }
57
+ return parts.map((part) => part.trim());
58
+ }
59
+ /** A value as written: a quoted string's text, else the token. */
60
+ const unquoted = (value) => (value.startsWith('"') && value.endsWith('"') && value.length > 1 ? value.slice(1, -1).replace(/\\(.)/g, "$1") : value);
61
+ /** Text as compared: its ASCII letters lowercased and nothing else (domain names fold ASCII only, as addresses do). */
62
+ const folded = (text) => text.trim().replace(/[A-Z]+/g, (letters) => letters.toLowerCase());
63
+ const VALUE = String.raw `("(?:[^"\\]|\\.)*"|[^\s";]+)`;
64
+ /** A result's start: `method[/version] = result`. */
65
+ const RESULT = new RegExp(String.raw `^([^\s=";]+)\s*=\s*${VALUE}`);
66
+ /** A property after it: `ptype.property = value` (or `reason = value`). */
67
+ const PROPERTY = new RegExp(String.raw `([^\s=";]+)\s*=\s*${VALUE}`, "g");
68
+ /** An Authentication-Results header's value read: its authserv-id and each method's result. Undefined when it doesn't
69
+ * read: no authserv-id, a comment or quoted string that never ends, or a part that is no `method=result`. A part that
70
+ * says `none` holds no result. */
71
+ export function resultsOf(value) {
72
+ const text = uncommented(value);
73
+ const [head, ...rest] = partsOf(text);
74
+ const id = /^("(?:[^"\\]|\\.)*"|[^\s";]+)/.exec(head ?? "")?.[1];
75
+ if (!id)
76
+ return undefined;
77
+ const results = [];
78
+ for (const part of rest) {
79
+ if (part === "" || /^none$/i.test(part))
80
+ continue;
81
+ const first = RESULT.exec(part);
82
+ if (!first)
83
+ return undefined;
84
+ const properties = new Map([...part.slice(first[0].length).matchAll(PROPERTY)].map((m) => [folded(unquoted(m[1])), unquoted(m[2])]));
85
+ results.push({ method: folded(first[1].split("/")[0]), result: folded(unquoted(first[2])), properties });
86
+ }
87
+ return { authservId: folded(unquoted(id)), results };
88
+ }
89
+ /** Whether the receiving server said DMARC passed for a message's From: `results`, the message's Authentication-Results
90
+ * values, topmost first; `from`, every address of its From header (exactly one, or no verdict); `authservId`, the
91
+ * account's provider's (undefined: none known, no verdict). Only the topmost header is read, and only when its
92
+ * authserv-id is the provider's: one lower down may be the sender's own. It passes when that header has a dmarc result,
93
+ * every dmarc result it has is `pass`, and each one's header.from is the From's domain (ASCII case-blind). dkim=pass or
94
+ * spf=pass alone is no pass. */
95
+ export function dmarcPassed(results, from, authservId) {
96
+ if (!authservId || from.length !== 1)
97
+ return false;
98
+ const at = from[0].lastIndexOf("@");
99
+ const domain = at > 0 ? folded(from[0].slice(at + 1)) : "";
100
+ const [top] = results;
101
+ const read = domain && top !== undefined ? resultsOf(top) : undefined;
102
+ if (!read || read.authservId !== folded(authservId))
103
+ return false;
104
+ const dmarc = read.results.filter((one) => one.method === "dmarc");
105
+ return dmarc.length > 0 && dmarc.every((one) => one.result === "pass" && folded(one.properties.get("header.from") ?? "") === domain);
106
+ }
@@ -8,6 +8,8 @@ export type FauxMessage = {
8
8
  from?: string;
9
9
  to?: string | readonly string[];
10
10
  cc?: string | readonly string[];
11
+ /** Its Bcc header: as a sender's own copy in Sent keeps it. */
12
+ bcc?: string | readonly string[];
11
13
  subject?: string;
12
14
  text?: string;
13
15
  html?: string;
@@ -76,6 +78,8 @@ export type EmailFaux = {
76
78
  commands(): string[];
77
79
  /** On: every sign-in, IMAP and SMTP, is refused as a wrong password is. */
78
80
  refuseLogin(on: boolean): void;
81
+ /** On: every APPEND is refused, as a mailbox over its quota refuses one (a send's copy is then not filed in Sent). */
82
+ refuseAppend(on: boolean): void;
79
83
  /** The next IMAP command whose logged line `pattern` takes is answered only once the returned release is called: a
80
84
  * mail server that is slow at one step (a trigger's start, held while the trigger is edited). */
81
85
  hold(pattern: RegExp): () => void;
@@ -83,15 +87,20 @@ export type EmailFaux = {
83
87
  setUidValidity(n: number, mailbox?: string): void;
84
88
  close(): Promise<void>;
85
89
  };
90
+ /** A layout: a plain account's, Gmail's, or a plain account's with no Sent folder at all. */
91
+ type Layout = "standard" | "gmail" | "no-sent";
86
92
  /** Starts the fake account's two servers on loopback. `layout`: the folders it has (default a plain account's); the Gmail
87
93
  * layout's server says X-GM-EXT-1. `now`: its clock. `slowInReplyTo`: a search by HEADER In-Reply-To is never answered,
88
94
  * as Gmail's on a large mailbox (it indexes Message-ID and References, not In-Reply-To). `password`: the one it signs in
89
- * with (default a fresh random one). */
95
+ * with (default a fresh random one). `trailingDelimiter`: every mailbox name a command gives is read without one
96
+ * trailing `/`, as CREATE always reads it, so `Sent/` is Sent (a server that maps a name onto another's). */
90
97
  export declare function startEmailFaux(options?: {
91
98
  imapPort?: number;
92
99
  smtpPort?: number;
93
- layout?: "standard" | "gmail";
100
+ layout?: Layout;
94
101
  now?: () => Date;
95
102
  slowInReplyTo?: boolean;
96
103
  password?: string;
104
+ trailingDelimiter?: boolean;
97
105
  }): Promise<EmailFaux>;
106
+ export {};
@@ -3,7 +3,7 @@
3
3
  // GitHub. Hand-written, the IMAP subset a mail client library uses (imapflow): CAPABILITY, LOGIN, LIST and LSUB with
4
4
  // special-use flags, STATUS, SELECT and EXAMINE with UIDVALIDITY and UIDNEXT, SEARCH and UID SEARCH, FETCH and UID FETCH
5
5
  // (BODY[] and BODY.PEEK[], a part of one, HEADER.FIELDS), STORE, APPEND, CREATE (and SUBSCRIBE), UID MOVE, NOOP, CLOSE,
6
- // UNSELECT, LOGOUT; on the Gmail layout also X-GM-EXT-1's labels (FETCH and STORE of X-GM-LABELS: a message in INBOX
6
+ // UNSELECT, LOGOUT (SEARCH's FROM, TO, CC, BCC and SUBJECT a substring of the header, as a real server's); on the Gmail layout also X-GM-EXT-1's labels (FETCH and STORE of X-GM-LABELS: a message in INBOX
7
7
  // carries \Inbox, and one whose \Inbox is taken off leaves INBOX for [Gmail]/All Mail; a label's mailbox lists every
8
8
  // message carrying the label, one message in each mailbox it shows in, so a STORE through any of them shows in all of
9
9
  // them, and a message put in a label's mailbox is one in [Gmail]/All Mail under the label), and with `slowInReplyTo`
@@ -13,7 +13,7 @@
13
13
  // at RCPT with a 550, as a server refuses an address it won't deliver to, and the rest are delivered. A fetch of BODY[]
14
14
  // without PEEK marks the message \Seen, as a
15
15
  // real server does, so a test can tell a read that changes the inbox from one that does not. The test seeds the
16
- // mailboxes, reads them back and what SMTP received, and switches the sign-in off or the UIDVALIDITY to another. Plaintext
16
+ // mailboxes, reads them back and what SMTP received, and switches the sign-in or APPEND off or the UIDVALIDITY to another. Plaintext
17
17
  // on the loopback address only: never a server anyone else reaches.
18
18
  import { randomBytes } from "node:crypto";
19
19
  import { createServer } from "node:net";
@@ -27,8 +27,10 @@ const INBOX_LABEL = "\\Inbox";
27
27
  const ALL_MAIL = "[Gmail]/All Mail";
28
28
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
29
29
  /** The folders of a layout: a plain account's (Drafts, Sent, Trash at the top), or Gmail's (under [Gmail]/, each with its
30
- * special-use flag, its sent folder "Sent Mail"). */
30
+ * special-use flag, its sent folder "Sent Mail"); "no-sent", the plain one without Sent. */
31
31
  function layoutOf(layout) {
32
+ if (layout === "no-sent")
33
+ return layoutOf("standard").filter((box) => box.name !== "Sent");
32
34
  if (layout === "gmail") {
33
35
  return [
34
36
  { name: "INBOX", flags: [] },
@@ -78,6 +80,8 @@ function compose(message, messageId, date) {
78
80
  lines.push(`To: ${list(message.to).join(", ")}`);
79
81
  if (list(message.cc).length)
80
82
  lines.push(`Cc: ${list(message.cc).join(", ")}`);
83
+ if (list(message.bcc).length)
84
+ lines.push(`Bcc: ${list(message.bcc).join(", ")}`);
81
85
  lines.push(`Subject: ${message.subject ?? ""}`);
82
86
  lines.push(`Date: ${date.toUTCString().replace("GMT", "+0000")}`);
83
87
  if (messageId)
@@ -194,20 +198,25 @@ const literal = (text) => `{${Buffer.byteLength(text, "utf8")}}${CRLF}${text}`;
194
198
  /** Starts the fake account's two servers on loopback. `layout`: the folders it has (default a plain account's); the Gmail
195
199
  * layout's server says X-GM-EXT-1. `now`: its clock. `slowInReplyTo`: a search by HEADER In-Reply-To is never answered,
196
200
  * as Gmail's on a large mailbox (it indexes Message-ID and References, not In-Reply-To). `password`: the one it signs in
197
- * with (default a fresh random one). */
201
+ * with (default a fresh random one). `trailingDelimiter`: every mailbox name a command gives is read without one
202
+ * trailing `/`, as CREATE always reads it, so `Sent/` is Sent (a server that maps a name onto another's). */
198
203
  export async function startEmailFaux(options = {}) {
199
204
  // Its clock: a seeded message's default date and an appended one's arrival (a template eval case's `now`, else the real one).
200
205
  const now = options.now ?? (() => new Date());
201
206
  const user = "agent@faux.example";
202
207
  const password = options.password ?? `faux-${randomBytes(9).toString("hex")}`;
203
208
  let refusing = false;
209
+ let refusingAppend = false;
204
210
  const commandLog = [];
205
211
  const holds = [];
206
212
  const delivered = [];
207
213
  const gmail = options.layout === "gmail";
208
214
  const capabilities = gmail ? GMAIL_CAPABILITIES : CAPABILITIES;
209
215
  const boxes = layoutOf(options.layout ?? "standard").map((box, i) => ({ name: box.name, flags: box.flags, selectable: box.selectable !== false, uidValidity: 1000 + i, uidNext: 1, messages: [] }));
210
- const boxNamed = (name) => boxes.find((box) => (name.toUpperCase() === "INBOX" ? box.name === "INBOX" : box.name === name));
216
+ const boxNamed = (given) => {
217
+ const name = options.trailingDelimiter ? given.replace(/\/$/, "") : given;
218
+ return boxes.find((box) => (name.toUpperCase() === "INBOX" ? box.name === "INBOX" : box.name === name));
219
+ };
211
220
  /** "Drafts" and "Sent" name the layout's special-use folder; any other name its folder. */
212
221
  const resolve = (name) => {
213
222
  const special = { drafts: "\\Drafts", sent: "\\Sent" }[name.replace(/^\\/, "").toLowerCase()];
@@ -384,9 +393,11 @@ export async function startEmailFaux(options = {}) {
384
393
  case "DRAFT": return (m) => m.flags.includes("\\Draft");
385
394
  case "DELETED": return (m) => m.flags.includes("\\Deleted");
386
395
  case "UNDELETED": return (m) => !m.flags.includes("\\Deleted");
396
+ // A substring of the header's raw value, case-blind, as RFC 3501 has it: TO "a@b.co" takes "data@b.com".
387
397
  case "FROM":
388
398
  case "TO":
389
399
  case "CC":
400
+ case "BCC":
390
401
  case "SUBJECT": {
391
402
  const needle = arg();
392
403
  return (m) => has(header(m, key), needle);
@@ -530,6 +541,8 @@ export async function startEmailFaux(options = {}) {
530
541
  const box = boxNamed(word(args[0]));
531
542
  if (!box || !box.selectable)
532
543
  return send(`${tag} NO [TRYCREATE] no such mailbox`);
544
+ if (refusingAppend)
545
+ return send(`${tag} NO [OVERQUOTA] the mailbox is full`);
533
546
  let i = 1;
534
547
  const flags = args[i] && "list" in args[i] ? args[i++].list.map(word) : [];
535
548
  // An optional date-time before the message.
@@ -832,6 +845,9 @@ export async function startEmailFaux(options = {}) {
832
845
  refuseLogin(on) {
833
846
  refusing = on;
834
847
  },
848
+ refuseAppend(on) {
849
+ refusingAppend = on;
850
+ },
835
851
  setUidValidity(n, mailbox = "INBOX") {
836
852
  const box = resolve(mailbox);
837
853
  if (!box)
@@ -15,6 +15,9 @@ export declare const SEARCH_BYTES: number;
15
15
  export declare const READ_BYTES: number;
16
16
  /** The header email_send marks everything it sends with (its value the run's id): a poll leaves such a message. */
17
17
  export declare const SENT_HEADER = "X-AgentRun-Sent";
18
+ /** The most of Sent's messages that the search for one address takes whose headers a send's check reads (newest first,
19
+ * SENT_HITS_BATCH at a time): past them, with no exact match among those read, the check can't say (fail closed). */
20
+ export declare const SENT_HITS_MAX = 200;
18
21
  /** Why a mail server did not do what was asked: `unreachable`, it could not be reached; `refused`, it refused the
19
22
  * sign-in; `missing`, a mailbox or message is not there; `failed`, anything else. Its message is fit to show. */
20
23
  export declare class MailError extends Error {
@@ -23,6 +26,9 @@ export declare class MailError extends Error {
23
26
  }
24
27
  /** `error`, from the server at `endpoint` over `protocol`, as a MailError whose words hold nothing of `password`. */
25
28
  export declare function mailError(error: unknown, endpoint: Endpoint, protocol: "IMAP" | "SMTP", password: string): MailError;
29
+ /** An address as two are compared: trimmed, its ASCII letters lowercased and nothing else. JS toLowerCase folds U+212A
30
+ * KELVIN SIGN to "k" and U+212B ANGSTROM SIGN to "å", so two addresses SMTP keeps apart would compare equal. */
31
+ export declare const addressKey: (address: string) => string;
26
32
  /** A message as the tools and the trigger read it: where it is, its flags, and its fields. */
27
33
  export type MailMessage = {
28
34
  uid: number;
@@ -45,6 +51,13 @@ export type MailMessage = {
45
51
  }[];
46
52
  /** The X-AgentRun-Sent header's value, when it has one: this server sent it. */
47
53
  sent_here?: string;
54
+ /** What the receiving server's DMARC verdict is read from (authentication.ts dmarcPassed): the values of its
55
+ * Authentication-Results headers, topmost first, unfolded, and every address of its From (none when the message has
56
+ * no From header or more than one). Never in a payload or an answer. */
57
+ authentication: {
58
+ results: string[];
59
+ from: string[];
60
+ };
48
61
  };
49
62
  /** A fetched message, parsed: `source` its bytes (the first `READ_BYTES` or `SEARCH_BYTES` of it). */
50
63
  export declare function messageOf(row: Pick<FetchMessageObject, "uid" | "flags" | "source" | "internalDate">, mailbox: string): Promise<MailMessage>;
@@ -52,6 +65,12 @@ export declare function messageOf(row: Pick<FetchMessageObject, "uid" | "flags"
52
65
  export type MailHead = Pick<MailMessage, "uid" | "mailbox" | "from" | "to" | "cc" | "date" | "message_id" | "in_reply_to" | "references"> & {
53
66
  size: number;
54
67
  };
68
+ /** Of `addresses` (bare), those the account `own` (its address) has never sent to: no message of its Sent folder (the
69
+ * special-use \Sent, Gmail's Sent Mail) from `own`, not a draft, is to them in its To, Cc or Bcc. Mail received from
70
+ * them counts for nothing, and so does a draft or another's message that ended up in Sent. Sent is opened read-only
71
+ * (EXAMINE) and only the From, To, Cc and Bcc headers and the flags of the messages its search takes are read
72
+ * (ImapSession.holdsTo). No Sent folder: MailError `missing`. */
73
+ export declare function neverSentTo(session: ImapSession, addresses: readonly string[], own: string): Promise<string[]>;
55
74
  /** Whether `address` (bare, any case) is one of `m`'s From, To or Cc. */
56
75
  export declare const involves: (m: Pick<MailMessage, "from" | "to" | "cc">, address: string) => boolean;
57
76
  /** The payload's fields (a trigger's firing, a read's message). */
@@ -137,6 +156,12 @@ export declare class ImapSession {
137
156
  /** The open mailbox's messages of `uids`, read cheaply: who they are between, their ids, their date and their size from a few headers,
138
157
  * INTERNALDATE and RFC822.SIZE, never a body. What a thread read picks from before it fetches any message whole. */
139
158
  heads(path: string, uids: readonly number[]): Promise<MailHead[]>;
159
+ /** Whether the open mailbox `path` holds a message from `own` to `address`: the exact address, case-blind, in its To,
160
+ * Cc or Bcc, its From `own` alone, and no \Draft flag (a draft, or another's message, put in Sent is no send). The
161
+ * server's search only finds the candidates, since TO, CC and BCC take a substring (RFC 3501: "a@b.co" takes
162
+ * data@b.com); each candidate's From, To, Cc and Bcc (BODY.PEEK of those fields, never a body) and flags are then read
163
+ * and parsed, newest first, SENT_HITS_MAX at most. Past those with no match: MailError `failed`, saying how many. */
164
+ holdsTo(path: string, address: string, own: string): Promise<boolean>;
140
165
  /** The clause that takes the thread of `ids` on this server. Gmail (X-GM-EXT-1) indexes Message-ID and References but
141
166
  * not In-Reply-To, a search by which takes minutes on a large mailbox: there a reply is found by its References, which
142
167
  * a mail client writes with its In-Reply-To. */