@parcha/agentrun-serve 0.1.0-beta.51 → 0.1.0-beta.53

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 (322) hide show
  1. package/CHANGELOG.md +160 -1
  2. package/README.md +306 -36
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +14 -4
  5. package/dist/agent-delete.js +30 -58
  6. package/dist/agent-package.d.ts +71 -0
  7. package/dist/agent-package.js +345 -0
  8. package/dist/agents-store.d.ts +28 -18
  9. package/dist/agents-store.js +48 -34
  10. package/dist/api-only.d.ts +30 -8
  11. package/dist/api-only.js +40 -16
  12. package/dist/archil-routes.d.ts +1 -0
  13. package/dist/archil-routes.js +28 -2
  14. package/dist/claude-login.d.ts +1 -0
  15. package/dist/claude-login.js +1 -1
  16. package/dist/cli-learning/cli.d.ts +3 -0
  17. package/dist/cli-learning/cli.js +17 -3
  18. package/dist/cli-learning/connections.js +3 -2
  19. package/dist/cli-learning/schema.js +2 -1
  20. package/dist/cli.js +70 -7
  21. package/dist/composio-preset.d.ts +2 -1
  22. package/dist/composio-preset.js +4 -3
  23. package/dist/composio-triggers.d.ts +4 -0
  24. package/dist/composio-triggers.js +4 -1
  25. package/dist/computer-needs.d.ts +32 -0
  26. package/dist/computer-needs.js +80 -0
  27. package/dist/computer-setting.d.ts +9 -0
  28. package/dist/computer-setting.js +19 -1
  29. package/dist/computers.d.ts +6 -2
  30. package/dist/computers.js +2 -2
  31. package/dist/console/assets/index-BFgyZzF_.js +734 -0
  32. package/dist/console/assets/index-DbilxljH.css +1 -0
  33. package/dist/console/index.html +2 -2
  34. package/dist/console-links.d.ts +1 -0
  35. package/dist/console-links.js +2 -0
  36. package/dist/env-switch.d.ts +14 -0
  37. package/dist/env-switch.js +23 -0
  38. package/dist/errors.d.ts +1 -0
  39. package/dist/errors.js +3 -0
  40. package/dist/eval-previous.js +4 -3
  41. package/dist/fal-price.d.ts +76 -0
  42. package/dist/fal-price.js +365 -0
  43. package/dist/handed-secret.d.ts +4 -0
  44. package/dist/handed-secret.js +10 -0
  45. package/dist/harness-archive.d.ts +15 -5
  46. package/dist/harness-archive.js +71 -34
  47. package/dist/harness-check.d.ts +2 -1
  48. package/dist/harness-check.js +36 -95
  49. package/dist/harness-egress.d.ts +23 -0
  50. package/dist/harness-egress.js +69 -0
  51. package/dist/harness-recipe-entry.d.ts +71 -0
  52. package/dist/harness-recipe-entry.js +184 -0
  53. package/dist/harness-recipe.d.ts +73 -6
  54. package/dist/harness-recipe.js +185 -31
  55. package/dist/harness-sign-in.d.ts +29 -0
  56. package/dist/harness-sign-in.js +122 -0
  57. package/dist/harness-table.d.ts +21 -0
  58. package/dist/harness-table.js +58 -3
  59. package/dist/harness-zip.d.ts +6 -0
  60. package/dist/harness-zip.js +203 -0
  61. package/dist/ids.d.ts +11 -0
  62. package/dist/ids.js +36 -0
  63. package/dist/learn/commit.d.ts +19 -1
  64. package/dist/learn/commit.js +160 -2
  65. package/dist/learn/compile.d.ts +13 -5
  66. package/dist/learn/compile.js +46 -15
  67. package/dist/learn/delete.d.ts +12 -6
  68. package/dist/learn/delete.js +17 -11
  69. package/dist/learn/folder.d.ts +16 -0
  70. package/dist/learn/folder.js +30 -4
  71. package/dist/learn/learning-of.d.ts +8 -0
  72. package/dist/learn/learning-of.js +8 -0
  73. package/dist/learn/learning.sh +29 -4
  74. package/dist/learn/promote.d.ts +51 -7
  75. package/dist/learn/promote.js +51 -8
  76. package/dist/learn/secrets.js +30 -7
  77. package/dist/learning-reset.d.ts +18 -0
  78. package/dist/learning-reset.js +115 -0
  79. package/dist/learning-routes.d.ts +23 -11
  80. package/dist/learning-routes.js +110 -20
  81. package/dist/learning-words.d.ts +5 -0
  82. package/dist/learning-words.js +5 -0
  83. package/dist/learning.d.ts +15 -10
  84. package/dist/learning.js +14 -8
  85. package/dist/llms.txt +1 -0
  86. package/dist/mcp-gateway.d.ts +39 -2
  87. package/dist/mcp-gateway.js +56 -12
  88. package/dist/mcp-pin-first.js +1 -1
  89. package/dist/mcp-probe.d.ts +3 -0
  90. package/dist/mcp-probe.js +7 -2
  91. package/dist/mcp-resources.d.ts +44 -0
  92. package/dist/mcp-resources.js +100 -0
  93. package/dist/mcp-servers-store.d.ts +17 -12
  94. package/dist/mcp-servers-store.js +2 -1
  95. package/dist/media-duration.d.ts +2 -0
  96. package/dist/media-duration.js +136 -0
  97. package/dist/model.d.ts +4 -4
  98. package/dist/model.js +6 -6
  99. package/dist/native/cli.js +9 -2
  100. package/dist/native/connection.d.ts +2 -2
  101. package/dist/native/connection.js +5 -2
  102. package/dist/native/discovery.d.ts +2 -0
  103. package/dist/native/discovery.js +10 -6
  104. package/dist/native/remote-worker-bridge.js +36 -4
  105. package/dist/native/remote.d.ts +18 -1
  106. package/dist/native/remote.js +126 -37
  107. package/dist/native/schema.d.ts +6 -0
  108. package/dist/native/schema.js +31 -6
  109. package/dist/native/source-account.d.ts +13 -0
  110. package/dist/native/source-account.js +114 -0
  111. package/dist/native/source-capture-hooks.d.ts +5 -0
  112. package/dist/native/source-capture-hooks.js +102 -0
  113. package/dist/native/source-mcp-selection.d.ts +13 -0
  114. package/dist/native/source-mcp-selection.js +72 -0
  115. package/dist/native/source-runtime-tools.d.ts +19 -0
  116. package/dist/native/source-runtime-tools.js +103 -0
  117. package/dist/native/source-snapshot-types.d.ts +138 -0
  118. package/dist/native/source-snapshot-types.js +12 -0
  119. package/dist/native/source-snapshot.d.ts +8 -0
  120. package/dist/native/source-snapshot.js +1201 -0
  121. package/dist/observation/learning.js +3 -2
  122. package/dist/openapi.js +211 -47
  123. package/dist/print.js +1 -1
  124. package/dist/provider.d.ts +8 -0
  125. package/dist/provider.js +14 -2
  126. package/dist/purged-workflow.d.ts +12 -0
  127. package/dist/purged-workflow.js +43 -0
  128. package/dist/refusal-words.d.ts +0 -3
  129. package/dist/refusal-words.js +0 -3
  130. package/dist/request-metadata.d.ts +20 -0
  131. package/dist/request-metadata.js +24 -0
  132. package/dist/run-keys.d.ts +46 -0
  133. package/dist/run-keys.js +109 -0
  134. package/dist/run-launch.d.ts +29 -5
  135. package/dist/run-launch.js +44 -4
  136. package/dist/run-learning-served.d.ts +2 -2
  137. package/dist/run-model-key.d.ts +2 -2
  138. package/dist/run-model-key.js +5 -5
  139. package/dist/run-secrets.d.ts +2 -0
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-usage.d.ts +48 -4
  142. package/dist/run-usage.js +156 -39
  143. package/dist/run-view.d.ts +18 -1
  144. package/dist/run-view.js +28 -8
  145. package/dist/runner/adapter-loop.d.ts +14 -4
  146. package/dist/runner/adapter-loop.js +150 -31
  147. package/dist/runner/adapter-run-spec.d.ts +1 -1
  148. package/dist/runner/adapter-run-spec.js +35 -22
  149. package/dist/runner/audit.d.ts +10 -3
  150. package/dist/runner/audit.js +30 -7
  151. package/dist/runner/beside.js +2 -1
  152. package/dist/runner/claim-secrets.d.ts +31 -4
  153. package/dist/runner/claim-secrets.js +43 -7
  154. package/dist/runner/cli-run-spec.d.ts +1 -1
  155. package/dist/runner/cli-run-spec.js +32 -20
  156. package/dist/runner/conformance/harness.js +4 -2
  157. package/dist/runner/dispatch.js +4 -2
  158. package/dist/runner/harness-loops.d.ts +6 -0
  159. package/dist/runner/harness-loops.js +16 -3
  160. package/dist/runner/held.d.ts +4 -0
  161. package/dist/runner/journal-kinds.d.ts +5 -0
  162. package/dist/runner/learned-first.d.ts +2 -0
  163. package/dist/runner/learned-first.js +1 -1
  164. package/dist/runner/learning-end.d.ts +9 -3
  165. package/dist/runner/learning-end.js +66 -29
  166. package/dist/runner/learning-seed.d.ts +9 -3
  167. package/dist/runner/learning-seed.js +2 -2
  168. package/dist/runner/main.d.ts +1 -0
  169. package/dist/runner/main.js +20 -13
  170. package/dist/runner/mcp-claim.js +7 -2
  171. package/dist/runner/mcp-run.d.ts +12 -0
  172. package/dist/runner/mcp-run.js +14 -1
  173. package/dist/runner/model-route.js +7 -4
  174. package/dist/runner/monid-run.js +9 -11
  175. package/dist/runner/project-checkpoint.d.ts +35 -0
  176. package/dist/runner/project-checkpoint.js +116 -0
  177. package/dist/runner/project-drain.d.ts +8 -0
  178. package/dist/runner/project-drain.js +25 -0
  179. package/dist/runner/project-host.d.ts +10 -0
  180. package/dist/runner/project-host.js +52 -0
  181. package/dist/runner/promotion.d.ts +51 -24
  182. package/dist/runner/promotion.js +206 -78
  183. package/dist/runner/redact.d.ts +13 -0
  184. package/dist/runner/redact.js +67 -1
  185. package/dist/runner/run-channel.d.ts +9 -0
  186. package/dist/runner/run-channel.js +15 -2
  187. package/dist/runner/run-child-host.d.ts +8 -4
  188. package/dist/runner/run-child-host.js +174 -42
  189. package/dist/runner/run-errors.js +2 -2
  190. package/dist/runner/runner-check.js +5 -2
  191. package/dist/runner/runner.js +41 -12
  192. package/dist/runner/sdk-loop.d.ts +2 -2
  193. package/dist/runner/sdk-loop.js +3 -3
  194. package/dist/runner/store-port.d.ts +3 -0
  195. package/dist/runner/store-secrets.js +7 -3
  196. package/dist/runner/workflow-first.d.ts +4 -0
  197. package/dist/runner/workflow-first.js +13 -0
  198. package/dist/runner/workflow-loop.d.ts +2 -1
  199. package/dist/runner/workflow-loop.js +2 -1
  200. package/dist/runner/workflow-spec.js +4 -4
  201. package/dist/runs-over-store.d.ts +39 -8
  202. package/dist/runs-over-store.js +147 -32
  203. package/dist/sdk/check.d.ts +6 -5
  204. package/dist/sdk/check.js +17 -16
  205. package/dist/sdk/runs.d.ts +11 -1
  206. package/dist/sdk/runs.js +185 -78
  207. package/dist/sdk/schema.js +12 -2
  208. package/dist/sdk/workflows.d.ts +1 -1
  209. package/dist/server.d.ts +68 -32
  210. package/dist/server.js +678 -124
  211. package/dist/skills/agentrun-serve/SKILL.md +2 -1
  212. package/dist/source-sync/adoption.d.ts +15 -0
  213. package/dist/source-sync/adoption.js +36 -0
  214. package/dist/source-sync/auxiliary.d.ts +23 -0
  215. package/dist/source-sync/auxiliary.js +64 -0
  216. package/dist/source-sync/capture-git.d.ts +5 -0
  217. package/dist/source-sync/capture-git.js +272 -0
  218. package/dist/source-sync/capture-project.d.ts +53 -0
  219. package/dist/source-sync/capture-project.js +206 -0
  220. package/dist/source-sync/capture-refusal.d.ts +7 -0
  221. package/dist/source-sync/capture-refusal.js +16 -0
  222. package/dist/source-sync/capture.d.ts +11 -0
  223. package/dist/source-sync/capture.js +22 -0
  224. package/dist/source-sync/checkpoint-gate.d.ts +21 -0
  225. package/dist/source-sync/checkpoint-gate.js +52 -0
  226. package/dist/source-sync/checkpoints.d.ts +66 -0
  227. package/dist/source-sync/checkpoints.js +168 -0
  228. package/dist/source-sync/claim.d.ts +11 -0
  229. package/dist/source-sync/claim.js +48 -0
  230. package/dist/source-sync/destination.d.ts +47 -0
  231. package/dist/source-sync/destination.js +239 -0
  232. package/dist/source-sync/io.d.ts +15 -0
  233. package/dist/source-sync/io.js +52 -0
  234. package/dist/source-sync/local.d.ts +43 -0
  235. package/dist/source-sync/local.js +229 -0
  236. package/dist/source-sync/prepare.d.ts +59 -0
  237. package/dist/source-sync/prepare.js +93 -0
  238. package/dist/source-sync/projects.d.ts +61 -0
  239. package/dist/source-sync/projects.js +130 -0
  240. package/dist/source-sync/registry.d.ts +95 -0
  241. package/dist/source-sync/registry.js +226 -0
  242. package/dist/source-sync/service.d.ts +33 -0
  243. package/dist/source-sync/service.js +118 -0
  244. package/dist/source-sync/skill-edits.d.ts +12 -0
  245. package/dist/source-sync/skill-edits.js +122 -0
  246. package/dist/source-sync/snapshots.d.ts +48 -0
  247. package/dist/source-sync/snapshots.js +448 -0
  248. package/dist/source-sync/types.d.ts +9 -0
  249. package/dist/source-sync/types.js +14 -0
  250. package/dist/source-sync/workspace.d.ts +66 -0
  251. package/dist/source-sync/workspace.js +273 -0
  252. package/dist/store/agent-body.d.ts +8 -0
  253. package/dist/store/agent-body.js +20 -6
  254. package/dist/store/index.d.ts +2 -2
  255. package/dist/store/index.js +1 -1
  256. package/dist/store/journal/storage.d.ts +2 -0
  257. package/dist/store/journal/storage.js +2 -1
  258. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  259. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  260. package/dist/store/schema.d.ts +15 -1
  261. package/dist/store/schema.js +43 -4
  262. package/dist/store/seal.d.ts +5 -1
  263. package/dist/store/seal.js +12 -3
  264. package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
  265. package/dist/store/sqlite/project-checkpoints.js +70 -0
  266. package/dist/store/sqlite/run-launch.d.ts +14 -0
  267. package/dist/store/sqlite/run-launch.js +58 -7
  268. package/dist/store/sqlite/run-patch.d.ts +2 -1
  269. package/dist/store/sqlite/run-patch.js +4 -3
  270. package/dist/store/sqlite/store.js +319 -153
  271. package/dist/store/store-schema.js +2 -2
  272. package/dist/store/store.d.ts +173 -33
  273. package/dist/store/store.js +14 -1
  274. package/dist/store-reads/learning.d.ts +12 -8
  275. package/dist/store-reads/learning.js +33 -24
  276. package/dist/store-reads/loop.d.ts +4 -3
  277. package/dist/store-reads/loop.js +7 -5
  278. package/dist/store-view.d.ts +3 -1
  279. package/dist/store-view.js +17 -5
  280. package/dist/template-eval.js +4 -4
  281. package/dist/template-import.d.ts +10 -2
  282. package/dist/template-import.js +116 -13
  283. package/dist/templates.d.ts +29 -5
  284. package/dist/templates.js +68 -14
  285. package/dist/timeline/index.d.ts +1 -1
  286. package/dist/timeline/index.js +1 -1
  287. package/dist/timeline/labels.js +1 -1
  288. package/dist/timeline/timeline.d.ts +5 -0
  289. package/dist/timeline/timeline.js +8 -0
  290. package/dist/tool-plane.d.ts +12 -12
  291. package/dist/tools.d.ts +8 -8
  292. package/dist/tools.js +1 -1
  293. package/dist/trigger-launch-hook.d.ts +47 -0
  294. package/dist/trigger-launch-hook.js +90 -0
  295. package/dist/trigger-targets.d.ts +14 -1
  296. package/dist/trigger-targets.js +20 -0
  297. package/dist/triggers.d.ts +54 -5
  298. package/dist/triggers.js +143 -8
  299. package/dist/uploads-archil.js +2 -1
  300. package/dist/uploads.d.ts +0 -3
  301. package/dist/uploads.js +2 -11
  302. package/dist/validate.js +4 -1
  303. package/dist/web-save.d.ts +3 -0
  304. package/dist/web-save.js +17 -2
  305. package/dist/workspace/archil-exec.js +1 -1
  306. package/dist/workspace/archil.js +1 -1
  307. package/dist/workspace/computer-for-claim.d.ts +2 -0
  308. package/dist/workspace/computer-for-claim.js +43 -0
  309. package/dist/workspace/paths.d.ts +6 -0
  310. package/dist/workspace/paths.js +6 -0
  311. package/dist/workspace/resolve-computer.d.ts +1 -0
  312. package/dist/workspace/revision-skills.js +24 -11
  313. package/dist/workspace/run-tools.d.ts +2 -0
  314. package/dist/workspace/run-tools.js +8 -0
  315. package/dist/workspace/synced-folder.d.ts +3 -3
  316. package/dist/workspace/synced-folder.js +7 -6
  317. package/launcher/agentrun-serve +1 -1
  318. package/package.json +10 -10
  319. package/skills/agentrun-serve/SKILL.md +2 -1
  320. package/templates/README.md +5 -2
  321. package/dist/console/assets/index-Bt1B51b7.js +0 -733
  322. package/dist/console/assets/index-sVftE9Ht.css +0 -1
@@ -7,6 +7,8 @@ type KeyRow = {
7
7
  fields: readonly string[];
8
8
  unlocks: readonly string[];
9
9
  };
10
+ /** Each field of a `tool` row of `rows` that unlocks one of `tools`: the tool keys a run of them reads. */
11
+ export declare const unlockedFields: (tools: readonly string[], rows?: readonly KeyRow[]) => string[];
10
12
  /** What of a revision decides the secrets its runs are handed, none of it a key, read once per revision (a revision
11
13
  * never changes): its harness, the model it names, the tools it binds (an agentic revision's `tools`, a workflow's on
12
14
  * its model nodes and its `call` nodes), a workflow's tiers (those its model nodes and `llm` calls run on), and its
@@ -8,6 +8,7 @@ import { GATEWAY_KEY_ENV, llmTiers, modelKeys, nodeTiers, PROVIDER_KEYS, workflo
8
8
  import { DECISION_KEYS, SECRET_NAMES } from "./secrets.js";
9
9
  import { TOOL_FIELDS, TOOL_KEYS, unlocksTool } from "./tool-keys.js";
10
10
  import { workflowTools } from "./tools.js";
11
+ import { LAUNCH_HOOK_SECRET_ENV } from "./trigger-launch-hook.js";
11
12
  import { ARCHIL_API_KEY_ENV } from "./workspace/archil-key.js";
12
13
  /** The computer providers' account keys a run never gets: every computer key (computer-keys.ts COMPUTER_KEY_NAMES) but
13
14
  * a tool key's field (Browserbase's and Kernel's, which a run's `browser` tool takes when its revision binds it). Only
@@ -16,14 +17,16 @@ const COMPUTER_ACCOUNT_KEYS = COMPUTER_KEY_NAMES.filter((name) => !TOOL_FIELDS.i
16
17
  /** The server's own secrets, which a run never gets: the API token, by name or by value, the seal key the tool keys are
17
18
  * kept under (tool-keys.ts), the store's URL (it may hold the database's password), the remote boxes' keys
18
19
  * (place-offers.ts BOX_KEYS) and every other computer provider's account key, which only the server's and the runner's
19
- * computer providers use, and the Archil account key (archil-key.ts), from which the claim mints each run's own mount
20
- * credential. */
21
- const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_TOKENS", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS, ...COMPUTER_ACCOUNT_KEYS, ARCHIL_API_KEY_ENV]);
20
+ * computer providers use, the Archil account key (archil-key.ts), from which the claim mints each run's own mount
21
+ * credential, and the launch hook's signing secret (trigger-launch-hook.ts). */
22
+ const SERVER_ONLY = new Set(["AGENTRUN_TOKEN", "AGENTRUN_TOKENS", "AGENTRUN_API_KEY", "AGENTRUN_SEAL_KEY", "AGENTRUN_STORE_URL", ...BOX_KEYS, ...COMPUTER_ACCOUNT_KEYS, ARCHIL_API_KEY_ENV, LAUNCH_HOOK_SECRET_ENV]);
22
23
  /** The secrets a run may be handed: every one but the server's own and the decision keys, which go apart. */
23
24
  export const RUN_SECRETS = SECRET_NAMES.filter((name) => !SERVER_ONLY.has(name) && !DECISION_KEYS.includes(name));
24
25
  /** The fields a run gets only when its revision names what they unlock: a `tool` key's. Any other kind's (a model key's)
25
26
  * is the model's to need, as every model key is. */
26
27
  const scopedOf = (rows) => rows.filter((row) => row.kind === "tool").flatMap((row) => row.fields);
28
+ /** Each field of a `tool` row of `rows` that unlocks one of `tools`: the tool keys a run of them reads. */
29
+ export const unlockedFields = (tools, rows = TOOL_KEYS) => [...new Set(rows.filter((row) => row.kind === "tool" && row.unlocks.some((unlock) => tools.some((name) => unlocksTool(unlock, name)))).flatMap((row) => row.fields))];
27
30
  /** The model keys: every key of pi-ai's providers (model.ts' PROVIDER_KEYS) and the gateway's. A run gets those its model
28
31
  * needs and no other (keysFor). A workflow's decision keys, OpenRouter's among them, go apart (decisions.ts), whatever
29
32
  * its model. */
@@ -49,7 +52,7 @@ export async function needsOf(revision) {
49
52
  * (HarnessEntry.ownKeys: Cursor's CURSOR_API_KEY) on a run of any other harness. Read at each claim, so a key saved with no restart counts at
50
53
  * the next. */
51
54
  export function keysFor(needs, env, rows = TOOL_KEYS) {
52
- const unlocked = new Set(rows.filter((row) => row.unlocks.some((unlock) => needs.tools.some((name) => unlocksTool(unlock, name)))).flatMap((row) => row.fields));
55
+ const unlocked = new Set(unlockedFields(needs.tools, rows));
53
56
  const scoped = scopedOf(rows);
54
57
  const entry = harnessOf(env, needs.harness);
55
58
  const model = new Set(!entry || entry.facts ? harnessModelKeys(needs.harness, env, needs.model) : needs.tiers ? modelKeys(env, undefined, needs.tiers) : modelKeys(env, needs.model));
@@ -2,7 +2,7 @@ import { type BrowserSessionLine } from "./browser-sessions.js";
2
2
  import { type CostBasis, type CostWords } from "./runner/metrics.js";
3
3
  import type { RunLaunch } from "./run-launch.js";
4
4
  import { type SignInReader } from "./run-view.js";
5
- import { type ComputerIntervalRow, type Store } from "./store/index.js";
5
+ import { type ComputerIntervalRow, type RunAttemptRow, type Store } from "./store/index.js";
6
6
  import { type ComputeResource, type ComputeUnit } from "./compute-cost.js";
7
7
  import { type EntryLike } from "./timeline/index.js";
8
8
  /** The meters a run's lines are on: the contract's `tokens` and `browser_time`, and this server's `tools` and
@@ -26,6 +26,12 @@ export type RunUsageLine = {
26
26
  quantity: number | null;
27
27
  unit: "token" | "call" | "second" | ComputeUnit;
28
28
  basis: CostBasis;
29
+ /** The attempt at its turn the line's requests were made in (1 the first, 2 its first redo, …); null for a run whose
30
+ * claims kept no attempt. */
31
+ attempt: number | null;
32
+ /** False for an attempt that was cut and whose turn another attempt worked again: its requests were made again, the
33
+ * infrastructure's cost (the run's `infra_usd`), not the task's. Charging does not read it yet. */
34
+ billable: boolean;
29
35
  /** On `compute_time`: the resource (vcpu, memory, gpu, disk), a GPU's type, the part of `quantity` no claim held (in
30
36
  * no cost), and how many of its computers are still open, their time counted up to `measured_to`. */
31
37
  resource?: ComputeResource;
@@ -61,10 +67,14 @@ export type RunUsage = {
61
67
  lines: RunUsageLine[] | null;
62
68
  /** One record per browser session the run opened (browser-sessions.ts), for matching `browser_time` to the provider's
63
69
  * own records by its session id; null exactly when `lines` is. */
64
- browser_sessions: BrowserSessionLine[] | null;
70
+ browser_sessions: RunBrowserSession[] | null;
65
71
  /** One record per computer the run made (computerIntervalsOf), by when each was made; null exactly when `lines` is.
66
72
  * Computer time is not priced: its cost is in no line and not in `total`. */
67
73
  computer_intervals: ComputerIntervalLine[] | null;
74
+ /** The sum of the lines that are not billable (`billable: false`): what the infrastructure's redo of cut attempts cost.
75
+ * 0 for a run no attempt of which was cut; null with no lines, and when one such line's cost is unknown. Inside
76
+ * `total`, never beside it. */
77
+ infra_usd: number | null;
68
78
  reason: UsageReason | null;
69
79
  };
70
80
  /** One computer the run made through its provider (a sandbox, a desktop, a phone), as GET /runs/{run_id}/usage serves
@@ -88,9 +98,38 @@ export type ComputerIntervalLine = {
88
98
  ended_at: string | null;
89
99
  kept: boolean;
90
100
  booked_seconds: number;
101
+ /** The attempt whose claim made the computer, and whether that attempt is billable (RunUsageLine). */
102
+ attempt: number | null;
103
+ billable: boolean;
91
104
  };
92
105
  /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
93
- export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[]): ComputerIntervalLine[];
106
+ export declare function computerIntervalsOf(rows: readonly ComputerIntervalRow[], attempts?: readonly RunAttemptRow[]): ComputerIntervalLine[];
107
+ /** Which attempt a part of a run's usage was made in, and whether it is billable. */
108
+ export type AttemptTag = {
109
+ attempt: number | null;
110
+ billable: boolean;
111
+ };
112
+ /** A run's attempts (`rows`, by epoch) as tags: the attempt a journal entry was written in (the last claim whose first
113
+ * entry id is at or below the entry's), and the one a time falls in (the last claim made at or before it, on the
114
+ * store's clock: a computer is made a moment after its claim). `spans` splits a stretch of time across the claims whose
115
+ * windows it falls in (each claim's window runs from its claim to the next claim's). Every part is billable: a claim
116
+ * that takes over a cut turn resumes from what the cut one saved (its answered requests, its finished calls), so that
117
+ * work is the task's, done once. `redoneAt` is the one exception: the attempt an entry was written in, billable unless
118
+ * another claim worked its turn again after it (the same turn, one attempt more), for a model request that attempt sent
119
+ * and never finished (usageLinesOf), which the claim after it sends again. With no rows (a run from before
120
+ * them), every part is NO_ATTEMPT: attempt null, billable. A part before the first row is NO_ATTEMPT too, unless that
121
+ * row is the run's first claim (taken from queued): then nothing came before it, and a part read a moment early (a
122
+ * runner's clock behind the store's) is that claim's. A run that took its first row after the change that writes them
123
+ * (an older run's follow-up) never counts what it did before as any attempt's. */
124
+ export declare function attemptTags(rows: readonly RunAttemptRow[]): {
125
+ atEntry(id: unknown): AttemptTag;
126
+ redoneAt(id: unknown): AttemptTag;
127
+ atTime(ms: number): AttemptTag;
128
+ spans(from: number, to: number): {
129
+ at: AttemptTag;
130
+ ms: number;
131
+ }[];
132
+ };
94
133
  /** A workflow decision's receipt as the lines read it (store-reads/decisions.ts): by its `decision_id`, which its
95
134
  * request's booking names (`decision:<id>`), the model and provider that answered it, and how its cost was reached. */
96
135
  export type DecisionReceiptLike = {
@@ -107,10 +146,15 @@ export type DecisionReceiptLike = {
107
146
  export declare function usageLinesOf(entries: readonly EntryLike[], launch?: Pick<RunLaunch, "model">, receipts?: ReadonlyMap<string, DecisionReceiptLike>, computers?: {
108
147
  readonly rows: readonly ComputerIntervalRow[];
109
148
  readonly at: number;
110
- }): {
149
+ }, attempts?: readonly RunAttemptRow[]): {
111
150
  lines: RunUsageLine[];
112
151
  total: CostWords;
113
152
  };
153
+ /** A browser session as the usage read serves it: its record (BrowserSessionLine), and the attempt whose claim opened it
154
+ * and whether that attempt is billable (RunUsageLine). */
155
+ export type RunBrowserSession = BrowserSessionLine & AttemptTag;
156
+ /** The sum of the lines no customer is charged for (`billable: false`): null when one of them has no known figure. */
157
+ export declare function infraUsdOf(lines: readonly RunUsageLine[]): number | null;
114
158
  /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
115
159
  * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
116
160
  * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
package/dist/run-usage.js CHANGED
@@ -22,6 +22,13 @@
22
22
  // run's ledger booked for it while a claim held it, so `total` stays the run's `cost.usd`. Time no claim held (a computer
23
23
  // kept for a follow-up, one deleted after its run, one whose delete failed) is said apart (`unheld_quantity`) and costs
24
24
  // nothing on the line or in `total`. A resource with no price is `unpriced`, its `usd` null.
25
+ //
26
+ // Each line is one attempt's (store run_attempts): a claim that was cut (its runner drained, crashed or lost its lease, or
27
+ // its turn was tried again) and whose turn another claim worked again made every request and paid call of it again. Its
28
+ // lines say so (`billable: false`, its `attempt` beside it), apart from the attempt that finished the turn, and the run's
29
+ // `infra_usd` is their sum: the cost of the infrastructure's own redo, not of the run's task. Data only: `total` and
30
+ // `cost.usd` still hold every line, billable or not, as the run was charged before. A run whose claims kept no attempt
31
+ // (one made before them) reads each line's `attempt` as null and every line billable.
25
32
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
26
33
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
27
34
  import { TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
@@ -44,7 +51,8 @@ import { FINAL_STATES } from "./store/index.js";
44
51
  import { COMPUTE_TOOL, COMPUTE_UNITS, computeTag, resourcesOf, unmetered } from "./compute-cost.js";
45
52
  import { TOOL_UNMETERED } from "./timeline/index.js";
46
53
  /** The run's computer rows as served (ComputerIntervalLine), in the order the store reads them (by when each was made). */
47
- export function computerIntervalsOf(rows) {
54
+ export function computerIntervalsOf(rows, attempts = []) {
55
+ const tags = attemptTags(attempts);
48
56
  return rows.map((row) => ({
49
57
  provider: row.provider,
50
58
  provider_id: row.providerId,
@@ -57,8 +65,55 @@ export function computerIntervalsOf(rows) {
57
65
  ended_at: row.endedAt === null ? null : new Date(row.endedAt).toISOString(),
58
66
  kept: row.kept,
59
67
  booked_seconds: row.bookedMs / 1000,
68
+ ...tags.atTime(row.startedAt),
60
69
  }));
61
70
  }
71
+ const NO_ATTEMPT = { attempt: null, billable: true };
72
+ /** A run's attempts (`rows`, by epoch) as tags: the attempt a journal entry was written in (the last claim whose first
73
+ * entry id is at or below the entry's), and the one a time falls in (the last claim made at or before it, on the
74
+ * store's clock: a computer is made a moment after its claim). `spans` splits a stretch of time across the claims whose
75
+ * windows it falls in (each claim's window runs from its claim to the next claim's). Every part is billable: a claim
76
+ * that takes over a cut turn resumes from what the cut one saved (its answered requests, its finished calls), so that
77
+ * work is the task's, done once. `redoneAt` is the one exception: the attempt an entry was written in, billable unless
78
+ * another claim worked its turn again after it (the same turn, one attempt more), for a model request that attempt sent
79
+ * and never finished (usageLinesOf), which the claim after it sends again. With no rows (a run from before
80
+ * them), every part is NO_ATTEMPT: attempt null, billable. A part before the first row is NO_ATTEMPT too, unless that
81
+ * row is the run's first claim (taken from queued): then nothing came before it, and a part read a moment early (a
82
+ * runner's clock behind the store's) is that claim's. A run that took its first row after the change that writes them
83
+ * (an older run's follow-up) never counts what it did before as any attempt's. */
84
+ export function attemptTags(rows) {
85
+ const sorted = [...rows].sort((a, b) => a.epoch - b.epoch);
86
+ const tagOf = (row) => (row === undefined ? NO_ATTEMPT : { attempt: row.attempt, billable: true });
87
+ const redoneOf = (row) => row === undefined ? NO_ATTEMPT : { attempt: row.attempt, billable: !sorted.some((later) => later.epoch > row.epoch && later.turn === row.turn && later.attempt === row.attempt + 1) };
88
+ const last = (fits) => sorted.filter(fits).at(-1);
89
+ const before = sorted[0]?.from === "queued" ? sorted[0] : undefined;
90
+ const entryRow = (id) => {
91
+ const n = Number(id);
92
+ return Number.isFinite(n) ? last((row) => row.journalFrom <= n) ?? before : sorted.at(-1);
93
+ };
94
+ return {
95
+ atEntry: (id) => tagOf(entryRow(id)),
96
+ redoneAt: (id) => redoneOf(entryRow(id)),
97
+ atTime: (ms) => tagOf(last((row) => row.claimedAt <= ms) ?? before),
98
+ spans: (from, to) => {
99
+ if (!(to > from))
100
+ return [{ at: tagOf(last((row) => row.claimedAt <= from) ?? before), ms: 0 }];
101
+ const out = [];
102
+ // The edges of each claim's window, the first one's reaching back to `from` when it is the run's first claim.
103
+ const edges = sorted.map((row, i) => ({ row, start: i === 0 && before ? Number.NEGATIVE_INFINITY : row.claimedAt, end: sorted[i + 1]?.claimedAt ?? Number.POSITIVE_INFINITY }));
104
+ const firstStart = edges[0]?.start ?? Number.POSITIVE_INFINITY;
105
+ if (from < firstStart)
106
+ out.push({ at: NO_ATTEMPT, ms: Math.min(to, firstStart) - from });
107
+ for (const edge of edges) {
108
+ const ms = Math.min(to, edge.end) - Math.max(from, edge.start);
109
+ if (ms > 0)
110
+ out.push({ at: tagOf(edge.row), ms });
111
+ }
112
+ return out;
113
+ },
114
+ };
115
+ }
116
+ const attemptKey = (at) => `${at.attempt ?? ""}:${at.billable ? 1 : 0}`;
62
117
  /** `entries` with the run's booked requests (runner.request and runner.turn) left in only where `keep` says so of its
63
118
  * turn; every other entry (each session's key among them) kept, so bookedSpend reads that part alone. */
64
119
  function onlyRequests(entries, turnOf, keep) {
@@ -96,14 +151,42 @@ function upstreamOf(model, launch) {
96
151
  * provider (`browser_time`); and their join, `total`. A meter with nothing booked has no line. `launch` names the
97
152
  * run's own model's provider; `receipts`, a workflow's decisions by id, the model and provider each was answered on
98
153
  * (its booking names the decision alone), which this server called itself. */
99
- export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }) {
154
+ export function usageLinesOf(entries, launch, receipts = new Map(), computers = { rows: [], at: 0 }, attempts = []) {
100
155
  const conversation = (key) => entries.find((e) => e.kind === KINDS.sessionKey && e.data?.key === key)?.data;
101
156
  const paidConv = Number(conversation(TOOL_SESSION)?.conversation ?? Number.NaN);
102
157
  const conv = (e) => Number(e.conversationId);
103
158
  const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
104
159
  // A line is one meter, one name and, on `tokens`, one route: a model reached two ways (the run's own requests behind a
105
160
  // gateway, a decision on its provider) is two lines, never one labelled with either's provider.
106
- const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}`;
161
+ const keyOf = (group) => `${group.meter}\u0000${group.name ?? ""}\u0000${group.provider ?? ""}\u0000${group.tag ?? ""}\u0000${attemptKey(group.at)}`;
162
+ // Each booked request's attempt: the claim that wrote its first record (its hold, or its booking), never a later
163
+ // claim's settling of it.
164
+ const tags = attemptTags(attempts);
165
+ // A browser charge is the attempt's whose claim wrote it on the root (BROWSER_CHARGED), even when its booking landed
166
+ // under a later claim (browser-cost.ts bookRootCharges books one its process lost): the booking names it by its ref.
167
+ const chargeAt = new Map();
168
+ for (const e of entries) {
169
+ const d = (e.data ?? {});
170
+ if (e.kind === BROWSER_CHARGED && typeof d.tag === "string")
171
+ chargeAt.set(`browser:${d.tag}@${String(d.at)}${d.final ? "/final" : ""}`, tags.atEntry(e.id));
172
+ }
173
+ // A model request its attempt sent and never finished: no answer booked (a crash cut it off), or booked as cut (a stop
174
+ // cut it, at its hold). The claim that takes the turn over sends it again, so when a later claim redid that turn it is
175
+ // the infrastructure's (redoneAt). An answered request, and every paid call, is the task's: the next claim reuses it.
176
+ const answered = new Set();
177
+ for (const e of entries) {
178
+ if (e.kind === RUNNER_RECORDS.turn && e.data?.cut !== true)
179
+ answered.add(turnOf(e));
180
+ }
181
+ const unfinished = (e) => conv(e) !== paidConv && !answered.has(turnOf(e));
182
+ const atOf = new Map();
183
+ for (const e of entries) {
184
+ if (!(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || atOf.has(turnOf(e)))
185
+ continue;
186
+ const ref = e.data?.ref;
187
+ atOf.set(turnOf(e), (typeof ref === "string" ? chargeAt.get(ref) : undefined) ?? (unfinished(e) ? tags.redoneAt(e.id) : tags.atEntry(e.id)));
188
+ }
189
+ const at = (e) => atOf.get(turnOf(e)) ?? tags.atEntry(e.id);
107
190
  // Each booked request's group, by its turn: a model request's or a decision's, the model its runner.request was sent on;
108
191
  // a paid charge's, who charged for it (`charged_by`), on browser_time when it is the browser's session time. A paid
109
192
  // charge settled at its provider's own figure says so on its request (`reported`). A decision's request names the
@@ -121,15 +204,15 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
121
204
  const d = (e.data ?? {});
122
205
  // A computer's time (compute-cost.ts) by its provider and resource (its tag); a browser's by its provider.
123
206
  if (conv(e) === paidConv)
124
- groups.set(turnOf(e), d.tool === COMPUTE_TOOL ? { meter: "compute_time", name: named(d.charged_by), tag: named(d.tag) } : { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by) });
207
+ groups.set(turnOf(e), d.tool === COMPUTE_TOOL ? { meter: "compute_time", name: named(d.charged_by), tag: named(d.tag), at: at(e) } : { meter: d.tool === "browser" ? "browser_time" : "tools", name: named(d.charged_by), at: at(e) });
125
208
  else if (named(d.model)?.startsWith("decision:")) {
126
209
  const receipt = receipts.get(String(d.model).slice("decision:".length));
127
210
  if (receipt && chargedByParallel(receipt)) {
128
- groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER });
211
+ groups.set(turnOf(e), { meter: "tools", name: PARALLEL_CHARGER, at: at(e) });
129
212
  continue;
130
213
  }
131
214
  // A receipt that names no model leaves `model` null: its provider is said as the provider, never as a model.
132
- groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider) } : { meter: "tokens", name: null, provider: null });
215
+ groups.set(turnOf(e), receipt ? { meter: "tokens", name: named(receipt.model), provider: named(receipt.provider), at: at(e) } : { meter: "tokens", name: null, provider: null, at: at(e) });
133
216
  if (receipt?.cost_basis === "reported")
134
217
  reported.add(turnOf(e));
135
218
  else if (receipt?.cost_basis === "estimate")
@@ -141,7 +224,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
141
224
  decisionTokens.set(turnOf(e), { input, output });
142
225
  }
143
226
  else
144
- groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch) });
227
+ groups.set(turnOf(e), { meter: "tokens", name: named(d.model), provider: upstreamOf(named(d.model), launch), at: at(e) });
145
228
  if (d.reported === true)
146
229
  reported.add(turnOf(e));
147
230
  }
@@ -155,7 +238,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
155
238
  for (const e of entries) {
156
239
  if (e.kind !== RUNNER_RECORDS.request && e.kind !== RUNNER_RECORDS.turn)
157
240
  continue;
158
- const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null } : { meter: "tokens", name: null, provider: null });
241
+ const group = groups.get(turnOf(e)) ?? (conv(e) === paidConv ? { meter: "tools", name: null, at: at(e) } : { meter: "tokens", name: null, provider: null, at: at(e) });
159
242
  if (!found.has(keyOf(group)))
160
243
  found.set(keyOf(group), group);
161
244
  turnKeys.set(turnOf(e), keyOf(group));
@@ -174,7 +257,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
174
257
  for (const e of entries) {
175
258
  const d = (e.data ?? {});
176
259
  if (e.kind === TOOL_UNMETERED) {
177
- const group = { meter: "tools", name: named(d.charged_by) };
260
+ const group = { meter: "tools", name: named(d.charged_by), at: tags.atEntry(e.id) };
178
261
  unpricedCalls.set(keyOf(group), (unpricedCalls.get(keyOf(group)) ?? 0) + 1);
179
262
  if (!found.has(keyOf(group)))
180
263
  found.set(keyOf(group), group);
@@ -182,7 +265,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
182
265
  }
183
266
  if (e.kind !== BROWSER_CHARGED || d.tool !== "browser" || typeof d.seconds !== "number" || !Number.isFinite(d.seconds))
184
267
  continue;
185
- const group = { meter: "browser_time", name: named(d.charged_by) };
268
+ const group = { meter: "browser_time", name: named(d.charged_by), at: tags.atEntry(e.id) };
186
269
  seconds.set(keyOf(group), (seconds.get(keyOf(group)) ?? 0) + d.seconds);
187
270
  if (!found.has(keyOf(group)))
188
271
  found.set(keyOf(group), group);
@@ -198,7 +281,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
198
281
  if (group.meter === "compute_time") {
199
282
  // A hold for a stretch names no resource (no tag) and books nothing: it is given back.
200
283
  if (group.tag !== null && group.tag !== undefined)
201
- computeBooked.set(computeKey(group.name ?? "", group.tag), booked);
284
+ computeBooked.set(computeKey(group.name ?? "", group.tag, group.at), { booked, at: group.at });
202
285
  continue;
203
286
  }
204
287
  const notMetered = unpricedCalls.get(key);
@@ -216,7 +299,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
216
299
  const unmetered = Math.max(0, booked.unmetered - told.filter((turn) => noUsage.has(turn)).length);
217
300
  // A decision's booking keeps no price table's mark: its receipt says how its cost was reached.
218
301
  const priced = { reported: booked.priced.reported + turns.filter((turn) => reported.has(turn)).length, estimated: booked.priced.estimated + turns.filter((turn) => estimated.has(turn)).length };
219
- lines.push({ meter: "tokens", model: group.name, provider: group.provider ?? null, charged_by: null, quantity: input + output + cacheRead + cacheWrite, unit: "token", basis: costBasisOf({ priced }), ...costWordsOf(booked.parts), requests: booked.requests, tokens: { input, output, cache_read: cacheRead, cache_write: cacheWrite }, unmetered_requests: unmetered });
302
+ lines.push({ meter: "tokens", model: group.name, provider: group.provider ?? null, charged_by: null, quantity: input + output + cacheRead + cacheWrite, unit: "token", basis: costBasisOf({ priced }), ...group.at, ...costWordsOf(booked.parts), requests: booked.requests, tokens: { input, output, cache_read: cacheRead, cache_write: cacheWrite }, unmetered_requests: unmetered });
220
303
  }
221
304
  else if (group.meter === "tools") {
222
305
  // `reported` when every charge with a figure was settled at its provider's own (monid's answer says what it
@@ -225,7 +308,7 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
225
308
  const basis = priced <= 0 ? "unpriced" : turns.every((turn) => reported.has(turn)) ? "reported" : "estimate";
226
309
  // Calls that ran unpriced only: none booked, so nothing is charged on the line, by its owner's choice of no price.
227
310
  const words = booked.requests === 0 ? { usd: 0 } : costWordsOf(booked.parts);
228
- lines.push({ meter: "tools", model: null, provider: group.name, charged_by: group.name, quantity: booked.requests, unit: "call", basis, ...words, ...(notMetered ? { not_metered_calls: notMetered } : {}) });
311
+ lines.push({ meter: "tools", model: null, provider: group.name, charged_by: group.name, quantity: booked.requests, unit: "call", basis, ...group.at, ...words, ...(notMetered ? { not_metered_calls: notMetered } : {}) });
229
312
  }
230
313
  else {
231
314
  const s = seconds.get(key);
@@ -235,10 +318,10 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
235
318
  continue;
236
319
  // A browser provider whose time no charge booked (none, or each given back) still ran: its seconds with no figure.
237
320
  const words = booked.requests === 0 ? { usd: null } : costWordsOf(booked.parts);
238
- lines.push({ meter: "browser_time", model: null, provider: group.name, charged_by: null, quantity: s === undefined ? null : Math.round(s * 1e6) / 1e6, unit: "second", basis: priced > 0 ? "estimate" : "unpriced", ...words });
321
+ lines.push({ meter: "browser_time", model: null, provider: group.name, charged_by: null, quantity: s === undefined ? null : Math.round(s * 1e6) / 1e6, unit: "second", basis: priced > 0 ? "estimate" : "unpriced", ...group.at, ...words });
239
322
  }
240
323
  }
241
- lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked));
324
+ lines.push(...computeLinesOf(computers.rows, computers.at, computeBooked, tags.spans));
242
325
  // Each meter by its name (a model, a charger, a browser provider; none first), `tokens` then by its route's provider,
243
326
  // `compute_time` then by its resource in compute-cost.ts's order and a GPU's type.
244
327
  const sortKey = (line) => line.meter === "tokens"
@@ -248,7 +331,9 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
248
331
  : line.meter === "compute_time"
249
332
  ? `${line.provider ?? ""}\u0000${RESOURCE_ORDER[line.resource ?? "vcpu"]}\u0000${line.gpu_type ?? ""}`
250
333
  : line.provider ?? "";
251
- lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0));
334
+ // Then by attempt, a line of no attempt first, and a cut attempt's before the billable one of the same number.
335
+ const attemptOrder = (line) => (line.attempt ?? 0) * 2 + (line.billable ? 1 : 0);
336
+ lines.sort((a, b) => ORDER[a.meter] - ORDER[b.meter] || (sortKey(a) < sortKey(b) ? -1 : sortKey(a) > sortKey(b) ? 1 : 0) || attemptOrder(a) - attemptOrder(b));
252
337
  // The join over the whole booking, never the lines' rounded figures: the same figure cost.usd is. A browser line whose
253
338
  // time no charge booked is unknown beside it: the total is too, with the booking's figure as what is known.
254
339
  const total = costWordsOf([bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")]);
@@ -258,8 +343,8 @@ export function usageLinesOf(entries, launch, receipts = new Map(), computers =
258
343
  const known = total.usd ?? total.so_far_usd ?? 0;
259
344
  return { lines, total: { usd: null, so_far_usd: known, unpriced: (total.usd === null ? (total.unpriced ?? 0) : 0) + unbooked } };
260
345
  }
261
- /** A compute line's key: its provider and its resource's tag (computeTag). */
262
- const computeKey = (provider, tag) => `${provider}\u0000${tag}`;
346
+ /** A compute line's key: its provider, its resource's tag (computeTag) and its attempt. */
347
+ const computeKey = (provider, tag, at) => `${provider}\u0000${tag}\u0000${attemptKey(at)}`;
263
348
  const RESOURCE_ORDER = { vcpu: 0, memory: 1, gpu: 2, disk: 3 };
264
349
  /** Up to the millionth, as the browser's seconds are. */
265
350
  const micro = (value) => Math.round(value * 1e6) / 1e6;
@@ -267,23 +352,32 @@ const micro = (value) => Math.round(value * 1e6) / 1e6;
267
352
  * its figure, an open one's up to `at` (the read), and the part no claim held (its life less its booked time) apart in
268
353
  * `unheld_quantity`. Its money is what the run's ledger booked for it (`booked`, by computeKey): `estimate` when any was;
269
354
  * $0 for a provider that bills nothing; else `unpriced`, its usd null. A figure no one said makes its quantity null. */
270
- function computeLinesOf(rows, at, booked) {
355
+ function computeLinesOf(rows, at, booked, spans) {
271
356
  const sums = new Map();
272
357
  for (const row of rows) {
273
- const livedS = Math.max(0, (row.endedAt ?? at) - row.startedAt) / 1000;
358
+ const end = row.endedAt ?? at;
359
+ const livedS = Math.max(0, end - row.startedAt) / 1000;
274
360
  const unheldS = Math.max(0, livedS - row.bookedMs / 1000);
275
- for (const one of resourcesOf(row)) {
276
- const key = computeKey(row.provider, computeTag(one));
277
- const sum = sums.get(key) ?? { provider: row.provider, resource: one.resource, gpuType: one.gpuType, quantity: 0, unheld: 0, open: 0 };
278
- sum.quantity = sum.quantity === null || one.perSecond === null ? null : sum.quantity + one.perSecond * livedS;
279
- sum.unheld = sum.unheld === null || one.perSecond === null ? null : sum.unheld + one.perSecond * unheldS;
280
- if (row.endedAt === null)
281
- sum.open += 1;
282
- sums.set(key, sum);
361
+ // Its time is the claims' that held it, by each claim's window (a computer kept across a park is billed by the claim
362
+ // that resumed it), so each stretch sits with the attempt whose bookings paid for it. The part no claim held is kept
363
+ // per computer alone: it is spread over the windows by their share of its life.
364
+ const pieces = spans(row.startedAt, end);
365
+ for (const span of pieces) {
366
+ const share = livedS > 0 ? span.ms / 1000 / livedS : 1;
367
+ for (const one of resourcesOf(row)) {
368
+ const key = computeKey(row.provider, computeTag(one), span.at);
369
+ const sum = sums.get(key) ?? { provider: row.provider, resource: one.resource, gpuType: one.gpuType, quantity: 0, unheld: 0, open: 0, at: span.at };
370
+ sum.quantity = sum.quantity === null || one.perSecond === null ? null : sum.quantity + one.perSecond * (span.ms / 1000);
371
+ sum.unheld = sum.unheld === null || one.perSecond === null ? null : sum.unheld + one.perSecond * unheldS * share;
372
+ // An open computer counts once, on the line of the window it is in now.
373
+ if (row.endedAt === null && span === pieces.at(-1))
374
+ sum.open += 1;
375
+ sums.set(key, sum);
376
+ }
283
377
  }
284
378
  }
285
379
  // A booking whose computer has no row here (one made before this server kept them): its money, with no quantity.
286
- for (const key of booked.keys()) {
380
+ for (const [key, one] of booked) {
287
381
  if (sums.has(key))
288
382
  continue;
289
383
  const [provider = "", tag = ""] = key.split("\u0000");
@@ -291,16 +385,16 @@ function computeLinesOf(rows, at, booked) {
291
385
  const resource = (gpu ? "gpu" : tag);
292
386
  if (!Object.hasOwn(COMPUTE_UNITS, resource))
293
387
  continue;
294
- sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0 });
388
+ sums.set(key, { provider, resource, gpuType: gpu ? tag.slice("gpu:".length) : null, quantity: null, unheld: null, open: 0, at: one.at });
295
389
  }
296
390
  return [...sums.entries()].map(([key, sum]) => {
297
- const spend = booked.get(key);
391
+ const spend = booked.get(key)?.booked;
298
392
  const charged = spend !== undefined && spend.requests > 0;
299
393
  const free = !charged && unmetered(sum.provider);
300
394
  const words = charged ? costWordsOf(spend.parts) : free ? { usd: 0 } : { usd: null };
301
395
  return {
302
396
  meter: "compute_time", model: null, provider: sum.provider, charged_by: sum.provider,
303
- quantity: sum.quantity === null ? null : micro(sum.quantity), unit: COMPUTE_UNITS[sum.resource], basis: charged || free ? "estimate" : "unpriced", ...words,
397
+ quantity: sum.quantity === null ? null : micro(sum.quantity), unit: COMPUTE_UNITS[sum.resource], basis: charged || free ? "estimate" : "unpriced", ...sum.at, ...words,
304
398
  resource: sum.resource, gpu_type: sum.gpuType, unheld_quantity: sum.unheld === null ? null : micro(sum.unheld), open_computers: sum.open,
305
399
  ...(sum.open > 0 ? { measured_to: new Date(at).toISOString() } : {}),
306
400
  };
@@ -310,16 +404,37 @@ function computeLinesOf(rows, at, booked) {
310
404
  * turn), each with its end read from the whole journal (`all`). The run's end lets its browsers go inside the learning
311
405
  * turn's range (reflectRanges runs to the run's end), so an end read from `job` alone would be missing for a session
312
406
  * released there. A session the learning turn opened is not the job's, as its cost is not. */
313
- function jobSessions(job, all) {
407
+ function jobSessions(job, all, attempts = []) {
314
408
  const ends = new Map(browserSessionsOf(all).map((one) => [one.tag, one]));
409
+ // A session is the attempt's whose claim first wrote of it (its open, else its first charge).
410
+ const tags = attemptTags(attempts);
411
+ const first = new Map();
412
+ for (const e of job) {
413
+ const tag = e.data?.tag;
414
+ if (typeof tag === "string" && !first.has(tag))
415
+ first.set(tag, tags.atEntry(e.id));
416
+ }
315
417
  return browserSessionsOf(job).map((one) => {
418
+ const at = first.get(one.tag) ?? NO_ATTEMPT;
316
419
  const whole = ends.get(one.tag);
317
420
  if (one.ended_at !== null || !whole || whole.ended_at === null)
318
- return one;
421
+ return { ...one, ...at };
319
422
  const { provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status } = whole;
320
- return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status };
423
+ return { ...one, provider: one.provider || whole.provider, provider_session_id, started_at, ended_at, release_reason, provider_record, provider_record_status, ...at };
321
424
  });
322
425
  }
426
+ /** The sum of the lines no customer is charged for (`billable: false`): null when one of them has no known figure. */
427
+ export function infraUsdOf(lines) {
428
+ let sum = 0;
429
+ for (const line of lines) {
430
+ if (line.billable)
431
+ continue;
432
+ if (line.usd === null)
433
+ return null;
434
+ sum += line.usd;
435
+ }
436
+ return Math.round(sum * 1e12) / 1e12;
437
+ }
323
438
  /** Run `runId`'s usage lines (GET /runs/{run_id}/usage); undefined for an unknown run. No lines (`reason`) while it is at
324
439
  * work, for a run whose figure is not its booking's, and for a learning run a follow-up opened again: the cases where
325
440
  * `cost.tools_usd` is null for the same reasons. Its state, launch, learning rounds and journal are read in one snapshot
@@ -330,7 +445,7 @@ export async function runUsageOverStore(store, runId) {
330
445
  if (!run)
331
446
  return undefined;
332
447
  const ended = FINAL_STATES.includes(run.state) && run.endedAt !== null ? new Date(run.endedAt).toISOString() : null;
333
- const none = (reason) => ({ run_id: runId, ended_at: reason === "running" ? null : ended, currency: "USD", total: null, lines: null, browser_sessions: null, computer_intervals: null, reason });
448
+ const none = (reason) => ({ run_id: runId, ended_at: reason === "running" ? null : ended, currency: "USD", total: null, lines: null, browser_sessions: null, computer_intervals: null, infra_usd: null, reason });
334
449
  if (!FINAL_STATES.includes(run.state))
335
450
  return none("running");
336
451
  const launch = await launchOf(snapshot, runId);
@@ -348,9 +463,11 @@ export async function runUsageOverStore(store, runId) {
348
463
  // Its computers in the same snapshot, an open one's time counted up to now; a store that keeps none (a test's) reads
349
464
  // as none made.
350
465
  const rows = snapshot.computerIntervals ? await snapshot.computerIntervals.forRun(runId) : [];
351
- const { lines, total } = usageLinesOf(entries, launch, receipts, { rows, at: Date.now() });
352
- const computers = computerIntervalsOf(rows);
353
- return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries), computer_intervals: computers, reason: null };
466
+ // Its claims' attempts in the same snapshot; a store that keeps none (a test's) reads as a run of no attempts.
467
+ const attempts = snapshot.runAttempts ? await snapshot.runAttempts.forRun(runId) : [];
468
+ const { lines, total } = usageLinesOf(entries, launch, receipts, { rows, at: Date.now() }, attempts);
469
+ const computers = computerIntervalsOf(rows, attempts);
470
+ return { run_id: runId, ended_at: ended, currency: "USD", total, lines, browser_sessions: jobSessions(entries, records.entries, attempts), computer_intervals: computers, infra_usd: infraUsdOf(lines), reason: null };
354
471
  });
355
472
  }
356
473
  /** Run `runId`'s usage lines as served: each name taken from its record (a model, its provider, a tool's charger) through
@@ -10,6 +10,20 @@ import type { CostParts } from "@parcha/agentrun-kernel";
10
10
  /** The sign-in read surface a run's served view needs: a run's handed-pointer cut reads only `peek` (the agent's saved
11
11
  * pointer) and `forgotten` (its tombstoned ones), over the store (sign-ins-store.ts signInReads). */
12
12
  export type SignInReader = ReturnType<typeof signInReads>;
13
+ /** How a run wound down for its spend cap (`max_cost_usd`), from its journal's root entries: the tool calls the cap's
14
+ * wrap-up refused (CAP_REFUSED, each call once however often it was refused: a replay is the same call), and whether it
15
+ * wound down under the cap it has now (`capUsd`, its newest raise's, else its start's): its model was told to wrap up
16
+ * under that cap (a CAP_WRAPUP naming it; the free-request limit's note names none, and is no dollar cap's), or a call
17
+ * was refused under it. A cap raised past a wrap-up is a new cap the run has not wound down under. `skip`: entries not
18
+ * the job's (its end-of-run turn's), which count for neither. The view's `stopped_for` and `budget_refused_calls`. */
19
+ export declare function windDownOf(entries: readonly {
20
+ readonly kind?: string;
21
+ readonly id?: unknown;
22
+ readonly data?: unknown;
23
+ }[], capUsd: number | undefined, skip?: (id: number) => boolean): {
24
+ readonly refusedCalls: number;
25
+ readonly woundDown: boolean;
26
+ };
13
27
  /** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
14
28
  export declare const costOf: (rows: readonly TimelineEvent[]) => number | null;
15
29
  /** The run's cost in its usage row's own words (a bound with its exact part and holds, an unknown cost with what is
@@ -55,7 +69,7 @@ export type Status = "queued" | "working" | "paused" | "input_required" | "compl
55
69
  export type State = "working" | "waiting" | "idle";
56
70
  /** A tool call that waited for a person's approval, as the run's store has it (tool-gate.ts): `resolved` once the run's
57
71
  * process acted on the answer. */
58
- /** `asks_because`: why the gate asked a call its setting allows (its card's ASKED_BECAUSE), kept out of `args_json`. */
72
+ /** `asks_because`: why the gate asked a call its setting allows (its ask's own `because`, never one of the call's arguments). */
59
73
  export type Approval = {
60
74
  id: string;
61
75
  tool: string;
@@ -337,6 +351,9 @@ export interface RunMoment {
337
351
  readonly id: string;
338
352
  readonly agentId: string;
339
353
  readonly kind: "agentic" | "workflow";
354
+ /** The harness its revision names (run.harness): a trigger's message to a run on a plan-billed recipe is refused
355
+ * (trigger-targets.ts). Absent only where a caller builds a moment by hand. */
356
+ readonly harness?: string;
340
357
  /** Where an imported run came from (run.imported?.source); absent for a run started here. An imported run takes no act. */
341
358
  readonly importedSource?: string;
342
359
  /** A cancel is in flight (run.cancel), whether or not its end is written yet. */
package/dist/run-view.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // The pieces here so far: the cost reads (a run's cost, its paid tools' charges, the cost a view shows, what it has cost so
7
7
  // far when the total is unknown) and the served row transforms a view applies to the timeline (the over-cap row, the
8
8
  // paused run's waiting row). All read the same rows the timeline renders.
9
- import { chargedTool, isMessageRow, NOTE_SUFFIX, registerLabel, registerTurnEnding, scrubUrls } from "./timeline/index.js";
9
+ import { CAP_REFUSED, CAP_WRAPUP, chargedTool, isMessageRow, NOTE_SUFFIX, registerLabel, registerTurnEnding, scrubUrls } from "./timeline/index.js";
10
10
  import { CAP_TOLERANCE, FIT_TOLERANCE, money, roomRefusal } from "./cap.js";
11
11
  import { APPROVAL_ROW, previewOf } from "./tool-gate.js";
12
12
  import { ASK_TOOL, toolOf } from "./tools.js";
@@ -17,8 +17,30 @@ import { pointerHash } from "./sign-ins-store.js";
17
17
  import { MIN_SECRET } from "./learn/secrets.js";
18
18
  import { costWordsOf, usageParts } from "./runner/metrics.js";
19
19
  import { KINDS } from "./runner/journal-kinds.js";
20
- import { ASKED_BECAUSE, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
21
- import { isObject } from "./validate.js";
20
+ import { ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "./refusal-words.js";
21
+ /** How a run wound down for its spend cap (`max_cost_usd`), from its journal's root entries: the tool calls the cap's
22
+ * wrap-up refused (CAP_REFUSED, each call once however often it was refused: a replay is the same call), and whether it
23
+ * wound down under the cap it has now (`capUsd`, its newest raise's, else its start's): its model was told to wrap up
24
+ * under that cap (a CAP_WRAPUP naming it; the free-request limit's note names none, and is no dollar cap's), or a call
25
+ * was refused under it. A cap raised past a wrap-up is a new cap the run has not wound down under. `skip`: entries not
26
+ * the job's (its end-of-run turn's), which count for neither. The view's `stopped_for` and `budget_refused_calls`. */
27
+ export function windDownOf(entries, capUsd, skip) {
28
+ const underCap = (cap) => capUsd !== undefined && typeof cap === "number" && Math.abs(cap - capUsd) <= CAP_TOLERANCE;
29
+ const calls = new Set();
30
+ let woundDown = false;
31
+ for (const entry of entries) {
32
+ if (entry.kind !== CAP_REFUSED && entry.kind !== CAP_WRAPUP)
33
+ continue;
34
+ if (skip?.(Number(entry.id)))
35
+ continue;
36
+ const data = (entry.data ?? {});
37
+ if (entry.kind === CAP_REFUSED && typeof data.callId === "string")
38
+ calls.add(data.callId);
39
+ if (underCap(data.capUsd))
40
+ woundDown = true;
41
+ }
42
+ return { refusedCalls: calls.size, woundDown };
43
+ }
22
44
  /** The run's newest usage row, which carries its cost. */
23
45
  const usageOf = (rows) => rows.findLast((r) => r.kind === "usage");
24
46
  /** The run's cost from its usage row: null when a response's cost is unknown, 0 before any request. */
@@ -136,15 +158,12 @@ export function asksOf(entries) {
136
158
  if (typeof d?.callId !== "string" || map.has(d.callId))
137
159
  continue;
138
160
  const price = priceOfAsk(d.price);
139
- // The card's reason for asking a call its setting allows is the gate's, never one of the call's arguments.
140
- const raw = d.args ?? {};
141
- const { [ASKED_BECAUSE]: because, ...args } = isObject(raw) ? raw : {};
142
161
  map.set(d.callId, {
143
162
  id: d.callId,
144
163
  tool: d.tool,
145
164
  call_id: d.callId,
146
- args_json: JSON.stringify(isObject(raw) ? args : raw) ?? "{}",
147
- ...(typeof because === "string" ? { asks_because: because } : {}),
165
+ args_json: JSON.stringify(d.args ?? {}) ?? "{}",
166
+ ...(typeof d.because === "string" ? { asks_because: d.because } : {}),
148
167
  requested_at: d.requestedAt,
149
168
  ...(price !== undefined ? { price } : {}),
150
169
  ...(d.destructive === true ? { destructive: true } : {}),
@@ -480,6 +499,7 @@ export function momentOf(run, facts, live) {
480
499
  id: run.id,
481
500
  agentId: run.agentId,
482
501
  kind: run.kind,
502
+ harness: run.harness,
483
503
  ...(run.imported ? { importedSource: run.imported.source } : {}),
484
504
  cancelled: run.cancel,
485
505
  terminal,