@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.57

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