@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58

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 (312) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +246 -66
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +15 -5
  11. package/dist/api-only.js +32 -8
  12. package/dist/box-paths.d.ts +4 -3
  13. package/dist/box-paths.js +7 -4
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/chatgpt-plan.d.ts +18 -8
  19. package/dist/chatgpt-plan.js +91 -34
  20. package/dist/claude-login-token.d.ts +117 -0
  21. package/dist/claude-login-token.js +737 -0
  22. package/dist/claude-login.d.ts +120 -22
  23. package/dist/claude-login.js +347 -63
  24. package/dist/claude-sign-in.d.ts +17 -6
  25. package/dist/claude-sign-in.js +42 -39
  26. package/dist/cli.js +33 -10
  27. package/dist/composio-made.d.ts +4 -0
  28. package/dist/composio-made.js +4 -0
  29. package/dist/composio-preset.d.ts +43 -2
  30. package/dist/composio-preset.js +92 -4
  31. package/dist/computer-attach.d.ts +35 -17
  32. package/dist/computer-attach.js +301 -49
  33. package/dist/computer-held-routes.d.ts +5 -4
  34. package/dist/computer-held-routes.js +29 -8
  35. package/dist/computer-held.d.ts +6 -1
  36. package/dist/computer-held.js +14 -0
  37. package/dist/computer-record.js +4 -2
  38. package/dist/computer-viewer.js +4 -1
  39. package/dist/computers.d.ts +10 -10
  40. package/dist/computers.js +5 -5
  41. package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
  42. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  43. package/dist/console/assets/index-DPh29cyz.js +747 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/decisions.d.ts +1 -1
  46. package/dist/decisions.js +1 -1
  47. package/dist/dial-relay.d.ts +25 -4
  48. package/dist/dial-relay.js +129 -1
  49. package/dist/docker-host-addresses.d.ts +22 -11
  50. package/dist/docker-host-addresses.js +38 -26
  51. package/dist/env-switch.d.ts +8 -0
  52. package/dist/env-switch.js +31 -2
  53. package/dist/errors.d.ts +1 -0
  54. package/dist/errors.js +2 -0
  55. package/dist/fal-price.d.ts +56 -20
  56. package/dist/fal-price.js +400 -90
  57. package/dist/handed-values.d.ts +43 -1
  58. package/dist/handed-values.js +119 -2
  59. package/dist/harness-archive.d.ts +13 -10
  60. package/dist/harness-archive.js +60 -34
  61. package/dist/harness-check.d.ts +3 -1
  62. package/dist/harness-check.js +25 -46
  63. package/dist/harness-keys.d.ts +73 -27
  64. package/dist/harness-keys.js +194 -61
  65. package/dist/harness-recipe-entry.d.ts +8 -7
  66. package/dist/harness-recipe-entry.js +21 -32
  67. package/dist/harness-recipe.d.ts +38 -25
  68. package/dist/harness-recipe.js +49 -36
  69. package/dist/harness-sign-in.js +12 -23
  70. package/dist/harness-table.d.ts +10 -3
  71. package/dist/harness-table.js +26 -21
  72. package/dist/harness.d.ts +1 -0
  73. package/dist/harness.js +17 -5
  74. package/dist/hosted-search.d.ts +1 -1
  75. package/dist/hosted-search.js +1 -2
  76. package/dist/import-worker.d.ts +4 -2
  77. package/dist/import-worker.js +9 -2
  78. package/dist/in-flight.d.ts +26 -0
  79. package/dist/in-flight.js +52 -0
  80. package/dist/key-refusal.d.ts +9 -4
  81. package/dist/key-refusal.js +107 -25
  82. package/dist/learn/ledger.d.ts +170 -0
  83. package/dist/learn/ledger.js +218 -0
  84. package/dist/learn/promote.d.ts +3 -3
  85. package/dist/learn/promote.js +1 -1
  86. package/dist/learn/secrets.d.ts +13 -3
  87. package/dist/learn/secrets.js +118 -17
  88. package/dist/learning-cost.d.ts +28 -23
  89. package/dist/learning-cost.js +19 -23
  90. package/dist/link-check.js +1 -1
  91. package/dist/live-reach.d.ts +2 -0
  92. package/dist/live-reach.js +2 -0
  93. package/dist/llms.txt +1 -1
  94. package/dist/marketplace.d.ts +77 -0
  95. package/dist/marketplace.js +224 -0
  96. package/dist/mcp-api-only-origins.d.ts +35 -0
  97. package/dist/mcp-api-only-origins.js +57 -0
  98. package/dist/mcp-gateway.d.ts +7 -5
  99. package/dist/mcp-gateway.js +9 -12
  100. package/dist/mcp-secret-writes.js +5 -3
  101. package/dist/mcp-servers-store.d.ts +28 -6
  102. package/dist/mcp-servers-store.js +53 -4
  103. package/dist/media-duration.d.ts +3 -0
  104. package/dist/media-duration.js +90 -9
  105. package/dist/micro.d.ts +2 -0
  106. package/dist/micro.js +2 -0
  107. package/dist/model-form.d.ts +5 -4
  108. package/dist/model-form.js +11 -7
  109. package/dist/model.d.ts +10 -6
  110. package/dist/model.js +16 -11
  111. package/dist/monid.d.ts +14 -1
  112. package/dist/monid.js +103 -26
  113. package/dist/ollama-provider.d.ts +7 -1
  114. package/dist/ollama-provider.js +14 -2
  115. package/dist/openapi.js +210 -37
  116. package/dist/otel/genai.d.ts +65 -0
  117. package/dist/otel/genai.js +116 -0
  118. package/dist/otel/tracer.d.ts +55 -0
  119. package/dist/otel/tracer.js +308 -0
  120. package/dist/page.d.ts +2 -0
  121. package/dist/page.js +3 -1
  122. package/dist/paid-calls.d.ts +1 -32
  123. package/dist/paid-calls.js +4 -39
  124. package/dist/place-offers.d.ts +4 -0
  125. package/dist/place-offers.js +7 -4
  126. package/dist/provider.d.ts +11 -2
  127. package/dist/provider.js +59 -8
  128. package/dist/redact/match.d.ts +30 -3
  129. package/dist/redact/match.js +422 -41
  130. package/dist/refusal-words.d.ts +11 -0
  131. package/dist/refusal-words.js +11 -0
  132. package/dist/run-census.d.ts +67 -0
  133. package/dist/run-census.js +240 -0
  134. package/dist/run-computer.d.ts +6 -3
  135. package/dist/run-computer.js +4 -1
  136. package/dist/run-cut.d.ts +15 -6
  137. package/dist/run-cut.js +30 -9
  138. package/dist/run-files.d.ts +3 -0
  139. package/dist/run-files.js +3 -0
  140. package/dist/run-launch.d.ts +12 -1
  141. package/dist/run-launch.js +9 -10
  142. package/dist/run-learning-served.d.ts +4 -2
  143. package/dist/run-model-key.d.ts +8 -0
  144. package/dist/run-model-key.js +31 -1
  145. package/dist/run-reads-over-store.d.ts +24 -6
  146. package/dist/run-reads-over-store.js +67 -23
  147. package/dist/run-recordings.d.ts +5 -1
  148. package/dist/run-recordings.js +39 -14
  149. package/dist/run-timeline-served.d.ts +2 -0
  150. package/dist/run-timeline-served.js +2 -2
  151. package/dist/run-usage.d.ts +1 -0
  152. package/dist/run-view.d.ts +1 -2
  153. package/dist/run-view.js +2 -1
  154. package/dist/runnable.d.ts +10 -1
  155. package/dist/runnable.js +20 -8
  156. package/dist/runner/adapter-loop.d.ts +11 -0
  157. package/dist/runner/adapter-loop.js +58 -26
  158. package/dist/runner/adapter-run-spec.d.ts +55 -11
  159. package/dist/runner/adapter-run-spec.js +183 -52
  160. package/dist/runner/adapters/pi.js +25 -3
  161. package/dist/runner/beside.d.ts +9 -2
  162. package/dist/runner/beside.js +27 -9
  163. package/dist/runner/big-writes.js +1 -10
  164. package/dist/runner/claim-secrets.d.ts +27 -10
  165. package/dist/runner/claim-secrets.js +49 -22
  166. package/dist/runner/cli-run-spec.d.ts +6 -0
  167. package/dist/runner/cli-run-spec.js +97 -38
  168. package/dist/runner/computer-journal.d.ts +9 -1
  169. package/dist/runner/computer-journal.js +26 -0
  170. package/dist/runner/conformance/harness.js +1 -1
  171. package/dist/runner/feedback-round.js +3 -0
  172. package/dist/runner/harness-loops.d.ts +6 -5
  173. package/dist/runner/harness-loops.js +7 -7
  174. package/dist/runner/held.d.ts +24 -6
  175. package/dist/runner/journal-kinds.d.ts +5 -0
  176. package/dist/runner/journal-kinds.js +5 -0
  177. package/dist/runner/main.d.ts +11 -6
  178. package/dist/runner/main.js +19 -9
  179. package/dist/runner/mcp-claim.js +31 -3
  180. package/dist/runner/mcp-run.d.ts +9 -0
  181. package/dist/runner/mcp-run.js +11 -5
  182. package/dist/runner/model-route.d.ts +17 -0
  183. package/dist/runner/model-route.js +120 -2
  184. package/dist/runner/presence.d.ts +11 -1
  185. package/dist/runner/presence.js +7 -0
  186. package/dist/runner/reflect-hook.js +1 -1
  187. package/dist/runner/run-child-host.d.ts +22 -8
  188. package/dist/runner/run-child-host.js +128 -41
  189. package/dist/runner/run-child.js +5 -2
  190. package/dist/runner/runner.d.ts +17 -3
  191. package/dist/runner/runner.js +130 -34
  192. package/dist/runner/save-slots.js +2 -1
  193. package/dist/runner/store-port.d.ts +1 -1
  194. package/dist/runner/store-secrets.d.ts +6 -0
  195. package/dist/runner/store-secrets.js +49 -7
  196. package/dist/runner/subagent.d.ts +11 -0
  197. package/dist/runner/subagent.js +16 -38
  198. package/dist/runner/workflow-first.d.ts +35 -15
  199. package/dist/runner/workflow-first.js +38 -25
  200. package/dist/runner/workflow-spec.js +4 -3
  201. package/dist/runs-over-store.d.ts +15 -6
  202. package/dist/runs-over-store.js +33 -21
  203. package/dist/scrub-command.d.ts +73 -0
  204. package/dist/scrub-command.js +307 -0
  205. package/dist/secret-cut.d.ts +73 -0
  206. package/dist/secret-cut.js +291 -4
  207. package/dist/secret-rules.d.ts +143 -0
  208. package/dist/secret-rules.js +2564 -0
  209. package/dist/secrets.d.ts +7 -0
  210. package/dist/secrets.js +20 -0
  211. package/dist/server-keys.d.ts +20 -0
  212. package/dist/server-keys.js +25 -6
  213. package/dist/server.d.ts +65 -13
  214. package/dist/server.js +470 -157
  215. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  216. package/dist/slots.d.ts +9 -0
  217. package/dist/slots.js +45 -0
  218. package/dist/store/index.d.ts +1 -1
  219. package/dist/store/index.js +1 -1
  220. package/dist/store/journal/storage.js +1 -1
  221. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  222. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  223. package/dist/store/schema.d.ts +23 -0
  224. package/dist/store/schema.js +58 -2
  225. package/dist/store/seal.d.ts +6 -1
  226. package/dist/store/seal.js +5 -3
  227. package/dist/store/sqlite/run-launch.d.ts +9 -1
  228. package/dist/store/sqlite/run-launch.js +24 -13
  229. package/dist/store/sqlite/run-patch.d.ts +12 -2
  230. package/dist/store/sqlite/run-patch.js +42 -5
  231. package/dist/store/sqlite/store.js +105 -12
  232. package/dist/store/store.d.ts +57 -2
  233. package/dist/store/store.js +20 -0
  234. package/dist/store-reads/learning.d.ts +84 -124
  235. package/dist/store-reads/learning.js +210 -274
  236. package/dist/store-view.d.ts +3 -0
  237. package/dist/store-view.js +3 -3
  238. package/dist/suggestions.js +3 -2
  239. package/dist/template-eval.d.ts +39 -9
  240. package/dist/template-eval.js +191 -60
  241. package/dist/template-import.js +6 -2
  242. package/dist/templates.d.ts +10 -2
  243. package/dist/templates.js +28 -8
  244. package/dist/timeline/labels.d.ts +6 -4
  245. package/dist/timeline/labels.js +18 -6
  246. package/dist/timeline/timeline.d.ts +5 -0
  247. package/dist/timeline/timeline.js +14 -8
  248. package/dist/timeline/util.js +1 -1
  249. package/dist/timeline/web-calls.d.ts +22 -7
  250. package/dist/timeline/web-calls.js +106 -35
  251. package/dist/tool-gate.d.ts +42 -3
  252. package/dist/tool-gate.js +66 -5
  253. package/dist/tool-keys-store.d.ts +2 -4
  254. package/dist/tool-keys-store.js +5 -21
  255. package/dist/tool-keys.d.ts +2 -2
  256. package/dist/tool-keys.js +2 -2
  257. package/dist/tool-list.js +1 -1
  258. package/dist/tool-plane.d.ts +2 -2
  259. package/dist/tool-plane.js +35 -33
  260. package/dist/tools.js +13 -7
  261. package/dist/trigger-targets.d.ts +4 -0
  262. package/dist/trigger-targets.js +9 -2
  263. package/dist/triggers.d.ts +67 -4
  264. package/dist/triggers.js +171 -22
  265. package/dist/until.d.ts +3 -0
  266. package/dist/until.js +11 -0
  267. package/dist/web-fake.d.ts +1 -3
  268. package/dist/web-fake.js +7 -18
  269. package/dist/web-fetch.d.ts +6 -72
  270. package/dist/web-fetch.js +11 -265
  271. package/dist/web-run.d.ts +31 -0
  272. package/dist/web-run.js +90 -0
  273. package/dist/web-save.d.ts +10 -13
  274. package/dist/web-save.js +13 -55
  275. package/dist/web-search.d.ts +9 -127
  276. package/dist/web-search.js +23 -259
  277. package/dist/wires.d.ts +13 -0
  278. package/dist/wires.js +11 -0
  279. package/dist/workflow-run.d.ts +5 -4
  280. package/dist/workflow-run.js +5 -4
  281. package/dist/workspace/attached-computers.d.ts +32 -9
  282. package/dist/workspace/attached-computers.js +77 -13
  283. package/dist/workspace/computer-deps.d.ts +8 -2
  284. package/dist/workspace/computer-deps.js +10 -3
  285. package/dist/workspace/computer-for-claim.d.ts +12 -1
  286. package/dist/workspace/computer-for-claim.js +83 -11
  287. package/dist/workspace/computer-kept.d.ts +3 -0
  288. package/dist/workspace/computer-kept.js +11 -2
  289. package/dist/workspace/index.d.ts +1 -1
  290. package/dist/workspace/index.js +1 -1
  291. package/dist/workspace/kind-skills.d.ts +4 -0
  292. package/dist/workspace/kind-skills.js +9 -0
  293. package/dist/workspace/paired-route.d.ts +91 -0
  294. package/dist/workspace/paired-route.js +153 -0
  295. package/dist/workspace/synced-folder.js +3 -4
  296. package/dist/wrapped.d.ts +20 -6
  297. package/dist/wrapped.js +66 -25
  298. package/package.json +17 -11
  299. package/skills/agentrun-serve/SKILL.md +4 -0
  300. package/templates/README.md +32 -10
  301. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  302. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  303. package/dist/exa-keyless.d.ts +0 -34
  304. package/dist/exa-keyless.js +0 -118
  305. package/dist/firecrawl-keyless.d.ts +0 -41
  306. package/dist/firecrawl-keyless.js +0 -152
  307. package/dist/keyless-mcp.d.ts +0 -36
  308. package/dist/keyless-mcp.js +0 -127
  309. package/dist/text-urls.d.ts +0 -38
  310. package/dist/text-urls.js +0 -170
  311. package/dist/web-fetch-direct.d.ts +0 -119
  312. package/dist/web-fetch-direct.js +0 -190
package/dist/fal-price.js CHANGED
@@ -4,15 +4,18 @@
4
4
  // - The unit price is the server's own get_pricing, asked with exactly `{ endpoint_id: "<id>" }` (a contract: a fake
5
5
  // server matches arguments by equality), one endpoint a call, kept PRICE_TTL_MS.
6
6
  // - The units are read from the job's input (unitsBefore). Nothing is guessed: an input that leaves out the size or
7
- // length its model would default is unpriceable.
7
+ // length its model would default is unpriceable, and a length is read only from the field that sets it on the
8
+ // endpoints known to take one (NAMED_LENGTH). A job billed by its media's length reads that media first; a talking
9
+ // head reads its voice alone (TALKING_HEADS).
8
10
  // - fal's reply states no cost, so the charge is this estimate (chargeOfJob).
9
11
  // fal can bill what get_pricing does not expose (a minimum, a discount, a rate that depends on a setting such as
10
12
  // resolution): a booked figure is fal's list price for the job, not its invoice.
11
13
  // fal's hosted server also keeps one submission_key journal per fal account, which refuses a key it has seen with another
12
14
  // request: a server at fal's own host scopes each key to the run before it leaves (falKeys).
13
15
  import { createHash } from "node:crypto";
14
- import { mediaSeconds } from "./media-duration.js";
16
+ import { mediaSeconds, voiceSeconds } from "./media-duration.js";
15
17
  import { SAVE_MAX_BYTES, SERVER_SLOTS } from "./web-save.js";
18
+ import { micro } from "./micro.js";
16
19
  /** The host of fal's hosted MCP server (its key endpoint /mcp and its sign-in endpoint /mcp-relay). */
17
20
  export const FAL_MCP_HOST = "mcp.fal.ai";
18
21
  /** A pin's `meter` for a fal server. */
@@ -21,12 +24,17 @@ export const FAL_METER = "fal";
21
24
  export const PRICE_TTL_MS = 5 * 60_000;
22
25
  /** One deadline for reading an input media file's length. */
23
26
  export const MEDIA_TIMEOUT_MS = 120_000;
24
- /** Whether a saved server is fal's: its owner's toolkit for it is `fal`, or its URL is on fal's MCP host. */
25
- export function falServer(url, toolkit) {
26
- return toolkit === FAL_METER || URL.parse(url)?.hostname === FAL_MCP_HOST;
27
- }
28
- /** The `meter` a save pins for a server at `url` with `toolkit` (mcp-gateway.ts mcpPinOf). */
29
- export const meterNamed = (url, toolkit) => (falServer(url, toolkit) ? FAL_METER : undefined);
27
+ /** The most of a talking head's voice read to price it: a minute of 48 kHz stereo 32-bit WAV (23 MB) fits, and fal's
28
+ * talking heads take a minute of voice at most (OmniHuman v1.5's OpenAPI). A larger voice is unpriceable. */
29
+ export const VOICE_MAX_BYTES = 32 * 1024 * 1024;
30
+ /** How a talking head's voice is read: https only, under VOICE_MAX_BYTES, and following no redirect, so a fal.media URL
31
+ * can't send the read to a host whose bytes may change (voiceOf). fal.media serves its files with no redirect. */
32
+ export const VOICE_READ = { maxBytes: VOICE_MAX_BYTES, httpsOnly: true, maxRedirects: 0 };
33
+ /** Whether `url` is on fal's MCP host. */
34
+ const onFalHost = (url) => URL.parse(url)?.hostname === FAL_MCP_HOST;
35
+ /** The one test of a server being fal's: `fal` when `named` (its owner's toolkit for it, or the meter a pin carries) is
36
+ * `fal` or its URL is on fal's MCP host; the `meter` a save pins (mcp-gateway.ts mcpPinOf). */
37
+ export const meterNamed = (url, named) => (named === FAL_METER || onFalHost(url) ? FAL_METER : undefined);
30
38
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
39
  const jobOf = (given) => {
32
40
  const one = isObject(given) ? given : {};
@@ -42,6 +50,8 @@ export function falJobsOf(tool, args) {
42
50
  const requests = isObject(args) && Array.isArray(args.requests) ? args.requests : [];
43
51
  return requests.length ? requests.map(jobOf) : [jobOf(undefined)];
44
52
  }
53
+ /** Whether fal bills a call of `tool`: one that submits jobs. */
54
+ export const falBills = (tool) => falJobsOf(tool, {}) !== undefined;
45
55
  /** fal's image_size presets, in pixels. */
46
56
  const SIZES = { square_hd: [1024, 1024], square: [512, 512], portrait_4_3: [768, 1024], portrait_16_9: [576, 1024], landscape_4_3: [1024, 768], landscape_16_9: [1024, 576] };
47
57
  /** A unit as one of it reads: "per image". */
@@ -61,32 +71,249 @@ function countOf(input, unit) {
61
71
  const n = input[field];
62
72
  return Number.isInteger(n) && n > 0 ? { n: n, from: field } : undefined;
63
73
  }
64
- /** The length in seconds the input names: `duration` ("5", "5s" or a number), duration_seconds, seconds_total,
65
- * music_length_ms, or a music composition plan's sections. */
66
- function namedSeconds(input) {
67
- for (const [field, per] of [["duration", 1], ["duration_seconds", 1], ["seconds_total", 1], ["music_length_ms", 1000]]) {
68
- const given = input[field];
69
- if (given === undefined)
70
- continue;
71
- const said = typeof given === "string" && /^\d+(\.\d+)?s?$/.test(given.trim()) ? Number.parseFloat(given) : given;
72
- return positive(said) ? { seconds: said / per, from: field } : "bad";
73
- }
74
+ /** The endpoints whose input sets the length of the output fal bills, and the one field that does, from fal's OpenAPI
75
+ * (read 2026-11-23): Kling's and Hailuo's `duration` ("5", "10"), Veo's ("4s", "6s", "8s"), ACE-Step's (seconds),
76
+ * Stable Audio's `seconds_total`, and ElevenLabs Music's `music_length_ms` or its composition plan's sections (planSeconds). Only
77
+ * these are read: on another endpoint a length its input names may be a field fal ignores, or none it has, while fal
78
+ * bills its media or an output no input sets, so a job could name 0.001 s and be billed for minutes. A listed endpoint
79
+ * whose input names no length is not priced at the model's default either. */
80
+ const NAMED_LENGTH = new Map([
81
+ ...["fal-ai/kling-video/v2.5-turbo/pro/text-to-video", "fal-ai/kling-video/v2.5-turbo/pro/image-to-video", "fal-ai/kling-video/v3/pro/image-to-video", "fal-ai/minimax/hailuo-02/standard/text-to-video", "fal-ai/veo3/fast", "fal-ai/veo3.1", "fal-ai/veo3.1/fast", "fal-ai/veo3.1/image-to-video", "fal-ai/ace-step"].map((endpoint) => [endpoint, "duration"]),
82
+ ["fal-ai/stable-audio-25/text-to-audio", "seconds_total"],
83
+ ["fal-ai/elevenlabs/music", "music_length_ms"],
84
+ ]);
85
+ /** The length in seconds `input` names in `field` (NAMED_LENGTH): `duration` as "5", "5s" or a number, seconds_total,
86
+ * or music_length_ms; a music job with a composition plan is read by planSeconds. "bad" when it names one that is not
87
+ * above 0; `why`, in words, when what it names can't be the length fal bills. */
88
+ function namedSeconds(input, field) {
89
+ if (field === "music_length_ms" && input.composition_plan !== undefined && input.composition_plan !== null)
90
+ return planSeconds(input);
91
+ const given = input[field];
92
+ if (given === undefined)
93
+ return undefined;
94
+ const said = typeof given === "string" && /^\d+(\.\d+)?s?$/.test(given.trim()) ? Number.parseFloat(given) : given;
95
+ return positive(said) ? { seconds: said / (field === "music_length_ms" ? 1000 : 1), from: field } : "bad";
96
+ }
97
+ /** The length of an ElevenLabs Music job with a composition plan, from fal's OpenAPI (read 2026-11-23): the plan sets the
98
+ * song's length, and music_length_ms is "used only in conjunction with prompt", so a job naming both is not read
99
+ * (either could be what fal bills). The sections' duration_ms are summed only while the model keeps them:
100
+ * respect_sections_durations true, or left out (its default is true); false lets the model change them. */
101
+ function planSeconds(input) {
102
+ if (input.music_length_ms !== undefined)
103
+ return { why: "names both music_length_ms and a composition_plan: a plan sets the song's length and music_length_ms goes only with a prompt (fal's OpenAPI), so send one of them" };
104
+ const keep = input.respect_sections_durations;
105
+ if (keep !== undefined && keep !== true)
106
+ return { why: `has a composition_plan with respect_sections_durations ${JSON.stringify(keep)}, so the model may change its sections' lengths: they are read only when it is true or left out (fal's OpenAPI default is true)` };
74
107
  const sections = isObject(input.composition_plan) ? input.composition_plan.sections : undefined;
75
- if (Array.isArray(sections) && sections.length) {
76
- const each = sections.map((section) => (isObject(section) ? section.duration_ms : undefined));
77
- return each.every(positive) ? { seconds: each.reduce((sum, ms) => sum + ms, 0) / 1000, from: "its composition plan's sections" } : "bad";
78
- }
79
- return undefined;
108
+ if (!Array.isArray(sections) || !sections.length)
109
+ return undefined;
110
+ const each = sections.map((section) => (isObject(section) ? section.duration_ms : undefined));
111
+ return each.every(positive) ? { seconds: each.reduce((sum, ms) => sum + ms, 0) / 1000, from: "its composition plan's sections" } : "bad";
80
112
  }
81
113
  /** The endpoints fal bills per minute of media whose length the input's media bound (fal's model pages, read 2026-11-21):
82
114
  * dubbing and voice isolation return the media they are given, re-voiced or cleaned; speech-to-text returns text, so
83
115
  * its input is the only media to bill; sync-lipsync v2 bills "per minute of video", held at the longest it is given.
84
- * Each settles at the length its output states, if it states one. Another endpoint billed by length
85
- * whose input names none bills its output's (a talking video made from a voice, LatentSync's video, an upscale), which
86
- * no input states: it is unpriceable. */
116
+ * Each settles at the length its output states, if it states one, and none is priced from a length its input names.
117
+ * Another endpoint billed by length, not in NAMED_LENGTH, bills its output's (LatentSync's video, infinitalk's, a
118
+ * merge, an upscale), which no input states: it is unpriceable, but for the talking heads (TALKING_HEADS). */
87
119
  const BY_INPUT_MEDIA = new Set(["fal-ai/elevenlabs/dubbing", "fal-ai/elevenlabs/audio-isolation", "fal-ai/elevenlabs/speech-to-text", "fal-ai/sync-lipsync/v2"]);
88
120
  /** The input's audio_url and video_url. */
89
121
  const mediaOf = (input) => [input.audio_url, input.video_url].filter((url) => typeof url === "string" && url !== "");
122
+ /** The talking heads fal bills per second of the video they make, which runs as long as the voice they lip-sync: fal's
123
+ * OpenAPI (read 2026-11-23) gives OmniHuman v1.5's output `duration` as "Duration of audio input/video output as used
124
+ * for billing", and Fabric's video is its voice's picture. Such a job is held at that voice's length in whole seconds,
125
+ * as fal bills them. The length is read from the audio at its audio_url alone (https only, under VOICE_MAX_BYTES), as
126
+ * long as it plays (media-duration.ts voiceSeconds: an MP3 or a PCM WAV), never from a length its header or its input
127
+ * states, never from its image.
128
+ * The voice is read once here and fetched again by fal, so a host that served this read a short voice and fal a long
129
+ * one would pass the cap: only a voice on fal's own media (fal.media and its subdomains, where fal puts what it makes
130
+ * and what is uploaded to it, a new URL for each file) is priced. Any other is unpriceable.
131
+ * Fabric's rate depends on its resolution (RATE_TIERS). OmniHuman v1.5 has one rate: fal's model page (read
132
+ * 2026-11-23) bills it per second at $0.16, with no rate by resolution or turbo_mode. */
133
+ const TALKING_HEADS = new Set(["veed/fabric-1.0", "fal-ai/bytedance/omnihuman/v1.5"]);
134
+ /** `input`'s `field`, or `fallback` (its default) when the job leaves it out, if it is one of the values `named`
135
+ * (compared exactly: the string "false" is not false); else why not, in words. */
136
+ function settingOf(input, field, named, fallback) {
137
+ const given = input[field];
138
+ if (given === undefined && fallback === undefined)
139
+ return { why: `its ${field} sets, and ${field} has no default and this job sets none` };
140
+ const value = given === undefined ? fallback : given;
141
+ if (!named.includes(value))
142
+ return { why: `its ${field} sets, and fal's model page names no rate for ${field} ${JSON.stringify(given)}` };
143
+ return { value, words: `${field} ${JSON.stringify(value)}${given === undefined ? ", its default" : ""}` };
144
+ }
145
+ /** A rate set by one setting: `rates` by value. */
146
+ const byOne = (unit, field, base, rates, fallback) => ({
147
+ base,
148
+ unit,
149
+ rate: (input) => {
150
+ const setting = settingOf(input, field, [...rates.keys()], fallback);
151
+ return "why" in setting ? setting : { rate: rates.get(setting.value), words: setting.words };
152
+ },
153
+ });
154
+ /** A rate without and with audio. */
155
+ const audio = (off, on) => ({ off, on });
156
+ /** Veo's rate: by its resolution (`rates`, one for each resolution it takes; 720p is the default) and whether it makes
157
+ * audio (on by default). */
158
+ const veo = (base, rates) => ({
159
+ base,
160
+ unit: "seconds",
161
+ rate: (input) => {
162
+ const sound = settingOf(input, "generate_audio", [true, false], true);
163
+ if ("why" in sound)
164
+ return sound;
165
+ const resolution = settingOf(input, "resolution", Object.keys(rates), "720p");
166
+ if ("why" in resolution)
167
+ return resolution;
168
+ const at = rates[resolution.value];
169
+ return { rate: sound.value ? at.on : at.off, words: `${resolution.words}, ${sound.words}` };
170
+ },
171
+ });
172
+ const VEO31 = veo(0.4, { "720p": audio(0.2, 0.4), "1080p": audio(0.2, 0.4), "4k": audio(0.4, 0.6) });
173
+ const VEO31_FAST = veo(0.15, { "720p": audio(0.1, 0.15), "1080p": audio(0.1, 0.15), "4k": audio(0.3, 0.35) });
174
+ const VEO31_LITE = veo(0.05, { "720p": audio(0.03, 0.05), "1080p": audio(0.05, 0.08) });
175
+ /** Kling v3's rate: audio off, on (the default) or with voice control (any element naming a voice_id), each held at no
176
+ * less than `floor` (get_pricing's rate where the page disagrees with it). `voice` is undefined where the page names
177
+ * no rate for voice control. */
178
+ const kling = (base, page, floor = 0) => ({
179
+ base,
180
+ unit: "seconds",
181
+ rate: (input) => {
182
+ const sound = settingOf(input, "generate_audio", [true, false], true);
183
+ if ("why" in sound)
184
+ return sound;
185
+ const elements = input.elements;
186
+ if (elements !== undefined && elements !== null && !Array.isArray(elements))
187
+ return { why: "voice control sets (an element's voice_id), and this job's elements are not a list" };
188
+ // Any element naming a voice_id, whatever its value: the page names no rate for one that turns out not to be a voice.
189
+ const voiced = Array.isArray(elements) && elements.some((element) => isObject(element) && element.voice_id !== undefined && element.voice_id !== null);
190
+ const held = (rate) => Math.max(rate, floor);
191
+ if (voiced && page.voice === undefined)
192
+ return { why: "voice control sets (an element's voice_id), and fal's model page names no rate for voice control" };
193
+ if (voiced && !sound.value)
194
+ return { why: "its generate_audio and voice control set, and fal's model page names no rate for voice control with generate_audio false" };
195
+ if (voiced)
196
+ return { rate: held(page.voice), words: `${sound.words}, with voice control (an element's voice_id)` };
197
+ return { rate: held(sound.value ? page.on : page.off), words: sound.words };
198
+ },
199
+ });
200
+ const IDEOGRAM_V3 = byOne("images", "rendering_speed", 0.03, new Map([["TURBO", 0.03], ["BALANCED", 0.06], ["QUALITY", 0.09]]), "BALANCED");
201
+ /** A web search's charge, per unit: $0.015 when enable_web_search is true (its default is false). */
202
+ const webSearch = (input) => {
203
+ const search = settingOf(input, "enable_web_search", [true, false], false);
204
+ return "why" in search ? search : search.value ? { usd: 0.015, words: "a web search" } : undefined;
205
+ };
206
+ const NANO_BANANA_PRO = { ...byOne("images", "resolution", 0.15, new Map([["1K", 0.15], ["2K", 0.15], ["4K", 0.3]]), "1K"), perUnitUsd: webSearch };
207
+ /** Nano Banana 2: by its resolution, plus a web search's charge and high thinking's ($0.002, thinking_level "high"; none
208
+ * for "minimal" or none, its default), each per unit. */
209
+ const NANO_BANANA_2 = {
210
+ ...byOne("images", "resolution", 0.08, new Map([["0.5K", 0.06], ["1K", 0.08], ["2K", 0.12], ["4K", 0.16]]), "1K"),
211
+ perUnitUsd: (input) => {
212
+ const search = webSearch(input);
213
+ if (search && "why" in search)
214
+ return search;
215
+ const thinking = settingOf(input, "thinking_level", [null, "minimal", "high"], null);
216
+ if ("why" in thinking)
217
+ return thinking;
218
+ const added = [...(search ? [search] : []), ...(thinking.value === "high" ? [{ usd: 0.002, words: "high thinking" }] : [])];
219
+ return added.length ? { usd: micro(added.reduce((sum, one) => sum + one.usd, 0)), words: added.map((one) => one.words).join(" and ") } : undefined;
220
+ },
221
+ };
222
+ const KLING_PRO = kling(0.14, { off: 0.112, on: 0.168, voice: 0.196 }, 0.14);
223
+ const KLING_STANDARD = kling(0.14, { off: 0.084, on: 0.126, voice: 0.154 }, 0.14);
224
+ const FABRIC = byOne("seconds", "resolution", 0.08, new Map([["480p", 0.08], ["720p", 0.15]]));
225
+ const RATE_TIERS = new Map([
226
+ ...["", "/edit", "/remix", "/reframe", "/replace-background", "/generate-transparent"].map((variant) => [`fal-ai/ideogram/v3${variant}`, IDEOGRAM_V3]),
227
+ ...["", "/edit", "/remix"].map((variant) => [`fal-ai/ideogram/character${variant}`, byOne("images", "rendering_speed", 0.05, new Map([["TURBO", 0.1], ["BALANCED", 0.15], ["QUALITY", 0.2]]), "BALANCED")]),
228
+ ...["", "/image-to-video", "/first-last-frame-to-video", "/reference-to-video"].map((variant) => [`fal-ai/veo3.1${variant}`, VEO31]),
229
+ ["fal-ai/veo3.1/extend-video", veo(0.4, { "720p": audio(0.2, 0.4) })],
230
+ ...["/fast", "/fast/image-to-video", "/fast/first-last-frame-to-video", "/fast/reference-to-video"].map((variant) => [`fal-ai/veo3.1${variant}`, VEO31_FAST]),
231
+ ["fal-ai/veo3.1/fast/extend-video", veo(0.15, { "720p": audio(0.1, 0.15) })],
232
+ ...["/lite", "/lite/image-to-video", "/lite/first-last-frame-to-video"].map((variant) => [`fal-ai/veo3.1${variant}`, VEO31_LITE]),
233
+ ...["", "/image-to-video"].map((variant) => [`fal-ai/veo3${variant}`, veo(0.4, { "720p": audio(0.2, 0.4), "1080p": audio(0.2, 0.4) })]),
234
+ ...["/fast", "/fast/image-to-video"].map((variant) => [`fal-ai/veo3${variant}`, veo(0.15, { "720p": audio(0.1, 0.15), "1080p": audio(0.1, 0.15) })]),
235
+ ["fal-ai/kling-video/v3/pro/image-to-video", KLING_PRO],
236
+ ["fal-ai/kling-video/v3/pro/text-to-video", KLING_PRO],
237
+ ["fal-ai/kling-video/v3/standard/image-to-video", KLING_STANDARD],
238
+ ["fal-ai/kling-video/v3/standard/text-to-video", KLING_STANDARD],
239
+ ["fal-ai/kling-video/v3/4k/image-to-video", kling(0.42, { off: 0.42, on: 0.42 })],
240
+ ["fal-ai/sync-lipsync/v2", byOne("minutes", "model", 3, new Map([["lipsync-2", 3], ["lipsync-2-pro", 5]]), "lipsync-2")],
241
+ ["fal-ai/nano-banana-pro", NANO_BANANA_PRO],
242
+ ["fal-ai/nano-banana-pro/edit", NANO_BANANA_PRO],
243
+ ["fal-ai/gemini-3-pro-image-preview", NANO_BANANA_PRO],
244
+ ["fal-ai/gemini-3-pro-image-preview/edit", NANO_BANANA_PRO],
245
+ ...["fal-ai/nano-banana-2", "fal-ai/nano-banana-2/edit", "fal-ai/gemini-3.1-flash-image-preview", "fal-ai/gemini-3.1-flash-image-preview/edit"].map((endpoint) => [endpoint, NANO_BANANA_2]),
246
+ ["veed/fabric-1.0", FABRIC],
247
+ ["veed/fabric-1.0/text", FABRIC],
248
+ ["veed/fabric-1.0/fast", byOne("seconds", "resolution", 0.1, new Map([["480p", 0.1], ["720p", 0.2]]))],
249
+ ]);
250
+ /** The families fal bills by their settings: an endpoint is in one when it is the family's id or under it. Ideogram v4's
251
+ * pages (read 2026-11-23 13:13Z) bill by rendering_speed and megapixels, and get_pricing (13:20:43Z) states most of
252
+ * them in "units", which no input counts, and its tiling and tiling LoRA $0.04 and $0.045 an image: none of its rates
253
+ * is decided here, so each of its endpoints is refused under a cap. Ideogram v4.5 and v4.6 (billed by quality, and
254
+ * v4.6 by size) and Nano Banana 2.1 (by resolution), with their edits, likewise: get_pricing states them in "units"
255
+ * (13:20:43Z), and as families they stay refused whatever unit it states, never held at one flat rate. */
256
+ const TIERED_FAMILIES = ["fal-ai/ideogram/v3", "fal-ai/ideogram/character", "fal-ai/nano-banana-pro", "fal-ai/gemini-3-pro-image-preview", "fal-ai/nano-banana-2", "fal-ai/gemini-3.1-flash-image-preview", "ideogram/v4", "ideogram/v4.5", "ideogram/v4.6", "google/nano-banana-2.1", "fal-ai/veo3", "fal-ai/veo3.1", "fal-ai/kling-video/v3", "fal-ai/sync-lipsync/v2", "veed/fabric-1.0"];
257
+ /** The endpoints in those families with one rate, whatever their settings (their model pages, read 2026-11-23): Kling v3
258
+ * 4k text-to-video ($0.42 with audio on or off), turbo pro ($0.14) and turbo standard ($0.112), motion-control pro
259
+ * ($0.168) and standard ($0.126); Ideogram v3 layerize-text ($0.09 an image, the rate get_pricing states too, read
260
+ * 13:20:43Z); sync-lipsync v2 pro ($5 a minute). */
261
+ const ONE_RATE = new Set([
262
+ "fal-ai/kling-video/v3/4k/text-to-video",
263
+ "fal-ai/kling-video/v3/turbo/pro/image-to-video",
264
+ "fal-ai/kling-video/v3/turbo/pro/text-to-video",
265
+ "fal-ai/kling-video/v3/turbo/standard/image-to-video",
266
+ "fal-ai/kling-video/v3/turbo/standard/text-to-video",
267
+ "fal-ai/kling-video/v3/pro/motion-control",
268
+ "fal-ai/kling-video/v3/standard/motion-control",
269
+ "fal-ai/ideogram/v3/layerize-text",
270
+ "fal-ai/sync-lipsync/v2/pro",
271
+ ]);
272
+ /** What is decided here, for the test that pins it against fal's catalog: the families billed by their settings, the
273
+ * endpoints priced by their settings (RATE_TIERS), and those with one rate (ONE_RATE). */
274
+ export function decidedRates() {
275
+ return { families: [...TIERED_FAMILIES], tiered: [...RATE_TIERS.keys()], oneRate: [...ONE_RATE] };
276
+ }
277
+ /** The rate a job of `endpoint` is billed at, against get_pricing's (in `unit`): `ratio`, its tier's rate over the rate
278
+ * get_pricing states (RATE_TIERS), `perUnitUsd` a charge added to each unit's price, and `words` the settings they came from (none at
279
+ * get_pricing's own rate); or `unknown`, why it can't be known (get_pricing stating it in another unit than its tiers' among them). 1 and nothing for an endpoint with one rate; unknown for
280
+ * an endpoint in a family fal bills by its settings whose rate is not decided here (TIERED_FAMILIES). */
281
+ export function rateOf(endpoint, unit, input) {
282
+ const tiers = RATE_TIERS.get(endpoint);
283
+ if (!tiers) {
284
+ const family = TIERED_FAMILIES.find((id) => endpoint === id || endpoint.startsWith(`${id}/`));
285
+ // A variant fal adds to a family is refused until its rate is decided here, never held at get_pricing's one rate.
286
+ if (family && !ONE_RATE.has(endpoint))
287
+ return { unknown: `fal bills ${family} by its settings and ${endpoint} has no rate decided here` };
288
+ return { ratio: 1, perUnitUsd: 0, words: [] };
289
+ }
290
+ // The ratios and the model page's rates hold only in the unit they were decided in: per second, minute or image.
291
+ if (unit !== tiers.unit)
292
+ return { unknown: `get_pricing states ${endpoint} per ${oneOf(unit)}, and its rates were decided per ${oneOf(tiers.unit)}` };
293
+ if (!isObject(input))
294
+ return { ratio: 1, perUnitUsd: 0, words: [] };
295
+ const bills = `fal bills ${endpoint} per ${oneOf(unit)} at a rate`;
296
+ const tier = tiers.rate(input);
297
+ if ("why" in tier)
298
+ return { unknown: `${bills} ${tier.why}` };
299
+ const extra = tiers.perUnitUsd?.(input);
300
+ if (extra && "why" in extra)
301
+ return { unknown: `${bills} plus a charge ${extra.why}` };
302
+ const ratio = tier.rate / tiers.base;
303
+ return { ratio, perUnitUsd: extra?.usd ?? 0, words: [...(ratio === 1 ? [] : [`× ${shown(ratio)} for ${tier.words} (fal's model page: $${tier.rate} against $${tiers.base})`]), ...(extra ? [`plus $${extra.usd} per ${oneOf(unit)} for ${extra.words}`] : [])] };
304
+ }
305
+ /** A talking head's voice: its input's audio_url when that is an https URL on fal's own media, written as it parses
306
+ * (TALKING_HEADS). */
307
+ function voiceOf(input) {
308
+ const url = typeof input.audio_url === "string" ? URL.parse(input.audio_url) : null;
309
+ // The cap rests on this check. It assumes a file on fal.media never changes: fal gives each file its own path and
310
+ // never overwrites one, so the voice this meter reads (VOICE_READ, no redirect followed) is the voice fal fetches. If
311
+ // fal ever serves changing bytes at one fal.media URL, this is where the cap breaks. The host is the parsed URL's, so
312
+ // fal.media as a user name, a path or a query is not it.
313
+ // The URL read is the URL fal is sent, as written: one whose parsed form differs (case, spaces, dot segments, a port)
314
+ // is not priced, so no difference between two URL parsers can make the read and fal's fetch two files.
315
+ return url?.protocol === "https:" && url.href === input.audio_url && (url.hostname === "fal.media" || url.hostname.endsWith(".fal.media")) ? url.href : undefined;
316
+ }
90
317
  /** ffmpeg-api/compose's timeline end in seconds: the last keyframe's end across its tracks (timestamp and duration are
91
318
  * milliseconds, by its OpenAPI). */
92
319
  function composeSeconds(input) {
@@ -102,6 +329,12 @@ export function unitsBefore(endpoint, unit, input) {
102
329
  return { unknown: `${bills}, which can't be known before the job runs` };
103
330
  if (!isObject(input))
104
331
  return { unknown: `${bills}, and this job has no input to count them from` };
332
+ // limit_generations holds a job to num_images, and is true by default in each fal OpenAPI read with it (Nano Banana
333
+ // Pro, 2, 2.1 and lite, the Gemini image previews, Ideogram v3 layerize-text, their edits; 2026-11-23 13:13Z); false
334
+ // lets its prompt ask for more, and fal bills each image made, so no count can be read. Only true or none is priced.
335
+ if ((unit === "images" || unit === "megapixels") && input.limit_generations !== undefined && input.limit_generations !== true) {
336
+ return { unknown: `${bills}, and this job's limit_generations ${JSON.stringify(input.limit_generations)} lets its prompt ask for more images than num_images, each one billed: it is priced only with limit_generations true or left out (its default is true)` };
337
+ }
105
338
  if (unit === "images" || unit === "audios") {
106
339
  const count = countOf(input, unit);
107
340
  return count ? { units: count.n, from: count.from } : { unknown: `${bills}, and this job's input does not say how many as a whole number above 0` };
@@ -127,15 +360,23 @@ export function unitsBefore(endpoint, unit, input) {
127
360
  const end = composeSeconds(input);
128
361
  return end ? { units: end / per, from: "its timeline's end" } : { unknown: `${bills}, and this job's tracks have no keyframes with a timestamp and a duration to read its length from` };
129
362
  }
130
- const named = namedSeconds(input);
363
+ if (TALKING_HEADS.has(endpoint)) {
364
+ const voice = voiceOf(input);
365
+ return voice ? { voice } : { unknown: `fal bills ${endpoint} per ${oneOf(unit)} of the video it makes, as long as the voice at its audio_url, and this job's audio_url is not an https URL on fal.media, written as fal answered it (a voice fal made, or one uploaded to fal): the voice's length is read before the call and fal fetches it again, and only fal's own media is known to serve the same file both times` };
366
+ }
367
+ if (BY_INPUT_MEDIA.has(endpoint)) {
368
+ const media = mediaOf(input);
369
+ return media.length ? { media } : { unknown: `${bills} of the media it is given, and this job's input has no audio_url or video_url` };
370
+ }
371
+ const field = NAMED_LENGTH.get(endpoint);
372
+ if (!field)
373
+ return { unknown: `${bills}, and no input of this endpoint is known to set the length fal bills, so a length it names is not read` };
374
+ const named = namedSeconds(input, field);
131
375
  if (named === "bad")
132
376
  return { unknown: `${bills}, and the length this job's input names is not a number above 0` };
133
- if (named)
134
- return { units: named.seconds / per, from: named.from };
135
- const media = BY_INPUT_MEDIA.has(endpoint) ? mediaOf(input) : [];
136
- if (media.length)
137
- return { media };
138
- return { unknown: `${bills}, and this job's input names no length (duration, duration_seconds, seconds_total or music_length_ms)` };
377
+ if (named && "why" in named)
378
+ return { unknown: `${bills}, and this job's input ${named.why}` };
379
+ return named ? { units: named.seconds / per, from: named.from } : { unknown: `${bills}, and this job's input names no length (its ${field === "music_length_ms" ? "music_length_ms or composition_plan" : field})` };
139
380
  }
140
381
  return { unknown: `${bills}, a unit this server can't count` };
141
382
  }
@@ -175,17 +416,15 @@ function bodyOf(result) {
175
416
  return undefined;
176
417
  }
177
418
  }
178
- /** In whole millionths of a dollar. */
179
- const usd = (dollars) => Math.round(dollars * 1e6) / 1e6;
180
- const shown = (n) => String(Math.round(n * 1e6) / 1e6);
419
+ const shown = (n) => String(micro(n));
181
420
  /** A MediaReader over the public-host guard web_fetch and web_save download through (`guard`: their fetch options),
182
421
  * within web_save's size cap and download slots. */
183
- export const publicMedia = (guard, slots = SERVER_SLOTS) => async (url, signal) => {
422
+ export const publicMedia = (guard, slots = SERVER_SLOTS) => async (url, signal, read = {}) => {
184
423
  const { publicDownload } = await import("@parcha/pi-browser");
185
424
  const bound = AbortSignal.any([signal, AbortSignal.timeout(MEDIA_TIMEOUT_MS)]);
186
425
  const release = await slots.take(bound);
187
426
  try {
188
- const file = await publicDownload(url, { ...(await guard()), maxBytes: SAVE_MAX_BYTES, signal: bound });
427
+ const file = await publicDownload(url, { ...(await guard()), maxBytes: Math.min(read.maxBytes ?? SAVE_MAX_BYTES, SAVE_MAX_BYTES), httpsOnly: read.httpsOnly === true, maxRedirects: read.maxRedirects, signal: bound });
189
428
  if (!file.bytes)
190
429
  throw new Error(`the host answered ${file.status}`);
191
430
  return file.bytes;
@@ -194,12 +433,19 @@ export const publicMedia = (guard, slots = SERVER_SLOTS) => async (url, signal)
194
433
  release();
195
434
  }
196
435
  };
436
+ /** The endpoints fal bills by a length rounded up to a whole step, in seconds: the talking heads in whole seconds
437
+ * (TALKING_HEADS), ElevenLabs Music and dubbing in whole minutes (fal's model pages, read 2026-11-23: music "will be
438
+ * rounded up to the closest minute", dubbing "based on the closest minute after rounding upwards"). A job of one is
439
+ * held, and settled, at its length rounded up to that step. */
440
+ const BILLING_STEP = new Map([...[...TALKING_HEADS].map((endpoint) => [endpoint, 1]), ["fal-ai/elevenlabs/music", 60], ["fal-ai/elevenlabs/dubbing", 60]]);
197
441
  /** A reply in which fal says it refused the job's input: status "rejected", or an error of type validation_error or
198
442
  * with field_errors. */
199
443
  const refusedInput = (item) => item.status === "rejected" || (isObject(item.error) && (item.error.type === "validation_error" || Array.isArray(item.error.field_errors)));
200
444
  /** What one job charged, by its reply `item` (run_model's reply, or its own entry of submit_jobs'): $0 when the
201
- * submission was replayed or fal refused its input; a completed job's stated units at its unit price; else its hold
202
- * (still running, or nothing stated). Null for a job with no price whose reply says it was accepted. */
445
+ * submission was replayed or fal refused its input; a completed job's stated units at its unit price (its settings'
446
+ * rate, RATE_TIERS; in whole steps for one billed so); else its hold (still running, or nothing stated). Null for a job with no price whose reply says
447
+ * it was accepted. A talking head whose output states no length (Fabric) is booked at its hold: the ledger books its
448
+ * voice's length, read before the call, not a length fal reports. */
203
449
  function chargeOfJob(quote, item) {
204
450
  const hold = "holdUsd" in quote ? quote.holdUsd : null;
205
451
  if (!isObject(item))
@@ -213,34 +459,46 @@ function chargeOfJob(quote, item) {
213
459
  if (!("holdUsd" in quote))
214
460
  return null;
215
461
  const after = item.status === "completed" ? unitsAfter(quote.unit, item.result) : undefined;
216
- return after === undefined ? quote.holdUsd : usd(quote.unitPrice * after);
462
+ if (after === undefined)
463
+ return quote.holdUsd;
464
+ return micro(quote.unitPrice * (quote.step ? roundedUp(after, quote.unit, quote.step) : after));
217
465
  }
466
+ /** `units` of `unit` (seconds or minutes) rounded up to a whole `step` of seconds, in `unit`. Rounded to the
467
+ * microsecond first, so a length a float sum or a conversion leaves a hair over a whole step (125 frames of 0.024 s)
468
+ * is that step. */
469
+ const roundedUp = (units, unit, step) => {
470
+ const per = unit === "minutes" ? 60 : 1;
471
+ return (Math.ceil(Math.round(units * per * 1e6) / 1e6 / step) * step) / per;
472
+ };
218
473
  /** fal's tools that take a submission_key: the three that submit jobs, and get_submission, which reads one back. */
219
474
  const KEYED = new Set(["run_model", "submit_job", "submit_jobs", "get_submission"]);
220
475
  /** fal's longest submission_key: its tools declare `^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`. */
221
- export const KEY_MAX = 128;
476
+ const KEY_MAX = 128;
222
477
  const hex16 = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
478
+ /** What a run adds to each key: `.` and 16 hex. */
479
+ const KEY_TAIL = 17;
480
+ /** The longest submission_key an agent can send fal in a run: fal's KEY_MAX less the run's KEY_TAIL. */
481
+ const KEY_ROOM = KEY_MAX - KEY_TAIL;
482
+ /** The submission keys of a call of fal's `tool`: its own, and for submit_jobs each request's. */
483
+ const keysOf = (tool, args) => [args.submission_key, ...(tool === "submit_jobs" && Array.isArray(args.requests) ? args.requests.map((one) => (isObject(one) ? one.submission_key : undefined)) : [])];
223
484
  /** The submission keys of one run on fal's hosted server (McpMeter.keys). fal's journal is per account, so the same key
224
485
  * from two runs (a model makes the same key for the same task) would bind the second run's request to the first's and be
225
486
  * refused. Each key leaves as the agent's key and `.<16 hex of the run>`: the same run's key leaves the same each time,
226
- * so a retry is deduped, and another run's never matches it. A key too long for KEY_MAX with that suffix keeps its start
227
- * and a hash of the whole key in its place, never cut into another key, and ends `:<16 hex of the run>` instead: its
228
- * shortened start is itself a valid key, and the different mark keeps an agent key that spells it from leaving as the
229
- * same key. `back` reads each scoped key in a reply as the agent's: by the keys this gateway sent, else by taking the
487
+ * on every claim of it, so a retry is deduped, and another run's never matches it. A key with no room for that suffix
488
+ * (over KEY_ROOM) is refused unsent, in words. `back` reads each scoped key in a reply as the agent's by taking the
230
489
  * suffix off. */
231
490
  export function falKeys(run) {
232
491
  const mark = hex16(`agentrun fal submission_key\0${run}`);
233
- const tail = mark.length + 1;
234
- const own = new Map();
235
- const scoped = (key) => {
236
- if (typeof key !== "string" || !key)
237
- return key;
238
- const sent = key.length + tail <= KEY_MAX ? `${key}.${mark}` : `${key.slice(0, KEY_MAX - tail - 17)}.${hex16(key)}:${mark}`;
239
- own.set(sent, key);
240
- return sent;
241
- };
242
- const anyScoped = new RegExp(`[A-Za-z0-9._:-]+[.:]${mark}(?![A-Za-z0-9._:-])`, "g");
492
+ const scoped = (key) => (typeof key === "string" && key ? `${key}.${mark}` : key);
493
+ // The suffix where a key ends: one pass, so an agent's key that itself ends like a scoped one keeps that ending.
494
+ const suffix = new RegExp(`\\.${mark}(?![A-Za-z0-9._:-])`, "g");
243
495
  return {
496
+ refused(tool, args) {
497
+ if (!KEYED.has(tool))
498
+ return undefined;
499
+ const long = keysOf(tool, args).find((key) => typeof key === "string" && key.length > KEY_ROOM);
500
+ return long === undefined ? undefined : `its submission_key ${long.slice(0, 24)}… is ${long.length} characters, over the ${KEY_ROOM} a run can send fal (fal takes ${KEY_MAX}, and the run adds ${KEY_TAIL} to keep its keys its own): send a shorter key`;
501
+ },
244
502
  out(tool, args) {
245
503
  if (!KEYED.has(tool))
246
504
  return args;
@@ -249,29 +507,22 @@ export function falKeys(run) {
249
507
  sent = { ...sent, requests: args.requests.map((one) => (isObject(one) && Object.hasOwn(one, "submission_key") ? { ...one, submission_key: scoped(one.submission_key) } : one)) };
250
508
  return sent;
251
509
  },
252
- back(text) {
253
- if (!text.includes(mark))
254
- return text;
255
- // One pass: a key read back once is never read again, so an agent's key that ends like a scoped one stays as it is.
256
- const known = [...own.keys()].sort((a, b) => b.length - a.length);
257
- return text.replace(anyScoped, (token) => {
258
- const sent = known.find((key) => token.endsWith(key));
259
- return sent ? `${token.slice(0, -sent.length)}${own.get(sent)}` : token.slice(0, -tail);
260
- });
261
- },
510
+ back: (text) => (text.includes(mark) ? text.replace(suffix, "") : text),
262
511
  };
263
512
  }
264
513
  /** A fal server's meter: fal's unit prices read through the gateway's `ask`, kept per endpoint for PRICE_TTL_MS.
265
- * `media` reads an input media file (none: such a job is unpriceable); `now`, the clock; `run`, the run whose
266
- * submission keys it scopes (falKeys; none: they leave as the agent sent them). */
267
- export function falMeter({ media, now = Date.now, run } = {}) {
514
+ * `media` reads an input media file (none: such a job is unpriceable); `now`, the clock. */
515
+ export function falMeter({ media, now = Date.now } = {}) {
268
516
  const prices = new Map();
269
- const unitPrice = async (endpoint, ask) => {
270
- const kept = prices.get(endpoint);
271
- if (kept && now() - kept.at < PRICE_TTL_MS)
272
- return kept;
273
- const answer = await ask("get_pricing", { endpoint_id: endpoint });
517
+ /** The reads under way, by endpoint: calls sent together share one get_pricing call rather than each sending its own.
518
+ * `signal` is the signal of the call that sent it. */
519
+ const reading = new Map();
520
+ const readPrice = async (endpoint, ask) => {
274
521
  const unread = (why) => ({ why: `fal's price for ${endpoint} could not be read (its get_pricing ${why})` });
522
+ // get_pricing reads a price and runs no job: an error or no answer is asked once more, never kept as the price.
523
+ let answer = await ask("get_pricing", { endpoint_id: endpoint });
524
+ if (!answer || answer.isError === true)
525
+ answer = await ask("get_pricing", { endpoint_id: endpoint });
275
526
  if (!answer)
276
527
  return unread("did not answer");
277
528
  if (answer.isError === true)
@@ -279,15 +530,49 @@ export function falMeter({ media, now = Date.now, run } = {}) {
279
530
  const price = priceIn(bodyOf(answer), endpoint);
280
531
  if (!price)
281
532
  return unread("lists no USD price for it");
533
+ // fal bills its jobs: a rate of $0 is no price, so the job is unpriceable (refused under a cap, booked as unknown).
534
+ if (price.unitPrice === 0)
535
+ return unread(`states $0 per ${oneOf(price.unit)} for it, which is no price`);
282
536
  const read = { ...price, at: now() };
283
537
  prices.set(endpoint, read);
284
538
  return read;
285
539
  };
286
- /** The longest of the media at `urls`, in seconds, or the URL whose length could not be read. */
287
- const longest = async (urls, signal) => {
540
+ const unitPrice = async (endpoint, ask, signal) => {
541
+ for (;;) {
542
+ const kept = prices.get(endpoint);
543
+ if (kept && now() - kept.at < PRICE_TTL_MS)
544
+ return kept;
545
+ const shared = reading.get(endpoint);
546
+ if (!shared)
547
+ break;
548
+ try {
549
+ const read = await shared.read;
550
+ // A read whose call stopped (its deadline, its run's abort) got no answer from fal, which says nothing of the
551
+ // price: a call still live reads again, with its own ask. A read that failed while its call was live stands.
552
+ if (!("why" in read) || !shared.signal.aborted || signal.aborted)
553
+ return read;
554
+ }
555
+ catch {
556
+ // The call that sent it threw: this one reads with its own ask.
557
+ }
558
+ if (reading.get(endpoint) === shared)
559
+ reading.delete(endpoint);
560
+ }
561
+ const mine = { read: readPrice(endpoint, ask), signal };
562
+ reading.set(endpoint, mine);
563
+ try {
564
+ return await mine.read;
565
+ }
566
+ finally {
567
+ if (reading.get(endpoint) === mine)
568
+ reading.delete(endpoint);
569
+ }
570
+ };
571
+ /** The longest of the media at `urls`, in seconds by `measure`, or the URL whose length could not be read. */
572
+ const longest = async (urls, signal, read, measure = mediaSeconds) => {
288
573
  const lengths = await Promise.all([...new Set(urls)].map(async (url) => {
289
574
  try {
290
- return (media && mediaSeconds(await media(url, signal))) || { unread: url };
575
+ return (media && measure(await media(url, signal, read))) || { unread: url };
291
576
  }
292
577
  catch {
293
578
  return { unread: url };
@@ -298,9 +583,13 @@ export function falMeter({ media, now = Date.now, run } = {}) {
298
583
  const quoteJob = async (job, ask, signal) => {
299
584
  if (!job.endpoint)
300
585
  return { job, why: "this job names no endpoint_id to price" };
301
- const price = await unitPrice(job.endpoint, ask);
586
+ const price = await unitPrice(job.endpoint, ask, signal);
302
587
  if ("why" in price)
303
588
  return { job, why: price.why };
589
+ // The rate its settings are billed at, before any media is read for a job that can't be priced.
590
+ const rate = rateOf(job.endpoint, price.unit, job.input);
591
+ if ("unknown" in rate)
592
+ return { job, why: rate.unknown };
304
593
  let units = unitsBefore(job.endpoint, price.unit, job.input);
305
594
  if ("media" in units) {
306
595
  const seconds = await longest(units.media, signal);
@@ -308,13 +597,33 @@ export function falMeter({ media, now = Date.now, run } = {}) {
308
597
  return { job, why: `fal bills ${job.endpoint} per ${oneOf(price.unit)} of its input media, and the length of ${seconds.unread.slice(0, 200)} could not be read` };
309
598
  units = { units: seconds / (price.unit === "minutes" ? 60 : 1), from: units.media.length > 1 ? "the longest of its input media, read before the call" : "its input media's length, read before the call" };
310
599
  }
600
+ if ("voice" in units) {
601
+ // The length the voice plays (voiceSeconds), never one its header states: whoever sends the job made the file.
602
+ const seconds = await longest([units.voice], signal, VOICE_READ, voiceSeconds);
603
+ if (typeof seconds !== "number")
604
+ return { job, why: `fal bills ${job.endpoint} per ${oneOf(price.unit)} of the voice at its audio_url, and the length of ${seconds.unread.slice(0, 200)} could not be read` };
605
+ units = { units: seconds / (price.unit === "minutes" ? 60 : 1), from: "its voice at audio_url, read before the call" };
606
+ }
311
607
  if ("unknown" in units)
312
608
  return { job, why: units.unknown };
313
- return { job, holdUsd: usd(price.unitPrice * units.units), unitPrice: price.unitPrice, unit: price.unit, at: price.at, words: `fal's price for ${job.endpoint}: $${price.unitPrice} per ${oneOf(price.unit)} × ${shown(units.units)} (${units.from})` };
609
+ const step = price.unit === "seconds" || price.unit === "minutes" ? BILLING_STEP.get(job.endpoint) : undefined;
610
+ if (step)
611
+ units = { units: roundedUp(units.units, price.unit, step), from: `${units.from}, in whole ${step === 60 ? "minutes" : "seconds"}` };
612
+ // The ratios were decided against get_pricing's rate as it stood (page.base). When fal states another, the scaled
613
+ // rate can fall under what its model page bills this tier, and the hold and the booking (the same unitPrice) with it:
614
+ // the job is held at the higher of the two.
615
+ const scaled = price.unitPrice * rate.ratio;
616
+ const base = RATE_TIERS.get(job.endpoint)?.base;
617
+ // The tier's rate on the model page: the ratio was decided as that rate over base (rateOf).
618
+ const page = base === undefined ? undefined : micro(base * rate.ratio);
619
+ const moved = base !== undefined && page !== undefined && price.unitPrice !== base && page > scaled;
620
+ const rated = (moved ? page : scaled) + rate.perUnitUsd;
621
+ const drift = moved ? [`(get_pricing states $${price.unitPrice}, not the $${base} its rates were decided at: held at the model page's $${page} per ${oneOf(price.unit)})`] : [];
622
+ const words = [`fal's price for ${job.endpoint}: $${price.unitPrice} per ${oneOf(price.unit)}`, ...rate.words, ...drift, `× ${shown(units.units)} (${units.from})`].join(" ");
623
+ return { job, holdUsd: micro(rated * units.units), unitPrice: rated, unit: price.unit, at: price.at, words, ...(step ? { step } : {}) };
314
624
  };
315
625
  return {
316
- ...(run ? { keys: falKeys(run) } : {}),
317
- bills: (tool) => falJobsOf(tool, {}) !== undefined,
626
+ bills: falBills,
318
627
  async quote(tool, args, ask, signal) {
319
628
  const quotes = [];
320
629
  // One at a time: each endpoint's price is read once, the next job's from what the last one kept.
@@ -323,14 +632,15 @@ export function falMeter({ media, now = Date.now, run } = {}) {
323
632
  const priced = quotes.filter((quote) => "holdUsd" in quote);
324
633
  const unpriced = quotes.find((quote) => "why" in quote);
325
634
  const basis = priced.length ? `${priced.map((quote) => quote.words).join("; ")}, from get_pricing at ${new Date(Math.min(...priced.map((quote) => quote.at))).toISOString()}` : "fal's price for it could not be worked out";
326
- const holdUsd = usd(priced.reduce((sum, quote) => sum + quote.holdUsd, 0));
635
+ const holdUsd = micro(priced.reduce((sum, quote) => sum + quote.holdUsd, 0));
327
636
  return {
328
637
  holdUsd,
329
638
  basis: unpriced && priced.length ? `${basis}; not counting what could not be priced` : basis,
330
639
  ...(unpriced ? { unpriceable: unpriced.why } : {}),
331
640
  chargeOf(reply) {
641
+ // A reply lost after the call left: each job at the hold it was sent at, unknown when one had no price.
332
642
  if (!reply)
333
- return null;
643
+ return unpriced ? null : holdUsd;
334
644
  const body = bodyOf(reply);
335
645
  if (tool !== "submit_jobs")
336
646
  return chargeOfJob(quotes[0], body);
@@ -347,7 +657,7 @@ export function falMeter({ media, now = Date.now, run } = {}) {
347
657
  return null;
348
658
  total += charge;
349
659
  }
350
- return usd(total);
660
+ return micro(total);
351
661
  },
352
662
  };
353
663
  },
@@ -355,11 +665,11 @@ export function falMeter({ media, now = Date.now, run } = {}) {
355
665
  }
356
666
  /** The meter of a pinned server (mcp-gateway.ts McpPin entry): fal's for one marked `fal` at its save, or, for a pin made
357
667
  * before servers were marked, one whose URL is on fal's MCP host. Only a server at fal's host scopes its submission keys
358
- * to `deps.run`: the journal they collide in is that server's, and a server marked `fal` elsewhere (a template eval's
359
- * fake, whose answers and log graders read by the agent's own key) receives them as the agent sent them. */
360
- export const meterFor = (pinned, deps) => {
361
- if (!falServer(pinned.url, pinned.meter))
668
+ * to `run` (falKeys): the journal they collide in is that server's, and a server marked `fal` elsewhere (a template
669
+ * eval's fake, whose answers and log graders read by the agent's own key) receives them as the agent sent them. */
670
+ export const meterFor = (pinned, { run, ...deps } = {}) => {
671
+ if (!meterNamed(pinned.url, pinned.meter))
362
672
  return undefined;
363
- const { run, ...rest } = deps ?? {};
364
- return falMeter({ ...rest, ...(run && URL.parse(pinned.url)?.hostname === FAL_MCP_HOST ? { run } : {}) });
673
+ const meter = falMeter(deps);
674
+ return run && onFalHost(pinned.url) ? { ...meter, keys: falKeys(run) } : meter;
365
675
  };