@parcha/agentrun-serve 0.1.0-beta.58 → 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 (375) hide show
  1. package/CHANGELOG.md +325 -1
  2. package/README.md +332 -88
  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/attach-conformance.js +5 -4
  11. package/dist/box-paths.d.ts +3 -2
  12. package/dist/box-paths.js +5 -4
  13. package/dist/browser-computer.d.ts +3 -8
  14. package/dist/browser-computer.js +12 -35
  15. package/dist/browser-cost.js +94 -20
  16. package/dist/capacity.d.ts +1 -1
  17. package/dist/capacity.js +3 -3
  18. package/dist/chatgpt-plan.d.ts +5 -0
  19. package/dist/chatgpt-plan.js +25 -11
  20. package/dist/claude-login-token.d.ts +15 -11
  21. package/dist/claude-login-token.js +167 -107
  22. package/dist/claude-login.d.ts +76 -31
  23. package/dist/claude-login.js +426 -79
  24. package/dist/claude-sign-in.d.ts +3 -0
  25. package/dist/claude-sign-in.js +10 -1
  26. package/dist/cli.js +323 -292
  27. package/dist/composio-made.d.ts +1 -6
  28. package/dist/composio-made.js +1 -6
  29. package/dist/composio-owners.d.ts +26 -0
  30. package/dist/composio-owners.js +36 -0
  31. package/dist/composio-preset.d.ts +56 -23
  32. package/dist/composio-preset.js +173 -77
  33. package/dist/composio-triggers.d.ts +4 -4
  34. package/dist/composio-triggers.js +6 -7
  35. package/dist/compute-cost.js +11 -2
  36. package/dist/computer-attach.d.ts +6 -3
  37. package/dist/computer-attach.js +41 -29
  38. package/dist/computer-held-routes.d.ts +1 -1
  39. package/dist/computer-held-routes.js +9 -4
  40. package/dist/computer-keys.d.ts +11 -1
  41. package/dist/computer-keys.js +26 -1
  42. package/dist/computer-record.js +3 -1
  43. package/dist/computer-view.d.ts +5 -3
  44. package/dist/computer-view.js +10 -6
  45. package/dist/computer-viewer.js +36 -7
  46. package/dist/computers.d.ts +2 -1
  47. package/dist/computers.js +6 -3
  48. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  49. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  50. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  51. package/dist/console/assets/share-L84tlUDW.js +6 -0
  52. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  53. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  54. package/dist/console/index.html +4 -3
  55. package/dist/console/share.html +17 -0
  56. package/dist/decisions.d.ts +17 -7
  57. package/dist/decisions.js +41 -15
  58. package/dist/dial-relay.js +10 -4
  59. package/dist/docker-daemon.js +4 -5
  60. package/dist/docker-host-addresses.js +29 -11
  61. package/dist/email/account.d.ts +6 -0
  62. package/dist/email/account.js +6 -0
  63. package/dist/email/authentication.d.ts +21 -0
  64. package/dist/email/authentication.js +106 -0
  65. package/dist/email/email-faux.d.ts +11 -2
  66. package/dist/email/email-faux.js +21 -5
  67. package/dist/email/mail.d.ts +25 -0
  68. package/dist/email/mail.js +58 -2
  69. package/dist/email/names.js +2 -2
  70. package/dist/email/tools.d.ts +9 -4
  71. package/dist/email/tools.js +95 -13
  72. package/dist/env-switch.d.ts +12 -2
  73. package/dist/env-switch.js +23 -3
  74. package/dist/errors.d.ts +1 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/fal-price.d.ts +11 -1
  77. package/dist/fal-price.js +33 -0
  78. package/dist/faux-computers.js +1 -1
  79. package/dist/filed-answer.d.ts +2 -2
  80. package/dist/filed-answer.js +2 -2
  81. package/dist/graph-served.d.ts +10 -5
  82. package/dist/graph-served.js +40 -10
  83. package/dist/handed-values.js +1 -2
  84. package/dist/harness-check.d.ts +2 -1
  85. package/dist/harness-check.js +45 -12
  86. package/dist/harness-keys.js +9 -6
  87. package/dist/harness-opencode/facts.js +2 -0
  88. package/dist/harness-recipe-entry.d.ts +9 -3
  89. package/dist/harness-recipe-entry.js +18 -9
  90. package/dist/harness-recipe.d.ts +21 -0
  91. package/dist/harness-recipe.js +25 -3
  92. package/dist/harness-table.d.ts +8 -0
  93. package/dist/harness-table.js +17 -6
  94. package/dist/helper-env.d.ts +4 -1
  95. package/dist/helper-env.js +4 -1
  96. package/dist/host-check.d.ts +2 -3
  97. package/dist/host-check.js +13 -7
  98. package/dist/hosted-search.js +1 -1
  99. package/dist/import.d.ts +11 -8
  100. package/dist/import.js +437 -186
  101. package/dist/key-refusal.d.ts +9 -2
  102. package/dist/key-refusal.js +86 -32
  103. package/dist/learn/audit.d.ts +8 -5
  104. package/dist/learn/audit.js +15 -7
  105. package/dist/learn/compile.d.ts +5 -2
  106. package/dist/learn/compile.js +45 -21
  107. package/dist/learn/field-check.d.ts +111 -0
  108. package/dist/learn/field-check.js +174 -0
  109. package/dist/learn/ledger.d.ts +32 -29
  110. package/dist/learn/ledger.js +26 -19
  111. package/dist/learn/promote.d.ts +79 -36
  112. package/dist/learn/promote.js +60 -65
  113. package/dist/learn/secrets.d.ts +4 -0
  114. package/dist/learn/secrets.js +12 -0
  115. package/dist/learned-nodes.d.ts +8 -5
  116. package/dist/learned-nodes.js +8 -5
  117. package/dist/learned-workflow.d.ts +2 -1
  118. package/dist/learned-workflow.js +13 -10
  119. package/dist/learning-cost.d.ts +25 -8
  120. package/dist/learning-cost.js +23 -8
  121. package/dist/learning-setting.d.ts +6 -0
  122. package/dist/learning-setting.js +11 -1
  123. package/dist/listen-first.d.ts +5 -4
  124. package/dist/listen-first.js +4 -5
  125. package/dist/live-reach.d.ts +7 -0
  126. package/dist/live-reach.js +7 -0
  127. package/dist/mcp-api-only-origins.d.ts +15 -0
  128. package/dist/mcp-api-only-origins.js +40 -0
  129. package/dist/mcp-gateway.d.ts +16 -2
  130. package/dist/mcp-gateway.js +41 -3
  131. package/dist/mcp-oauth.d.ts +1 -1
  132. package/dist/mcp-oauth.js +3 -2
  133. package/dist/mcp-probe.d.ts +3 -0
  134. package/dist/mcp-probe.js +3 -0
  135. package/dist/mcp-secret-writes.d.ts +24 -2
  136. package/dist/mcp-secret-writes.js +30 -2
  137. package/dist/mcp-servers-store.d.ts +52 -14
  138. package/dist/mcp-servers-store.js +165 -61
  139. package/dist/mcp-sources.d.ts +1 -2
  140. package/dist/mcp-sources.js +1 -2
  141. package/dist/mcp-store.d.ts +5 -5
  142. package/dist/mcp-store.js +3 -3
  143. package/dist/mcp.js +1 -1
  144. package/dist/model-gateway.d.ts +1 -1
  145. package/dist/model-gateway.js +20 -36
  146. package/dist/ollama-provider.d.ts +23 -9
  147. package/dist/ollama-provider.js +49 -20
  148. package/dist/openapi.js +202 -51
  149. package/dist/otel/genai.d.ts +83 -7
  150. package/dist/otel/genai.js +69 -9
  151. package/dist/otel/tracer.d.ts +42 -13
  152. package/dist/otel/tracer.js +241 -56
  153. package/dist/page.d.ts +7 -1
  154. package/dist/page.js +76 -22
  155. package/dist/paid-calls.d.ts +6 -4
  156. package/dist/paid-calls.js +15 -7
  157. package/dist/place-offers.d.ts +55 -34
  158. package/dist/place-offers.js +93 -54
  159. package/dist/place.d.ts +13 -14
  160. package/dist/place.js +56 -41
  161. package/dist/print.js +1 -1
  162. package/dist/provider.d.ts +3 -2
  163. package/dist/provider.js +17 -8
  164. package/dist/redact/match.d.ts +27 -9
  165. package/dist/redact/match.js +266 -57
  166. package/dist/run-census.d.ts +1 -1
  167. package/dist/run-census.js +4 -5
  168. package/dist/run-cut.js +4 -5
  169. package/dist/run-export-store.d.ts +15 -0
  170. package/dist/run-export-store.js +30 -0
  171. package/dist/run-export.d.ts +139 -0
  172. package/dist/run-export.js +379 -0
  173. package/dist/run-file-cut.d.ts +5 -0
  174. package/dist/run-file-cut.js +13 -0
  175. package/dist/run-launch.js +16 -3
  176. package/dist/run-model-key.d.ts +15 -6
  177. package/dist/run-model-key.js +30 -31
  178. package/dist/run-reads-over-store.js +4 -4
  179. package/dist/run-secrets.js +3 -5
  180. package/dist/run-timeline-served.js +3 -1
  181. package/dist/runnable.js +2 -2
  182. package/dist/runner/adapter-loop.d.ts +35 -18
  183. package/dist/runner/adapter-loop.js +94 -47
  184. package/dist/runner/adapter-run-spec.d.ts +14 -1
  185. package/dist/runner/adapter-run-spec.js +64 -28
  186. package/dist/runner/adapters/pi.js +4 -2
  187. package/dist/runner/audit.d.ts +8 -5
  188. package/dist/runner/audit.js +37 -17
  189. package/dist/runner/beside.js +5 -6
  190. package/dist/runner/claim-secrets.d.ts +10 -3
  191. package/dist/runner/claim-secrets.js +29 -13
  192. package/dist/runner/cli-run-spec.d.ts +18 -0
  193. package/dist/runner/cli-run-spec.js +81 -46
  194. package/dist/runner/compare-end.d.ts +2 -1
  195. package/dist/runner/compare-end.js +25 -10
  196. package/dist/runner/conformance/harness.js +2 -3
  197. package/dist/runner/conformance/subject.d.ts +4 -1
  198. package/dist/runner/harness-loops.js +3 -3
  199. package/dist/runner/held.d.ts +5 -2
  200. package/dist/runner/journal-kinds.d.ts +4 -1
  201. package/dist/runner/journal-kinds.js +22 -4
  202. package/dist/runner/learned-first.js +20 -4
  203. package/dist/runner/learning-end.d.ts +2 -8
  204. package/dist/runner/learning-end.js +11 -19
  205. package/dist/runner/live-ticker.js +7 -5
  206. package/dist/runner/loop-contract.d.ts +0 -2
  207. package/dist/runner/loop.d.ts +7 -0
  208. package/dist/runner/loop.js +1 -0
  209. package/dist/runner/main.js +12 -11
  210. package/dist/runner/mcp-claim.js +21 -5
  211. package/dist/runner/meta-tools.js +3 -2
  212. package/dist/runner/metrics.d.ts +7 -0
  213. package/dist/runner/metrics.js +19 -0
  214. package/dist/runner/model-route.d.ts +10 -7
  215. package/dist/runner/model-route.js +79 -15
  216. package/dist/runner/native-loop.js +10 -8
  217. package/dist/runner/presence.d.ts +1 -4
  218. package/dist/runner/presence.js +6 -8
  219. package/dist/runner/promotion.d.ts +25 -13
  220. package/dist/runner/promotion.js +125 -50
  221. package/dist/runner/redact.d.ts +3 -1
  222. package/dist/runner/redact.js +5 -3
  223. package/dist/runner/responses-fetch.d.ts +36 -0
  224. package/dist/runner/responses-fetch.js +511 -0
  225. package/dist/runner/run-child-host.d.ts +20 -5
  226. package/dist/runner/run-child-host.js +179 -77
  227. package/dist/runner/run-child.js +11 -4
  228. package/dist/runner/runner-check.js +5 -1
  229. package/dist/runner/runner.d.ts +2 -3
  230. package/dist/runner/runner.js +13 -9
  231. package/dist/runner/sdk-loop.js +8 -8
  232. package/dist/runner/spec-holds.d.ts +8 -1
  233. package/dist/runner/spec-holds.js +9 -4
  234. package/dist/runner/workflow-calls.d.ts +9 -0
  235. package/dist/runner/workflow-calls.js +150 -0
  236. package/dist/runner/workflow-first.d.ts +120 -32
  237. package/dist/runner/workflow-first.js +218 -94
  238. package/dist/runner/workflow-spec.js +1 -1
  239. package/dist/runs-over-store.js +8 -7
  240. package/dist/save-once.d.ts +14 -0
  241. package/dist/save-once.js +31 -0
  242. package/dist/scrub-command.d.ts +34 -31
  243. package/dist/scrub-command.js +116 -147
  244. package/dist/sdk/runs.d.ts +6 -0
  245. package/dist/sdk/runs.js +89 -10
  246. package/dist/seal-key.js +4 -4
  247. package/dist/secret-cut.d.ts +3 -0
  248. package/dist/secret-cut.js +7 -1
  249. package/dist/secret-rules.d.ts +8 -1
  250. package/dist/secret-rules.js +482 -53
  251. package/dist/secrets.d.ts +51 -9
  252. package/dist/secrets.js +311 -21
  253. package/dist/server-keys.d.ts +4 -3
  254. package/dist/server-keys.js +4 -3
  255. package/dist/server-secrets-store.js +2 -4
  256. package/dist/server.d.ts +15 -3
  257. package/dist/server.js +312 -80
  258. package/dist/share-context.d.ts +22 -0
  259. package/dist/share-context.js +76 -0
  260. package/dist/shell-lex.d.ts +105 -0
  261. package/dist/shell-lex.js +646 -0
  262. package/dist/sign-ins-store.d.ts +5 -7
  263. package/dist/sign-ins-store.js +12 -16
  264. package/dist/sign-ins.d.ts +7 -11
  265. package/dist/sign-ins.js +40 -41
  266. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  267. package/dist/start-switches.d.ts +6 -5
  268. package/dist/start-switches.js +8 -4
  269. package/dist/stats.d.ts +5 -1
  270. package/dist/stats.js +1 -1
  271. package/dist/store/agent-body.js +2 -2
  272. package/dist/store/dialect.d.ts +4 -0
  273. package/dist/store/dialect.js +1 -0
  274. package/dist/store/index.d.ts +2 -2
  275. package/dist/store/index.js +1 -1
  276. package/dist/store/mcp-record-keys.d.ts +10 -0
  277. package/dist/store/mcp-record-keys.js +13 -0
  278. package/dist/store/postgres/dialect.js +2 -0
  279. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  280. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  281. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  282. package/dist/store/postgres/store.js +4 -0
  283. package/dist/store/schema.d.ts +33 -10
  284. package/dist/store/schema.js +70 -16
  285. package/dist/store/seal.d.ts +4 -1
  286. package/dist/store/sqlite/run-launch.d.ts +3 -10
  287. package/dist/store/sqlite/run-launch.js +12 -23
  288. package/dist/store/sqlite/run-patch.d.ts +17 -10
  289. package/dist/store/sqlite/run-patch.js +50 -13
  290. package/dist/store/sqlite/store.d.ts +3 -0
  291. package/dist/store/sqlite/store.js +116 -34
  292. package/dist/store/store-schema.js +3 -4
  293. package/dist/store/store.d.ts +67 -32
  294. package/dist/store/store.js +14 -11
  295. package/dist/store-reads/analytics.d.ts +2 -1
  296. package/dist/store-reads/analytics.js +7 -5
  297. package/dist/store-reads/learning.d.ts +35 -26
  298. package/dist/store-reads/learning.js +120 -92
  299. package/dist/store-reads/stats.d.ts +2 -2
  300. package/dist/store-reads/stats.js +13 -7
  301. package/dist/store-view.js +10 -7
  302. package/dist/suggestions.d.ts +1 -1
  303. package/dist/suggestions.js +29 -13
  304. package/dist/template-eval.d.ts +72 -9
  305. package/dist/template-eval.js +358 -64
  306. package/dist/timeline/labels.d.ts +1 -1
  307. package/dist/timeline/labels.js +4 -3
  308. package/dist/timeline/timeline.d.ts +23 -11
  309. package/dist/timeline/timeline.js +115 -31
  310. package/dist/timeline/web-calls.d.ts +8 -6
  311. package/dist/timeline/web-calls.js +10 -6
  312. package/dist/tool-gate.d.ts +13 -1
  313. package/dist/tool-gate.js +43 -3
  314. package/dist/tool-keys-store.js +2 -4
  315. package/dist/tool-keys.d.ts +11 -0
  316. package/dist/tool-keys.js +16 -0
  317. package/dist/tool-plane.d.ts +50 -11
  318. package/dist/tool-plane.js +94 -30
  319. package/dist/tools.d.ts +5 -1
  320. package/dist/tools.js +7 -7
  321. package/dist/trigger-email.js +12 -6
  322. package/dist/triggers.d.ts +15 -34
  323. package/dist/triggers.js +119 -126
  324. package/dist/validate.d.ts +8 -1
  325. package/dist/validate.js +163 -23
  326. package/dist/web-fake.d.ts +2 -1
  327. package/dist/web-fake.js +8 -6
  328. package/dist/web-fetch.d.ts +8 -6
  329. package/dist/web-fetch.js +13 -11
  330. package/dist/web-holds.d.ts +32 -0
  331. package/dist/web-holds.js +86 -0
  332. package/dist/web-run.d.ts +32 -5
  333. package/dist/web-run.js +75 -28
  334. package/dist/web-save.js +23 -12
  335. package/dist/web-search.js +14 -25
  336. package/dist/wires.d.ts +4 -3
  337. package/dist/wires.js +5 -4
  338. package/dist/workspace/archil-claim.d.ts +12 -5
  339. package/dist/workspace/archil-claim.js +45 -5
  340. package/dist/workspace/attach.js +52 -19
  341. package/dist/workspace/attached-computers.d.ts +6 -2
  342. package/dist/workspace/attached-computers.js +5 -4
  343. package/dist/workspace/computer-deps.d.ts +23 -6
  344. package/dist/workspace/computer-deps.js +35 -17
  345. package/dist/workspace/computer-for-claim.d.ts +21 -4
  346. package/dist/workspace/computer-for-claim.js +160 -54
  347. package/dist/workspace/computer-intervals.d.ts +2 -0
  348. package/dist/workspace/computer-intervals.js +1 -1
  349. package/dist/workspace/computer-janitor.d.ts +48 -14
  350. package/dist/workspace/computer-janitor.js +153 -44
  351. package/dist/workspace/computer-kept.d.ts +158 -32
  352. package/dist/workspace/computer-kept.js +288 -63
  353. package/dist/workspace/computer-providers.d.ts +8 -3
  354. package/dist/workspace/computer-providers.js +12 -5
  355. package/dist/workspace/index.d.ts +1 -1
  356. package/dist/workspace/index.js +1 -1
  357. package/dist/workspace/local.js +41 -1
  358. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  359. package/dist/workspace/mount-revoke-left.js +72 -0
  360. package/dist/workspace/paired-route.js +4 -5
  361. package/dist/workspace/resolve-computer.d.ts +5 -2
  362. package/dist/workspace/resolve-computer.js +9 -3
  363. package/dist/workspace/run-end-computers.d.ts +11 -5
  364. package/dist/workspace/run-end-computers.js +153 -28
  365. package/dist/workspace/run-tools.d.ts +22 -3
  366. package/dist/workspace/run-tools.js +17 -5
  367. package/dist/workspace/run-workspace.d.ts +14 -1
  368. package/dist/workspace/run-workspace.js +34 -1
  369. package/dist/workspace/workspace.d.ts +6 -0
  370. package/package.json +12 -13
  371. package/skills/agentrun-serve/SKILL.md +5 -2
  372. package/templates/README.md +22 -6
  373. package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
  374. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  375. package/dist/console/assets/index-DPh29cyz.js +0 -747
@@ -4,52 +4,55 @@
4
4
  // type's), no exporter starts and nothing leaves the machine. On, the exporter is given its endpoint, headers and
5
5
  // timeout from the OTEL_EXPORTER_OTLP_* variables, and the resource OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
6
6
  // (deployment.environment.name among them) over our service.name=agentrun and service.version. Those variables are the
7
- // runner's own: no run's environment has them (runner/main.ts runEnv), and a run's own process reads them from its pipe
8
- // (secrets.ts handedOtel), so its harness, tools and computer never see an OTLP header.
7
+ // runner's own: no run's environment has them (runner/main.ts runEnv), and no run's process is handed them. A run in its
8
+ // own process (run-child.ts) traces over its channel (postedTracing): its runner makes its spans and exports them
9
+ // (tracePosts), so its harness, tools and computer never see an OTLP header, and it loads no exporter.
9
10
  //
10
11
  // What a span says is genai.ts's. Here: the spans' lifecycle, and the rules that keep a trace from costing a run
11
12
  // - one trace per run: its id is the run id's hash, so every claim of a run (a resume, a takeover) is in one trace, and
12
13
  // the sampler (always parent-based, its root's ratio from OTEL_TRACES_SAMPLER/_ARG) decides once per run, never
13
14
  // splitting a run's spans;
14
- // - an export that fails or throws is one log line, and its spans are dropped: never the run's failure. A claim's end
15
- // never waits on an export: the batch processor sends in the background, and the process flushes once as it closes
16
- // (flushTraces: the runner's close, a run's process before it exits), for at most FLUSH_MS.
15
+ // - tracing on says so once, as it is made (at the runner's start), with the origin of the endpoint its spans go to,
16
+ // never its user, password, path, query or fragment (shownEndpoint);
17
+ // - an export that fails or throws is a log line with the endpoint's origin and the time, then at most one a minute counting
18
+ // the failures it did not say (safeExporter), each cut by the runner's redactor, which holds each OTLP header value
19
+ // of 8 characters or more, then of each header value at any length (saidOf), and its spans are dropped: never the run's failure. A run's end never waits on an export: the batch processor sends
20
+ // in the background, a run's process never flushes, and only the runner's close flushes once (flushTraces), for at
21
+ // most FLUSH_MS.
17
22
  import { createHash, randomBytes } from "node:crypto";
18
23
  import { readFileSync } from "node:fs";
19
- import { handedOtel } from "../secrets.js";
20
- import { agentAttributes, chatAttributes, spanName, toolAttributes } from "./genai.js";
21
- /** The most a process's closing flush waits for its spans' export. */
24
+ import { runnerSecrets, secretRedactor } from "../runner/redact.js";
25
+ import { keyValues, otlpHeaderCut } from "../secrets.js";
26
+ import { agentAttributes, chatAttributes, spanName, toolAttributes, tracedAgent, written } from "./genai.js";
27
+ /** The most often a collector that keeps failing is said in the log: the failures between are counted in the next line. */
28
+ export const FAILURE_LINE_MS = 60_000;
29
+ /** The most the runner's closing flush waits for its spans' export. */
22
30
  export const FLUSH_MS = 3_000;
23
- /** `env`'s OpenTelemetry settings: its OTEL_* variables. */
24
- export const otelSettings = (env) => Object.fromEntries(Object.entries(env).filter((pair) => pair[0].startsWith("OTEL_") && typeof pair[1] === "string"));
25
- /** This process's OpenTelemetry settings: what its pipe handed it (a run's process: its runner's), under its own. */
26
- export const otelEnv = (env = process.env) => ({ ...handedOtel(), ...otelSettings(env) });
27
- /** A `key=value,key=value` list (OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES), each part percent-decoded; a
28
- * part that is not one is skipped. */
29
- function listOf(text) {
30
- const out = {};
31
- for (const part of (text ?? "").split(",")) {
32
- const at = part.indexOf("=");
33
- if (at <= 0)
34
- continue;
35
- try {
36
- const key = decodeURIComponent(part.slice(0, at).trim());
37
- if (key)
38
- out[key] = decodeURIComponent(part.slice(at + 1).trim());
39
- }
40
- catch {
41
- continue;
42
- }
43
- }
44
- return out;
45
- }
31
+ /** The most model requests, and apart the most tool calls, one claim's trace holds open at once: one started past it
32
+ * has no span. A run's process posts its own trace (tracePosts) and runs the agent's code, so one that starts calls and
33
+ * never ends them can't grow its runner's memory without bound. */
34
+ export const OPEN_MAX = 512;
46
35
  /** The OTLP exporter's settings from `env`, as the spec reads them: the traces endpoint as given, else the endpoint's
47
36
  * /v1/traces; the headers (the traces' over the general ones); the timeout. */
48
37
  export function exporterConfig(env) {
49
38
  const traces = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim();
50
39
  const url = traces || `${(env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "").trim().replace(/\/+$/, "")}/v1/traces`;
51
40
  const timeout = Number(env.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT ?? env.OTEL_EXPORTER_OTLP_TIMEOUT);
52
- return { url, headers: { ...listOf(env.OTEL_EXPORTER_OTLP_HEADERS), ...listOf(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS) }, ...(Number.isFinite(timeout) && timeout > 0 ? { timeoutMillis: timeout } : {}) };
41
+ return { url, headers: { ...keyValues(env.OTEL_EXPORTER_OTLP_HEADERS), ...keyValues(env.OTEL_EXPORTER_OTLP_TRACES_HEADERS) }, ...(Number.isFinite(timeout) && timeout > 0 ? { timeoutMillis: timeout } : {}) };
42
+ }
43
+ /** The endpoint `url` as a log line shows it: its origin alone (scheme://host[:port]). That says where spans go, and
44
+ * holds none of the parts a credential can be written in: the user and password, the path, the query, the fragment.
45
+ * One that is not a URL, or names no host, is shown as that alone, never as written. */
46
+ export function shownEndpoint(url) {
47
+ try {
48
+ const { protocol, host } = new URL(url);
49
+ if (host)
50
+ return `${protocol}//${host}`;
51
+ }
52
+ catch {
53
+ // Not a URL: said as that alone, below.
54
+ }
55
+ return "an endpoint that is not a URL";
53
56
  }
54
57
  const TRUE = new Set(["1", "true", "yes", "on"]);
55
58
  /** Whether `env` turns tracing on: an OTLP endpoint is named, and the SDK is not disabled. */
@@ -58,16 +61,158 @@ export function otelOn(env) {
58
61
  return false;
59
62
  return Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim() || env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim());
60
63
  }
64
+ /** A run's own process's tracing (run-child.ts): each call of its claim's trace posted to its runner (`post`, in order
65
+ * with the rest of its channel), whose tracing makes the spans and exports them (tracePosts). The process loads no
66
+ * OpenTelemetry module, holds no OTLP setting and never flushes: its end waits on no collector. */
67
+ export function postedTracing(post) {
68
+ return {
69
+ flush: async () => { },
70
+ open: ({ startedAt = Date.now() } = {}) => {
71
+ post("open", [startedAt]);
72
+ let requests = 0;
73
+ // An event that is no tool's or turn's end is read only as the first of its turn (a plan turn's start): one post.
74
+ let heard = false;
75
+ return {
76
+ known: (run) => post("known", [run]),
77
+ request: (model, route) => {
78
+ const id = requests++;
79
+ post("request", [id, model, route]);
80
+ return (usage, ended) => post("ended", [id, usage, ended]);
81
+ },
82
+ event: (event) => {
83
+ if (event.type === "other" && heard)
84
+ return;
85
+ heard = event.type !== "turn_end";
86
+ post("event", [event]);
87
+ },
88
+ end: async (failed) => post("end", [failed]),
89
+ };
90
+ },
91
+ };
92
+ }
93
+ /** The longest id a run's process posts (a call's, a parent's, a route's name) its runner keeps as given. */
94
+ const ID_MAX = 128;
95
+ const DIGEST = "sha256:";
96
+ /** An id a run's process posts, as its runner keeps it: as given when it is ID_MAX characters or fewer, else its
97
+ * SHA-256 (DIGEST and 64 hex), so every post of one id is kept as the same string of a fixed size. One given in that
98
+ * shape is hashed too, so no short id is ever taken for a long one. */
99
+ function keptId(id) {
100
+ return id.length > ID_MAX || id.startsWith(DIGEST) ? `${DIGEST}${createHash("sha256").update(id).digest("hex")}` : id;
101
+ }
102
+ const text = (value) => (typeof value === "string" ? value : undefined);
103
+ const fields = (value) => (value !== null && typeof value === "object" ? value : {});
104
+ const figure = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
105
+ /** A provider id's shape (`anthropic`, `openrouter`, `claude-login`), and a host's (a DNS name, or a bracketed IPv6
106
+ * address as URL.hostname writes one). A name the redactor cut holds "[redacted]", which is neither. */
107
+ const PROVIDER_ID = /^[a-z0-9][a-z0-9._-]*$/i;
108
+ const HOST = /^(\[[0-9a-f:.]+\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)$/i;
109
+ /** A run failure's code (`run-error`, `sdk_failed`, `ECONNREFUSED`). */
110
+ const FAILURE_CODE = /^[a-z][a-z0-9_.-]*$/i;
111
+ /** Every label a request's end that did not answer can have (Ended): the only ones its span's error.type takes. */
112
+ const END_LABELS = Object.freeze({ status: true, never_left: true, refused: true, error_before: true, error_after: true, gateway_timeout: true, retried: true, cut: true });
113
+ const TURN_STATUSES = new Set(["completed", "interrupted", "failed"]);
114
+ /** A request's end as a post gives it, rebuilt of the fields its span reads alone: its kind, and a label only from the
115
+ * kernel's own (END_LABELS; an answer's `filtered` or `error`). No reason, no other words. An end of any other shape is
116
+ * read as none. */
117
+ function endedOf(value) {
118
+ const given = fields(value);
119
+ if (given.end === "answered")
120
+ return (given.label === "filtered" || given.label === "error" ? { end: "answered", usd: figure(given.usd) ?? null, label: given.label } : { end: "answered", usd: figure(given.usd) ?? null });
121
+ if (given.end === "stopped")
122
+ return { end: "stopped", streamedTokens: figure(given.streamedTokens) ?? 0 };
123
+ if ((given.end === "nothing" || given.end === "lost") && typeof given.label === "string" && Object.hasOwn(END_LABELS, given.label))
124
+ return { end: given.end, label: given.label };
125
+ return undefined;
126
+ }
127
+ /** A request's usage as a post gives it, rebuilt of the fields its span reads alone: its counts as numbers (anything
128
+ * else is no count, and its span then has none), a plan's billing, a cut. */
129
+ function usageOf(value) {
130
+ const given = fields(value);
131
+ const count = (key) => (figure(given[key]) === undefined ? {} : { [key]: figure(given[key]) });
132
+ return { input: figure(given.input) ?? Number.NaN, output: figure(given.output) ?? Number.NaN, ...count("cacheRead"), ...count("cacheWrite"), usd: figure(given.usd) ?? null, ...(given.billing === "plan" ? { billing: "plan" } : {}), ...(given.cut === true ? { cut: true } : {}) };
133
+ }
134
+ /** The runner's side of a run's process's trace (postedTracing): the claim's one trace, opened from `tracing` for run
135
+ * `runId` whatever the process names, and each post read as data alone (the process runs the agent's code). No string a
136
+ * post gives reaches a span as given:
137
+ * - a name (harness, model) is cut by the runner's redactor (`redact`) and at WRITTEN_MAX (written);
138
+ * - a provider id and a host are cut the same way, and dropped unless they still have their shape (PROVIDER_ID, HOST);
139
+ * - a call's id is shown cut (TraceEvent.shownId); its id, and a parent's, only match a call's end and children, and
140
+ * are kept at ID_MAX (keptId), as a route's name is;
141
+ * - a route's name a request gives only finds its route; it is on no span; at most OPEN_MAX routes are known;
142
+ * - a request's end and usage are rebuilt (endedOf, usageOf): error.type comes from the kernel's labels alone;
143
+ * - a turn's status is one of TurnStatus's, else `failed`; the claim's failure is a code's shape, else `run-error`;
144
+ * - at most OPEN_MAX requests, and OPEN_MAX calls, are open at once: one started past that, or again under an id still
145
+ * open, has no span.
146
+ * - the run's agent is the one its runner read (`agent`: its id and name, cut as tracedAgent cuts them), never one a
147
+ * post names;
148
+ * `end`: the claim's end, for a process that is gone without ending its trace (after its own end, nothing is left). */
149
+ export function tracePosts(tracing, runId, redact, agent) {
150
+ let trace;
151
+ const ofRun = agent ? { agent: tracedAgent(agent, redact) } : {};
152
+ const requests = new Map();
153
+ const name = (value) => (typeof value === "string" ? written(value, redact) : undefined);
154
+ const shaped = (value, shape) => {
155
+ const cut = name(value);
156
+ return cut && shape.test(cut) ? cut : undefined;
157
+ };
158
+ const via = (value) => {
159
+ const given = fields(value);
160
+ const [provider, serverAddress, model] = [shaped(given.provider, PROVIDER_ID), shaped(given.serverAddress, HOST), name(given.model)];
161
+ return { ...(provider ? { provider } : {}), ...(serverAddress ? { serverAddress } : {}), ...(model ? { model } : {}) };
162
+ };
163
+ return {
164
+ post(method, args) {
165
+ if (method === "open")
166
+ trace ??= tracing.open(figure(args[0]) === undefined ? {} : { startedAt: figure(args[0]) });
167
+ if (!trace)
168
+ return;
169
+ if (method === "known") {
170
+ const run = fields(args[0]);
171
+ const routes = run.routes instanceof Map ? new Map([...run.routes].slice(0, OPEN_MAX).flatMap(([key, route]) => (typeof key === "string" ? [[keptId(key), via(route)]] : []))) : undefined;
172
+ trace.known({ runId, ...ofRun, harness: name(run.harness) ?? "unknown", ...(run.plan === true ? { plan: true } : {}), ...via(run), ...(routes ? { routes } : {}) });
173
+ }
174
+ else if (method === "request" && typeof args[0] === "number") {
175
+ const route = text(args[2]);
176
+ if (!requests.has(args[0]) && requests.size < OPEN_MAX)
177
+ requests.set(args[0], trace.request(name(args[1]), route === undefined ? undefined : keptId(route)));
178
+ }
179
+ else if (method === "ended" && typeof args[0] === "number") {
180
+ requests.get(args[0])?.(usageOf(args[1]), endedOf(args[2]));
181
+ requests.delete(args[0]);
182
+ }
183
+ else if (method === "event") {
184
+ const event = fields(args[0]);
185
+ const given = text(event.callId) ?? "";
186
+ const [callId, shownId] = [keptId(given), written(given, redact)];
187
+ const parentId = text(event.parent);
188
+ const parent = parentId ? { parent: keptId(parentId) } : {};
189
+ if (event.type === "tool_start" && event.refused === true)
190
+ trace.event({ type: "tool_start", callId, shownId, refused: true, ...parent });
191
+ else if (event.type === "tool_start")
192
+ trace.event({ type: "tool_start", callId, shownId, ...(name(event.name) ? { name: name(event.name) } : {}), ...(event.mcp === true ? { mcp: true } : {}), ...parent });
193
+ else if (event.type === "tool_end")
194
+ trace.event({ type: "tool_end", callId, isError: event.isError === true });
195
+ else if (event.type === "turn_end")
196
+ trace.event({ type: "turn_end", status: typeof event.status === "string" && TURN_STATUSES.has(event.status) ? event.status : "failed" });
197
+ else
198
+ trace.event({ type: "other" });
199
+ }
200
+ else if (method === "end")
201
+ void trace.end(args[0] === undefined || args[0] === null ? undefined : (shaped(args[0], FAILURE_CODE) ?? "run-error"));
202
+ },
203
+ end: async (failed) => trace?.end(failed),
204
+ };
205
+ }
61
206
  let shared;
62
207
  /** This process's tracing, or undefined while `env` leaves it off: then no @opentelemetry module is ever loaded. Made
63
208
  * once per process; a test's (`test`) is its own. */
64
- export function genAiTracing(env = otelEnv(), test) {
209
+ export function genAiTracing(env = process.env, test) {
65
210
  if (!otelOn(env))
66
211
  return Promise.resolve(undefined);
67
212
  if (test)
68
213
  return made(env, test);
69
214
  shared ??= made(env).catch((error) => {
70
- console.warn(`[otel] tracing is off: the OpenTelemetry SDK did not start: ${error?.message ?? error}`);
215
+ saidOf(env)(`[otel] tracing is off: the OpenTelemetry SDK did not start: ${error?.message ?? error}`);
71
216
  return undefined;
72
217
  });
73
218
  return shared;
@@ -81,10 +226,22 @@ export async function flushTraces() {
81
226
  /** A trace id for `runId`: the same for every claim of the run. */
82
227
  export const traceIdOf = (runId) => createHash("sha256").update(`agentrun-run:${runId}`).digest("hex").slice(0, 32);
83
228
  const serveVersion = () => JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
229
+ /** The tracing's log (`given`, else the runner's console): each `[otel]` line cut first by the runner's redactor over
230
+ * `env` (runner/redact.ts runnerSecrets: its OTLP header values among them), since an exporter's error may quote a
231
+ * header it sent, then of every OTLP header value at any length (secrets.ts otlpHeaderCut): the redactor cuts none
232
+ * shorter than MIN_SECRET, and a tracing key may be. Every line of this module goes through here. */
233
+ function saidOf(env, given) {
234
+ const cut = secretRedactor(runnerSecrets(env));
235
+ const headers = otlpHeaderCut(env);
236
+ const log = given ?? ((line) => console.warn(line));
237
+ return (line) => log(headers(cut(line)));
238
+ }
84
239
  async function made(env, test) {
85
- const [api, sdk, resources, semconv] = await Promise.all([import("@opentelemetry/api"), import("@opentelemetry/sdk-trace"), import("@opentelemetry/resources"), import("@opentelemetry/semantic-conventions")]);
86
- const log = test?.log ?? ((line) => console.warn(line));
87
- const exporter = safeExporter(test?.exporter ?? new (await import("@opentelemetry/exporter-trace-otlp-http")).OTLPTraceExporter(exporterConfig(env)), log);
240
+ const [api, sdk, resources] = await Promise.all([import("@opentelemetry/api"), import("@opentelemetry/sdk-trace"), import("@opentelemetry/resources")]);
241
+ const log = saidOf(env, test?.log);
242
+ const config = exporterConfig(env);
243
+ const where = shownEndpoint(config.url);
244
+ const exporter = safeExporter(test?.exporter ?? new (await import("@opentelemetry/exporter-trace-otlp-http")).OTLPTraceExporter(config), log, where, test?.now ?? Date.now);
88
245
  // The next root span's trace id (the run's), taken by the one startSpan that asks for it: startSpan is synchronous.
89
246
  const ids = { next: undefined };
90
247
  const idGenerator = {
@@ -95,12 +252,12 @@ async function made(env, test) {
95
252
  },
96
253
  generateSpanId: () => randomBytes(8).toString("hex"),
97
254
  };
98
- // The operator's resource attributes over ours, read from `env` (a run's process has them from its pipe, never from
99
- // its environment, so the SDK's own env detector would not see them).
255
+ // The operator's resource attributes over ours, read from `env` (a test's, or the runner's).
100
256
  const named = env.OTEL_SERVICE_NAME?.trim();
101
257
  const resource = resources.defaultResource()
102
- .merge(resources.resourceFromAttributes({ [semconv.ATTR_SERVICE_NAME]: "agentrun", [semconv.ATTR_SERVICE_VERSION]: serveVersion() }))
103
- .merge(resources.resourceFromAttributes({ ...listOf(env.OTEL_RESOURCE_ATTRIBUTES), ...(named ? { [semconv.ATTR_SERVICE_NAME]: named } : {}) }));
258
+ // The resource's names as the spec writes them: no module is loaded for two strings.
259
+ .merge(resources.resourceFromAttributes({ "service.name": "agentrun", "service.version": serveVersion() }))
260
+ .merge(resources.resourceFromAttributes({ ...keyValues(env.OTEL_RESOURCE_ATTRIBUTES), ...(named ? { "service.name": named } : {}) }));
104
261
  const provider = new sdk.TracerProvider({
105
262
  resource,
106
263
  idGenerator,
@@ -121,9 +278,11 @@ async function made(env, test) {
121
278
  // A process that ends by running out of work (no close, no exit call) flushes once first.
122
279
  if (!test)
123
280
  process.once("beforeExit", () => void flush());
281
+ // Said once, as the tracing is made: that it is on, and where its spans go (the endpoint's origin; no header).
282
+ log(`[otel] tracing is on: spans export to ${where}`);
124
283
  return {
125
284
  flush,
126
- open: ({ startedAt = Date.now(), mcp = () => false } = {}) => {
285
+ open: ({ startedAt = Date.now() } = {}) => {
127
286
  let run;
128
287
  let root;
129
288
  let rootContext;
@@ -168,7 +327,7 @@ async function made(env, test) {
168
327
  rootContext = api.trace.setSpan(api.ROOT_CONTEXT, root);
169
328
  },
170
329
  request: (model, route) => {
171
- if (!run || run.plan)
330
+ if (!run || run.plan || chats.size >= OPEN_MAX)
172
331
  return () => { };
173
332
  const on = run;
174
333
  const asked = { ...(model ? { model } : {}), ...(route === undefined ? {} : { route }) };
@@ -193,17 +352,22 @@ async function made(env, test) {
193
352
  if (on.plan && !turn)
194
353
  turn = child(spanName.chat(on.model), api.SpanKind.CLIENT, chatAttributes(on, {}));
195
354
  if (event.type === "tool_start") {
196
- if (tools.has(event.callId))
355
+ if (tools.has(event.callId) || tools.size >= OPEN_MAX)
197
356
  return;
198
357
  const parent = event.parent ? tools.get(event.parent)?.span : undefined;
199
- tools.set(event.callId, { span: child(spanName.tool(event.name), api.SpanKind.INTERNAL, toolAttributes(on, { name: event.name, callId: event.callId, mcp: mcp(event.name) }), parent ? api.trace.setSpan(api.ROOT_CONTEXT, parent) : undefined), turn: turns });
358
+ // A call its harness refused (a tool the session does not have) is never named: the name is the model's words.
359
+ const name = event.refused ? undefined : event.name;
360
+ const span = child(spanName.tool(name), api.SpanKind.INTERNAL, toolAttributes(on, { ...(name ? { name } : {}), callId: event.shownId ?? event.callId, ...(event.mcp ? { mcp: true } : {}) }), parent ? api.trace.setSpan(api.ROOT_CONTEXT, parent) : undefined);
361
+ if (event.refused)
362
+ failed(span, "tool_refused");
363
+ tools.set(event.callId, { span, turn: turns, refused: event.refused === true });
200
364
  }
201
365
  else if (event.type === "tool_end") {
202
366
  const call = tools.get(event.callId);
203
367
  if (!call)
204
368
  return;
205
369
  tools.delete(event.callId);
206
- if (event.isError)
370
+ if (event.isError && !call.refused)
207
371
  failed(call.span, "tool_error");
208
372
  call.span.end();
209
373
  }
@@ -276,24 +440,45 @@ function rootSampler(env, sdk) {
276
440
  }
277
441
  return new sdk.AlwaysOnSampler();
278
442
  }
279
- /** `exporter` made safe for a run: a throw or a failed export is said once, in one line, and the spans are dropped; the
280
- * next line is said only after an export has succeeded again, so a collector that is down is one line, not one a batch. */
281
- function safeExporter(exporter, log) {
282
- let failing = false;
443
+ /** `exporter` made safe for a run: a throw or a failed export drops its spans and is said in the log, with the endpoint
444
+ * (`where`, its origin: shownEndpoint) and the time (`now`): the first at once; after it, at most one line each FAILURE_LINE_MS,
445
+ * said by the next failure once that long has passed since the last line, counting every failure since that line, the
446
+ * current one among them. So a collector that is down is a line a minute at most, never one a batch or a span; a
447
+ * failure that no later one follows is counted in no line. */
448
+ function safeExporter(exporter, log, where, now) {
449
+ let saidAt;
450
+ let unsaid = 0;
451
+ const iso = (at) => new Date(at).toISOString();
452
+ const failedAt = (why) => {
453
+ const at = now();
454
+ const words = why?.message ?? why;
455
+ if (saidAt === undefined) {
456
+ log(`[otel] a trace export to ${where} failed at ${iso(at)}; its spans were dropped: ${words}`);
457
+ saidAt = at;
458
+ return;
459
+ }
460
+ unsaid += 1;
461
+ if (at - saidAt < FAILURE_LINE_MS)
462
+ return;
463
+ log(`[otel] ${unsaid} more trace export${unsaid === 1 ? "" : "s"} to ${where} failed since ${iso(saidAt)}, the last at ${iso(at)}; ${unsaid === 1 ? "its" : "their"} spans were dropped: ${words}`);
464
+ saidAt = at;
465
+ unsaid = 0;
466
+ };
283
467
  return {
284
468
  export: (spans, done) => {
285
469
  const failedWith = (why) => {
286
- if (!failing)
287
- log(`[otel] a trace export failed; its spans were dropped: ${why?.message ?? why}`);
288
- failing = true;
470
+ try {
471
+ failedAt(why);
472
+ }
473
+ catch {
474
+ // A log that throws loses its line, never the export's answer.
475
+ }
289
476
  done({ code: 1 });
290
477
  };
291
478
  try {
292
479
  exporter.export(spans, (result) => {
293
- if (result.code === 0) {
294
- failing = false;
480
+ if (result.code === 0)
295
481
  done(result);
296
- }
297
482
  else
298
483
  failedWith(result.error ?? "the exporter said it failed");
299
484
  });
package/dist/page.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import type { Owner } from "./owner.js";
3
+ /** The share page's CSP (share.html at /share/<run>): this origin's scripts, styles, data and images, and nothing from
4
+ * anywhere else. It is the page a share host serves, under the same policy; no favicon host, so a URL in a run's answer
5
+ * can never make a third party fetch anything. */
6
+ export declare const SHARE_PAGE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
3
7
  /** Strict-Transport-Security for a server whose public address (AGENTRUN_PUBLIC_URL) is https: a browser that saw it
4
8
  * once opens the address over https only, for a year. None over http or with no public address (a browser would pin
5
9
  * the loopback address to https and lose the console). */
@@ -20,6 +24,7 @@ export declare class ConsoleSessions {
20
24
  /** Whether `value` is a session this server made. */
21
25
  holds(value: string): boolean;
22
26
  }
27
+ /** The values of the request's cookies named `name`, in the order sent. */
23
28
  export declare const cookiesOf: (req: IncomingMessage, name: string) => string[];
24
29
  /** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
25
30
  * which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
@@ -70,7 +75,8 @@ export declare const byOwnerSession: (req: IncomingMessage) => boolean;
70
75
  /** Whether `req` came from the accounts-off console's page session (answerPage). */
71
76
  export declare const byConsoleSession: (req: IncomingMessage) => boolean;
72
77
  /**
73
- * Answers the console's paths ("/" and its /assets/*, and the addresses that moved to "/"), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
78
+ * Answers the console's paths ("/" and its /assets/*, the addresses that moved to "/", and the share preview under
79
+ * /share/), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
74
80
  * becomes the Bearer header for a GET or HEAD, and for any other method only when the request's Origin is this server's
75
81
  * own origin and its body is application/json, or the request is a PUT or POST to a route that takes bytes, with any
76
82
  * content type.
package/dist/page.js CHANGED
@@ -14,6 +14,10 @@ import { hostPort, hostRefusedPage, movedPage } from "./host-check.js";
14
14
  // icon from it (apps/console/src/components/ProviderIcon.tsx), sent with no referrer. Everything else is this origin's.
15
15
  const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: https://www.google.com https://t0.gstatic.com https://t1.gstatic.com https://t2.gstatic.com https://t3.gstatic.com; base-uri 'none'; form-action https://github.com; frame-ancestors 'none'";
16
16
  const SECURITY = { "content-security-policy": CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "cache-control": "no-store" };
17
+ /** The share page's CSP (share.html at /share/<run>): this origin's scripts, styles, data and images, and nothing from
18
+ * anywhere else. It is the page a share host serves, under the same policy; no favicon host, so a URL in a run's answer
19
+ * can never make a third party fetch anything. */
20
+ export const SHARE_PAGE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
17
21
  const HTML = "text/html; charset=utf-8";
18
22
  /** Strict-Transport-Security for a server whose public address (AGENTRUN_PUBLIC_URL) is https: a browser that saw it
19
23
  * once opens the address over https only, for a year. None over http or with no public address (a browser would pin
@@ -35,6 +39,16 @@ const CONSOLE_SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
35
39
  /** Addresses the console had before it took "/", and the old page's setup and sign-in, which the printed setup link
36
40
  * still names: each sends the browser to "/", which keeps the link's #code. */
37
41
  const MOVED = new Set(["/console", "/console/", "/setup", "/sign-in"]);
42
+ /** The share preview's addresses (the console's second entry, share.html): the page at /share/<run>, and the console's
43
+ * assets under /share/assets/, where the page's relative URLs land. */
44
+ const SHARE = "/share/";
45
+ /** A run's id as the share page's address names it: one segment, never a dot segment, a trailing slash allowed. */
46
+ const SHARE_RUN = /^[A-Za-z0-9_-][A-Za-z0-9._-]*\/?$/;
47
+ /** The share page's answer to a browser without this server's session: a fixed page under the CSP, never share.html. */
48
+ const SIGN_IN_FIRST = `<!doctype html>
49
+ <html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="robots" content="noindex" /><title>Sign in first · AgentRun</title></head>
50
+ <body><main><h1>Sign in to this server first</h1><p>A share preview shows what a run's share would publish, and only this server's owner may read it. Sign in at <a href="/">the console</a>, or open the link this server printed when it started, then open this page again.</p></main></body></html>
51
+ `;
38
52
  const digest = (text) => createHash("sha256").update(text).digest();
39
53
  const same = (given, expected) => timingSafeEqual(digest(given), digest(expected));
40
54
  /** The most console sessions a server keeps at once; past it, the oldest is forgotten (its browser opens the link again). */
@@ -70,7 +84,13 @@ export class ConsoleSessions {
70
84
  * (7340, published at 7350), and so does another beside it. A Host with no port keeps the socket's. */
71
85
  const browserPort = (req) => hostPort(req.headers.host) ?? req.socket.localPort;
72
86
  const cookieName = (req) => `agentrun-${browserPort(req)}`;
73
- export const cookiesOf = (req, name) => String(req.headers.cookie ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(`${name}=`)).map((part) => part.slice(name.length + 1));
87
+ /** The request's cookies, each name and value trimmed, in the order sent; a part with no name is left out. */
88
+ const cookiePairs = (req) => String(req.headers.cookie ?? "").split(";").flatMap((part) => {
89
+ const at = part.indexOf("=");
90
+ return at > 0 && part.slice(0, at).trim() ? [{ name: part.slice(0, at).trim(), value: part.slice(at + 1).trim() }] : [];
91
+ });
92
+ /** The values of the request's cookies named `name`, in the order sent. */
93
+ export const cookiesOf = (req, name) => cookiePairs(req).filter((pair) => pair.name === name).map((pair) => pair.value);
74
94
  /** Whether the browser reached this server over TLS, as the proxy in front says (X-Forwarded-Proto): `https`, or `wss`,
75
95
  * which some proxies (Traefik) send on a WebSocket upgrade. Both are the page's https origin and its `__Host-` cookie. */
76
96
  export const overHttps = (req) => ["https", "wss"].includes(String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim().toLowerCase());
@@ -86,11 +106,7 @@ export const ownerCookie = (req, value, maxAgeS, name = ownerCookieName(req)) =>
86
106
  * again through a tunnel at 8080 sends both to either. Which are this server's is the owner's to say (Owner.valid). */
87
107
  export const sessionsAtEveryPort = (req) => {
88
108
  const own = ownerCookieName(req);
89
- return String(req.headers.cookie ?? "").split(";").flatMap((part) => {
90
- const at = part.indexOf("=");
91
- const name = part.slice(0, at).trim();
92
- return at > 0 && (name === own || /^agentrun-\d{1,5}-session$/.test(name)) ? [{ name, value: part.slice(at + 1).trim() }] : [];
93
- });
109
+ return cookiePairs(req).filter(({ name }) => name === own || /^agentrun-\d{1,5}-session$/.test(name));
94
110
  };
95
111
  /** The owner's session cookies the request holds, valid or not. */
96
112
  export const heldSessions = (req) => cookiesOf(req, ownerCookieName(req));
@@ -115,7 +131,7 @@ const refuse = (req, res, error) => send(req, res, error.status, "application/js
115
131
  const redirect = (res, location, headers = {}) => (res.writeHead(303, { ...SECURITY, location, "content-length": 0, ...headers }), void res.end());
116
132
  /** A file of the console: a known type inside `dir`, read through no link that leaves it. Vite's hashed assets are cached
117
133
  * for a year; index.html is no-store. */
118
- async function file(req, res, raw, dir, rel, status = 200) {
134
+ async function file(req, res, raw, dir, rel, status = 200, headers = {}) {
119
135
  const missing = () => refuse(req, res, new ApiError("not_found", `no file ${raw} in the console`));
120
136
  const type = CONSOLE_TYPES[extname(rel).toLowerCase()];
121
137
  if (!type || !rel.split("/").every((segment) => CONSOLE_SEGMENT.test(segment)))
@@ -127,31 +143,68 @@ async function file(req, res, raw, dir, rel, status = 200) {
127
143
  }
128
144
  if (!real.startsWith(root + sep) || !(await stat(real)).isFile())
129
145
  return missing();
130
- send(req, res, status, type, await readFile(real), { "cache-control": rel.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-store" });
146
+ send(req, res, status, type, await readFile(real), { "cache-control": rel.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-store", ...headers });
131
147
  }
132
- async function answer(req, res, raw, server) {
148
+ async function answer(req, res, raw, server, held) {
133
149
  if (req.method !== "GET" && req.method !== "HEAD")
134
150
  return refuse(req, res, new ApiError("method_not_allowed", `the console answers GET and HEAD; ${req.method} is not one`, {}, { allow: "GET, HEAD" }));
135
151
  const dir = server.console ?? CONSOLE_DIR;
152
+ if (raw.startsWith(SHARE))
153
+ return share(req, res, raw, dir, server, held);
136
154
  if (MOVED.has(raw))
137
155
  return redirect(res, `/${(req.url ?? "").slice(raw.length)}`);
138
156
  if (raw !== "/")
139
157
  return file(req, res, raw, dir, raw.slice(1));
140
- // Without accounts, the printed link's launch code gives this browser a console session (ConsoleSessions). The token
141
- // is for scripts and the CLI: a token in the address signs nothing in, here or with an owner, and leaves it (the same
142
- // address without it, no cookie). With an owner the console is the owner's session alone.
158
+ const given = launch(req, res, raw, server, raw);
159
+ if (given === "answered")
160
+ return;
161
+ return file(req, res, raw, dir, "index.html", given === "wrong" ? 401 : 200);
162
+ }
163
+ /** The printed link's code in a page's address (`raw`: `/`, or `/share/<run>` the CLI opens). Without accounts, a right
164
+ * code gives this browser a console session (ConsoleSessions) and a redirect to the same page without it; "answered".
165
+ * The token is for scripts and the CLI: a token in the address signs nothing in, here or with an owner, and leaves it
166
+ * (the same address without it, no cookie). With an owner the console is the owner's session alone, so a code leaves
167
+ * the same way. A wrong code is "wrong" and sets nothing (the page answers 401); none is "none". `where` names the page
168
+ * in the failure log. */
169
+ function launch(req, res, raw, server, where) {
143
170
  const url = new URL(req.url ?? "/", "http://serve");
144
- const without = () => (url.searchParams.delete("token"), url.searchParams.delete("launch"), `/${url.searchParams.size ? `?${url.searchParams}` : ""}`);
171
+ const without = () => (url.searchParams.delete("token"), url.searchParams.delete("launch"), `${raw}${url.searchParams.size ? `?${url.searchParams}` : ""}`);
145
172
  const given = url.searchParams.get("launch");
146
173
  if (url.searchParams.has("token") || (server.owner && given !== null))
147
- return redirect(res, without());
174
+ return redirect(res, without()), "answered";
175
+ if (given === null)
176
+ return "none";
148
177
  // A code holds no "+", but a space in the link is one that was not encoded all the same.
149
- const id = given === null ? undefined : server.sessions?.open(given) ?? server.sessions?.open(given.replaceAll(" ", "+"));
178
+ const id = server.sessions?.open(given) ?? server.sessions?.open(given.replaceAll(" ", "+"));
150
179
  if (id !== undefined)
151
- return redirect(res, without(), { "set-cookie": `${cookieName(req)}=${id}; HttpOnly; SameSite=Strict; Path=/${overHttps(req) ? "; Secure" : ""}` });
152
- if (given !== null)
153
- server.authFailed?.(raw, "wrong_launch_code");
154
- return file(req, res, raw, dir, "index.html", given === null ? 200 : 401);
180
+ return redirect(res, without(), { "set-cookie": `${cookieName(req)}=${id}; HttpOnly; SameSite=Strict; Path=/${overHttps(req) ? "; Secure" : ""}` }), "answered";
181
+ server.authFailed?.(where, "wrong_launch_code");
182
+ return "wrong";
183
+ }
184
+ /** The share preview (share.html) at /share/<run>, the owner's alone: a browser without this server's session (`held`:
185
+ * the owner's signed-in session with accounts, the printed link's without) gets SIGN_IN_FIRST, a 401, and so does a
186
+ * wrong launch code; a right one opens the session here as on `/` (launch). The page reads the run's export with that
187
+ * session (GET /v2/runs/<run>/export) and nothing else. Its assets are the console's, public. */
188
+ async function share(req, res, raw, dir, server, held) {
189
+ const rest = raw.slice(SHARE.length);
190
+ if (rest.startsWith("assets/"))
191
+ return file(req, res, raw, dir, rest);
192
+ if (!SHARE_RUN.test(rest))
193
+ return refuse(req, res, new ApiError("not_found", `no page ${raw}: a share preview is /share/<run id>`));
194
+ // share.html's assets are relative (./assets/): under /share/<run>/ they resolve to /share/<run>/assets/, which is no
195
+ // file. So the slash goes, with the query kept, before anything else is asked.
196
+ if (rest.endsWith("/"))
197
+ return redirect(res, `${raw.slice(0, -1)}${new URL(req.url ?? "/", "http://serve").search}`);
198
+ // The CLI opens /share/<run>?launch=<code> when it knows the code: the same session as `/?launch=`, landing here.
199
+ const given = launch(req, res, raw, server, "/share");
200
+ if (given === "answered")
201
+ return;
202
+ if (given === "wrong" || !held) {
203
+ if (given === "none")
204
+ server.authFailed?.("/share", "no_session");
205
+ return send(req, res, 401, HTML, SIGN_IN_FIRST);
206
+ }
207
+ return file(req, res, raw, dir, "share.html", 200, { "content-security-policy": SHARE_PAGE_CSP });
155
208
  }
156
209
  /** The requests the owner's password session sends from the page (a write only from this server's own origin, with a
157
210
  * JSON body), never under an accounts-off console session. */
@@ -166,7 +219,8 @@ const consoleSessions = new WeakSet();
166
219
  /** Whether `req` came from the accounts-off console's page session (answerPage). */
167
220
  export const byConsoleSession = (req) => consoleSessions.has(req);
168
221
  /**
169
- * Answers the console's paths ("/" and its /assets/*, and the addresses that moved to "/"), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
222
+ * Answers the console's paths ("/" and its /assets/*, the addresses that moved to "/", and the share preview under
223
+ * /share/), and returns true; returns false for every other path. On a /v2 path with no Authorization header, the browser's cookie
170
224
  * becomes the Bearer header for a GET or HEAD, and for any other method only when the request's Origin is this server's
171
225
  * own origin and its body is application/json, or the request is a PUT or POST to a route that takes bytes, with any
172
226
  * content type.
@@ -187,12 +241,12 @@ export function answerPage(req, res, raw, server) {
187
241
  }
188
242
  return false;
189
243
  }
190
- if (raw !== "/" && !raw.startsWith("/assets/") && !MOVED.has(raw))
244
+ if (raw !== "/" && !raw.startsWith("/assets/") && !MOVED.has(raw) && !raw.startsWith(SHARE))
191
245
  return false;
192
246
  // Every page answer (the console, its assets, its redirects) at an https public address: HSTS.
193
247
  for (const [name, value] of Object.entries(hstsHeaders(server.publicUrl)))
194
248
  res.setHeader(name, value);
195
- answer(req, res, raw, server).catch(() => {
249
+ answer(req, res, raw, server, held).catch(() => {
196
250
  if (!res.headersSent)
197
251
  refuse(req, res, new ApiError("internal", "the console could not be read"));
198
252
  else