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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (388) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +580 -320
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +92 -22
  28. package/dist/composio-preset.d.ts +4 -3
  29. package/dist/composio-preset.js +81 -11
  30. package/dist/composio-triggers.d.ts +34 -2
  31. package/dist/composio-triggers.js +261 -31
  32. package/dist/computer-attach.d.ts +40 -5
  33. package/dist/computer-attach.js +130 -15
  34. package/dist/computer-keys.d.ts +3 -0
  35. package/dist/computer-keys.js +7 -1
  36. package/dist/computer-live.js +3 -2
  37. package/dist/computer-lost.d.ts +11 -0
  38. package/dist/computer-lost.js +19 -0
  39. package/dist/computer-record.d.ts +10 -2
  40. package/dist/computer-record.js +50 -18
  41. package/dist/computer-setting.d.ts +1 -0
  42. package/dist/computer-setting.js +2 -2
  43. package/dist/computers.d.ts +21 -10
  44. package/dist/computers.js +39 -28
  45. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  46. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decisions.d.ts +1 -1
  49. package/dist/dial-relay.d.ts +29 -0
  50. package/dist/dial-relay.js +94 -0
  51. package/dist/email/tools.js +10 -5
  52. package/dist/env-proxy.d.ts +2 -0
  53. package/dist/env-proxy.js +35 -0
  54. package/dist/errors.d.ts +4 -1
  55. package/dist/errors.js +10 -4
  56. package/dist/faux-computers.d.ts +8 -2
  57. package/dist/faux-computers.js +83 -6
  58. package/dist/harness-archive.d.ts +67 -0
  59. package/dist/harness-archive.js +177 -0
  60. package/dist/harness-goose.d.ts +34 -0
  61. package/dist/harness-goose.js +87 -0
  62. package/dist/harness-install.d.ts +21 -0
  63. package/dist/harness-install.js +24 -11
  64. package/dist/harness-opencode/adapter.js +1 -1
  65. package/dist/harness-table.d.ts +59 -3
  66. package/dist/harness-table.js +119 -14
  67. package/dist/harness.d.ts +17 -1
  68. package/dist/harness.js +22 -11
  69. package/dist/host.d.ts +12 -10
  70. package/dist/host.js +19 -16
  71. package/dist/import-worker.d.ts +3 -0
  72. package/dist/import-worker.js +7 -5
  73. package/dist/import.d.ts +22 -1
  74. package/dist/import.js +141 -28
  75. package/dist/key-check.js +3 -0
  76. package/dist/learn/audit.d.ts +6 -6
  77. package/dist/learn/audit.js +3 -7
  78. package/dist/learn/check.d.ts +26 -89
  79. package/dist/learn/check.js +58 -336
  80. package/dist/learn/commit.d.ts +63 -90
  81. package/dist/learn/commit.js +124 -316
  82. package/dist/learn/compile.d.ts +53 -50
  83. package/dist/learn/compile.js +88 -103
  84. package/dist/learn/corrections.d.ts +13 -0
  85. package/dist/learn/corrections.js +23 -0
  86. package/dist/learn/delete.d.ts +17 -0
  87. package/dist/learn/delete.js +42 -0
  88. package/dist/learn/folder.d.ts +35 -47
  89. package/dist/learn/folder.js +118 -134
  90. package/dist/learn/index.d.ts +3 -5
  91. package/dist/learn/index.js +6 -9
  92. package/dist/learn/learning.sh +45 -15
  93. package/dist/learn/promote.d.ts +20 -2
  94. package/dist/learn/promote.js +17 -4
  95. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
  96. package/dist/learn/{skills.js → workflow-draft.js} +65 -59
  97. package/dist/learn/workflow-nodes.d.ts +22 -1
  98. package/dist/learn/workflow-nodes.js +29 -10
  99. package/dist/learned-workflow.js +2 -2
  100. package/dist/learning-cost.d.ts +127 -13
  101. package/dist/learning-cost.js +142 -10
  102. package/dist/learning-routes.d.ts +99 -170
  103. package/dist/learning-routes.js +199 -420
  104. package/dist/learning-run.d.ts +19 -40
  105. package/dist/learning-run.js +23 -93
  106. package/dist/learning-setting.d.ts +4 -4
  107. package/dist/learning-setting.js +6 -6
  108. package/dist/learning-words.d.ts +28 -74
  109. package/dist/learning-words.js +64 -162
  110. package/dist/learning.d.ts +62 -393
  111. package/dist/learning.js +101 -651
  112. package/dist/listen-first.d.ts +30 -0
  113. package/dist/listen-first.js +115 -0
  114. package/dist/live-reach.d.ts +25 -2
  115. package/dist/live-reach.js +46 -4
  116. package/dist/llms.txt +2 -1
  117. package/dist/local-models.d.ts +3 -11
  118. package/dist/local-models.js +5 -6
  119. package/dist/mcp-servers-store.d.ts +16 -16
  120. package/dist/model-form.js +6 -5
  121. package/dist/model.d.ts +12 -4
  122. package/dist/model.js +41 -16
  123. package/dist/native/binding.js +1 -1
  124. package/dist/native/connection.js +1 -1
  125. package/dist/native/discovery.js +1 -1
  126. package/dist/native/instructions.d.ts +3 -0
  127. package/dist/native/instructions.js +5 -3
  128. package/dist/native/remote-worker-bridge.js +9 -43
  129. package/dist/native/remote.d.ts +8 -15
  130. package/dist/native/remote.js +3 -3
  131. package/dist/native/schema.js +1 -1
  132. package/dist/native/types.d.ts +2 -2
  133. package/dist/openapi.js +375 -347
  134. package/dist/owner.d.ts +8 -0
  135. package/dist/owner.js +11 -0
  136. package/dist/paid-calls.d.ts +14 -0
  137. package/dist/paid-calls.js +31 -1
  138. package/dist/particle-provider.d.ts +11 -0
  139. package/dist/particle-provider.js +135 -0
  140. package/dist/place.d.ts +8 -3
  141. package/dist/place.js +13 -9
  142. package/dist/port-models.d.ts +12 -4
  143. package/dist/port-models.js +28 -11
  144. package/dist/print.d.ts +27 -0
  145. package/dist/print.js +21 -0
  146. package/dist/provider.d.ts +7 -0
  147. package/dist/provider.js +30 -2
  148. package/dist/reflect-range.js +2 -3
  149. package/dist/run-launch.d.ts +14 -28
  150. package/dist/run-launch.js +9 -12
  151. package/dist/run-learning-served.d.ts +16 -90
  152. package/dist/run-listing.d.ts +34 -0
  153. package/dist/run-listing.js +128 -0
  154. package/dist/run-model-key.d.ts +64 -0
  155. package/dist/run-model-key.js +147 -0
  156. package/dist/run-timeline-served.js +5 -3
  157. package/dist/run-trace.d.ts +97 -0
  158. package/dist/run-trace.js +253 -0
  159. package/dist/run-view.d.ts +15 -0
  160. package/dist/run-view.js +9 -0
  161. package/dist/runnable.js +2 -1
  162. package/dist/runner/adapter-loop.d.ts +14 -6
  163. package/dist/runner/adapter-loop.js +25 -14
  164. package/dist/runner/adapter-run-spec.d.ts +22 -7
  165. package/dist/runner/adapter-run-spec.js +130 -77
  166. package/dist/runner/adapters/index.d.ts +4 -2
  167. package/dist/runner/adapters/index.js +35 -4
  168. package/dist/runner/adapters/pi.d.ts +4 -12
  169. package/dist/runner/adapters/pi.js +2 -2
  170. package/dist/runner/audit.d.ts +5 -1
  171. package/dist/runner/audit.js +31 -12
  172. package/dist/runner/beside.d.ts +7 -2
  173. package/dist/runner/beside.js +41 -9
  174. package/dist/runner/claim-secrets.d.ts +66 -1
  175. package/dist/runner/claim-secrets.js +136 -3
  176. package/dist/runner/cli-run-spec.d.ts +2 -1
  177. package/dist/runner/cli-run-spec.js +82 -59
  178. package/dist/runner/commands.d.ts +3 -6
  179. package/dist/runner/conformance/harness.d.ts +6 -0
  180. package/dist/runner/conformance/harness.js +16 -5
  181. package/dist/runner/dispatch.d.ts +2 -2
  182. package/dist/runner/end-of-run.d.ts +6 -14
  183. package/dist/runner/end-of-run.js +8 -33
  184. package/dist/runner/feedback-round.d.ts +5 -4
  185. package/dist/runner/feedback-round.js +14 -10
  186. package/dist/runner/github-app.js +3 -1
  187. package/dist/runner/harness-loops.d.ts +0 -8
  188. package/dist/runner/harness-loops.js +30 -56
  189. package/dist/runner/held.d.ts +170 -0
  190. package/dist/runner/held.js +57 -0
  191. package/dist/runner/journal-kinds.d.ts +7 -3
  192. package/dist/runner/journal-kinds.js +2 -3
  193. package/dist/runner/learned-first.d.ts +40 -0
  194. package/dist/runner/learned-first.js +32 -0
  195. package/dist/runner/learning-end.d.ts +77 -66
  196. package/dist/runner/learning-end.js +250 -299
  197. package/dist/runner/learning-seed.d.ts +15 -33
  198. package/dist/runner/learning-seed.js +24 -45
  199. package/dist/runner/loop-contract.d.ts +8 -3
  200. package/dist/runner/loop-contract.js +4 -0
  201. package/dist/runner/loop.js +6 -2
  202. package/dist/runner/main.d.ts +18 -9
  203. package/dist/runner/main.js +82 -22
  204. package/dist/runner/mcp-run.d.ts +11 -0
  205. package/dist/runner/mcp-run.js +67 -0
  206. package/dist/runner/memory-claim.d.ts +14 -6
  207. package/dist/runner/memory-claim.js +18 -9
  208. package/dist/runner/model-route.d.ts +7 -4
  209. package/dist/runner/model-route.js +22 -10
  210. package/dist/runner/native-loop.d.ts +0 -7
  211. package/dist/runner/native-loop.js +9 -101
  212. package/dist/runner/promotion.d.ts +13 -6
  213. package/dist/runner/promotion.js +63 -17
  214. package/dist/runner/reflect-hook.d.ts +64 -91
  215. package/dist/runner/reflect-hook.js +112 -206
  216. package/dist/runner/run-channel.d.ts +43 -0
  217. package/dist/runner/run-channel.js +467 -0
  218. package/dist/runner/run-child-host.d.ts +169 -0
  219. package/dist/runner/run-child-host.js +1222 -0
  220. package/dist/runner/run-child.d.ts +1 -0
  221. package/dist/runner/run-child.js +254 -0
  222. package/dist/runner/run-errors.d.ts +2 -0
  223. package/dist/runner/run-errors.js +20 -0
  224. package/dist/runner/runner.js +58 -9
  225. package/dist/runner/sdk-ask.d.ts +78 -0
  226. package/dist/runner/sdk-ask.js +158 -0
  227. package/dist/runner/sdk-loop.d.ts +2 -4
  228. package/dist/runner/sdk-loop.js +29 -49
  229. package/dist/runner/store-secrets.d.ts +5 -3
  230. package/dist/runner/store-secrets.js +14 -6
  231. package/dist/runner/workflow-first.d.ts +5 -0
  232. package/dist/runner/workflow-first.js +4 -0
  233. package/dist/runner/workflow-spec.js +17 -4
  234. package/dist/runs-over-store.d.ts +21 -32
  235. package/dist/runs-over-store.js +44 -41
  236. package/dist/sdk/runs.d.ts +6 -11
  237. package/dist/sdk/runs.js +20 -41
  238. package/dist/sdk/schema.js +3 -4
  239. package/dist/sdk/workflows.d.ts +1 -1
  240. package/dist/seal-key.d.ts +5 -0
  241. package/dist/seal-key.js +7 -0
  242. package/dist/secrets.d.ts +3 -0
  243. package/dist/secrets.js +16 -3
  244. package/dist/server.d.ts +119 -83
  245. package/dist/server.js +1121 -419
  246. package/dist/sign-ins-store.d.ts +8 -0
  247. package/dist/sign-ins-store.js +36 -1
  248. package/dist/skills.js +1 -1
  249. package/dist/store/index.d.ts +3 -3
  250. package/dist/store/index.js +2 -2
  251. package/dist/store/journal/storage.js +3 -0
  252. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  253. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  254. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  255. package/dist/store/schema.d.ts +53 -4
  256. package/dist/store/schema.js +137 -6
  257. package/dist/store/seal.d.ts +20 -2
  258. package/dist/store/seal.js +24 -8
  259. package/dist/store/sqlite/connection.d.ts +2 -0
  260. package/dist/store/sqlite/connection.js +3 -1
  261. package/dist/store/sqlite/run-launch.d.ts +4 -1
  262. package/dist/store/sqlite/run-launch.js +12 -0
  263. package/dist/store/sqlite/run-patch.d.ts +0 -17
  264. package/dist/store/sqlite/run-patch.js +4 -33
  265. package/dist/store/sqlite/store.d.ts +3 -2
  266. package/dist/store/sqlite/store.js +360 -75
  267. package/dist/store/sqlite/worker.js +25 -0
  268. package/dist/store/store.d.ts +231 -39
  269. package/dist/store/store.js +25 -3
  270. package/dist/store-reads/analytics.js +11 -1
  271. package/dist/store-reads/learning.d.ts +131 -194
  272. package/dist/store-reads/learning.js +292 -301
  273. package/dist/store-reads/loop.d.ts +0 -1
  274. package/dist/store-reads/loop.js +1 -1
  275. package/dist/store-reads/stats.js +13 -3
  276. package/dist/store-view.d.ts +34 -2
  277. package/dist/store-view.js +108 -41
  278. package/dist/telemetry.d.ts +59 -0
  279. package/dist/telemetry.js +153 -0
  280. package/dist/template-eval.d.ts +3 -6
  281. package/dist/template-eval.js +22 -36
  282. package/dist/templates.d.ts +2 -1
  283. package/dist/templates.js +6 -3
  284. package/dist/timeline/index.d.ts +1 -1
  285. package/dist/timeline/index.js +1 -1
  286. package/dist/timeline/timeline.d.ts +5 -1
  287. package/dist/timeline/timeline.js +16 -0
  288. package/dist/tool-gate.d.ts +0 -7
  289. package/dist/tool-gate.js +1 -15
  290. package/dist/tool-keys-store.d.ts +1 -1
  291. package/dist/tool-keys.d.ts +6 -4
  292. package/dist/tool-keys.js +12 -6
  293. package/dist/tool-plane.d.ts +12 -12
  294. package/dist/tools.d.ts +13 -13
  295. package/dist/tools.js +29 -9
  296. package/dist/trigger-adapter.d.ts +3 -0
  297. package/dist/trigger-adapters.d.ts +4 -0
  298. package/dist/trigger-adapters.js +13 -0
  299. package/dist/trigger-composio.d.ts +58 -1
  300. package/dist/trigger-composio.js +160 -6
  301. package/dist/triggers.d.ts +64 -5
  302. package/dist/triggers.js +141 -17
  303. package/dist/validate.d.ts +11 -7
  304. package/dist/validate.js +9 -8
  305. package/dist/webhooks.d.ts +4 -1
  306. package/dist/webhooks.js +11 -4
  307. package/dist/workspace/agent-computer.d.ts +2 -0
  308. package/dist/workspace/agent-computer.js +2 -0
  309. package/dist/workspace/archil-claim.d.ts +7 -0
  310. package/dist/workspace/archil-claim.js +29 -0
  311. package/dist/workspace/archil.d.ts +9 -1
  312. package/dist/workspace/archil.js +165 -3
  313. package/dist/workspace/attach.d.ts +3 -1
  314. package/dist/workspace/attach.js +2 -0
  315. package/dist/workspace/attached-computers.d.ts +16 -5
  316. package/dist/workspace/attached-computers.js +25 -9
  317. package/dist/workspace/computer-deps.js +1 -1
  318. package/dist/workspace/computer-for-claim.d.ts +22 -8
  319. package/dist/workspace/computer-for-claim.js +339 -46
  320. package/dist/workspace/computer-hold.js +2 -1
  321. package/dist/workspace/computer-kept.d.ts +11 -1
  322. package/dist/workspace/computer-kept.js +24 -3
  323. package/dist/workspace/resolve-computer.d.ts +41 -21
  324. package/dist/workspace/resolve-computer.js +172 -64
  325. package/dist/workspace/revision-skills.d.ts +1 -2
  326. package/dist/workspace/revision-skills.js +3 -4
  327. package/dist/workspace/run-workspace.d.ts +1 -1
  328. package/dist/workspace/run-workspace.js +5 -0
  329. package/dist/workspace/synced-folder.d.ts +85 -0
  330. package/dist/workspace/synced-folder.js +230 -0
  331. package/dist/workspace/workspace.d.ts +4 -0
  332. package/launcher/agentrun-serve +1 -1
  333. package/package.json +10 -9
  334. package/templates/README.md +7 -7
  335. package/templates/inbound-lead/agent.md +3 -3
  336. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  337. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  338. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  339. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  340. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  341. package/templates/inbound-lead/lead.schema.json +6 -5
  342. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  343. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  344. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  345. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  346. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  347. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  348. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  349. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  350. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  351. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  352. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  353. package/dist/console/assets/index-Bz6IWncl.js +0 -711
  354. package/dist/learn/grade.d.ts +0 -138
  355. package/dist/learn/grade.js +0 -682
  356. package/dist/learn/notes.d.ts +0 -81
  357. package/dist/learn/notes.js +0 -178
  358. package/dist/learn/reflect.d.ts +0 -77
  359. package/dist/learn/reflect.js +0 -228
  360. package/dist/learn/relevance.d.ts +0 -24
  361. package/dist/learn/relevance.js +0 -91
  362. package/dist/learn/seed-check.d.ts +0 -74
  363. package/dist/learn/seed-check.js +0 -103
  364. package/dist/learning-batch.d.ts +0 -291
  365. package/dist/learning-batch.js +0 -600
  366. package/dist/learning-evals.d.ts +0 -33
  367. package/dist/learning-evals.js +0 -98
  368. package/dist/native/context.d.ts +0 -6
  369. package/dist/native/context.js +0 -22
  370. package/dist/propose.d.ts +0 -52
  371. package/dist/propose.js +0 -224
  372. package/dist/runner/learning-ask.d.ts +0 -47
  373. package/dist/runner/learning-ask.js +0 -128
  374. package/dist/runner/learning-dispatch.d.ts +0 -45
  375. package/dist/runner/learning-dispatch.js +0 -99
  376. package/dist/runner/learning-factory.d.ts +0 -16
  377. package/dist/runner/learning-factory.js +0 -50
  378. package/dist/runner/learning-loop.d.ts +0 -273
  379. package/dist/runner/learning-loop.js +0 -521
  380. package/dist/usage.d.ts +0 -11
  381. package/dist/usage.js +0 -11
  382. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  383. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  384. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  385. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  386. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  387. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  388. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -8,7 +8,6 @@ export type LoopCompile = {
8
8
  round: number;
9
9
  at: string;
10
10
  workflow: string | null;
11
- from_notes: string[];
12
11
  attempts: {
13
12
  ok: boolean;
14
13
  errors: string[];
@@ -40,7 +40,7 @@ export async function agentLoopOverStore(store, agentId) {
40
40
  const own = named && kept16 ? promotionOf(promotions, named.workflow, kept16) : undefined;
41
41
  const unchecked = own?.decided === "hold" && own.check?.stopped && own.check.n === 0 ? [own.reason] : [];
42
42
  compiles.push({
43
- createdAt: kept.createdAt, run_id: run.id, round: kept.round, at: new Date(kept.createdAt).toISOString(), workflow: named ? named.workflow : null, from_notes: texts(named?.from_notes), attempts,
43
+ createdAt: kept.createdAt, run_id: run.id, round: kept.round, at: new Date(kept.createdAt).toISOString(), workflow: named ? named.workflow : null, attempts,
44
44
  digest: kept16, promoted: named && kept16 ? (promotedOf(promotions, named.workflow, kept16) ?? null) : null, draft_errors: [...errors, ...unchecked],
45
45
  });
46
46
  }
@@ -1,4 +1,5 @@
1
1
  import { runReadState } from "./runs.js";
2
+ import { isShadowRun, shadowRunId } from "../learn/audit.js";
2
3
  const RUN_STATES = ["running", "completed", "failed", "stopped", "escalated"];
3
4
  const emptyCounts = () => ({ total: 0, running: 0, completed: 0, failed: 0, stopped: 0, escalated: 0 });
4
5
  /** Every agent, by name then id (the old order), with its archive and name. */
@@ -18,7 +19,12 @@ export async function stats(store) {
18
19
  const running = [];
19
20
  // Each revision's kind, read once: an agentic run a person stopped reads running (runReadState).
20
21
  const kinds = new Map();
22
+ // An audit's shadow run is learning spend on the run it audits, never a run of its own (A8): its cost, once known, is
23
+ // in the dollars with that run, shown or hidden with it; it is in no count, and never running work.
24
+ const shadows = new Map(runs.filter((run) => isShadowRun(run.id)).map((run) => [run.id, run]));
21
25
  for (const run of runs) {
26
+ if (isShadowRun(run.id))
27
+ continue;
22
28
  if (!kinds.has(run.revisionId))
23
29
  kinds.set(run.revisionId, (await store.agents.revision(run.revisionId))?.kind === "workflow" ? "workflow" : "agentic");
24
30
  const state = runReadState(run, kinds.get(run.revisionId));
@@ -31,7 +37,10 @@ export async function stats(store) {
31
37
  }
32
38
  let g = shown.get(run.agentId);
33
39
  if (g === undefined)
34
- shown.set(run.agentId, (g = { counts: emptyCounts(), costUsd: 0, known: 0 }));
40
+ shown.set(run.agentId, (g = { counts: emptyCounts(), costUsd: 0, known: 0, shadowUsd: 0 }));
41
+ const shadow = shadows.get(shadowRunId(run.id));
42
+ if (shadow && runReadState(shadow, "agentic") !== "running" && shadow.costUsd !== null)
43
+ g.shadowUsd += shadow.costUsd;
35
44
  g.counts.total += 1;
36
45
  g.counts[state] += 1;
37
46
  if (state !== "running" && run.costUsd !== null) {
@@ -54,8 +63,9 @@ export async function stats(store) {
54
63
  for (const key of ["total", ...RUN_STATES])
55
64
  stats.runs[key] += counts[key];
56
65
  const known = g?.known ?? 0;
57
- if (known > 0)
58
- stats.cost.usd = (stats.cost.usd ?? 0) + (g?.costUsd ?? 0);
66
+ // A shadow's known $ is spent whether or not the run it audits has a known cost: never a null for its dollars.
67
+ if (known > 0 || (g?.shadowUsd ?? 0) > 0)
68
+ stats.cost.usd = (stats.cost.usd ?? 0) + (g?.costUsd ?? 0) + (g?.shadowUsd ?? 0);
59
69
  stats.cost.known += known;
60
70
  stats.cost.unknown += counts.total - known;
61
71
  }
@@ -1,7 +1,8 @@
1
1
  import { type TimelineEvent } from "./timeline/index.js";
2
2
  import { type ItemStatus } from "./learning.js";
3
- import { type RunMoment, type SignInReader } from "./run-view.js";
4
- import { type Store } from "./store/store.js";
3
+ import { type RunMoment, type SignInReader, type Status } from "./run-view.js";
4
+ import { type RunReadState } from "./store-reads/runs.js";
5
+ import { type RunListing, type Store } from "./store/store.js";
5
6
  import type { RecordingView } from "./run-recordings.js";
6
7
  /** What the store-backed view needs beside the store: where its console lives, every secret it never shows (read now, so
7
8
  * one rotated is cut at once), and the agents' saved sign-ins (for the handed-pointer cut). The server passes the same it
@@ -25,6 +26,13 @@ export interface ViewDeps {
25
26
  * so a list, a poll or a status read opens no file. */
26
27
  readonly recordings?: (agentId: string, runId: string, endedAt: number | null) => Promise<RecordingView[]>;
27
28
  }
29
+ /** A settled run's v2 status from its row alone (STATUS_OF), the status its view reads (statusOf returns the outcome
30
+ * first); undefined for a run still going, whose status only its journal says. */
31
+ export declare const settledStatusOf: (state: RunReadState) => Status | undefined;
32
+ /** How long a run's listing waits before it is built again when its build could not read what it needed (ms): a listing
33
+ * that withheld the run for a sign-in it could not read back (listingOverStore), and the lister's build that failed
34
+ * (run-listing.ts). */
35
+ export declare const LISTING_RETRY_MS = 30000;
28
36
  /** A run's whole answer as answerOfRun read it from the rows: its newest final-answer row, never the learning turn's, and
29
37
  * never an earlier turn's: a final answer row before the person's last message belongs to the turn that message
30
38
  * followed, so a follow-up whose own stop said nothing (no text block: a thinking-only stop) has no answer, null, not
@@ -35,6 +43,30 @@ export declare const answerOf: (timeline: readonly TimelineEvent[]) => string |
35
43
  export declare function viewOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
36
44
  /** The run list's answer from the store, byte-identical to runs.ts's summary: the view's subset a list shows. */
37
45
  export declare function summaryOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
46
+ /** What a list shows of a run's view (summaryOverStore). */
47
+ export declare function summaryOfView(view: Record<string, unknown>): Record<string, unknown>;
48
+ /** A runs list's item for a run, as its listing keeps it on the run's row (store/schema.ts RUN_LISTING_COLUMNS), built from
49
+ * the run's view once per change and read by every list after: its list item (summaryOverStore's) with the parts a list
50
+ * fills in when it reads it (console_url: the origin the request reached; archived_at: the run's or its agent's archive
51
+ * now) kept empty; the digest of the server's secrets it was cut of (`cut`, so a list cuts it again of any saved since);
52
+ * its status; whether a runner held the run (its status reads otherwise once that claim runs out); when it goes stale by
53
+ * the clock alone (the ask it waits on expires, or LISTING_RETRY_MS after a build that withheld the run because the
54
+ * sign-in it was handed could not be read: that read may fail only for now, and the run reads whole once it recovers);
55
+ * and what outside the run it read (LISTING_HELD, LISTING_KEYED). Undefined for an unknown run. */
56
+ export declare function listingOverStore(store: Store, runId: string, deps: ViewDeps): Promise<RunListing | undefined>;
57
+ /** Whether `listing` was cut of the server's secrets as they are now. A list builds one cut of others again before it
58
+ * shows it (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads
59
+ * [redacted]), which cutting the built item again could not do. */
60
+ export declare function cutOfNow(listing: {
61
+ readonly cut: string;
62
+ }, serverSecrets: readonly string[]): boolean;
63
+ /** A listing's list item as a list serves it (listingOverStore): its console link at `origin`, its archive time now
64
+ * (`archivedAt`, ms, the run's or its agent's), and, when the server's secrets moved between its build and this (within
65
+ * one list), every string in it cut again of them (redactedOutput), so a secret saved since never shows. */
66
+ export declare function listedItem(listing: {
67
+ readonly item: Record<string, unknown>;
68
+ readonly cut: string;
69
+ }, origin: string, archivedAt: number | null, serverSecrets: readonly string[]): Record<string, unknown>;
38
70
  /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
39
71
  * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
40
72
  * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */
@@ -13,30 +13,42 @@ import { isObject } from "./validate.js";
13
13
  import { currentLearning, holdsForOk, learningView, LEARNING_LABEL, secretsShown, shortOf } from "./learning.js";
14
14
  import { said } from "./learning-words.js";
15
15
  import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
16
+ import { COMPUTER_UNAVAILABLE_CODE, lostEndMessage } from "./computer-lost.js";
16
17
  import { launchOf } from "./handed-values.js";
17
18
  import { learningStartOf, seedFailed } from "./run-launch.js";
18
- import { momentOf, pendingOf, stoppedTurn, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costWordsOfView, freeOf, usersOf, withAsks, withApprovalRows, } from "./run-view.js";
19
+ import { momentOf, pendingOf, stoppedTurn, approvalOf, asksOf, answersOf, activePauseOf, budgetOf, browserPending, computerPending, redactorOf, servedRunErrorWith, servedReviewWith, statusOf, WITHHELD_SIGN_IN, WITHHELD_TITLE, costWordsOfView, freeOf, stopAsked, usersOf, withAsks, withApprovalRows, } from "./run-view.js";
19
20
  import { reflects } from "./reflect-range.js";
20
21
  import { freeCeilingMessage, overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kernel/cap";
21
22
  import { bookedSpend, cliModelWorked, costWordsOf, planSpend, runCostOf } from "./runner/metrics.js";
22
23
  import { journalRecords, recordOf } from "./runner/journal-reader.js";
23
24
  import { capNowOf, KINDS } from "./runner/journal-kinds.js";
24
- import { laidOf, notesReadOf, runLearningEnd, shadowSpendOf, usedOnly, withNotes } from "./store-reads/learning.js";
25
+ import { laidOf, runLearningEnd, usedOnly } from "./store-reads/learning.js";
26
+ import { correctionCount } from "./learn/corrections.js";
25
27
  import { isCliRecord, runReflect, runTimeline, wholeAnswerFor, wholeAnswers, withoutFeedbackRounds } from "./store-reads/journal.js";
26
28
  import { readRun } from "./store-reads/runs.js";
27
29
  import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
28
30
  import { Turns } from "./turns.js";
29
31
  import { harnessOfBody } from "./harness.js";
32
+ import { LOGIN_HARNESS } from "./claude-login.js";
30
33
  import { browserAsk as browserAskOf, BROWSER_HANDOVER_KIND } from "./browser-commands.js";
31
34
  import { computerAsk as computerAskOf, COMPUTER_HANDOVER_KIND } from "./computer-commands.js";
32
35
  import { approvalsOf } from "./approvals.js";
33
36
  import { FINAL_STATES, stoppedByPerson } from "./store/store.js";
37
+ import { LISTING_HELD, LISTING_KEYED } from "./store/schema.js";
38
+ import { createHash } from "node:crypto";
34
39
  /** A run that has ended reads one of these (the old RunRow state → the v2 status: an escalation is a completion with a
35
40
  * review; a stopped run is a cancellation), as runs.ts's STATUS_OF mapped them. A running run reads its status from the
36
41
  * journal, and so does an agentic run a person stopped, which reads running (runReadState). */
37
42
  const STATUS_OF = { completed: "completed", failed: "failed", escalated: "completed", stopped: "cancelled" };
43
+ /** A settled run's v2 status from its row alone (STATUS_OF), the status its view reads (statusOf returns the outcome
44
+ * first); undefined for a run still going, whose status only its journal says. */
45
+ export const settledStatusOf = (state) => (state === "running" ? undefined : STATUS_OF[state]);
38
46
  /** A run that has reached a last state (its view is its ended shape). */
39
47
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
48
+ /** How long a run's listing waits before it is built again when its build could not read what it needed (ms): a listing
49
+ * that withheld the run for a sign-in it could not read back (listingOverStore), and the lister's build that failed
50
+ * (run-listing.ts). */
51
+ export const LISTING_RETRY_MS = 30_000;
40
52
  const iso = (ms) => new Date(ms).toISOString();
41
53
  /** What a view last made of a run's text, by store and slot (a run's answer, or its input): the text it read (`input`),
42
54
  * the digest of the values it was redacted of (`key`) and what that gave (`out`), so a second view of the same text and
@@ -81,13 +93,17 @@ export const answerOf = (timeline) => {
81
93
  /** A failed run's error from its row (its own words are the summary; the store keeps no code or detail apart). A run
82
94
  * its cap ended once its cost passed it (the kernel's overCapEnd) is code spend_cap_reached, its message the words after
83
95
  * the code, as main served it; a provider's content-filter stop is `moderated`, in words a person can act on
84
- * (content-filter.ts); every other failure is run_failed. */
96
+ * (content-filter.ts); a run whose sandbox was lost more times than its claim starts new ones (computer-lost.ts lostEnd)
97
+ * is computer_unavailable, its message the words after the code; every other failure is run_failed. */
85
98
  const errorOfRow = (summary) => {
86
99
  // A run that reached its limit of requests on free models (the kernel cap's freeCeilingEnd) ends as its cap ends one: code
87
100
  // spend_cap_reached, its message the words after the code.
88
101
  const over = overCapMessage(summary) ?? freeCeilingMessage(summary);
89
102
  if (over !== undefined)
90
103
  return { code: SPEND_CAP_REACHED, message: over, retryable: false };
104
+ const lost = lostEndMessage(summary);
105
+ if (lost !== undefined)
106
+ return { code: COMPUTER_UNAVAILABLE_CODE, message: lost, retryable: false };
91
107
  if (summary !== null && contentFiltered(summary))
92
108
  return { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false };
93
109
  return { code: "run_failed", message: summary ?? "The run failed.", retryable: false };
@@ -198,14 +214,11 @@ async function storeRunIn(store, runId, deps, cut) {
198
214
  const nativeSession = records.entries.findLast(e => e.kind === "agentrun.native.session")?.data;
199
215
  const native = launch?.native ? { runtime: launch.native.runtime, project: launch.native.project, selector: launch.native.selector, machine_id: launch.native.machine_id, fingerprint: nativeConfiguration?.fingerprint ?? launch.native.fingerprint, session_id: nativeSession?.session_id ?? null, model: nativeEvents.at(-1)?.model ?? launch.native.model, learning_revision: launch.learning?.seed ?? null, usage: { task: nativeTaskUsage, reflection: nativeEvents.filter(e => e.phase === "reflection").map(e => e.usage) }, model_requests: null } : undefined;
200
216
  const skip = reflectRange ? (id) => reflects(reflectRange, id) : undefined;
201
- // The run's learning end with the notes its start gave it and those its job read (its own reads, keyed on the given, read
202
- // from its rows uncut: a note whose name holds a secret is cut where it is shown, after it is matched). Before its end, a
203
- // run that learns is seeded, then looking back once its end-of-run turn starts (main's seeded and reflecting).
217
+ // The run's learning end. Before its end, a run that learns is seeded, then looking back once its end-of-run turn starts
218
+ // (main's seeded and reflecting).
204
219
  const started = launch ? learningStartOf(launch) : undefined;
205
- const read = started?.given.length ? notesReadOf(started.given, reflectRange, await runTimeline(store, runId, context, { settled: terminal })) : [];
206
220
  const under = !ended && started && started.use ? usedOnly(started, terminal, iso(runRow.endedAt ?? runRow.startedAt)) : !ended && started && !seedFailed(started) ? underWay(started, laidOf(records.entries), reflectRange, iso(runRow.startedAt)) : null;
207
- const sofar = ended ?? under;
208
- const shownEnd = sofar && withNotes(sofar, started, read);
221
+ const shownEnd = ended ?? under;
209
222
  const turns = new Turns();
210
223
  turns.note(recordOf(records.entries), records.submissions ?? [], skip, liveRow?.updatedAt ?? deps.now?.() ?? Date.now());
211
224
  const working = live && turns.open > 0;
@@ -215,21 +228,32 @@ async function storeRunIn(store, runId, deps, cut) {
215
228
  // the answers given, which the status, pending and moment views read the same as the file path read them from the run's
216
229
  // store entries.
217
230
  const approvals = asksOf(records.entries);
231
+ // The run's command rows, read once for what needs them: a stop or a cancel asked for, a hand-over's answers, and the
232
+ // person's messages not yet taken.
233
+ let commandRows;
234
+ const commandsNow = async () => (commandRows ??= await store.commands(runId, 0));
235
+ // A person's stop of an agentic run (stoppedByPerson: its row reads running, readRun) is main's stop mark: the run is
236
+ // stopped while no message is newer than the stop (statusOf: input_required and idle), and a message reopens it. A stop
237
+ // asked for and not yet taken (stopAsked) is the mark too once nothing works: between the turn's cut and the end that
238
+ // takes the stop, a read would otherwise see the cut turn's input_required with nothing pending; a run waiting (on an
239
+ // approval, a person, a browser) reads stopped from the stop's answer on. While its turn still works it reads working:
240
+ // the cut is what books the request it cuts (its cost unknown), so a run read stopped before the cut would say the known
241
+ // sum as its cost.
242
+ const asked = !terminal && !working && stopAsked(row, runRow, await commandsNow());
218
243
  // A call asked before an end in the journal reads withdrawn in that end's words; a stopped or failed run's (states no
219
- // reopen leaves) whose journal holds no end, by its row (answersOf `final`).
220
- const answers = answersOf(records.entries, { final: runRow.state === "stopped" || runRow.state === "failed" ? runRow.state : undefined });
244
+ // reopen leaves) whose journal holds no end, by its row (answersOf `final`); every call still waiting once a stop is
245
+ // asked (stopAsked).
246
+ const answers = answersOf(records.entries, { final: runRow.state === "stopped" || runRow.state === "failed" ? runRow.state : asked ? "stopped" : undefined });
221
247
  // The rows a person reads: each call that waited for approval in order (held, your approval, what came of it), its
222
248
  // arguments and the person's notes through the run's redactor, as the file path's withApprovals served them.
223
249
  const rows = withApprovalRows(timeline, approvals, answers, redactorOf(values));
224
250
  // The run's cap as it stands, through the one reader the runner's gate reads too (capNowOf): a raise taken shows in the
225
251
  // run's cost.cap_usd and its budget card, never the old cap.
226
252
  const capUsd = capNowOf(launch?.maxCostUsd, records.entries);
227
- // A person's stop of an agentic run (stoppedByPerson: its row reads running, readRun) is main's stop mark: the run is
228
- // stopped while no message is newer than the stop (statusOf: input_required and idle), and a message reopens it.
229
253
  const meta = {
230
254
  ...(capUsd !== undefined ? { max_cost_usd: capUsd } : {}),
231
255
  ...(Object.keys(answers).length ? { approvals: answers } : {}),
232
- ...(stoppedByPerson(runRow, row.kind) ? { stopped_after: usersOf(rows) } : {}),
256
+ ...(stoppedByPerson(runRow, row.kind) || asked ? { stopped_after: usersOf(rows) } : {}),
233
257
  };
234
258
  // The budget card the run shows while it stands parked at its cap, from its journal's agentrun.budget park (none once a
235
259
  // raise clears it). Read over the same meta cap and rows the card's figures and time come from.
@@ -240,10 +264,7 @@ async function storeRunIn(store, runId, deps, cut) {
240
264
  const paused = pausedOf(runRow, records.entries);
241
265
  // The browser hand-over the agent waits on (E2c's reader over the run's hand-over entries and hand-back commands), read
242
266
  // against the server's clock. Only a run with a hand-over entry fetches its commands, so a run with none reads none and
243
- // makes no extra store read.
244
- // The run's command rows, read once for what needs them: a hand-over's answers, and the person's messages not yet taken.
245
- let commandRows;
246
- const commandsNow = async () => (commandRows ??= await store.commands(runId, 0));
267
+ // makes no extra store read beyond the one a running run's stop and cancel already make.
247
268
  const browserAsk = records.entries.some((e) => e.kind === BROWSER_HANDOVER_KIND)
248
269
  ? browserAskOf(records.entries, await commandsNow(), deps.now?.() ?? Date.now())
249
270
  : undefined;
@@ -308,24 +329,16 @@ async function storeRunIn(store, runId, deps, cut) {
308
329
  return { ...(sdk ? { sdk } : {}), ...(native ? { native } : {}), row, runRow, launch, rows, version, harness, learningEnd: shownEnd, shownEnd, view, unshown, values, live, updatedAtMs, lastProgressAt, budget, paused, browserAsk, computerAsk, approvalsMode, output, ...(review ? { review } : {}), structured, decisions, plan, ...(endCost ? { endCost, endSaidCost } : {}) };
309
330
  }
310
331
  /** A run's learning as the view shows it: its end from the store (what it held for the owner's OK as it reads now), in a
311
- * person's words cut of the host's secrets now, and, for an ended run, the notes it read. */
312
- function learningViewOf(learningEnd, shown, settled) {
332
+ * person's words cut of the host's secrets now. */
333
+ function learningViewOf(learningEnd, shown) {
313
334
  if (!learningEnd)
314
335
  return null;
315
- return learningView(learningEnd, shown, settled);
336
+ return learningView(learningEnd, shown);
316
337
  }
317
- /** A run's learning before its end: its seed's notes and the learned skills/workflows its claims actually laid,
318
- * until its end-of-run turn starts; then looking back. Merely offered skills are not counted as supplied. */
338
+ /** A run's learning before its end: the corrections its # Learned section holds and the learned workflows its claims
339
+ * laid, until its end-of-run turn starts; then looking back. */
319
340
  function underWay(started, laid, reflect, at) {
320
- return reflect ? { state: "reflecting", reason: null, detail: said.reflecting, at } : { state: "seeded", reason: null, detail: said.seeded(started.seedNotes ?? 0, laid.skills.length, laid.workflows.length), at };
321
- }
322
- /** A view's cost with its audit shadow run's (store-reads/learning.ts shadowSpendOf: unknown while it is queued or
323
- * running, 0 when none was started) added to `usd` (unknown once either is). */
324
- function withShadowCost(cost, shadow) {
325
- if (shadow === 0)
326
- return cost;
327
- const usd = typeof cost.usd === "number" && shadow !== null ? Math.round((cost.usd + shadow) * 1e6) / 1e6 : null;
328
- return { ...cost, usd };
341
+ return reflect ? { state: "reflecting", reason: null, detail: said.reflecting, at } : { state: "seeded", reason: null, detail: said.seeded(correctionCount(started.section), laid.workflows.length), at };
329
342
  }
330
343
  /** The cost a run's view shows (runs.ts cost): its rows' cost, else what the store kept, and its cap. */
331
344
  function costOfView(run) {
@@ -358,21 +371,26 @@ function costOfView(run) {
358
371
  const usd = words.usd;
359
372
  const counted = words.so_far_usd !== undefined && words.unpriced !== undefined ? { so_far_usd: words.so_far_usd, unpriced: words.unpriced } : undefined;
360
373
  const upper = words.upper_bound ? { upper_bound: true } : undefined;
361
- // A request billed to a ChatGPT plan costs no dollars, however it ended (the kernel's turnCostOf): every reader counts it
362
- // $0, so it is in no unpriced count; what it used on the plan is said beside the figure.
374
+ // A request billed to a person's plan costs no dollars, however it ended (the kernel's turnCostOf): every reader counts it
375
+ // $0, so it is in no unpriced count; what it used on the plan is said beside the figure, and which plan: a run on the
376
+ // login's harness was on Claude Code's login (claude-login.ts), any other on the ChatGPT sign-in.
363
377
  const plan = run.plan;
378
+ const on = run.harness === LOGIN_HARNESS ? "claude_code" : "chatgpt";
364
379
  // Beside its figure: while it is unknown, what is known so far; at $0 with every model request on a free model (and no
365
380
  // decision of its own), that it is free.
366
381
  const soFar = counted ?? (imported || decisions?.requests ? undefined : freeOf(run.rows, usd));
367
382
  // The run's cap as it stands (its view's meta: the newest raise's, else the launch's).
368
383
  const cap = run.view.meta.max_cost_usd;
369
- return { usd, basis: "estimate", charge_state: null, cap_usd: cap ?? null, ...(soFar ?? {}), ...(upper ?? {}), ...(plan ? { plan: { requests: plan.requests, tokens: plan.tokens } } : {}) };
384
+ return { usd, basis: "estimate", charge_state: null, cap_usd: cap ?? null, ...(soFar ?? {}), ...(upper ?? {}), ...(plan ? { plan: { requests: plan.requests, tokens: plan.tokens, on } } : {}) };
370
385
  }
371
386
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
372
387
  export async function viewOverStore(store, runId, deps) {
373
388
  const run = await storeRunOf(store, runId, deps);
374
- if (!run)
375
- return undefined;
389
+ return run && viewOfRun(store, runId, deps, run);
390
+ }
391
+ /** GET /runs/{id}'s answer for a run already read (storeRunOf). `read.withheld` is set to whether the answer withholds the
392
+ * run because this server could not read back the sign-in it was handed (its cut, or its error's words). */
393
+ async function viewOfRun(store, runId, deps, run, read) {
376
394
  const { row, runRow, launch, view, unshown, values, output, review: kept, structured } = run;
377
395
  const { status, state } = statusOf(view, factsOf(run));
378
396
  const terminal = TERMINAL.has(status);
@@ -417,6 +435,8 @@ export async function viewOverStore(store, runId, deps) {
417
435
  const failedReason = run.rows.findLast((r) => r.kind === "error")?.text ?? row.summary ?? null;
418
436
  const errorWords = status === "failed" && !unshown ? await runErrorWordsOf({ ...deps, keyEnv: deps.keyEnv ?? (() => process.env) }, store, runId, { workflow: row.kind === "workflow" }) : undefined;
419
437
  const withheld = unshown || errorWords === "unreadable";
438
+ if (read)
439
+ read.withheld = withheld;
420
440
  const error = status === "failed" ? (withheld ? { code: "run_failed", message: WITHHELD_SIGN_IN, retryable: false } : servedRunErrorWith(errorWords ?? shownWords, errorOfRow(failedReason))) : null;
421
441
  const review = endedAtMs === null ? null : servedReviewWith(shownWords, unshown, reviewAt(reviewOfRow(row.state, row.summary ?? null, kept), iso(endedAtMs)));
422
442
  // The card the run shows while it waits, in the order the file-backed view (runs.ts) picks them: a tool call parked for a
@@ -460,7 +480,8 @@ export async function viewOverStore(store, runId, deps) {
460
480
  error,
461
481
  review,
462
482
  pending,
463
- cost: withShadowCost(costOfView(run), (await shadowSpendOf(store, runId)).usd),
483
+ // Its own spend: an audit's shadow run of it is learning (GET /runs/{id}'s cost.learning_usd), never its cost.usd.
484
+ cost: costOfView(run),
464
485
  // The run an audit's shadow run audits (launch.audit, runner/audit.ts); null for any other run.
465
486
  audit_of: launch?.audit?.of ?? null,
466
487
  // Whether it ran unattended (its revision's approvals, as it started): never, an ask allowed at its gate; ask, the default.
@@ -472,7 +493,7 @@ export async function viewOverStore(store, runId, deps) {
472
493
  // The caller's labels, as given at the start ({} when none): its own strings, never cut.
473
494
  labels: runRow.labels,
474
495
  // Cut by the run's one cut (the pointers it was handed among them), and none for a withheld run, as its words.
475
- learning: unshown ? null : learningViewOf(run.learningEnd, secretsShown(values), settled),
496
+ learning: unshown ? null : learningViewOf(run.learningEnd, secretsShown(values)),
476
497
  // Its screen recordings (computer.record), from the files on this machine, where its read asks for them; none for a
477
498
  // withheld run, whose files are refused. A run that left running with no end stamped (parked) ends now, each read: only
478
499
  // a file's trailer finishes it there.
@@ -484,8 +505,10 @@ export async function viewOverStore(store, runId, deps) {
484
505
  /** The run list's answer from the store, byte-identical to runs.ts's summary: the view's subset a list shows. */
485
506
  export async function summaryOverStore(store, runId, deps) {
486
507
  const view = await viewOverStore(store, runId, deps);
487
- if (!view)
488
- return undefined;
508
+ return view && summaryOfView(view);
509
+ }
510
+ /** What a list shows of a run's view (summaryOverStore). */
511
+ export function summaryOfView(view) {
489
512
  const { run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title, effort, created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, labels, learning } = view;
490
513
  return {
491
514
  run_id, agent_id, agent_version, console_url, revision, kind, sha, status, state, title,
@@ -496,6 +519,50 @@ export async function summaryOverStore(store, runId, deps) {
496
519
  learning: learning ? shortOf(learning) : null,
497
520
  };
498
521
  }
522
+ /** A runs list's item for a run, as its listing keeps it on the run's row (store/schema.ts RUN_LISTING_COLUMNS), built from
523
+ * the run's view once per change and read by every list after: its list item (summaryOverStore's) with the parts a list
524
+ * fills in when it reads it (console_url: the origin the request reached; archived_at: the run's or its agent's archive
525
+ * now) kept empty; the digest of the server's secrets it was cut of (`cut`, so a list cuts it again of any saved since);
526
+ * its status; whether a runner held the run (its status reads otherwise once that claim runs out); when it goes stale by
527
+ * the clock alone (the ask it waits on expires, or LISTING_RETRY_MS after a build that withheld the run because the
528
+ * sign-in it was handed could not be read: that read may fail only for now, and the run reads whole once it recovers);
529
+ * and what outside the run it read (LISTING_HELD, LISTING_KEYED). Undefined for an unknown run. */
530
+ export async function listingOverStore(store, runId, deps) {
531
+ const cut = secretsDigest(deps.serverSecrets());
532
+ const run = await storeRunOf(store, runId, deps);
533
+ if (!run)
534
+ return undefined;
535
+ const read = { withheld: false };
536
+ const summary = summaryOfView(await viewOfRun(store, runId, deps, run, read));
537
+ const status = String(summary.status);
538
+ const terminal = TERMINAL.has(status);
539
+ const asks = terminal ? [] : [run.browserAsk?.expires_at, run.computerAsk?.expires_at].map((at) => (typeof at === "string" ? Date.parse(at) : Number.NaN)).filter((at) => Number.isFinite(at));
540
+ const expiries = read.withheld ? [...asks, (deps.now ?? Date.now)() + LISTING_RETRY_MS] : asks;
541
+ const flags = (run.shownEnd && holdsForOk(run.shownEnd) ? LISTING_HELD : 0) | (status === "failed" && run.row.kind !== "workflow" ? LISTING_KEYED : 0);
542
+ return {
543
+ item: { ...summary, console_url: null, archived_at: null },
544
+ cut,
545
+ status,
546
+ live: run.live,
547
+ until: expiries.length ? Math.min(...expiries) : null,
548
+ flags,
549
+ };
550
+ }
551
+ /** Whether `listing` was cut of the server's secrets as they are now. A list builds one cut of others again before it
552
+ * shows it (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads
553
+ * [redacted]), which cutting the built item again could not do. */
554
+ export function cutOfNow(listing, serverSecrets) {
555
+ return listing.cut === secretsDigest(serverSecrets);
556
+ }
557
+ /** A listing's list item as a list serves it (listingOverStore): its console link at `origin`, its archive time now
558
+ * (`archivedAt`, ms, the run's or its agent's), and, when the server's secrets moved between its build and this (within
559
+ * one list), every string in it cut again of them (redactedOutput), so a secret saved since never shows. */
560
+ export function listedItem(listing, origin, archivedAt, serverSecrets) {
561
+ const item = { ...listing.item, console_url: runLink(origin, String(listing.item.run_id)), archived_at: archivedAt === null ? null : iso(archivedAt) };
562
+ return listing.cut === secretsDigest(serverSecrets) ? item : redactedOutput(item, [...serverSecrets]);
563
+ }
564
+ /** A set of secrets' digest, the same for the same set in any order: what a listing was cut of. */
565
+ const secretsDigest = (values) => createHash("sha256").update([...new Set(values)].sort().join("\0")).digest("hex");
499
566
  /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
500
567
  * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
501
568
  * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */
@@ -0,0 +1,59 @@
1
+ /** Where events go: PostHog's capture route, behind this project's own name. */
2
+ export declare const TELEMETRY_URL = "https://telemetry.agentrun.ai/i/v0/e/";
3
+ /** The project's write-only key, public by design. Empty: this build sends nothing and prints no notice. */
4
+ export declare const TELEMETRY_KEY = "";
5
+ /** The file in the data directory that keeps the id, when the notice was printed and how many runs ended. */
6
+ export declare const TELEMETRY_FILE = ".telemetry.json";
7
+ /** How often a running server says it still runs. */
8
+ export declare const HEARTBEAT_MS: number;
9
+ export declare const TELEMETRY_NOTICE = "AgentRun sends anonymous usage counts (a random id, the version, the platform, how many runs as a range): never prompts, files, keys or names. Nothing was sent at this start. Turn it off with AGENTRUN_TELEMETRY=0 or DO_NOT_TRACK=1. Every field: https://github.com/Parcha-ai/agentrun/blob/main/docs/telemetry.md";
10
+ export type TelemetryEventName = "server_started" | "heartbeat" | "first_run_completed";
11
+ /** One event, as sent. `runs` is a range, never a count. */
12
+ export interface TelemetryEvent {
13
+ event: TelemetryEventName;
14
+ distinct_id: string;
15
+ timestamp: string;
16
+ properties: {
17
+ version: string;
18
+ os: string;
19
+ arch: string;
20
+ node: number;
21
+ runs: RunsRange;
22
+ $process_person_profile: false;
23
+ $geoip_disable: true;
24
+ };
25
+ }
26
+ export type RunsRange = "0" | "1-10" | "11-100" | "101+";
27
+ /** Why nothing is sent, or "on" / "debug" (events printed to stderr, none sent). */
28
+ export type TelemetryMode = "on" | "debug" | "off_setting" | "off_do_not_track" | "off_ci" | "off_faux" | "off_no_key";
29
+ /** What this start does, from its environment: the operator's own setting first, then DO_NOT_TRACK, CI and --faux. */
30
+ export declare function telemetryMode(env: NodeJS.ProcessEnv, o?: {
31
+ faux?: boolean;
32
+ key?: string;
33
+ }): TelemetryMode;
34
+ export declare const runsRange: (runs: number) => RunsRange;
35
+ export interface Telemetry {
36
+ mode: TelemetryMode;
37
+ /** The line to print once, at the start that first could send; undefined at every other. */
38
+ notice?: string;
39
+ /** A run reached its end here. `status` is the runner's (`ended` is a completed run). */
40
+ runEnded(status: string): void;
41
+ /** Stops the heartbeat and waits for the count's last write. Sends nothing. */
42
+ close(): Promise<void>;
43
+ }
44
+ export interface TelemetryOptions {
45
+ data: string;
46
+ /** The server's version (default: this package's). */
47
+ version?: string;
48
+ env?: NodeJS.ProcessEnv;
49
+ faux?: boolean;
50
+ /** For tests: the key, the route, the sender, the clock, the heartbeat's period and where debug lines go. */
51
+ key?: string;
52
+ url?: string;
53
+ fetch?: typeof fetch;
54
+ now?: () => Date;
55
+ heartbeatMs?: number;
56
+ say?: (line: string) => void;
57
+ }
58
+ /** Starts the counts for a server on `data`. Never throws: a data directory it cannot write turns it off. */
59
+ export declare function startTelemetry(o: TelemetryOptions): Telemetry;
@@ -0,0 +1,153 @@
1
+ // Anonymous usage counts (docs/telemetry.md): that a server started, that it is still running a day later, and that its
2
+ // first run completed. Each event holds a random id made for this data directory, the server's version, the platform,
3
+ // and how many runs ended here as a range. It never holds a prompt, a workflow, a key, a name, a path or an address.
4
+ //
5
+ // Off with AGENTRUN_TELEMETRY=0 or DO_NOT_TRACK=1, in CI, and under --faux. The start that first could send prints one
6
+ // notice and sends nothing at its start, so a person reads how to turn it off before anything leaves the machine.
7
+ // AGENTRUN_TELEMETRY=debug prints every event and sends none; it never stands in for that notice.
8
+ // Sending never delays a start, a run or a stop, and a send that fails is dropped without a word. A run's end is counted
9
+ // in memory and written behind it, one write at a time, so no request or run waits on the disk.
10
+ import { randomUUID } from "node:crypto";
11
+ import { readFileSync } from "node:fs";
12
+ import { rename, unlink, writeFile } from "node:fs/promises";
13
+ import { join } from "node:path";
14
+ import { tempOf, writeDurableSync } from "./server-fs.js";
15
+ /** Where events go: PostHog's capture route, behind this project's own name. */
16
+ export const TELEMETRY_URL = "https://telemetry.agentrun.ai/i/v0/e/";
17
+ /** The project's write-only key, public by design. Empty: this build sends nothing and prints no notice. */
18
+ export const TELEMETRY_KEY = "";
19
+ /** The file in the data directory that keeps the id, when the notice was printed and how many runs ended. */
20
+ export const TELEMETRY_FILE = ".telemetry.json";
21
+ /** How often a running server says it still runs. */
22
+ export const HEARTBEAT_MS = 24 * 60 * 60 * 1000;
23
+ /** How long one send may take before it is dropped. */
24
+ const SEND_TIMEOUT_MS = 3_000;
25
+ const ownVersion = () => JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
26
+ export const TELEMETRY_NOTICE = "AgentRun sends anonymous usage counts (a random id, the version, the platform, how many runs as a range): never prompts, files, keys or names. Nothing was sent at this start. Turn it off with AGENTRUN_TELEMETRY=0 or DO_NOT_TRACK=1. Every field: https://github.com/Parcha-ai/agentrun/blob/main/docs/telemetry.md";
27
+ const OFF = new Set(["0", "false", "off", "no"]);
28
+ /** What this start does, from its environment: the operator's own setting first, then DO_NOT_TRACK, CI and --faux. */
29
+ export function telemetryMode(env, o = {}) {
30
+ const setting = (env.AGENTRUN_TELEMETRY ?? "").trim().toLowerCase();
31
+ if (OFF.has(setting))
32
+ return "off_setting";
33
+ const dnt = (env.DO_NOT_TRACK ?? "").trim().toLowerCase();
34
+ if (dnt !== "" && !OFF.has(dnt))
35
+ return "off_do_not_track";
36
+ if (env.CI)
37
+ return "off_ci";
38
+ if (o.faux)
39
+ return "off_faux";
40
+ if (setting === "debug")
41
+ return "debug";
42
+ return (o.key ?? TELEMETRY_KEY) === "" ? "off_no_key" : "on";
43
+ }
44
+ export const runsRange = (runs) => (runs <= 0 ? "0" : runs <= 10 ? "1-10" : runs <= 100 ? "11-100" : "101+");
45
+ /** The kept state, or a new one when the file is missing or not what this wrote. */
46
+ function readState(file) {
47
+ try {
48
+ const kept = JSON.parse(readFileSync(file, "utf8"));
49
+ if (kept && typeof kept.id === "string" && /^[0-9a-f-]{36}$/.test(kept.id)) {
50
+ return {
51
+ id: kept.id,
52
+ runs: typeof kept.runs === "number" && Number.isInteger(kept.runs) && kept.runs >= 0 ? kept.runs : 0,
53
+ ...(typeof kept.noticed_at === "string" ? { noticed_at: kept.noticed_at } : {}),
54
+ ...(kept.first_run_sent === true ? { first_run_sent: true } : {}),
55
+ };
56
+ }
57
+ }
58
+ catch {
59
+ // Missing or unreadable: a new id, and the notice again.
60
+ }
61
+ return { id: randomUUID(), runs: 0 };
62
+ }
63
+ /** Starts the counts for a server on `data`. Never throws: a data directory it cannot write turns it off. */
64
+ export function startTelemetry(o) {
65
+ const env = o.env ?? process.env;
66
+ const key = o.key ?? TELEMETRY_KEY;
67
+ const mode = telemetryMode(env, { ...(o.faux ? { faux: true } : {}), key });
68
+ const idle = { mode, runEnded: () => { }, close: () => Promise.resolve() };
69
+ if (mode !== "on" && mode !== "debug")
70
+ return idle;
71
+ const file = join(o.data, TELEMETRY_FILE);
72
+ const now = o.now ?? (() => new Date());
73
+ const say = o.say ?? ((line) => void process.stderr.write(`${line}\n`));
74
+ const send = o.fetch ?? fetch;
75
+ const state = readState(file);
76
+ const version = o.version ?? ownVersion();
77
+ const text = () => `${JSON.stringify(state)}\n`;
78
+ // The start's one write, durable before anything is sent: the id, and the notice's time when this start prints it.
79
+ const keepNow = () => {
80
+ try {
81
+ writeDurableSync(file, text());
82
+ return true;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ };
88
+ // Every later write (a run's end) goes behind the caller: one at a time, the latest state each time, so ends that come
89
+ // together make one write and none waits on the disk. A write that fails is dropped; the next end writes again.
90
+ // Each goes through a temporary file of its own: a server that takes this data directory while this one still stops
91
+ // never shares one with it. The two can still each write the file whole, last one kept, so a restart that overlaps a
92
+ // run's end may count a few runs short: the count is sent as a range, and nothing else is kept here.
93
+ const whole = async () => {
94
+ const temp = tempOf(file);
95
+ try {
96
+ await writeFile(temp, text(), { mode: 0o600 });
97
+ await rename(temp, file);
98
+ }
99
+ catch {
100
+ await unlink(temp).catch(() => { });
101
+ }
102
+ };
103
+ let stale = false;
104
+ let writing;
105
+ const keepLater = () => {
106
+ stale = true;
107
+ writing ??= (async () => {
108
+ while (stale) {
109
+ stale = false;
110
+ await whole();
111
+ }
112
+ writing = undefined;
113
+ })();
114
+ };
115
+ // The start that first could send: the notice, kept before anything is sent. If it cannot be kept, the next start would
116
+ // print it again and still send nothing, so this one stays quiet too. Debug sends nothing and prints no notice, so it
117
+ // never marks the notice as read: a start that can send after it still prints the notice and holds its first event.
118
+ const first = mode === "on" && state.noticed_at === undefined;
119
+ if (first)
120
+ state.noticed_at = now().toISOString();
121
+ if (!keepNow())
122
+ return { ...idle, mode: "off_setting" };
123
+ const emit = (event) => {
124
+ const body = {
125
+ event,
126
+ distinct_id: state.id,
127
+ timestamp: now().toISOString(),
128
+ properties: { version, os: process.platform, arch: process.arch, node: Number(process.versions.node.split(".")[0]), runs: runsRange(state.runs), $process_person_profile: false, $geoip_disable: true },
129
+ };
130
+ if (mode === "debug")
131
+ return say(`agentrun-serve telemetry (debug, not sent): ${JSON.stringify(body)}`);
132
+ void send(o.url ?? TELEMETRY_URL, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ api_key: key, ...body }), signal: AbortSignal.timeout(SEND_TIMEOUT_MS) }).then(() => { }, () => { });
133
+ };
134
+ if (!first)
135
+ emit("server_started");
136
+ // A server that stays up is counted by its heartbeat, the first start's too: a day after the notice.
137
+ const beat = setInterval(() => emit("heartbeat"), o.heartbeatMs ?? HEARTBEAT_MS);
138
+ beat.unref();
139
+ return {
140
+ mode,
141
+ ...(first ? { notice: TELEMETRY_NOTICE } : {}),
142
+ runEnded(status) {
143
+ state.runs += 1;
144
+ const completed = status === "ended" && !state.first_run_sent;
145
+ if (completed)
146
+ state.first_run_sent = true;
147
+ keepLater();
148
+ if (completed)
149
+ emit("first_run_completed");
150
+ },
151
+ close: () => (clearInterval(beat), writing ?? Promise.resolve()),
152
+ };
153
+ }