@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -1,8 +1,13 @@
1
1
  import { type TimelineEvent } from "./timeline/index.js";
2
- import { type ItemStatus } from "./learning.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";
2
+ import { type ItemStatus, type Learning } from "./learning.js";
3
+ import { type RunLaunch } from "./run-launch.js";
4
+ import { type Pending, type RunMoment, type RunView, type SignInReader, type Status, type ComputerAsk } from "./run-view.js";
5
+ import { type BookedSpend, type RunCost } from "./runner/metrics.js";
6
+ import { type EndData } from "./runner/journal-kinds.js";
7
+ import { type RunReadState, readRun } from "./store-reads/runs.js";
8
+ import type { PendingAsk } from "./browser-person.js";
9
+ import { type Approvals } from "./approvals.js";
10
+ import { type KeptListing, type RunListing, type RunRow, type Store } from "./store/store.js";
6
11
  import type { RecordingView } from "./run-recordings.js";
7
12
  /** What the store-backed view needs beside the store: where its console lives, every secret it never shows (read now, so
8
13
  * one rotated is cut at once), and the agents' saved sign-ins (for the handed-pointer cut). The server passes the same it
@@ -39,6 +44,117 @@ export declare const LISTING_RETRY_MS = 30000;
39
44
  * the answer before it. Read on the job's turns (withoutFeedbackRounds): a grade's feedback round asks no turn of the
40
45
  * job's, so its words never cut the answer off. */
41
46
  export declare const answerOf: (timeline: readonly TimelineEvent[]) => string | null;
47
+ /** The run read from the store: the row, its launch, its timeline, its agent's revision count for the version, its
48
+ * learning end, and the sign-in cut it serves through. Undefined for an unknown run. */
49
+ interface StoreRun {
50
+ readonly native?: Record<string, unknown>;
51
+ readonly sdk?: Record<string, unknown>;
52
+ readonly row: NonNullable<Awaited<ReturnType<typeof readRun>>>;
53
+ readonly runRow: RunRow;
54
+ readonly launch: RunLaunch | undefined;
55
+ readonly rows: TimelineEvent[];
56
+ readonly version: number;
57
+ readonly harness: string;
58
+ readonly learningEnd: Learning | null;
59
+ readonly view: RunView;
60
+ /** The run's error text is withheld while this server can't read the sign-in it was handed. */
61
+ readonly unshown: boolean;
62
+ /** The values every served text is cut of (serverSecrets + the handed pointers that open). */
63
+ readonly values: string[];
64
+ /** A runner holds the run's claim now (not final, a runner named, its lease unexpired). */
65
+ readonly live: boolean;
66
+ /** The run's updated_at (ms): its latest change in the store — the runner's live tick while it runs, its end once ended,
67
+ * its start before either. */
68
+ readonly updatedAtMs: number;
69
+ /** When the turn of a message still open last wrote (the live tick), as ISO; null when none is open. */
70
+ readonly lastProgressAt: string | null;
71
+ /** The budget card the run shows while it stands parked at its cap (pending, kind budget), or undefined when it is not
72
+ * parked there. Also the source of the `budgetWaiting` fact. */
73
+ readonly budget: Pending | undefined;
74
+ /** Whether a workflow run stands paused in its process now (pausedOf): the source of the `paused` fact. */
75
+ readonly paused: boolean;
76
+ /** The browser hand-over the run's agent waits on (the newest ask still waiting), or undefined. Also the `browserAsk`
77
+ * fact. */
78
+ readonly browserAsk: PendingAsk | undefined;
79
+ /** The agent's ask on its desktop or phone the run waits on (computer-commands.ts), or undefined. Also the `computerAsk`
80
+ * fact. */
81
+ readonly computerAsk: ComputerAsk | undefined;
82
+ /** Whether the run ran unattended, as its revision kept it (approvals "never"), else the default (ask): the run read's
83
+ * `approvals` field, as runs.ts serves it. Named to stand apart from the approval-request map on the view. */
84
+ readonly approvalsMode: Approvals;
85
+ /** A completed workflow run's output, as its end kept it (EndData.output); null when it kept none. */
86
+ readonly output: unknown;
87
+ /** An escalated workflow run's review, as its end kept it (EndData.review); undefined when it kept none. */
88
+ readonly review?: EndData["review"];
89
+ /** An ended agentic run's structured answer against its revision's output schema (definition.output_schema), read off
90
+ * its final answer as the journal keeps it, whole and uncut (answer-json.ts structuredAnswer), or why it has none (a
91
+ * run with no final answer among them: result.output_error): undefined when the agent has no schema or the run has not
92
+ * ended. Cut of held values only when served (redactedOutput). */
93
+ readonly structured: {
94
+ value: unknown;
95
+ } | {
96
+ why: string;
97
+ } | undefined;
98
+ /** What the run's decisions booked (their own session, metrics.ts bookedSpend), undefined when it booked none: the run's cost
99
+ * adds it to its usage row's, as the timeline adds their receipts. */
100
+ readonly decisions: BookedSpend | undefined;
101
+ /** Its model requests billed to a ChatGPT plan (metrics.ts planSpend), undefined when it made none. */
102
+ readonly plan: {
103
+ readonly requests: number;
104
+ readonly tokens: number;
105
+ } | undefined;
106
+ /** What its model requests booked (metrics.ts bookedSpend "model": every session but its paid tools' and its
107
+ * decisions'): their tokens and how they were priced, for its cost's `tokens` and `basis`. */
108
+ readonly model: BookedSpend;
109
+ /** An ended run's cost from its booking (metrics.ts runCostOf, the rule its end stored it by), read in the same snapshot
110
+ * as its state; undefined for a run still going, imported, native, or that booked no request. */
111
+ readonly endCost?: RunCost;
112
+ /** Whether the run's last end wrote its cost (EndData.costUsd present: a figure or null), so the stored column holds the
113
+ * end's answer. False for an end whose spec reads no cost, which leaves the column as it was. */
114
+ readonly endSaidCost?: boolean;
115
+ /** Whether its end stored its cost unknown while this read, which reads its cost from its booking (an ended agentic run
116
+ * not native, or workflow, not imported), found no booked request: the end could not read the booking, nor can this. */
117
+ readonly endUnread?: boolean;
118
+ /** The cost its store's unknown one heals to (Runs.healCost), at the end it was read at: set while its stored cost is
119
+ * null with no bound and its booking gives a figure, written by the end's own rule (endCostOf: a bound when a cut
120
+ * request's hold is counted in it). */
121
+ readonly heal?: {
122
+ readonly epoch: number;
123
+ readonly endedAt: number;
124
+ readonly costUsd: number;
125
+ readonly costUpperBound: boolean;
126
+ };
127
+ }
128
+ /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
129
+ * view's `approvals`, asksOf), or a browser or desktop hand-over neither answered in its journal nor by a hand-back row.
130
+ * By the journal alone, never by the clock: a hand-over past its expiry still holds the turn until its expiry is written
131
+ * as its answer, and only then does the turn go on. Such a turn has no model request in flight. */
132
+ export declare function standsOnPerson(approvals: ReadonlyMap<string, {
133
+ readonly resolved?: true;
134
+ }>, entries: readonly {
135
+ kind: string;
136
+ data?: unknown;
137
+ }[], commands: Awaited<ReturnType<Store["commands"]>>): boolean;
138
+ /** Heals run `runId`'s stored unknown cost to the figure its booking gives (Runs.healCost), at the end it was read at.
139
+ * True when written; false when another write got there first, or when the write failed (said, never thrown: a read
140
+ * never fails on its heal, and the next read or start sweep writes it again). */
141
+ export declare function healStoredCost(store: Store, runId: string, heal: NonNullable<StoreRun["heal"]>): Promise<boolean>;
142
+ /** What run `runId`'s paid tool calls cost, the run read's `cost.tools_usd` (server.ts allInViewOf): the charges its
143
+ * paid-tools session booked (a monid endpoint's, a priced MCP tool's, Parallel's behind the web tools, the browser's
144
+ * time), joined and rounded by the one rule its `usd` is (costWordsOf), less those in its end-of-run turn, which are
145
+ * learning's as that turn's model requests are (runCostOf). A part of `usd`, never added to it; 0 with none. Null when
146
+ * one's charge is unknown (charged an unknown amount, cut, or still out) or counted at its hold; while the run is at work
147
+ * (not ended, stopped or failed), as its `usd` is the view's snapshot and a paid call booked after it would be read here
148
+ * and not there (an ended run's record no longer moves); for a run a follow-up
149
+ * opened again (a round past its first), whose job is what it had cost when its first round answered and whose paid
150
+ * calls the booking can't split by that; and for an imported, native or SDK run, whose `usd` is its import's or its
151
+ * harness's own figure, with no booking of its paid tool calls (a native or SDK run never opens the paid-tools session),
152
+ * and for an unknown run. */
153
+ export declare function toolsUsdOverStore(store: Store, runId: string): Promise<number | null>;
154
+ /** The start sweep's heal of run `runId` (cost-heal.ts): the same rule as its run read's (bookedCostOf, healOf), from its
155
+ * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning folder. True when
156
+ * it wrote the booking's figure; a failed read or write throws, for the sweep to count. */
157
+ export declare function healedOverStore(store: Store, runId: string): Promise<boolean>;
42
158
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
43
159
  export declare function viewOverStore(store: Store, runId: string, deps: ViewDeps): Promise<Record<string, unknown> | undefined>;
44
160
  /** The run list's answer from the store, byte-identical to runs.ts's summary: the view's subset a list shows. */
@@ -54,19 +170,14 @@ export declare function summaryOfView(view: Record<string, unknown>): Record<str
54
170
  * 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
171
  * and what outside the run it read (LISTING_HELD, LISTING_KEYED). Undefined for an unknown run. */
56
172
  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;
173
+ /** Whether `listing` is cut of the server's secrets as they are now. A list builds any other again before it shows it
174
+ * (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads [redacted]), which
175
+ * cutting the built item again could not do. */
176
+ export declare function builtOfNow(listing: KeptListing, serverSecrets: readonly string[]): boolean;
63
177
  /** A listing's list item as a list serves it (listingOverStore): its console link at `origin`, its archive time now
64
178
  * (`archivedAt`, ms, the run's or its agent's), and, when the server's secrets moved between its build and this (within
65
179
  * 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>;
180
+ export declare function listedItem(listing: KeptListing, origin: string, archivedAt: number | null, serverSecrets: readonly string[]): Record<string, unknown>;
70
181
  /** A run's facts as its view states them, and none of its words: its kind, revision, agent, status and times, and whether
71
182
  * its output is withheld (`unshown`). What a read that serves its own parts (the graph) needs of the run: read off the
72
183
  * run as viewOverStore reads it, with nothing of it served, so nothing is redacted here. Undefined for an unknown run. */
@@ -14,18 +14,20 @@ import { currentLearning, holdsForOk, learningView, LEARNING_LABEL, secretsShown
14
14
  import { said } from "./learning-words.js";
15
15
  import { CONTENT_FILTER_WORDS, contentFiltered, MODERATED } from "./content-filter.js";
16
16
  import { COMPUTER_UNAVAILABLE_CODE, lostEndMessage } from "./computer-lost.js";
17
+ import { refusedEndMessage, RUNNER_REFUSED_CODE } from "./runner/presence.js";
17
18
  import { launchOf } from "./handed-values.js";
18
19
  import { learningStartOf, seedFailed } from "./run-launch.js";
19
20
  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";
20
21
  import { reflects } from "./reflect-range.js";
21
22
  import { freeCeilingMessage, overCapMessage, SPEND_CAP_REACHED } from "@parcha/agentrun-kernel/kernel/cap";
22
- import { bookedSpend, cliModelWorked, costWordsOf, planSpend, runCostOf } from "./runner/metrics.js";
23
+ import { bookedSpend, cliModelWorked, costBasisOf, costWordsOf, endCostOf, planSpend, runCostOf, storedBasisOf } from "./runner/metrics.js";
23
24
  import { journalRecords, recordOf } from "./runner/journal-reader.js";
24
25
  import { capNowOf, KINDS } from "./runner/journal-kinds.js";
25
- import { laidOf, runLearningEnd, usedOnly } from "./store-reads/learning.js";
26
+ import { laidOf, pathViewOf, roundsOf, runLearningEnd, usedOnly } from "./store-reads/learning.js";
27
+ import { inReflect, reflectRanges } from "./runner/end-of-run.js";
26
28
  import { correctionCount } from "./learn/corrections.js";
27
29
  import { isCliRecord, runReflect, runTimeline, wholeAnswerFor, wholeAnswers, withoutFeedbackRounds } from "./store-reads/journal.js";
28
- import { readRun } from "./store-reads/runs.js";
30
+ import { costOfRun, readRun } from "./store-reads/runs.js";
29
31
  import { runCutValues, runErrorWordsOf, underCut } from "./run-cut.js";
30
32
  import { Turns } from "./turns.js";
31
33
  import { harnessOfBody } from "./harness.js";
@@ -104,6 +106,10 @@ const errorOfRow = (summary) => {
104
106
  const lost = lostEndMessage(summary);
105
107
  if (lost !== undefined)
106
108
  return { code: COMPUTER_UNAVAILABLE_CODE, message: lost, retryable: false };
109
+ // A run still queued when every runner here refused to claim (runner/presence.ts refusedEnd): runner_refused.
110
+ const refused = refusedEndMessage(summary);
111
+ if (refused !== undefined)
112
+ return { code: RUNNER_REFUSED_CODE, message: refused, retryable: false };
107
113
  if (summary !== null && contentFiltered(summary))
108
114
  return { code: MODERATED, message: CONTENT_FILTER_WORDS, retryable: false };
109
115
  return { code: "run_failed", message: summary ?? "The run failed.", retryable: false };
@@ -133,6 +139,15 @@ function pausedOf(runRow, entries) {
133
139
  function liveOf(runRow, now) {
134
140
  return !FINAL_STATES.includes(runRow.state) && runRow.runner !== null && runRow.claimedUntil !== null && runRow.claimedUntil >= now;
135
141
  }
142
+ /** Whether the run's turn stands on a person: a tool call asked for their approval with no answer in its journal (the
143
+ * view's `approvals`, asksOf), or a browser or desktop hand-over neither answered in its journal nor by a hand-back row.
144
+ * By the journal alone, never by the clock: a hand-over past its expiry still holds the turn until its expiry is written
145
+ * as its answer, and only then does the turn go on. Such a turn has no model request in flight. */
146
+ export function standsOnPerson(approvals, entries, commands) {
147
+ return [...approvals.values()].some((approval) => !approval.resolved) ||
148
+ browserAskOf(entries, commands, Number.NEGATIVE_INFINITY) !== undefined ||
149
+ computerAskOf(entries, commands, Number.NEGATIVE_INFINITY) !== undefined;
150
+ }
136
151
  /** Reads the run from the store and builds the RunView the view functions read. Every read of the run (its row, launch,
137
152
  * journal, live tick and commands) is made in one snapshot of the store (Store.snapshot), so the view is of one moment: a
138
153
  * runner's commit that lands while it is built is in all of it or in none. What is read through the server's own handles
@@ -151,12 +166,29 @@ async function storeRunOf(store, runId, deps) {
151
166
  if (!(await store.runs.get(runId)))
152
167
  return undefined;
153
168
  const run = await underCut(async () => (await cutOf()) ?? "unreadable", (cut) => store.snapshot((snapshot) => storeRunIn(snapshot, runId, deps, cut)));
169
+ // An ended run whose end stored its cost unknown while its booking is priced: its store is healed now, after the
170
+ // snapshot (which may not write), so every reader of the stored cost (the list, /stats, /usage, the learning bill)
171
+ // reads the figure this read shows. One conditional write (Runs.healCost); a failure is said and the next read tries again.
172
+ if (run?.heal)
173
+ await healStoredCost(store, runId, run.heal);
154
174
  if (!run?.shownEnd || !holdsForOk(run.shownEnd) || !deps.statuses)
155
175
  return run && { ...run, learningEnd: run.shownEnd };
156
176
  // What the learning end held for its owner's OK reads as it stands now on its agent's folder's main (learning.ts
157
177
  // currentLearning); its record stays as the merge wrote it.
158
178
  return { ...run, learningEnd: currentLearning(run.shownEnd, await deps.statuses(run.row.agent)) };
159
179
  }
180
+ /** Heals run `runId`'s stored unknown cost to the figure its booking gives (Runs.healCost), at the end it was read at.
181
+ * True when written; false when another write got there first, or when the write failed (said, never thrown: a read
182
+ * never fails on its heal, and the next read or start sweep writes it again). */
183
+ export async function healStoredCost(store, runId, heal) {
184
+ try {
185
+ return await store.runs.healCost(runId, heal, heal);
186
+ }
187
+ catch (error) {
188
+ console.warn(`[serve] an ended run's cost read from its booking could not be stored: ${error.message}; the next read stores it`);
189
+ return false;
190
+ }
191
+ }
160
192
  /** `storeRunOf`'s reads, over `store` (a snapshot) and the run's cut. */
161
193
  async function storeRunIn(store, runId, deps, cut) {
162
194
  const context = BACKGROUND_CONTEXT;
@@ -238,8 +270,11 @@ async function storeRunIn(store, runId, deps, cut) {
238
270
  // takes the stop, a read would otherwise see the cut turn's input_required with nothing pending; a run waiting (on an
239
271
  // approval, a person, a browser) reads stopped from the stop's answer on. While its turn still works it reads working:
240
272
  // 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());
273
+ // sum as its cost. A turn that stands on a person (standsOnPerson) has no request in flight to book: the runner that takes
274
+ // the stop claims the run with that turn still open, and it reads stopped under that claim too, never working between the
275
+ // stop's answer and its end.
276
+ const commands = terminal ? [] : await commandsNow();
277
+ const asked = !terminal && stopAsked(row, runRow, commands) && (!working || standsOnPerson(approvals, records.entries, commands));
243
278
  // A call asked before an end in the journal reads withdrawn in that end's words; a stopped or failed run's (states no
244
279
  // reopen leaves) whose journal holds no end, by its row (answersOf `final`); every call still waiting once a stop is
245
280
  // asked (stopAsked).
@@ -319,14 +354,18 @@ async function storeRunIn(store, runId, deps, cut) {
319
354
  const decisions = booked.requests ? booked : undefined;
320
355
  const onPlan = planSpend(records.entries);
321
356
  const plan = onPlan.requests ? onPlan : undefined;
357
+ const model = bookedSpend(records.entries, "model");
322
358
  // An ended run's booking by the one rule its end stored its cost by (metrics.ts runCostOf), read in the same snapshot as
323
359
  // its state: its so-far figures beside a stored unknown (costOfView reads the figure itself from the stored column). A
324
360
  // workflow's end stores it by the same rule (workflow-spec.ts); a native run's end reads its own, so it keeps the
325
361
  // reading below.
326
- const bookedCost = terminal && (row.kind === "workflow" || (row.kind === "agentic" && !native)) && !row.importedFrom ? runCostOf(records.entries, { unbooked: isCliRecord(records.entries) && cliModelWorked(records.entries) }) : undefined;
362
+ const bookedCost = bookedCostOf(row, native !== undefined, records.entries);
327
363
  const endCost = bookedCost?.requests ? bookedCost : undefined;
328
- const endSaidCost = endCost ? (records.entries.findLast((entry) => entry.kind === KINDS.end)?.data?.costUsd !== undefined) : false;
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 } : {}) };
364
+ const endSaid = records.entries.findLast((entry) => entry.kind === KINDS.end)?.data?.costUsd;
365
+ const endSaidCost = endCost ? endSaid !== undefined : false;
366
+ const endUnread = bookedCost !== undefined && !endCost && endSaid === null;
367
+ const heal = healOf(endCost, runRow);
368
+ 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, model, ...(endCost ? { endCost, endSaidCost } : {}), ...(endUnread ? { endUnread } : {}), ...(heal ? { heal } : {}) };
330
369
  }
331
370
  /** 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
332
371
  * person's words cut of the host's secrets now. */
@@ -354,21 +393,27 @@ function costOfView(run) {
354
393
  // Its decisions' booked cost joins its usage row's (costView), one unknown making it unknown.
355
394
  const decisions = run.decisions;
356
395
  // An ended run that booked its requests reads the cost its end stored by its booking (runCostOf), the answer the list,
357
- // usage and stats read too: one figure on every reader. Its end reads that cost again when a read fails
358
- // (loop.ts readAgain), so a null is kept only when the booking could not be read within the end's bound. The booking,
359
- // read in the snapshot that read its state, adds only what the stored figure agrees with: what is known so far when both
360
- // are unknown. An end that wrote no cost (a spec that reads none) left the column alone: the booking is the answer then.
396
+ // usage and stats read too. Its end reads that cost again when a read fails (loop.ts readAgain), and stores it unknown
397
+ // only when the booking could not be read within the end's bound: then this read, which reads the booking in the
398
+ // snapshot that read its state, says what the booking says (a figure, or unknown with what is known so far), so a late
399
+ // read heals on the next GET and never reads as a null with no reason. An end that wrote no cost (a spec that reads
400
+ // none) left the column alone: the booking is the answer then too.
361
401
  const booked = run.endCost;
362
402
  const said = booked !== undefined && run.endSaidCost === true;
363
403
  // Its cost in the Cost's words (CostWords), each figure by the one rule (costWordsOf): a hold is never spend, so while
364
404
  // the total is unknown each held request counts as not priced, and a bound says its exact part and held count beside it.
365
405
  // A run still going or ended unbooked: its usage row joined with its decisions' booking (costWordsOfView). An imported
366
- // run: what the import stored, exact. An ended run that booked its requests: its booking's words, or, where its end
367
- // stored a figure, that figure, with what the booking says beside it only where the two agree (the same unknown, the
368
- // same bound); a bound its end stored is said so (cost_upper_bound), the bound the list and the column read too.
406
+ // run: what the import stored, exact, else the catalog's estimate it kept beside it (costOfRun). An ended run that
407
+ // booked its requests: its booking's words, or, where its end stored a figure, that figure, with what the booking says
408
+ // beside it only where the two agree (the same unknown, the same bound); a bound its end stored is said so
409
+ // (cost_upper_bound), the bound the list and the column read too.
369
410
  const bookedWords = booked ? costWordsOf([booked]) : undefined;
370
- const words = !booked ? (imported ? { usd: stored ?? null } : costWordsOfView(run.rows, stored, decisions)) : !said ? bookedWords : stored !== null && stored !== undefined ? { usd: stored } : storedAtMost !== null ? { ...(bookedWords.upper_bound ? bookedWords : {}), usd: storedAtMost, upper_bound: true } : bookedWords.usd === null ? bookedWords : { usd: null };
411
+ const words = !booked ? (imported ? { usd: costOfRun(run.runRow) } : costWordsOfView(run.rows, stored, decisions)) : !said ? bookedWords : stored !== null && stored !== undefined ? { usd: stored } : storedAtMost !== null ? { ...(bookedWords.upper_bound ? bookedWords : {}), usd: storedAtMost, upper_bound: true } : bookedWords;
371
412
  const usd = words.usd;
413
+ // A run whose end stored its cost unknown and whose booking this read finds no request in, its cost unknown with
414
+ // nothing else to say why (no charge counted unpriced, no bound): the booking could not be read. Said in `unknown`,
415
+ // never a bare null.
416
+ const unread = run.endUnread && usd === null && words.unpriced === undefined && !words.upper_bound ? { unknown: "booking_unread" } : undefined;
372
417
  const counted = words.so_far_usd !== undefined && words.unpriced !== undefined ? { so_far_usd: words.so_far_usd, unpriced: words.unpriced } : undefined;
373
418
  const upper = words.upper_bound ? { upper_bound: true } : undefined;
374
419
  // A request billed to a person's plan costs no dollars, however it ended (the kernel's turnCostOf): every reader counts it
@@ -381,7 +426,92 @@ function costOfView(run) {
381
426
  const soFar = counted ?? (imported || decisions?.requests ? undefined : freeOf(run.rows, usd));
382
427
  // The run's cap as it stands (its view's meta: the newest raise's, else the launch's).
383
428
  const cap = run.view.meta.max_cost_usd;
384
- return { usd, basis: "estimate", charge_state: null, cap_usd: cap ?? null, ...(soFar ?? {}), ...(upper ?? {}), ...(plan ? { plan: { requests: plan.requests, tokens: plan.tokens, on } } : {}) };
429
+ const tokens = tokensOfView(run);
430
+ return { usd, basis: basisOfView(run, words), charge_state: null, cap_usd: cap ?? null, ...(soFar ?? {}), ...(upper ?? {}), ...(unread ?? {}), ...(plan ? { plan: { requests: plan.requests, tokens: plan.tokens, on } } : {}), ...(tokens ? { tokens } : {}) };
431
+ }
432
+ /** What run `runId`'s paid tool calls cost, the run read's `cost.tools_usd` (server.ts allInViewOf): the charges its
433
+ * paid-tools session booked (a monid endpoint's, a priced MCP tool's, Parallel's behind the web tools, the browser's
434
+ * time), joined and rounded by the one rule its `usd` is (costWordsOf), less those in its end-of-run turn, which are
435
+ * learning's as that turn's model requests are (runCostOf). A part of `usd`, never added to it; 0 with none. Null when
436
+ * one's charge is unknown (charged an unknown amount, cut, or still out) or counted at its hold; while the run is at work
437
+ * (not ended, stopped or failed), as its `usd` is the view's snapshot and a paid call booked after it would be read here
438
+ * and not there (an ended run's record no longer moves); for a run a follow-up
439
+ * opened again (a round past its first), whose job is what it had cost when its first round answered and whose paid
440
+ * calls the booking can't split by that; and for an imported, native or SDK run, whose `usd` is its import's or its
441
+ * harness's own figure, with no booking of its paid tool calls (a native or SDK run never opens the paid-tools session),
442
+ * and for an unknown run. */
443
+ export async function toolsUsdOverStore(store, runId) {
444
+ const runRow = await store.runs.get(runId);
445
+ const launch = await launchOf(store, runId);
446
+ if (!runRow || !FINAL_STATES.includes(runRow.state) || runRow.importedFrom || launch?.native || launch?.sdk || (await roundsOf(store, runId)).length > 1)
447
+ return null;
448
+ const records = await journalRecords(store.readJournal(runId), BACKGROUND_CONTEXT);
449
+ const turns = reflectRanges(records.submissions ?? [], records.entries);
450
+ const words = costWordsOf([bookedSpend(records.entries.filter((entry) => !inReflect(turns, Number(entry.id))), "paid")]);
451
+ return words.upper_bound ? null : words.usd;
452
+ }
453
+ /** How a run's cost was reached (metrics.ts CostBasis): by how its model requests were priced, as its booking says, while
454
+ * it booked one; else as its end stored it, or, where nothing says, an `estimate` when it cost anything (a native, SDK or
455
+ * imported run's figure is its harness's or the catalog's), `unpriced` when nothing was priced. */
456
+ function basisOfView(run, words) {
457
+ if (run.model.requests > 0)
458
+ return costBasisOf(run.model);
459
+ return storedBasisOf(run.row.state === "running" ? undefined : run.runRow.metrics, words.usd ?? words.so_far_usd);
460
+ }
461
+ /** A run's tokens as its cost says them: its model requests' input (cached input apart), output, cache reads and writes,
462
+ * how many requests it booked, and how many of those reported no tokens (`unmetered`). From its booking while it booked a
463
+ * request; else from the metrics its end stored (an imported run's); undefined when neither says. A native or SDK run
464
+ * books one record for its whole task (`aggregate`), not one per request, so its tokens are its stored metrics' alone,
465
+ * with its request count unknown (left out), and none while any count is unknown (stored null), never a 0 for one. */
466
+ function tokensOfView(run) {
467
+ const booked = run.model;
468
+ const aggregate = run.native !== undefined || run.sdk !== undefined;
469
+ if (booked.requests > 0 && !aggregate)
470
+ return { input: booked.tokens.input, output: booked.tokens.output, cache_read: booked.tokens.cacheRead, cache_write: booked.tokens.cacheWrite, requests: booked.requests, unmetered: booked.unmetered };
471
+ const stored = (run.row.state === "running" ? undefined : run.runRow.metrics);
472
+ if ([stored?.input, stored?.output, stored?.cacheRead, stored?.cacheWrite].some((value) => value === null))
473
+ return undefined;
474
+ const count = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined);
475
+ const [input, output] = [count(stored?.input), count(stored?.output)];
476
+ if (input === undefined || output === undefined)
477
+ return undefined;
478
+ const requests = count(stored?.requests);
479
+ if (requests === 0 && input + output === 0)
480
+ return undefined;
481
+ return { input, output, cache_read: count(stored?.cacheRead) ?? 0, cache_write: count(stored?.cacheWrite) ?? 0, ...(requests === undefined ? {} : { requests }), ...(count(stored?.unmetered) === undefined ? {} : { unmetered: count(stored?.unmetered) }) };
482
+ }
483
+ /** An ended run's booking by the one rule its end stored its cost by (metrics.ts runCostOf). Undefined for a run still
484
+ * going, a native run (its end reads its own), or an imported one. */
485
+ function bookedCostOf(row, native, entries) {
486
+ if (row.state === "running" || !(row.kind === "workflow" || (row.kind === "agentic" && !native)) || row.importedFrom)
487
+ return undefined;
488
+ return runCostOf(entries, { unbooked: isCliRecord(entries) && cliModelWorked(entries) });
489
+ }
490
+ /** What an ended run's stored cost heals to (Runs.healCost), at the end it was read at: what its end would have stored
491
+ * had it read its booking (endCostOf, the one rule every end writes by: its figure, a bound when a cut request's hold is
492
+ * counted in it), when that booking has a request and a figure while the stored cost is null with no bound. */
493
+ function healOf(endCost, runRow) {
494
+ if (!endCost || endCost.usd === null)
495
+ return undefined;
496
+ if (runRow.costUsd !== null || runRow.costAtMostUsd !== null || runRow.endedAt === null)
497
+ return undefined;
498
+ const { costUpperBound } = endCostOf(endCost);
499
+ return { epoch: runRow.epoch, endedAt: runRow.endedAt, costUsd: endCost.usd, costUpperBound };
500
+ }
501
+ /** The start sweep's heal of run `runId` (cost-heal.ts): the same rule as its run read's (bookedCostOf, healOf), from its
502
+ * row, its launch and its journal alone, so a sweep over many runs reads no timeline and no learning folder. True when
503
+ * it wrote the booking's figure; a failed read or write throws, for the sweep to count. */
504
+ export async function healedOverStore(store, runId) {
505
+ const heal = await store.snapshot(async (snapshot) => {
506
+ const runRow = await snapshot.runs.get(runId);
507
+ const row = runRow && (await readRun(snapshot, runId, BACKGROUND_CONTEXT));
508
+ if (!runRow || !row)
509
+ return undefined;
510
+ const launch = await launchOf(snapshot, runId);
511
+ const booked = bookedCostOf(row, Boolean(launch?.native), (await journalRecords(snapshot.readJournal(runId), BACKGROUND_CONTEXT)).entries);
512
+ return healOf(booked?.requests ? booked : undefined, runRow);
513
+ });
514
+ return heal !== undefined && (await store.runs.healCost(runId, heal, heal));
385
515
  }
386
516
  /** GET /runs/{id}'s answer from the store, byte-identical to runs.ts's view for the same run. Undefined for an unknown run. */
387
517
  export async function viewOverStore(store, runId, deps) {
@@ -484,6 +614,9 @@ async function viewOfRun(store, runId, deps, run, read) {
484
614
  cost: costOfView(run),
485
615
  // The run an audit's shadow run audits (launch.audit, runner/audit.ts); null for any other run.
486
616
  audit_of: launch?.audit?.of ?? null,
617
+ // The path it took and the learned workflow that served it, as its record keeps them: the read the cost per run makes
618
+ // (store-reads/learning.ts pathViewOf).
619
+ ...pathViewOf(runRow, row.kind, launch ? learningStartOf(launch) : undefined),
487
620
  // Whether it ran unattended (its revision's approvals, as it started): never, an ask allowed at its gate; ask, the default.
488
621
  approvals: run.approvalsMode,
489
622
  archived_at: row.archivedAt ?? null,
@@ -517,6 +650,8 @@ export function summaryOfView(view) {
517
650
  ...(effort ? { effort } : {}),
518
651
  created_at, ended_at, error, review, pending, cost, archived_at, imported_from, trigger, labels,
519
652
  learning: learning ? shortOf(learning) : null,
653
+ // Read off the run's record, so a list carries it with no read of the run's journal.
654
+ path: view.path, workflow: view.workflow,
520
655
  };
521
656
  }
522
657
  /** 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
@@ -548,10 +683,10 @@ export async function listingOverStore(store, runId, deps) {
548
683
  flags,
549
684
  };
550
685
  }
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) {
686
+ /** Whether `listing` is cut of the server's secrets as they are now. A list builds any other again before it shows it
687
+ * (server.ts runsPage): the run's view cuts a value whole where it holds a secret (a note's name reads [redacted]), which
688
+ * cutting the built item again could not do. */
689
+ export function builtOfNow(listing, serverSecrets) {
555
690
  return listing.cut === secretsDigest(serverSecrets);
556
691
  }
557
692
  /** A listing's list item as a list serves it (listingOverStore): its console link at `origin`, its archive time now
@@ -1,15 +1,16 @@
1
1
  /** Where events go: PostHog's capture route, behind this project's own name. */
2
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 = "";
3
+ /** The PostHog project's write-only key, public by design: that project holds these counts and nothing else. Empty, a build sends nothing and prints no notice. */
4
+ export declare const TELEMETRY_KEY = "phc_kz3ieB34X89r2bv6gLbdeXDiNNn78KiAPRCZCxMzUBuA";
5
5
  /** The file in the data directory that keeps the id, when the notice was printed and how many runs ended. */
6
6
  export declare const TELEMETRY_FILE = ".telemetry.json";
7
7
  /** How often a running server says it still runs. */
8
8
  export declare const HEARTBEAT_MS: number;
9
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
10
  export type TelemetryEventName = "server_started" | "heartbeat" | "first_run_completed";
11
- /** One event, as sent. `runs` is a range, never a count. */
11
+ /** One event, as sent (and as debug prints it). `runs` is a range, never a count. */
12
12
  export interface TelemetryEvent {
13
+ api_key: string;
13
14
  event: TelemetryEventName;
14
15
  distinct_id: string;
15
16
  timestamp: string;
@@ -25,8 +26,8 @@ export interface TelemetryEvent {
25
26
  }
26
27
  export type RunsRange = "0" | "1-10" | "11-100" | "101+";
27
28
  /** 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. */
29
+ export type TelemetryMode = "on" | "debug" | "off_setting" | "off_do_not_track" | "off_ci" | "off_faux" | "off_test" | "off_no_key";
30
+ /** What this start does, from its environment (docs/telemetry.md). */
30
31
  export declare function telemetryMode(env: NodeJS.ProcessEnv, o?: {
31
32
  faux?: boolean;
32
33
  key?: string;
@@ -47,12 +48,11 @@ export interface TelemetryOptions {
47
48
  version?: string;
48
49
  env?: NodeJS.ProcessEnv;
49
50
  faux?: boolean;
50
- /** For tests: the key, the route, the sender, the clock, the heartbeat's period and where debug lines go. */
51
+ /** For tests: the key, the route, the sender, the clock and where debug lines go. */
51
52
  key?: string;
52
53
  url?: string;
53
54
  fetch?: typeof fetch;
54
55
  now?: () => Date;
55
- heartbeatMs?: number;
56
56
  say?: (line: string) => void;
57
57
  }
58
58
  /** Starts the counts for a server on `data`. Never throws: a data directory it cannot write turns it off. */
package/dist/telemetry.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // first run completed. Each event holds a random id made for this data directory, the server's version, the platform,
3
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
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
5
+ // Off with AGENTRUN_TELEMETRY=0 or DO_NOT_TRACK=1, in CI, under a test runner, and under --faux. The start that first could send prints one
6
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.
7
+ // AGENTRUN_TELEMETRY=debug prints every event and sends none, and writes nothing, so it never stands in for that notice.
8
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
9
  // in memory and written behind it, one write at a time, so no request or run waits on the disk.
10
10
  import { randomUUID } from "node:crypto";
@@ -14,8 +14,8 @@ import { join } from "node:path";
14
14
  import { tempOf, writeDurableSync } from "./server-fs.js";
15
15
  /** Where events go: PostHog's capture route, behind this project's own name. */
16
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 = "";
17
+ /** The PostHog project's write-only key, public by design: that project holds these counts and nothing else. Empty, a build sends nothing and prints no notice. */
18
+ export const TELEMETRY_KEY = "phc_kz3ieB34X89r2bv6gLbdeXDiNNn78KiAPRCZCxMzUBuA";
19
19
  /** The file in the data directory that keeps the id, when the notice was printed and how many runs ended. */
20
20
  export const TELEMETRY_FILE = ".telemetry.json";
21
21
  /** How often a running server says it still runs. */
@@ -25,7 +25,7 @@ const SEND_TIMEOUT_MS = 3_000;
25
25
  const ownVersion = () => JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
26
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
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. */
28
+ /** What this start does, from its environment (docs/telemetry.md). */
29
29
  export function telemetryMode(env, o = {}) {
30
30
  const setting = (env.AGENTRUN_TELEMETRY ?? "").trim().toLowerCase();
31
31
  if (OFF.has(setting))
@@ -39,6 +39,9 @@ export function telemetryMode(env, o = {}) {
39
39
  return "off_faux";
40
40
  if (setting === "debug")
41
41
  return "debug";
42
+ // A server a test starts inherits node --test's mark: this repository's suites, and anyone's, are never counted.
43
+ if (env.NODE_TEST_CONTEXT)
44
+ return "off_test";
42
45
  return (o.key ?? TELEMETRY_KEY) === "" ? "off_no_key" : "on";
43
46
  }
44
47
  export const runsRange = (runs) => (runs <= 0 ? "0" : runs <= 10 ? "1-10" : runs <= 100 ? "11-100" : "101+");
@@ -51,7 +54,7 @@ function readState(file) {
51
54
  id: kept.id,
52
55
  runs: typeof kept.runs === "number" && Number.isInteger(kept.runs) && kept.runs >= 0 ? kept.runs : 0,
53
56
  ...(typeof kept.noticed_at === "string" ? { noticed_at: kept.noticed_at } : {}),
54
- ...(kept.first_run_sent === true ? { first_run_sent: true } : {}),
57
+ ...(kept.first_run === "held" || kept.first_run === "sent" ? { first_run: kept.first_run } : {}),
55
58
  };
56
59
  }
57
60
  }
@@ -103,6 +106,8 @@ export function startTelemetry(o) {
103
106
  let stale = false;
104
107
  let writing;
105
108
  const keepLater = () => {
109
+ if (mode === "debug")
110
+ return;
106
111
  stale = true;
107
112
  writing ??= (async () => {
108
113
  while (stale) {
@@ -113,15 +118,17 @@ export function startTelemetry(o) {
113
118
  })();
114
119
  };
115
120
  // 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.
121
+ // print it again and still send nothing, so this one stays quiet too. Debug runs the same rules on the kept state in
122
+ // memory and writes nothing: what it printed never left, so a start that can send after it still prints the notice and
123
+ // still says the first run.
118
124
  const first = mode === "on" && state.noticed_at === undefined;
119
125
  if (first)
120
126
  state.noticed_at = now().toISOString();
121
- if (!keepNow())
127
+ if (mode === "on" && !keepNow())
122
128
  return { ...idle, mode: "off_setting" };
123
129
  const emit = (event) => {
124
130
  const body = {
131
+ api_key: key,
125
132
  event,
126
133
  distinct_id: state.id,
127
134
  timestamp: now().toISOString(),
@@ -129,23 +136,39 @@ export function startTelemetry(o) {
129
136
  };
130
137
  if (mode === "debug")
131
138
  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(() => { }, () => { });
139
+ void send(o.url ?? TELEMETRY_URL, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(SEND_TIMEOUT_MS) }).then(() => { }, () => { });
140
+ };
141
+ // The start that printed the notice sends nothing until its first heartbeat, a day later: a first run that completes
142
+ // before then is kept as held and said with that heartbeat, or at the next start, whichever comes first.
143
+ let holding = first;
144
+ const sayHeld = () => {
145
+ if (state.first_run !== "held")
146
+ return;
147
+ state.first_run = "sent";
148
+ keepLater();
149
+ emit("first_run_completed");
133
150
  };
134
- if (!first)
151
+ if (!first) {
135
152
  emit("server_started");
153
+ sayHeld();
154
+ }
136
155
  // 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);
156
+ const beat = setInterval(() => {
157
+ holding = false;
158
+ emit("heartbeat");
159
+ sayHeld();
160
+ }, HEARTBEAT_MS);
138
161
  beat.unref();
139
162
  return {
140
163
  mode,
141
164
  ...(first ? { notice: TELEMETRY_NOTICE } : {}),
142
165
  runEnded(status) {
143
166
  state.runs += 1;
144
- const completed = status === "ended" && !state.first_run_sent;
167
+ const completed = status === "ended" && state.first_run === undefined;
145
168
  if (completed)
146
- state.first_run_sent = true;
169
+ state.first_run = holding ? "held" : "sent";
147
170
  keepLater();
148
- if (completed)
171
+ if (completed && !holding)
149
172
  emit("first_run_completed");
150
173
  },
151
174
  close: () => (clearInterval(beat), writing ?? Promise.resolve()),