@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/cap.js ADDED
@@ -0,0 +1,721 @@
1
+ // A run's spend cap (`max_cost_usd`), held in the run's own process, where its model requests are sent. Before each
2
+ // request, what the run has spent plus the request's worst case must stay within the cap. The worst case is the request's
3
+ // input bound (inputBound: one token per UTF-8 byte of what is sent, plus what the provider adds server-side) at the
4
+ // higher of the model's input and cache-write prices, plus the output it is sent with at the output price, plus any fee
5
+ // its tokens do not show (pi's own search request's). Each request is limited to the output what is left of the cap can
6
+ // buy (thinking included, never more than it asks for), and held at that: the limit is the wire's (pi's options, the
7
+ // model proxy's body for claude-agent and codex), so the cap stays exact. Only when what is left cannot buy its least (1,024
8
+ // tokens for the answer, and its thinking's least, leastOutput) is it not sent, and the run's turn ends on a model error
9
+ // the server reads as `spend_cap_reached`, saying in plain words what was spent and what the request needs. A model serve has
10
+ // no price for cannot be kept within a cap, so under one its requests are refused; a model listed at $0 is a known $0. What the run has
11
+ // spent is read back from its store when the process starts, so it survives a restart, plus each response since; a
12
+ // request in flight holds its worst case until it answers. A request the person stopped before its end counts at its input,
13
+ // what it streamed (one token a byte) and STOP_ALLOWANCE_TOKENS of output the provider may have produced after the last
14
+ // word read, never more than its worst case: a cut stream's own usage is not what it charged, and its worst case, once
15
+ // the request is limited to what is left, is the rest of the cap. One that ended on an error after its response began
16
+ // counts at its worst case. The figure is written on the request's end mark (request-start.ts), so a later process
17
+ // counts it the same. Nor can a spend no one
18
+ // knows (a request a crash cut, a cost that is not a number) or a model whose output is priced and that has no output
19
+ // ceiling be kept within a cap: under one, each refuses the request, never passes as $0.
20
+ // A request carrying a native web search tool reads pages into its input that its body does not hold: on claude-agent
21
+ // its bound is its body's plus a stated allowance (NATIVE_SEARCH_ALLOWANCE_TOKENS, which its adapter adds, adapters.ts),
22
+ // and pi's own search request is held at its context plus HOSTED_SEARCH_ALLOWANCE_TOKENS and its most fee; what it
23
+ // cost, booked once it answers, stops the next request. A run whose booked spend passes its cap shows by how much on its
24
+ // timeline (runs.ts withOverCap).
25
+ //
26
+ // A paid tool's charge (monid.run's, monid.ts) is the run's spend too: booked in the run's store as a TOOL_COST, which
27
+ // the run's cost and spentIn both count, and added to what the run's process counts as spent (useSpend), so the next
28
+ // request's check sees it. A charge the call does not say (null: stopped, timed out, failed with no cost) leaves the
29
+ // run's cost unknown, and the cap counts the call at what it was held at, the bound it let the call go at, as it counts
30
+ // one a crash cut: in the run's process and from its mark in the store. Before each paid call, paidCall holds it as a
31
+ // request is held: refused unless what the run has spent plus what the call is held at (its quote, else an allowance)
32
+ // fits the cap, and whenever the spend is unknown; paid calls go one at a time, so each check sees the charge before
33
+ // it. A call sent holds its figure until its charge joins the spend (paidHolds), so a model request judged meanwhile, on
34
+ // pi or on another harness, counts it beside the spend, as a paid call's check counts the model requests in flight.
35
+ import { DatabaseSync } from "node:sqlite";
36
+ import { existsSync } from "node:fs";
37
+ import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
38
+ import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
39
+ /** A run's cap in USD, passed to its process. */
40
+ export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
41
+ /** How a request the cap refused begins its error, which the server ends the run with. */
42
+ export const SPEND_CAP_REACHED = "spend_cap_reached";
43
+ /** The option a request's worst case rides on from the cap to its marks (request-start.ts): what the cap held for it. A
44
+ * symbol, so no provider ever sends it. */
45
+ export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
46
+ /** pi's messages for requests that ended on an error after their response had begun (an event came in first), as the
47
+ * marks (request-start.ts) saw them: each left and the provider may have billed what it generated, so it counts at its
48
+ * hold, as one stopped does. An error before any event (refused at the HTTP level: a 429, a 5xx) counts at its own
49
+ * usage. Kept by identity, never on the message: pi writes the message to the store as strict JSON, which fails on a
50
+ * symbol key. */
51
+ const responseBegan = new WeakSet();
52
+ /** Records that `message` ended on an error after its response began. */
53
+ export const markResponseBegan = (message) => void responseBegan.add(message);
54
+ /** The field of a request's end mark (REQUEST_ENDED) that says what the cap held for it, when its stream ended aborted
55
+ * or its summary failed: the request counts at that figure. Optional: an end with none (an older store, a run with no
56
+ * cap) leaves the request cut, at an unknown cost. */
57
+ export const HELD_FIELD = "heldUsd";
58
+ /** The field of the start mark (REQUEST_STARTED) written for a request this cap refused: it never left, and pi's error
59
+ * entry for it answers this mark, never an earlier request's. */
60
+ export const CAP_REFUSED_FIELD = "capRefused";
61
+ /** The option a request the cap limited rides on to its start mark (request-start.ts, as `clamp`): the output tokens it was
62
+ * limited to, what was left of the cap for it, and the cap, so a reply cut short there says so. */
63
+ export const CLAMP = Symbol.for("agentrun.serve.clamp");
64
+ /** The tokens a limited request keeps for its answer (pi-ai's MIN_ANSWER_TOKENS): a request is refused, never sent, when
65
+ * what is left of its cap cannot buy them (or what it asked for, when it asked for fewer). */
66
+ export const ANSWER_TOKENS_LEAST = 1024;
67
+ /** The least thinking budget Anthropic takes: a request that thinks on an API whose thinking takes a budget keeps it
68
+ * beside its answer, the budget squeezed to it at the least. */
69
+ export const THINKING_BUDGET_LEAST = 1024;
70
+ /** The APIs whose thinking takes a token budget added to the request's own output limit (pi-ai's
71
+ * adjustMaxTokensForThinking). Elsewhere a model's reasoning shares the output limit and takes no budget, so it is
72
+ * allowed its thinking level's budget beside the answer, else it comes back incomplete with no answer. */
73
+ const BUDGET_APIS = new Set(["anthropic-messages", "bedrock-converse-stream"]);
74
+ /** The output tokens a request the person stopped counts beyond what it streamed: what the provider may have produced after
75
+ * the last word read, before it saw the stop. A stopped request counts its input, each byte it streamed as a token, and
76
+ * these, never more than it was held at (stoppedFigure). A stated bound, as NATIVE_SEARCH_ALLOWANCE_TOKENS is. */
77
+ export const STOP_ALLOWANCE_TOKENS = 1024;
78
+ /** The option a request's stopped figure rides on to its end mark (request-start.ts): what it counts at, given the answer
79
+ * it streamed, when it is stopped before its end. A symbol, so no provider ever sends it. */
80
+ export const STOPPED_USD = Symbol.for("agentrun.serve.stopped_usd");
81
+ /** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. Each
82
+ * byte counts as a token (a byte-level tokenizer never makes a token of less than one byte), as inputBound counts input. */
83
+ export function streamedBytes(message) {
84
+ const blocks = Array.isArray(message?.content) ? message.content : [];
85
+ let bytes = 0;
86
+ for (const block of blocks) {
87
+ if (typeof block?.text === "string")
88
+ bytes += Buffer.byteLength(block.text, "utf8");
89
+ if (typeof block?.thinking === "string")
90
+ bytes += Buffer.byteLength(block.thinking, "utf8");
91
+ if (block?.type === "toolCall")
92
+ bytes += Buffer.byteLength(`${typeof block.name === "string" ? block.name : ""}${JSON.stringify(block.arguments ?? {})}`, "utf8");
93
+ }
94
+ return bytes;
95
+ }
96
+ /** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
97
+ * at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
98
+ export const stoppedFigure = (cost, limit, worst, streamed) => Math.min(worst, cost(Math.min(limit, streamed + STOP_ALLOWANCE_TOKENS)));
99
+ /** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
100
+ * request never left, so the entry answers none, and spentIn leaves it out by this. */
101
+ export const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
102
+ /** The input a request carrying claude-agent's native web search may read in beyond its body, added to its input bound
103
+ * by its adapter (adapters.ts hands it over): Claude's CLI asks for at most 8 searches a request (max_uses 8), and each
104
+ * search's results are billed as input, about 25,000 tokens a search as a working estimate. */
105
+ export const NATIVE_SEARCH_ALLOWANCE_TOKENS = 8 * 25_000;
106
+ export const sideRequests = new WeakMap();
107
+ /** The run's cap from its process's environment; absent for a run without one. */
108
+ export function capOf(env) {
109
+ const text = env[CAP_ENV];
110
+ if (text === undefined || text === "")
111
+ return undefined;
112
+ const cap = Number(text);
113
+ if (!(Number.isFinite(cap) && cap > 0))
114
+ throw new Error(`${CAP_ENV} is ${text}, not a number above 0`);
115
+ return cap;
116
+ }
117
+ /** The code a cap's refusal begins with: `spend_cap_reached: `, or with a note after it, as a request it limited refuses
118
+ * in (CAP_REFUSAL_CODE, "spend_cap_reached (out of budget): "). Every reader of a refusal's text (a run's end, its
119
+ * learning, the spend read back) reads the code through this, never a bare prefix. */
120
+ export const CAP_REFUSAL_PREFIX = /^spend_cap_reached(?: \([^)]*\))?: /;
121
+ /** Whether `entry` is pi's answer to a request this cap refused (capModels): an error that begins spend_cap_reached. */
122
+ const refusedHere = (entry) => {
123
+ const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
124
+ return message?.stopReason === "error" && typeof message.errorMessage === "string" && CAP_REFUSAL_PREFIX.test(message.errorMessage);
125
+ };
126
+ /** Whether `entry` is pi's error for a request whose start mark could not be written (request-start.ts, MARK_NOT_WRITTEN):
127
+ * it never left and has no mark of its own, so it answers no request, and read as an answer it would close another's. */
128
+ const notSentHere = (entry) => {
129
+ const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
130
+ return message?.stopReason === "error" && typeof message.errorMessage === "string" && message.errorMessage.startsWith(MARK_NOT_WRITTEN);
131
+ };
132
+ /** The cost an entry adds to what a run spent, as the timeline counts it: a pi answer's total (none for one stopped
133
+ * before its end), and the usd of a cost written apart from an answer, a paid tool's charge among them; 0 for anything
134
+ * else, or for a cost that is not a number (which makes the whole spend unknown, by the timeline's verdict). */
135
+ const costOf = (entry) => {
136
+ const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
137
+ const cost = message ? (message.stopReason === "aborted" ? undefined : message.usage?.cost?.total)
138
+ : entry.kind === REQUEST_COST || entry.kind === REQUEST_COST_LATE || entry.kind === TOOL_COST ? entry.data?.usd : undefined;
139
+ return typeof cost === "number" && Number.isFinite(cost) ? cost : 0;
140
+ };
141
+ /** A held figure as a mark carries it: a finite number, else none. */
142
+ const figureOf = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
143
+ /** Takes one figure out of `open`: `figure` itself when it is there, else the smallest, a figure that is not there reading
144
+ * as the largest (a start with none stays while any other could go). */
145
+ const close = (open, figure) => {
146
+ if (!open.length)
147
+ return;
148
+ let at = figure === undefined ? -1 : open.indexOf(figure);
149
+ if (at < 0)
150
+ at = open.reduce((low, f, i) => (f !== undefined && (open[low] === undefined || f < open[low]) ? i : low), 0);
151
+ open.splice(at, 1);
152
+ };
153
+ /** The figures of the requests of each kind that `entries` leave open, marked as sent with no answer, cost or end, read in
154
+ * order, as the run's timeline counts them (pi-durable-agent's meter), so the two agree on how many were cut. A start adds
155
+ * its figure. An end mark closes its own start: a stopped request's at the figure it names, a withdrawn one's (`unsent`,
156
+ * which names none) the smallest. An end that names none for a request that left (an older store) closes nothing, so
157
+ * that request stays cut. An answer, or a summary's cost, closes the smallest figure still open, since when requests
158
+ * overlap the marks do not say which one it answered. What stays open is then never less than the requests truly open,
159
+ * figure for figure: taking the smallest, or the very figure an end names, never leaves a smaller figure open than any
160
+ * other way of reading the same marks. It is exactly them when requests do not overlap. pi's answer to a request that
161
+ * never left (REQUEST_REFUSED's error entry) and a harness answer's continuation close nothing. */
162
+ function openFigures(entries) {
163
+ const open = { generation: [], compaction: [] };
164
+ let [refused, continued] = [0, 0];
165
+ for (const entry of entries) {
166
+ const message = entry.model?.[0];
167
+ const data = (entry.data ?? {});
168
+ // A side request (a compaction's summary, a tool's own request): marked with a label, as the timeline reads it.
169
+ const kind = typeof data.request === "string" ? "compaction" : "generation";
170
+ if (entry.kind === REQUEST_REFUSED)
171
+ refused += 1;
172
+ else if (entry.kind === "pi.assistant" && refused > 0 && message?.stopReason === "error")
173
+ refused -= 1;
174
+ else if (entry.kind === REQUEST_CONTINUED)
175
+ continued += 1;
176
+ else if (entry.kind === "pi.assistant" && continued > 0 && message)
177
+ continued -= 1;
178
+ else if (entry.kind === REQUEST_STARTED)
179
+ open[kind].push(figureOf(data[HELD_FIELD]));
180
+ else if (entry.kind === REQUEST_ENDED) {
181
+ if (data.unsent === true)
182
+ close(open[kind]);
183
+ else if (figureOf(data[HELD_FIELD]) !== undefined)
184
+ close(open[kind], figureOf(data[HELD_FIELD]));
185
+ }
186
+ else if (entry.kind === REQUEST_COST)
187
+ close(open.compaction);
188
+ else if (entry.kind === "pi.assistant" && message)
189
+ close(open.generation);
190
+ }
191
+ return open;
192
+ }
193
+ /** What the run's store says its model requests cost, across every conversation in it: known or not as the run's own
194
+ * timeline says (pi-durable-agent's timelineOf), read as a settled run, since the process that wrote it is gone, and
195
+ * then the full amount, never the timeline's total rounded for display. Every response, and each cost written apart
196
+ * from one (a compaction summary's; a harness request's that came in after its answer). A cost that is not a number, or
197
+ * one still pending, leaves it unknown, as the timeline says. These readings are the cap's own, on its copy of the
198
+ * entries (the run's shown cost is the timeline's, unchanged): a request stopped before its end counts at the figure its
199
+ * end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
200
+ * holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
201
+ * cost. A paid call settled at a charge it did not say, like one a crash cut, counts at the figure its mark holds. And
202
+ * this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
203
+ export function spentIn(storeFile) {
204
+ if (!existsSync(storeFile))
205
+ return 0;
206
+ const db = new DatabaseSync(storeFile, { readOnly: true });
207
+ const entries = [];
208
+ // The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
209
+ const read = [];
210
+ let marked = false;
211
+ const rows = [];
212
+ try {
213
+ for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate())
214
+ rows.push(JSON.parse(String(row.record)));
215
+ }
216
+ finally {
217
+ db.close();
218
+ }
219
+ // pi's error entry for a request that ended on an error after its response began is left out, as an aborted one is: its
220
+ // end mark (`error`) counts it at its hold. pi writes the entry as the mark is written, before it or after, so each such
221
+ // mark takes the nearest error entry not yet taken among those after the earliest start holding its figure (a request's
222
+ // start and end marks hold the same, request-start.ts). Its own entry comes after its own start, so it is always among
223
+ // them. An error before every such start answered an earlier request (a 429, before any event): taken when a crash came
224
+ // between the mark and pi's entry, it would leave that request open at its hold. The marks with the fewest entries to
225
+ // choose from take first, so as many are taken as the marks' own entries in the store and no more errors are read as
226
+ // answers than are, one of which could close a start a crash cut; which one a mark takes, when errors overlap, moves no
227
+ // figure below what can have been spent, as an answer's choice of start does not (openFigures). An earlier start holding
228
+ // the very same figure (a 429's retry, with the same context) leaves its 429 takeable, so the spend then reads high,
229
+ // never low: telling the two apart needs to know which request each entry answers, and the marks do not say. An error
230
+ // with no such mark (before any event: a 429, a 5xx) is its request's answer.
231
+ // A cancel's refusal (REQUEST_REFUSED) answers the next error entry, as openFigures and the timeline read them: those are
232
+ // no request's, and no end mark takes one.
233
+ const stopOf = (entry) => entry.model?.[0]?.stopReason;
234
+ const errorsAt = [];
235
+ let refusals = 0;
236
+ rows.forEach((entry, at) => {
237
+ if (entry.kind === REQUEST_REFUSED)
238
+ refusals += 1;
239
+ else if (entry.kind === "pi.assistant" && stopOf(entry) === "error" && !refusedHere(entry) && !notSentHere(entry)) {
240
+ if (refusals > 0)
241
+ refusals -= 1;
242
+ else
243
+ errorsAt.push(at);
244
+ }
245
+ });
246
+ const taken = new Set();
247
+ const fieldsOf = (entry) => (entry.data ?? {});
248
+ const generationStart = (entry) => entry.kind === REQUEST_STARTED && typeof fieldsOf(entry).request !== "string" && fieldsOf(entry)[CAP_REFUSED_FIELD] !== true;
249
+ // Each such end mark, with the earliest start holding its figure (-1 for none: any error entry then).
250
+ const ends = rows.flatMap((entry, at) => entry.kind === REQUEST_ENDED && fieldsOf(entry).error === true
251
+ ? [{ at, from: rows.findIndex((start, i) => i < at && generationStart(start) && figureOf(fieldsOf(start)[HELD_FIELD]) === figureOf(fieldsOf(entry)[HELD_FIELD])) }]
252
+ : []);
253
+ for (const { at, from } of ends.sort((a, b) => b.from - a.from)) {
254
+ let nearest = -1;
255
+ for (const error of errorsAt)
256
+ if (error > from && !taken.has(error) && (nearest < 0 || Math.abs(error - at) < Math.abs(nearest - at)))
257
+ nearest = error;
258
+ if (nearest >= 0)
259
+ taken.add(nearest);
260
+ }
261
+ // Each paid tool call marked and not settled, by call: what it was held at.
262
+ const calls = new Map();
263
+ for (const [at, entry] of rows.entries()) {
264
+ const data = (entry.data ?? {});
265
+ // A request this cap refused never left, and costs nothing: its mark and pi's error entry for it (an older store
266
+ // has the entry alone, which the timeline would count as answering an earlier request a crash cut). Nor did one
267
+ // whose start mark could not be written, whose error entry has no mark at all. A cancel's refusal is its mark
268
+ // (REQUEST_REFUSED) and pi's error for it, which close nothing together (openFigures, and the timeline).
269
+ if (refusedHere(entry) || notSentHere(entry) || (entry.kind === REQUEST_STARTED && data[CAP_REFUSED_FIELD] === true))
270
+ continue;
271
+ // A paid call settled at a charge it did not say: at the figure its mark holds, the cap's bound for it.
272
+ const bound = entry.kind === TOOL_COST && figureOf(data.usd) === undefined ? figureOf(calls.get(data.call)) : undefined;
273
+ if (entry.kind === TOOL_STARTED)
274
+ calls.set(data.call, data[HELD_FIELD]);
275
+ if (entry.kind === TOOL_COST)
276
+ calls.delete(data.call);
277
+ if (entry.kind === REQUEST_STARTED)
278
+ marked = true;
279
+ // pi's entry for a marked request stopped before its end (what had streamed of it): the request is counted by its
280
+ // marks instead, at the figure its end holds, or cut. Before the first mark (an older run) it stays unknown.
281
+ if (marked && entry.kind === "pi.assistant" && entry.model?.[0]?.stopReason === "aborted")
282
+ continue;
283
+ if (taken.has(at))
284
+ continue;
285
+ entries.push(bound === undefined ? entry : { ...entry, data: { ...data, usd: bound } });
286
+ read.push(entry);
287
+ const held = data[HELD_FIELD];
288
+ // A summary that ended on an error after its response began (its cost mark says `failed`) counts at its hold.
289
+ if (entry.kind === REQUEST_COST && data.failed === true && figureOf(held) !== undefined)
290
+ entries[entries.length - 1] = { ...entry, data: { ...data, usd: held } };
291
+ if (entry.kind !== REQUEST_ENDED || data.unsent === true || typeof held !== "number" || !Number.isFinite(held))
292
+ continue;
293
+ // The stopped request closed at what the cap held for it: a summary by its cost, a generation by an answer.
294
+ entries.push(typeof data.request === "string"
295
+ ? { kind: REQUEST_COST, data: { request: data.request, usd: held } }
296
+ : { kind: "pi.assistant", ...(entry.conversationId !== undefined ? { conversationId: entry.conversationId } : {}), model: [{ role: "assistant", content: [], stopReason: "stop", usage: { cost: { total: held } }, timestamp: 0 }] });
297
+ }
298
+ // A paid tool call a crash cut (marked, never settled) counts at its held figure, settled by it here, as a cut request.
299
+ for (const [call, figure] of calls)
300
+ entries.push({ kind: TOOL_COST, data: { call, usd: figureOf(figure) ?? null } });
301
+ // A request still open is one a crash cut, with no answer and no end: it counts at what the cap held for it, as its start
302
+ // mark says: its own figure when requests do not overlap, else one never less (openFigures). One still open with no
303
+ // figure (an older store) leaves them all cut, unknown.
304
+ const open = openFigures(read);
305
+ for (const kind of ["generation", "compaction"]) {
306
+ const figures = open[kind];
307
+ if (figures.some((figure) => figure === undefined))
308
+ continue;
309
+ for (const figure of figures) {
310
+ entries.push(kind === "compaction"
311
+ ? { kind: REQUEST_COST, data: { request: "compaction", usd: figure } }
312
+ : { kind: "pi.assistant", model: [{ role: "assistant", content: [], stopReason: "stop", usage: { cost: { total: figure } }, timestamp: 0 }] });
313
+ }
314
+ }
315
+ // The timeline says whether the spend is known; the amount is summed here, as it is, since the timeline rounds its total
316
+ // for display (to the millionth of a dollar), and a cap must not lose what that drops.
317
+ const usage = timelineOf(entries, { settled: true }).find((row) => row.kind === "usage")?.usage;
318
+ if (usage === undefined)
319
+ return 0;
320
+ if (typeof usage.usd !== "number" || !Number.isFinite(usage.usd))
321
+ return null;
322
+ return entries.reduce((sum, entry) => sum + costOf(entry), 0);
323
+ }
324
+ /** /usage's meters for a run that ended, from its store: `tools`, each TOOL_COST's `usd`, unknown (null) when one is,
325
+ * or when a call was cut (marked, never settled: what it charged no one knows); and `tokens`, the rest of its root
326
+ * conversation as its settled timeline prices it. A mark is never a charge here (the cap's alone). Never for a live
327
+ * run: its process holds the store exclusively. */
328
+ export function metersIn(storeFile) {
329
+ if (!existsSync(storeFile))
330
+ return { tools: 0, tokens: null };
331
+ const db = new DatabaseSync(storeFile, { readOnly: true, timeout: 2_000 });
332
+ try {
333
+ const rows = db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }));
334
+ const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
335
+ const marks = new Set();
336
+ const charges = [];
337
+ for (const { entry } of rows) {
338
+ const data = (entry.data ?? {});
339
+ if (entry.kind === TOOL_STARTED)
340
+ marks.add(data.call);
341
+ else if (entry.kind === TOOL_COST)
342
+ marks.delete(data.call), charges.push(figureOf(data.usd));
343
+ }
344
+ const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
345
+ const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
346
+ const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
347
+ return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0 };
348
+ }
349
+ finally {
350
+ db.close();
351
+ }
352
+ }
353
+ /** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
354
+ * settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
355
+ * null when one has no figure. The run's reported cost reads such a call unknown instead (the timeline). */
356
+ export function capToolSpend(entries) {
357
+ const open = new Map();
358
+ const figures = [];
359
+ for (const { kind, data } of entries) {
360
+ const at = (data ?? {});
361
+ if (kind === TOOL_STARTED)
362
+ open.set(at.call, at[HELD_FIELD]);
363
+ else if (kind === TOOL_COST)
364
+ figures.push(figureOf(at.usd) ?? open.get(at.call)), open.delete(at.call);
365
+ }
366
+ const all = [...figures, ...open.values()].map(figureOf);
367
+ return all.every((figure) => figure !== undefined) ? all.reduce((sum, figure) => sum + figure, 0) : null;
368
+ }
369
+ /** The worst case of each model request a cap admitted and whose cost is not booked yet, by its turn, for a paid tool's
370
+ * check on a harness whose booking counts a request only once its cost is in (harness-app.ts): `admitted` takes what
371
+ * the guard held, `started` gives it the turn that request leaves as (admissions run one at a time), `ended` drops it. */
372
+ export function holdsInFlight() {
373
+ const holds = new Map();
374
+ // One slot between admitted() and started(): the runner admits one model request at a time per session.
375
+ let next;
376
+ return {
377
+ admitted: (usd) => void (next = usd),
378
+ started: (turn) => void (next !== undefined && holds.set(turn, next), (next = undefined)),
379
+ ended: (turn) => void holds.delete(turn),
380
+ total: () => [...holds.values()].reduce((sum, usd) => sum + usd, 0),
381
+ };
382
+ }
383
+ let runSpend;
384
+ let paying = Promise.resolve();
385
+ export const useSpend = (spend) => void (runSpend = spend);
386
+ /** Each paid call sent under the cap and not settled, at what it is held at. */
387
+ const paidOpen = new Set();
388
+ /** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
389
+ * adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). */
390
+ export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
391
+ /** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
392
+ * its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
393
+ * quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
394
+ * call at a time, so each check sees the charge before it, and held at that figure (paidHolds) until the charge it
395
+ * reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
396
+ * fails, counts at its held figure, as its mark does from the store (spentIn), since it may have charged that much.
397
+ * With no cap it just runs. */
398
+ export async function paidCall(name, call, charge, hold) {
399
+ const spend = runSpend;
400
+ if (!spend)
401
+ return { result: await call() };
402
+ const turn = paying.then(async () => {
403
+ const read = await spend.spent();
404
+ if (read === null)
405
+ return { refused: `${SPEND_CAP_REACHED}: ${name} was not sent. What the run has spent is unknown, so its cap of $${spend.cap} cannot be kept: the run is out of budget.` };
406
+ const spent = read + paidHolds();
407
+ // Written so that a figure that is not a number refuses.
408
+ if (!(spent + hold.usd <= spend.cap))
409
+ return { refused: `${SPEND_CAP_REACHED}: ${name} was not sent. It could cost up to $${hold.usd} (${hold.basis}), and with $${spent.toFixed(6)} spent the run would pass its cap of $${spend.cap}: the run is out of budget.` };
410
+ // Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
411
+ const open = { usd: hold.usd };
412
+ paidOpen.add(open);
413
+ try {
414
+ const result = await call();
415
+ const usd = charge(result);
416
+ if (usd !== undefined)
417
+ spend.add(usd ?? hold.usd);
418
+ return { result };
419
+ }
420
+ catch (error) {
421
+ spend.add(hold.usd);
422
+ throw error;
423
+ }
424
+ finally {
425
+ paidOpen.delete(open);
426
+ }
427
+ });
428
+ paying = turn.catch(() => undefined);
429
+ return turn;
430
+ }
431
+ /** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
432
+ * raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
433
+ export const ceilingTokens = (model) => (model.maxTokens > 0 ? model.maxTokens : model.contextWindow);
434
+ /** The output tokens a request's worst case is priced at: the model's ceiling; none when the model names no ceiling and
435
+ * its output costs nothing at every price tier, so any number of output tokens is $0; undefined when its output is
436
+ * priced and it names no ceiling, so nothing bounds what a request may cost. */
437
+ function outputBound(model) {
438
+ const ceiling = ceilingTokens(model);
439
+ if (Number.isFinite(ceiling) && ceiling > 0)
440
+ return ceiling;
441
+ return [model.cost, ...(model.cost?.tiers ?? [])].every((rates) => rates?.output === 0) ? 0 : undefined;
442
+ }
443
+ /** A request's input tokens, bounded above: one per UTF-8 byte of what is sent (a byte-level tokenizer never takes
444
+ * fewer than one byte a token, and an image's base64 is far more bytes than its tokens), plus `overhead`, what the
445
+ * provider adds server-side that the body does not hold. The same bound on every harness. */
446
+ export const inputBound = (sent, overhead = 0) => Buffer.byteLength(sent, "utf8") + overhead;
447
+ /** What pi's provider adds server-side to a request of `context`, the same table the model proxy uses, by the model's API
448
+ * kind: undefined for a kind whose additions are not known. The context does not say how the request chooses a tool,
449
+ * so the dearer choice is taken. */
450
+ export function piOverhead(model, context) {
451
+ const parts = (context.messages ?? []).flatMap((message) => (Array.isArray(message.content) ? (message.content) : []));
452
+ return providerInputOverhead(model.api, { tools: (context.tools?.length ?? 0) > 0, toolChoice: "any", images: parts.filter((part) => part?.type === "image").length });
453
+ }
454
+ const unmeasured = (cap) => `${SPEND_CAP_REACHED}: the next model request was not sent. The size of a request's input is unknown, so the run's cap of $${cap} cannot be kept: the run is out of budget.`;
455
+ const noPrice = (cap) => `${SPEND_CAP_REACHED}: the next model request was not sent. Its model has no price here, so the run's cap of $${cap} cannot be kept: the run is out of budget.`;
456
+ const noCeiling = (cap) => `${SPEND_CAP_REACHED}: the next model request was not sent. Its model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of $${cap} cannot be kept: the run is out of budget.`;
457
+ const unknownSpend = (cap) => `${SPEND_CAP_REACHED}: the next model request was not sent. What the run has spent is unknown, so its cap of $${cap} cannot be kept: the run is out of budget.`;
458
+ /** A request's worst case at `model`'s price: `input` tokens at the dearer of its input and cache-write prices, and
459
+ * `output` tokens at its output price. */
460
+ function worstOf(calculateCost, model) {
461
+ const priced = (tokens) => calculateCost(model, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, ...tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }).total;
462
+ return (input, output) => Math.max(priced({ input, output }), priced({ cacheWrite: input, output }));
463
+ }
464
+ /** An amount in words: two decimals, or as many as it takes (up to eight) to show it whole ($0.50, $0.105, $0.0005). */
465
+ export function money(usd) {
466
+ // A whole number of dollars as given ($1), else two decimals or as many as it takes (up to eight) to show it whole.
467
+ if (Number.isInteger(usd))
468
+ return `$${usd}`;
469
+ for (let digits = 2; digits < 8; digits++)
470
+ if (Number(usd.toFixed(digits)) === Number(usd.toFixed(8)))
471
+ return `$${usd.toFixed(digits)}`;
472
+ return `$${usd.toFixed(8)}`;
473
+ }
474
+ /** The code a cap's refusal begins with: `spend_cap_reached`, which the server ends the run with, and "out of budget",
475
+ * which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
476
+ * words after it hold. The words after it are the ones a person reads. */
477
+ export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
478
+ /** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
479
+ * "Claude Sonnet 5.5"), else its id. */
480
+ export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
481
+ /** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
482
+ export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - 1e-9) / 100).toFixed(2)}`;
483
+ /** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers: what
484
+ * the run spent (and holds for requests still answering) of its cap, what the request needs at the least, and the cap
485
+ * that would run it (spent, held and that least, rounded up to the cent, so that it is enough). After its code
486
+ * (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. */
487
+ function capRefusal(cap, spent, held, name, least) {
488
+ const [need, raise] = [leastMoney(least), leastMoney(spent + held + least)];
489
+ if (spent === 0 && held === 0)
490
+ return `${CAP_REFUSAL_CODE}Not sent: this run's cap of ${money(cap)} can't cover one ${name} request (at least ${need}). Raise the cap to at least ${raise} to run it.`;
491
+ const owes = held > 0 ? `spent ${money(spent)} and holds ${money(held)} for requests still answering, of its ${money(cap)} cap` : `spent ${money(spent)} of its ${money(cap)} cap`;
492
+ return `${CAP_REFUSAL_CODE}Not sent: the run has ${owes}, and its next ${name} request needs at least ${need}. Raise the cap to at least ${raise} to run it.`;
493
+ }
494
+ /** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
495
+ * many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
496
+ function mostOutput(cost, least, asked, left) {
497
+ // Written so that a cost that is not a number refuses.
498
+ if (!(cost(least) <= left))
499
+ return undefined;
500
+ if (cost(asked) <= left)
501
+ return asked;
502
+ let [low, high] = [least, asked];
503
+ while (high - low > 1) {
504
+ const mid = Math.floor((low + high) / 2);
505
+ if (cost(mid) <= left)
506
+ low = mid;
507
+ else
508
+ high = mid;
509
+ }
510
+ return low;
511
+ }
512
+ /** The least output a pi request may be limited to and still answer: the answer's 1,024 tokens, and when it thinks,
513
+ * the least budget on an API whose thinking takes one (squeezed to it), else its thinking level's budget, since its
514
+ * reasoning then shares the limit. */
515
+ export function leastOutput(model, thinking, budgetOf) {
516
+ if (!model.reasoning || !thinking || thinking === "off")
517
+ return ANSWER_TOKENS_LEAST;
518
+ return ANSWER_TOKENS_LEAST + (BUDGET_APIS.has(model.api) ? THINKING_BUDGET_LEAST : budgetOf(thinking));
519
+ }
520
+ /** A run on another harness: before each request, what the run has spent, plus the worst case of each request still in
521
+ * flight (at the output limit it was admitted with), must leave room for this request at its least output (1,024 tokens,
522
+ * or what its body says it needs to think and answer; what it asks for when that is fewer), else the request is refused
523
+ * with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at most what
524
+ * it asks for and its model's ceiling), which the model proxy writes into its body: what it is held at is then what the
525
+ * provider can bill for it. A request's worst case is at the run model's
526
+ * price, as on pi (a request on a cheaper model is held at that price too, which only refuses sooner). What cannot be
527
+ * kept within a cap is refused under one: a spend that is unknown (a request a crash cut), an input that could not be
528
+ * measured, a model serve has no price for (`listed: false`, or none at all), and a model whose output is priced and
529
+ * that has no output ceiling. With no cap, nothing is refused. */
530
+ export async function capBefore(cap, model, { listed = true } = {}) {
531
+ if (cap === undefined)
532
+ return undefined;
533
+ if (model === undefined || !listed)
534
+ return { beforeRequest: () => ({ refuse: noPrice(cap) }) };
535
+ const output = outputBound(model);
536
+ if (output === undefined)
537
+ return { beforeRequest: () => ({ refuse: noCeiling(cap) }) };
538
+ const price = worstOf((await import("@earendil-works/pi-ai")).calculateCost, model);
539
+ const name = nameOf(model);
540
+ const held = (request) => price(request.inputTokensMax, request.outputTokensMax ?? output);
541
+ return {
542
+ beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast }) {
543
+ if (spentUsd === null)
544
+ return { refuse: unknownSpend(cap) };
545
+ const inputs = [inputTokensMax, ...inFlight.map((request) => request.inputTokensMax)];
546
+ if (inputs.some((input) => typeof input !== "number" || !Number.isFinite(input)))
547
+ return { refuse: unmeasured(cap) };
548
+ // Its requests in flight at the limit each was admitted with, and its paid calls under way at what they are held at.
549
+ const holding = inFlight.reduce((sum, request) => sum + held(request), paidHolds());
550
+ const left = cap - spentUsd - holding;
551
+ const cost = (tokens) => price(inputTokensMax, tokens);
552
+ // A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
553
+ if (output === 0)
554
+ return cost(0) <= left ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)) };
555
+ const asked = Math.min(outputTokensAsked ?? output, output);
556
+ const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
557
+ const most = mostOutput(cost, least, asked, left);
558
+ return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)) } : { outputTokensMax: most };
559
+ },
560
+ worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
561
+ stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
562
+ ? price(request.inputTokensMax, Math.min(request.outputTokensMax ?? output, streamed + STOP_ALLOWANCE_TOKENS)) : undefined),
563
+ };
564
+ }
565
+ /** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
566
+ * server-side) and the most fee it can run up: a tool's own request adds what its hosted tool may read
567
+ * (hosted-search.ts), and its most fee. Undefined when its input cannot be measured. */
568
+ export function requestParts(overhead = piOverhead) {
569
+ return (model, context) => {
570
+ const added = overhead(model, context);
571
+ if (added === undefined)
572
+ return undefined;
573
+ const side = sideRequests.get(context);
574
+ return { input: inputBound(JSON.stringify(context), added + (side?.extraInputTokens ?? 0)), feeUsd: side?.maxFeeUsd ?? 0 };
575
+ };
576
+ }
577
+ /** `models`, each request limited to the output tokens what is left of `cap` after `spent` USD (and what requests in flight
578
+ * hold) can buy, at most what it asks for, thinking included (CLAMP on its marks when that is less), and refused when that
579
+ * cannot buy its least (`leastOutput`: 1,024 tokens for the answer, and its thinking's least), saying so in plain words;
580
+ * and, under the cap,
581
+ * each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
582
+ * ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
583
+ * (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
584
+ * `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
585
+ * request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
586
+ * `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry. */
587
+ export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused } = {}) {
588
+ const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
589
+ const partsOf = requestParts(overhead);
590
+ let held = 0;
591
+ const judge = (model, context, options, simpleCall) => {
592
+ if (unpriced.has(model.id))
593
+ return { why: noPrice(cap) };
594
+ const ceiling = outputBound(model);
595
+ if (ceiling === undefined)
596
+ return { why: noCeiling(cap) };
597
+ if (spent === null)
598
+ return { why: unknownSpend(cap) };
599
+ const parts = partsOf(model, context);
600
+ if (parts === undefined)
601
+ return { why: unmeasured(cap) };
602
+ const price = worstOf(calculateCost, model);
603
+ const cost = (tokens) => price(parts.input, tokens) + parts.feeUsd;
604
+ // What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
605
+ // each paid call under way at what it is held at.
606
+ const holding = held + paidHolds();
607
+ const left = cap - spent - holding;
608
+ const name = nameOf(model);
609
+ // A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit.
610
+ if (ceiling === 0)
611
+ return cost(0) <= left ? { worst: cost(0), stopped: () => cost(0) } : { why: capRefusal(cap, spent, holding, name, cost(0)) };
612
+ // What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
613
+ // context leaves, and on an API whose thinking takes a budget adds the budget to it.
614
+ const transcript = context;
615
+ const thinking = simpleCall && model.reasoning && options?.reasoning ? options.reasoning : undefined;
616
+ const budgeted = thinking !== undefined && BUDGET_APIS.has(model.api);
617
+ const base = simple.clampMaxTokensToContext(model, transcript, options?.maxTokens ?? ceilingTokens(model));
618
+ const asked = Math.min(ceiling, budgeted ? simple.clampMaxTokensToContext(model, transcript, simple.adjustMaxTokensForThinking(base, ceilingTokens(model), thinking, options?.thinkingBudgets).maxTokens) : base);
619
+ const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
620
+ const most = mostOutput(cost, least, asked, left);
621
+ if (most === undefined)
622
+ return { why: capRefusal(cap, spent, holding, name, cost(least)) };
623
+ // Stopped before its end, at most the output it was sent with: what it streamed and the allowance, within its worst case.
624
+ const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message));
625
+ if (most === asked)
626
+ return { worst: cost(asked), stopped: stoppedAt(asked) };
627
+ // Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
628
+ // the answer's 1,024, and maxTokens is what is left of `most` beside it, so pi-ai's sum is `most`.
629
+ const clamp = { tokens: most, leftUsd: Math.round(left * 1e6) / 1e6, capUsd: cap };
630
+ if (!budgeted)
631
+ return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most, [CLAMP]: clamp } };
632
+ const level = simple.clampReasoning(thinking);
633
+ const budget = Math.min(simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets), most - ANSWER_TOKENS_LEAST);
634
+ return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most - budget, thinkingBudgets: { ...options?.thinkingBudgets, [level]: budget }, [CLAMP]: clamp } };
635
+ };
636
+ const refusal = (model, why) => ({
637
+ role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
638
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
639
+ // "out of budget" is final to pi-ai's retry policy, whatever digits the amounts hold.
640
+ errorMessage: why,
641
+ });
642
+ /** Adds what `answer` cost to what the run has spent once it settles. One stopped before its end counts at `stopped`
643
+ * of what it streamed (stoppedFigure, at most `worst`); one that ended on an error after its response began
644
+ * (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
645
+ * answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
646
+ * response) it is unknown, as is a cost that is not a number, from then on. */
647
+ const count = (answer, worst, stopped) => {
648
+ const add = (cost) => void (spent = spent !== null && typeof cost === "number" && Number.isFinite(cost) ? spent + cost : null);
649
+ const at = (message) => message.stopReason === "aborted" ? (stopped ? stopped(message) : worst)
650
+ : message.stopReason === "error" && responseBegan.has(message) ? worst : message.usage?.cost?.total;
651
+ return answer.then((message) => add(at(message)), () => add(worst));
652
+ };
653
+ /** Sends a request judged to fit at `worst`, holding that until `answer` settles. */
654
+ const admit = (worst, stopped, answer) => {
655
+ held += worst;
656
+ let answered;
657
+ try {
658
+ answered = answer();
659
+ }
660
+ catch (error) {
661
+ held -= worst;
662
+ throw error;
663
+ }
664
+ void count(answered, worst, stopped).finally(() => void (held -= worst));
665
+ return answered;
666
+ };
667
+ // A paid tool's check reads the spend with the requests in flight held at their worst case (and adds the paid holds
668
+ // itself), and its charge joins it.
669
+ useSpend({ cap, spent: () => (spent === null ? null : spent + held), add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null) });
670
+ /** `options` with the request's worst case, and its figure if it is stopped, for its marks. */
671
+ const carrying = (options, { worst, stopped }) => ({ ...options, [HELD_USD]: worst, [STOPPED_USD]: stopped });
672
+ const stream = (send, simpleCall) => (model, context, options) => {
673
+ const judged = judge(model, context, options, simpleCall);
674
+ if ("worst" in judged) {
675
+ let events;
676
+ admit(judged.worst, judged.stopped, () => (events = send(model, context, carrying(judged.options ?? options, judged))).result());
677
+ return events;
678
+ }
679
+ const refused = createAssistantMessageEventStream();
680
+ const message = refusal(model, judged.why);
681
+ // Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
682
+ // cut. A mark that cannot be written still ends the request: spentIn leaves refusals out either way.
683
+ void Promise.resolve()
684
+ .then(() => markRefused?.())
685
+ .catch(() => undefined)
686
+ .then(() => {
687
+ refused.push({ type: "error", reason: "error", error: message });
688
+ refused.end(message);
689
+ });
690
+ return refused;
691
+ };
692
+ const complete = (send, simpleCall) => (model, context, options) => {
693
+ const judged = judge(model, context, options, simpleCall);
694
+ return "worst" in judged ? admit(judged.worst, judged.stopped, () => send(model, context, carrying(judged.options ?? options, judged))) : Promise.resolve(refusal(model, judged.why));
695
+ };
696
+ const guarded = {
697
+ stream: stream(models.stream.bind(models), false),
698
+ streamSimple: stream(models.streamSimple.bind(models), true),
699
+ complete: complete(models.complete.bind(models), false),
700
+ completeSimple: complete(models.completeSimple.bind(models), true),
701
+ // A deferred response was admitted when it was sent; what it cost is counted when it is fetched.
702
+ streamDeferred: (...args) => {
703
+ const events = models.streamDeferred(...args);
704
+ void count(events.result());
705
+ return events;
706
+ },
707
+ fetchDeferred: (...args) => {
708
+ const answer = models.fetchDeferred(...args);
709
+ void count(answer);
710
+ return answer;
711
+ },
712
+ };
713
+ return new Proxy(models, {
714
+ get: (target, key) => {
715
+ if (key in guarded)
716
+ return guarded[key];
717
+ const value = Reflect.get(target, key, target);
718
+ return typeof value === "function" ? value.bind(target) : value;
719
+ },
720
+ });
721
+ }