@blockrun/clawrouter 0.12.307 → 0.12.309

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.
package/dist/cli.js CHANGED
@@ -6840,7 +6840,8 @@ var init_top_models = __esm({
6840
6840
  "free/north-mini-code",
6841
6841
  "free/nemotron-3-nano-omni-30b-a3b-reasoning",
6842
6842
  "free/nemotron-3-ultra-550b",
6843
- "free/llama-3.2-11b-vision",
6843
+ "free/nemotron-3.5-bolt",
6844
+ "free/nemotron-3-super-120b",
6844
6845
  "free/muse-glimmer-30b"
6845
6846
  ];
6846
6847
  }
@@ -7328,10 +7329,10 @@ var init_models = __esm({
7328
7329
  "mistral-free": "free/nemotron-3.5-lightning",
7329
7330
  "glm-free": "free/nemotron-3.5-lightning",
7330
7331
  // seed-oss-36b (the prior target) EOL'd 2026-08-03
7331
- // A free Llama exists again: nemotron-super-49b (Llama-3.3-based) hit 410 on
7332
- // 2026-08-30, and a 12-model sweep of what NVIDIA still serves found Llama 3.2
7333
- // 11B Vision as the only one that finishes a real completion.
7334
- "llama-free": "free/llama-3.2-11b-vision",
7332
+ // No free Llama is left: NVIDIA deprovisioned Llama 3.2 11B Vision on 2026-11-02.
7333
+ // blockrun's /free-llama page now leads with Muse, so the shorthand follows it.
7334
+ "llama-free": "free/muse-glimmer-30b",
7335
+ // no free Llama left; Muse is Meta's open line after it
7335
7336
  // qwen3-coder-480b retired 2026-06-14 → seed-oss-36b, which then EOL'd 2026-08-03.
7336
7337
  // Follow the gateway's own retarget rather than chaining to a second dead model.
7337
7338
  "qwen-coder": "free/nemotron-3.5-lightning",
@@ -7370,11 +7371,8 @@ var init_models = __esm({
7370
7371
  // Vision-capable free models
7371
7372
  "nemotron-omni": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
7372
7373
  "nano-omni": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
7373
- // `vision-free` kept for backward compatibility ONLY — it still resolves to
7374
- // nano-omni, which is the strongest free model, but the free tier no longer
7375
- // claims working image input on either chain (see the catalog note). Do not
7376
- // advertise this alias as a way to get free vision.
7377
- "vision-free": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
7374
+ // `vision-free` names the one free model that proved it reads images.
7375
+ "vision-free": "free/nemotron-3.5-bolt",
7378
7376
  // Retired shorthand aliases redirect to live successors. The catch-all target
7379
7377
  // moved llama-4-maverick → gpt-oss-120b (2026-07-17) → step-3.7-flash
7380
7378
  // (2026-08-29) → nemotron-3.5-lightning (2026-08-30, blockrun #448).
@@ -7382,7 +7380,8 @@ var init_models = __esm({
7382
7380
  // strongest live Nemotron
7383
7381
  "nemotron-ultra": "free/nemotron-3.5-lightning",
7384
7382
  "nemotron-253b": "free/nemotron-3.5-lightning",
7385
- "nemotron-super": "free/nemotron-3.5-lightning",
7383
+ "nemotron-super": "free/nemotron-3-super-120b",
7384
+ // now names a real free model
7386
7385
  "nemotron-49b": "free/nemotron-3.5-lightning",
7387
7386
  "nemotron-120b": "free/nemotron-3.5-lightning",
7388
7387
  devstral: "free/nemotron-3.5-lightning",
@@ -7427,6 +7426,12 @@ var init_models = __esm({
7427
7426
  // free on NVIDIA. A reasoning model: a small max_tokens is spent entirely in
7428
7427
  // reasoning and returns empty content.
7429
7428
  "nvidia/muse-glimmer-30b": "free/muse-glimmer-30b",
7429
+ "nvidia/nemotron-3.5-bolt": "free/nemotron-3.5-bolt",
7430
+ "nemotron-3.5-bolt": "free/nemotron-3.5-bolt",
7431
+ bolt: "free/nemotron-3.5-bolt",
7432
+ "nvidia/nemotron-3-super-120b": "free/nemotron-3-super-120b",
7433
+ "nemotron-3-super-120b": "free/nemotron-3-super-120b",
7434
+ "super-120b": "free/nemotron-3-super-120b",
7430
7435
  muse: "free/muse-glimmer-30b",
7431
7436
  "muse-glimmer": "free/muse-glimmer-30b",
7432
7437
  "muse-glimmer-30b": "free/muse-glimmer-30b",
@@ -9145,7 +9150,9 @@ var init_models = __esm({
9145
9150
  // (Llama-3.3-based) hit NVIDIA's 410 EOL. A 12-model sweep found exactly two
9146
9151
  // survivors and only the 11B finishes a real completion. Older than the rest
9147
9152
  // of the tier and deliberately so: it is a real Llama that actually answers.
9148
- // Slowest in the tier (~18 tok/s) — last rung of the cascade.
9153
+ // Retired 2026-11-02: NVIDIA deprovisioned it and blockrun delisted it. Entry
9154
+ // kept so explicit pins stay routable;
9155
+ // off the picker, the FREE_MODELS cascade and every default.
9149
9156
  id: "free/llama-3.2-11b-vision",
9150
9157
  name: "[Free] Llama 3.2 11B Vision",
9151
9158
  version: "3.2-11b-vision",
@@ -9205,6 +9212,35 @@ var init_models = __esm({
9205
9212
  maxOutput: 16384,
9206
9213
  reasoning: true
9207
9214
  },
9215
+ {
9216
+ // Nemotron 3.5 Bolt (blockrun 2026-11-04): about a second to answer, no
9217
+ // thinking pass. The one free model flagged for vision. 2026-11-05, 64x64
9218
+ // solid-colour PNGs: 8 of 8 correct across Base and Solana, and every
9219
+ // response's `model` field named Bolt itself, so no rescue did the reading.
9220
+ id: "free/nemotron-3.5-bolt",
9221
+ name: "[Free] Nemotron 3.5 Bolt",
9222
+ version: "3.5-bolt",
9223
+ inputPrice: 0,
9224
+ outputPrice: 0,
9225
+ contextWindow: 131072,
9226
+ maxOutput: 16384,
9227
+ vision: true
9228
+ },
9229
+ {
9230
+ // Nemotron 3.5 Super, served under its older 3-super-120b id (blockrun
9231
+ // 2026-11-04). Reasoning, and the gateway's redirect target for the retired
9232
+ // Llama. NO `vision`, although blockrun tags it: on 2026-11-05 only 2 of 8
9233
+ // image probes were answered by this model; the rest were rescued by
9234
+ // nano-omni or refused with a capacity 429, which proves nothing about it.
9235
+ id: "free/nemotron-3-super-120b",
9236
+ name: "[Free] Nemotron 3 Super 120B",
9237
+ version: "3-super-120b",
9238
+ inputPrice: 0,
9239
+ outputPrice: 0,
9240
+ contextWindow: 131072,
9241
+ maxOutput: 16384,
9242
+ reasoning: true
9243
+ },
9208
9244
  // ── 2026-08-30 paid catalog refresh (blockrun #449) ─────────────────────
9209
9245
  // Three additions, each probe-verified upstream with a real completion AND a
9210
9246
  // real image before listing. All three carry `vision: true` on that evidence
@@ -89302,7 +89338,7 @@ function usdToMicros(usd2) {
89302
89338
  function microsToUsd(micros) {
89303
89339
  return Number(micros) / 1e6;
89304
89340
  }
89305
- var SessionSpend, CostCapError;
89341
+ var SessionSpend, CostCapError, ZERO_CAP_REFUSAL;
89306
89342
  var init_session_spend = __esm({
89307
89343
  "src/session-spend.ts"() {
89308
89344
  "use strict";
@@ -89437,11 +89473,15 @@ var init_session_spend = __esm({
89437
89473
  }
89438
89474
  };
89439
89475
  CostCapError = class extends SpendPolicyError {
89440
- constructor(reason) {
89476
+ /** A graceful-mode refusal: the budget ran out, and nothing cheaper may be swapped in. */
89477
+ budgetExhausted;
89478
+ constructor(reason, budgetExhausted = false) {
89441
89479
  super(reason);
89442
89480
  this.name = "CostCapError";
89481
+ this.budgetExhausted = budgetExhausted;
89443
89482
  }
89444
89483
  };
89484
+ ZERO_CAP_REFUSAL = "ClawRouter cost cap: maxCostPerRun is 0, so no paid call is made";
89445
89485
  }
89446
89486
  });
89447
89487
 
@@ -155598,7 +155638,116 @@ function gatewaySettledCostUsd(response) {
155598
155638
  if (!Number.isFinite(value) || value < 0) return void 0;
155599
155639
  return value;
155600
155640
  }
155601
- async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPaymentUsd, accountPassthrough = false, authMode = "wallet") {
155641
+ function refuseOverCostCap(res, err) {
155642
+ if (!(err instanceof CostCapError) || res.headersSent) return false;
155643
+ res.writeHead(429, {
155644
+ "Content-Type": "application/json",
155645
+ "X-ClawRouter-Cost-Cap-Exceeded": "1",
155646
+ ...err.budgetExhausted ? { "X-ClawRouter-Budget-Mode": "blocked" } : {}
155647
+ });
155648
+ res.end(
155649
+ JSON.stringify({
155650
+ error: {
155651
+ message: err.message,
155652
+ type: "cost_cap_exceeded",
155653
+ code: err.budgetExhausted ? "budget_exhausted" : "cost_cap_exceeded"
155654
+ }
155655
+ })
155656
+ );
155657
+ return true;
155658
+ }
155659
+ function capMessagesRequest(body, headers, cap) {
155660
+ let parsed = {};
155661
+ try {
155662
+ const value = JSON.parse(body.toString());
155663
+ if (value && typeof value === "object" && !Array.isArray(value)) {
155664
+ parsed = value;
155665
+ }
155666
+ } catch {
155667
+ }
155668
+ const messages = Array.isArray(parsed.messages) ? parsed.messages.filter(
155669
+ (m) => typeof m?.role === "string" && m.content !== void 0
155670
+ ) : [];
155671
+ const sessionId = getSessionId(headers) ?? deriveSessionId(messages) ?? NO_SESSION_ID;
155672
+ const store = paymentStore.getStore();
155673
+ const track = () => {
155674
+ const spend2 = SessionSpend.track(cap.sessions, sessionId);
155675
+ if (store) store.sessionSpend = spend2;
155676
+ return spend2;
155677
+ };
155678
+ const model = typeof parsed.model === "string" ? parsed.model : void 0;
155679
+ if (model !== void 0 && cap.isFree(model)) {
155680
+ track();
155681
+ return { recordSuccess: () => {
155682
+ } };
155683
+ }
155684
+ const estimate = parseMicros(
155685
+ model === void 0 ? void 0 : estimateAmount(
155686
+ resolveModelAlias(model),
155687
+ body.length,
155688
+ resolveMaxTokens(parsed),
155689
+ new Map(cap.models.map((m) => [m.id, m]))
155690
+ )
155691
+ );
155692
+ let spend;
155693
+ if (cap.mode === "strict") {
155694
+ const admission = SessionSpend.admit(
155695
+ cap.sessions,
155696
+ sessionId,
155697
+ usdToMicros(cap.usd),
155698
+ // As on the chat path: the key rail has no signing check behind this one, so
155699
+ // one micro refuses a model it can't price once the session has nothing left.
155700
+ estimate ?? (cap.authMode === "api-key" ? 1n : 0n)
155701
+ );
155702
+ if (!admission.admitted) {
155703
+ const projected = admission.spentMicros + admission.heldMicros + admission.estimateMicros;
155704
+ throw new CostCapError(
155705
+ `ClawRouter cost cap exceeded: projected spend $${microsToUsd(projected).toFixed(4)} would exceed limit $${cap.usd}`
155706
+ );
155707
+ }
155708
+ spend = admission.spend;
155709
+ if (store) store.sessionSpend = spend;
155710
+ } else {
155711
+ const remainingUsd = cap.usd - cap.sessions.getSessionCostUsd(sessionId);
155712
+ const canAfford = estimate !== void 0 ? microsToUsd(estimate) <= remainingUsd : remainingUsd > 0;
155713
+ if (!canAfford) {
155714
+ throw new CostCapError(
155715
+ `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${cap.usd}). Increase maxCostPerRun to continue.`,
155716
+ true
155717
+ );
155718
+ }
155719
+ spend = track();
155720
+ }
155721
+ return {
155722
+ recordSuccess: () => {
155723
+ if (estimate !== void 0) spend.recordSuccess(estimate);
155724
+ }
155725
+ };
155726
+ }
155727
+ function withZeroCapGuard(inner, isFree) {
155728
+ return async (input2, init2) => {
155729
+ const { pathname } = new URL(input2 instanceof Request ? input2.url : String(input2));
155730
+ const path8 = pathname.slice(Math.max(pathname.indexOf("/v1/"), 0));
155731
+ const method = (init2?.method ?? "GET").toUpperCase();
155732
+ let allowed;
155733
+ if (/^\/v1\/(?:chat\/completions|messages)$/.test(path8)) {
155734
+ const body = init2?.body;
155735
+ let model;
155736
+ try {
155737
+ const text = typeof body === "string" ? body : body instanceof Uint8Array ? Buffer.from(body).toString() : "";
155738
+ model = JSON.parse(text).model;
155739
+ } catch {
155740
+ model = void 0;
155741
+ }
155742
+ allowed = typeof model === "string" && isFree(model);
155743
+ } else {
155744
+ allowed = ZERO_CAP_FREE_READ.test(path8) && (method === "GET" || method === "HEAD");
155745
+ }
155746
+ if (!allowed) throw new CostCapError(ZERO_CAP_REFUSAL);
155747
+ return inner(input2, init2);
155748
+ };
155749
+ }
155750
+ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPaymentUsd, accountPassthrough = false, authMode = "wallet", capRequest) {
155602
155751
  const startTime = Date.now();
155603
155752
  const upstreamUrl = `${apiBase}${req.url}`;
155604
155753
  const isBlockrunExa = req.url?.startsWith("/v1/exa/") ?? false;
@@ -155610,6 +155759,7 @@ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPayment
155610
155759
  bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
155611
155760
  }
155612
155761
  const body = Buffer.concat(bodyChunks);
155762
+ const capped = capRequest?.(body);
155613
155763
  const headers = {};
155614
155764
  for (const [key3, value] of Object.entries(req.headers)) {
155615
155765
  if (key3 === "host" || key3 === "connection" || key3 === "transfer-encoding" || key3 === "content-length")
@@ -155631,6 +155781,7 @@ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPayment
155631
155781
  body: body.length > 0 ? new Uint8Array(body) : void 0,
155632
155782
  signal: clientAbort.signal
155633
155783
  });
155784
+ if (upstream.ok) capped?.recordSuccess();
155634
155785
  const responseHeaders = {};
155635
155786
  upstream.headers.forEach((value, key3) => {
155636
155787
  if (key3 === "transfer-encoding" || key3 === "connection" || key3 === "content-encoding" || key3 === "content-length")
@@ -155762,6 +155913,12 @@ function assertExistingProxyBillsUs(existing, requested) {
155762
155913
  }
155763
155914
  }
155764
155915
  async function startProxy(options) {
155916
+ if (options.maxCostPerRunUsd !== void 0 && !Number.isFinite(options.maxCostPerRunUsd)) {
155917
+ console.warn(
155918
+ `[ClawRouter] Ignoring maxCostPerRun: ${String(options.maxCostPerRunUsd)} is not a finite number`
155919
+ );
155920
+ options = { ...options, maxCostPerRunUsd: void 0 };
155921
+ }
155765
155922
  const upstreamProxy = await applyUpstreamProxy(options.upstreamProxy);
155766
155923
  if (upstreamProxy) {
155767
155924
  console.log(`[ClawRouter] Upstream proxy: ${upstreamProxy}`);
@@ -155862,6 +156019,7 @@ async function startProxy(options) {
155862
156019
  const account = walletKey ? privateKeyToAccount(walletKey) : void 0;
155863
156020
  const x402 = authMode === "wallet" ? new x402Client().setSpendControls(false) : void 0;
155864
156021
  const registerCostCapHook = (client) => client.onBeforePaymentCreation(async (context) => {
156022
+ if (options.maxCostPerRunUsd === 0) throw new CostCapError(ZERO_CAP_REFUSAL);
155865
156023
  const spend = paymentStore.getStore()?.sessionSpend;
155866
156024
  if (!spend?.isStrict) return;
155867
156025
  const quote = parseQuotedAmountMicros(context.selectedRequirements);
@@ -155983,8 +156141,13 @@ async function startProxy(options) {
155983
156141
  );
155984
156142
  }
155985
156143
  const requestOptions = solanaBatch ? { ...options, _solanaBatchActive: true } : options;
156144
+ const keyFetch = apiKey ? createApiKeyFetch(apiKey, fetch, apiBase) : void 0;
156145
+ const isFreeForCap = (model) => {
156146
+ const { freeIds } = catalog.current();
156147
+ return freeIds.has(resolveModelAlias(model)) || [...freeIds].some((id2) => toUpstreamModelId(id2) === model);
156148
+ };
155986
156149
  const payFetch = authMode === "api-key" ? withSpendPolicy(
155987
- createApiKeyFetch(apiKey, fetch, apiBase),
156150
+ options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
155988
156151
  options.spendControl ?? getSharedSpendControl(),
155989
156152
  () => {
155990
156153
  const store = paymentStore.getStore();
@@ -156553,6 +156716,7 @@ async function startProxy(options) {
156553
156716
  res.end(JSON.stringify(result));
156554
156717
  } catch (err) {
156555
156718
  if (clientAbort.signal.aborted) return;
156719
+ if (refuseOverCostCap(res, err)) return;
156556
156720
  const msg = err instanceof Error ? err.message : String(err);
156557
156721
  console.error(`[ClawRouter] Image generation error: ${msg}`);
156558
156722
  if (!res.headersSent) {
@@ -156690,6 +156854,7 @@ async function startProxy(options) {
156690
156854
  res.end(JSON.stringify(result));
156691
156855
  } catch (err) {
156692
156856
  if (clientAbort.signal.aborted) return;
156857
+ if (refuseOverCostCap(res, err)) return;
156693
156858
  const msg = err instanceof Error ? err.message : String(err);
156694
156859
  console.error(`[ClawRouter] Image editing error: ${msg}`);
156695
156860
  if (!res.headersSent) {
@@ -156786,6 +156951,7 @@ async function startProxy(options) {
156786
156951
  res.end(JSON.stringify(result));
156787
156952
  } catch (err) {
156788
156953
  if (clientAbort.signal.aborted) return;
156954
+ if (refuseOverCostCap(res, err)) return;
156789
156955
  const msg = err instanceof Error ? err.message : String(err);
156790
156956
  console.error(`[ClawRouter] Audio generation error: ${msg}`);
156791
156957
  if (!res.headersSent) {
@@ -156952,6 +157118,7 @@ async function startProxy(options) {
156952
157118
  res.end(JSON.stringify(finalResult));
156953
157119
  } catch (err) {
156954
157120
  if (clientAbort.signal.aborted) return;
157121
+ if (refuseOverCostCap(res, err)) return;
156955
157122
  const msg = err instanceof Error ? err.message : String(err);
156956
157123
  console.error(`[ClawRouter] Video generation error: ${msg}`);
156957
157124
  if (!res.headersSent) {
@@ -156961,10 +157128,9 @@ async function startProxy(options) {
156961
157128
  }
156962
157129
  return;
156963
157130
  }
156964
- const isVerbatimGatewayPath = req.url === "/v1/messages" || (req.url?.startsWith("/v1/messages?") ?? false) || req.url === "/v1/audio/speech" || (req.url?.startsWith("/v1/audio/speech?") ?? false);
156965
- if (isVerbatimGatewayPath || req.url?.match(
156966
- /^\/v1\/(?:partner|pm|exa|modal|stocks|usstock|crypto|fx|commodity|phone|voice)\//
156967
- )) {
157131
+ const isMessagesPath = req.url === "/v1/messages" || (req.url?.startsWith("/v1/messages?") ?? false);
157132
+ const isVerbatimGatewayPath = isMessagesPath || req.url === "/v1/audio/speech" || (req.url?.startsWith("/v1/audio/speech?") ?? false);
157133
+ if (isVerbatimGatewayPath || req.url?.match(PAID_API_PATH)) {
156968
157134
  try {
156969
157135
  await proxyPaidApiRequest(
156970
157136
  req,
@@ -156973,9 +157139,19 @@ async function startProxy(options) {
156973
157139
  payFetch,
156974
157140
  () => paymentStore.getStore()?.amountUsd ?? 0,
156975
157141
  false,
156976
- authMode
157142
+ authMode,
157143
+ // $0 is enforced below this, where calls are signed or fetched.
157144
+ isMessagesPath && options.maxCostPerRunUsd !== void 0 && options.maxCostPerRunUsd !== 0 ? (body) => capMessagesRequest(body, req.headers, {
157145
+ usd: options.maxCostPerRunUsd,
157146
+ mode: options.maxCostPerRunMode ?? "graceful",
157147
+ authMode,
157148
+ sessions: sessionStore,
157149
+ models: catalog.current().models,
157150
+ isFree: isFreeForCap
157151
+ }) : void 0
156977
157152
  );
156978
157153
  } catch (err) {
157154
+ if (refuseOverCostCap(res, err)) return;
156979
157155
  const error62 = err instanceof Error ? err : new Error(String(err));
156980
157156
  options.onError?.(error62);
156981
157157
  if (!res.headersSent) {
@@ -156988,6 +157164,8 @@ async function startProxy(options) {
156988
157164
  } else if (!res.writableEnded) {
156989
157165
  res.end();
156990
157166
  }
157167
+ } finally {
157168
+ paymentStore.getStore()?.sessionSpend?.release();
156991
157169
  }
156992
157170
  return;
156993
157171
  }
@@ -157008,6 +157186,7 @@ async function startProxy(options) {
157008
157186
  authMode
157009
157187
  );
157010
157188
  } catch (err) {
157189
+ if (refuseOverCostCap(res, err)) return;
157011
157190
  const error62 = err instanceof Error ? err : new Error(String(err));
157012
157191
  options.onError?.(error62);
157013
157192
  if (!res.headersSent) {
@@ -157800,6 +157979,7 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de
157800
157979
  }
157801
157980
  } catch (err) {
157802
157981
  if (imagegenAbort.signal.aborted) return;
157982
+ if (refuseOverCostCap(res, err)) return;
157803
157983
  const errMsg = err instanceof Error ? err.message : String(err);
157804
157984
  console.error(`[ClawRouter] /imagegen error: ${errMsg}`);
157805
157985
  if (!res.headersSent) {
@@ -158006,6 +158186,7 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de
158006
158186
  sendImg2ImgText(responseText);
158007
158187
  } catch (err) {
158008
158188
  if (img2imgAbort.signal.aborted) return;
158189
+ if (refuseOverCostCap(res, err)) return;
158009
158190
  const errMsg = err instanceof Error ? err.message : String(err);
158010
158191
  console.error(`[ClawRouter] /img2img error: ${errMsg}`);
158011
158192
  if (!res.headersSent) {
@@ -158429,13 +158610,20 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de
158429
158610
  }
158430
158611
  }
158431
158612
  let sessionSpend;
158432
- if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "strict") {
158613
+ if (options.maxCostPerRunUsd !== void 0 && !effectiveSessionId) {
158614
+ effectiveSessionId = NO_SESSION_ID;
158615
+ }
158616
+ if (options.maxCostPerRunUsd !== void 0 && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "strict") {
158433
158617
  const thisReqEstStr = estimatedCostMicros !== void 0 ? estimatedCostMicros.toString() : modelId ? estimate(modelId, body.length, maxTokens) : void 0;
158434
158618
  const admission = SessionSpend.admit(
158435
158619
  sessionStore,
158436
158620
  effectiveSessionId,
158437
158621
  usdToMicros(options.maxCostPerRunUsd),
158438
- parseMicros(thisReqEstStr) ?? 0n
158622
+ // No local price usually means zero here: on the wallet rail the signing
158623
+ // check still reads the real quote, and eco's free rungs carry no estimate.
158624
+ // The key rail has nothing behind this check, so count one micro, which
158625
+ // refuses a model it cannot price once the session has nothing left.
158626
+ parseMicros(thisReqEstStr) ?? (options.apiKey?.trim() && !catalog.freeIds.has(resolveModelAlias(modelId ?? "")) ? 1n : 0n)
158439
158627
  );
158440
158628
  if (!admission.admitted) {
158441
158629
  const spentUsd = microsToUsd(admission.spentMicros);
@@ -158463,12 +158651,12 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de
158463
158651
  return;
158464
158652
  }
158465
158653
  sessionSpend = admission.spend;
158466
- } else if (options.maxCostPerRunUsd && effectiveSessionId) {
158654
+ } else if (options.maxCostPerRunUsd !== void 0 && effectiveSessionId) {
158467
158655
  sessionSpend = SessionSpend.track(sessionStore, effectiveSessionId);
158468
158656
  }
158469
158657
  const requestStore = paymentStore.getStore();
158470
158658
  if (requestStore) requestStore.sessionSpend = sessionSpend;
158471
- if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
158659
+ if (options.maxCostPerRunUsd !== void 0 && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
158472
158660
  const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);
158473
158661
  const remainingUsd = options.maxCostPerRunUsd - runCostUsd;
158474
158662
  const isComplexOrAgentic = hasTools || routingDecision?.tier === "COMPLEX" || routingDecision?.tier === "REASONING";
@@ -158501,7 +158689,7 @@ async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, de
158501
158689
  }
158502
158690
  } else if (!routingDecision && modelId && !catalog.freeIds.has(modelId)) {
158503
158691
  const est = estimate(modelId, body.length, maxTokens);
158504
- const canAfford = !est || Number(est) / 1e6 <= remainingUsd;
158692
+ const canAfford = est ? Number(est) / 1e6 <= remainingUsd : remainingUsd > 0;
158505
158693
  if (!canAfford) {
158506
158694
  console.log(
158507
158695
  `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining \u2014 blocking (user explicitly chose ${modelId})`
@@ -158731,14 +158919,14 @@ data: [DONE]
158731
158919
  modelsToTry.push(freeFallback);
158732
158920
  }
158733
158921
  }
158734
- if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
158922
+ if (options.maxCostPerRunUsd !== void 0 && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
158735
158923
  const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);
158736
158924
  const remainingUsd = options.maxCostPerRunUsd - runCostUsd;
158737
158925
  const beforeFilter = [...modelsToTry];
158738
158926
  modelsToTry = modelsToTry.filter((m) => {
158739
- if (catalog.freeIds.has(m)) return true;
158927
+ if (catalog.freeIds.has(resolveModelAlias(m))) return true;
158740
158928
  const est = estimate(m, body.length, maxTokens);
158741
- if (!est) return true;
158929
+ if (!est) return remainingUsd > 0;
158742
158930
  return Number(est) / 1e6 <= remainingUsd;
158743
158931
  });
158744
158932
  const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));
@@ -158777,14 +158965,16 @@ data: [DONE]
158777
158965
  res.removeListener("close", onClientClose);
158778
158966
  return;
158779
158967
  }
158780
- if (excluded.length > 0) {
158968
+ if (excluded.length > 0 && modelsToTry[0] !== beforeFilter[0]) {
158781
158969
  const budgetSummary = remainingUsd > 0 ? `$${remainingUsd.toFixed(4)} remaining` : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;
158782
158970
  console.log(
158783
158971
  `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(", ")}`
158784
158972
  );
158785
158973
  const fromModel = excluded[0];
158786
158974
  const usingFree = modelsToTry.length === 1 && catalog.freeIds.has(modelsToTry[0]);
158787
- if (usingFree) {
158975
+ if (options.maxCostPerRunUsd === 0) {
158976
+ budgetDowngradeNotice = void 0;
158977
+ } else if (usingFree) {
158788
158978
  budgetDowngradeNotice = `> **\u26A0\uFE0F Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) \u2014 downgraded to free model. Quality may be reduced. Increase \`maxCostPerRun\` to continue with ${fromModel}.
158789
158979
 
158790
158980
  `;
@@ -159695,7 +159885,7 @@ data: [DONE]
159695
159885
  });
159696
159886
  }
159697
159887
  }
159698
- var paymentStore, SOLANA_PUBLIC_RPC, BLOCKRUN_API, BLOCKRUN_SOLANA_API, BLOCKRUN_ARC_API, DESKTOP_SERVICE_TOKEN_FILE, IMAGE_DIR, AUDIO_DIR, VIDEO_DIR, AUTO_MODEL, ROUTING_PROFILES, FREE_MODELS, gatewayModelIds, FREE_MODEL, FREE_UPSTREAM_OVERRIDES, MAX_MESSAGES, CONTEXT_LIMIT_KB, HEARTBEAT_INTERVAL_MS, BALANCE_CHECK_TIMEOUT_MS, GATEWAY_CATALOG_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, PER_MODEL_TIMEOUT_MS, REASONING_MODEL_TIMEOUT_MS, MAX_FALLBACK_ATTEMPTS, HEALTH_CHECK_TIMEOUT_MS, RATE_LIMIT_COOLDOWN_MS, OVERLOAD_COOLDOWN_MS, PORT_RETRY_ATTEMPTS, PORT_RETRY_DELAY_MS, MODEL_BODY_READ_TIMEOUT_MS, ERROR_BODY_READ_TIMEOUT_MS, ClientDisconnectedError, rateLimitedModels, overloadedModels, perProviderErrors, BALANCE_CHECK_BUFFER, BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP, PROVIDER_ERROR_PATTERNS, DEGRADED_RESPONSE_PATTERNS, DEGRADED_LOOP_PATTERNS, VALID_ROLES, ROLE_MAPPINGS, VALID_TOOL_ID_PATTERN, KIMI_BLOCK_RE, KIMI_TOKEN_RE, THINKING_TAG_RE, THINKING_BLOCK_RE, BLOCKRUN_MODEL_BY_ID, IMAGE_PRICING, IMAGE_MODEL_IDS, IMAGE_MODEL_SIZES, IMAGE_MODEL_ALIASES, VIDEO_PRICING, PHONE_PRICING, LOW_CREDIT_USD, lowCreditWarned;
159888
+ var paymentStore, SOLANA_PUBLIC_RPC, BLOCKRUN_API, BLOCKRUN_SOLANA_API, BLOCKRUN_ARC_API, DESKTOP_SERVICE_TOKEN_FILE, IMAGE_DIR, AUDIO_DIR, VIDEO_DIR, AUTO_MODEL, ROUTING_PROFILES, FREE_MODELS, gatewayModelIds, FREE_MODEL, FREE_UPSTREAM_OVERRIDES, MAX_MESSAGES, CONTEXT_LIMIT_KB, HEARTBEAT_INTERVAL_MS, BALANCE_CHECK_TIMEOUT_MS, GATEWAY_CATALOG_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, PER_MODEL_TIMEOUT_MS, REASONING_MODEL_TIMEOUT_MS, MAX_FALLBACK_ATTEMPTS, HEALTH_CHECK_TIMEOUT_MS, RATE_LIMIT_COOLDOWN_MS, OVERLOAD_COOLDOWN_MS, PORT_RETRY_ATTEMPTS, PORT_RETRY_DELAY_MS, MODEL_BODY_READ_TIMEOUT_MS, ERROR_BODY_READ_TIMEOUT_MS, ClientDisconnectedError, rateLimitedModels, overloadedModels, perProviderErrors, BALANCE_CHECK_BUFFER, BALANCE_PREFLIGHT_OUTPUT_TOKEN_CAP, PROVIDER_ERROR_PATTERNS, DEGRADED_RESPONSE_PATTERNS, DEGRADED_LOOP_PATTERNS, VALID_ROLES, ROLE_MAPPINGS, VALID_TOOL_ID_PATTERN, KIMI_BLOCK_RE, KIMI_TOKEN_RE, THINKING_TAG_RE, THINKING_BLOCK_RE, BLOCKRUN_MODEL_BY_ID, IMAGE_PRICING, IMAGE_MODEL_IDS, IMAGE_MODEL_SIZES, IMAGE_MODEL_ALIASES, VIDEO_PRICING, PHONE_PRICING, LOW_CREDIT_USD, lowCreditWarned, NO_SESSION_ID, PAID_API_PATH, ZERO_CAP_FREE_READ;
159699
159889
  var init_proxy = __esm({
159700
159890
  "src/proxy.ts"() {
159701
159891
  "use strict";
@@ -159763,12 +159953,14 @@ var init_proxy = __esm({
159763
159953
  // coding, ~161 tok/s — on our NVIDIA key
159764
159954
  "free/north-mini-code",
159765
159955
  // coding, 607ms median — OpenRouter $0 pool
159956
+ "free/nemotron-3.5-bolt",
159957
+ // about a second, reads images
159766
159958
  "free/nemotron-3-nano-omni-30b-a3b-reasoning",
159767
- // vision (text/image/video/audio)
159768
- "free/nemotron-3-ultra-550b",
159959
+ // 256K ctx, reasoning
159960
+ "free/nemotron-3-super-120b",
159961
+ // reasoning; rescued often when capacity is short
159962
+ "free/nemotron-3-ultra-550b"
159769
159963
  // largest free model, 1M ctx — but slow + flaky
159770
- "free/llama-3.2-11b-vision"
159771
- // only free Llama left; slowest, so last
159772
159964
  ]);
159773
159965
  FREE_MODEL = "free/nemotron-3.5-lightning";
159774
159966
  FREE_UPSTREAM_OVERRIDES = {
@@ -159973,9 +160165,7 @@ var init_proxy = __esm({
159973
160165
  "bytedance/seedance-2.5": {
159974
160166
  pricePerSecond: 0.315,
159975
160167
  defaultDurationSeconds: 5
159976
- },
159977
- // Sora 2 via Azure AI Foundry — flat $0.10/s for both t2v and i2v.
159978
- "azure/sora-2": { pricePerSecond: 0.1, defaultDurationSeconds: 4 }
160168
+ }
159979
160169
  };
159980
160170
  PHONE_PRICING = {
159981
160171
  "phone/lookup/fraud": 0.05,
@@ -159988,6 +160178,9 @@ var init_proxy = __esm({
159988
160178
  };
159989
160179
  LOW_CREDIT_USD = 1;
159990
160180
  lowCreditWarned = false;
160181
+ NO_SESSION_ID = "no-session";
160182
+ PAID_API_PATH = /^\/v1\/(?:partner|pm|exa|modal|stocks|usstock|crypto|fx|commodity|phone|voice)\//;
160183
+ ZERO_CAP_FREE_READ = /^\/v1\/(?:models|usage|balance|audio\/models|audio\/voices|images\/models|video\/models|health\/[^/]+)$/;
159991
160184
  }
159992
160185
  });
159993
160186
 
@@ -310503,7 +310696,7 @@ async function startProxyInBackground(api, startupGeneration) {
310503
310696
  api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);
310504
310697
  }
310505
310698
  const routingConfig = api.pluginConfig?.routing;
310506
- const maxCostPerRunUsd = typeof api.pluginConfig?.maxCostPerRun === "number" ? api.pluginConfig.maxCostPerRun : void 0;
310699
+ const maxCostPerRunUsd = typeof api.pluginConfig?.maxCostPerRun === "number" && Number.isFinite(api.pluginConfig.maxCostPerRun) ? api.pluginConfig.maxCostPerRun : void 0;
310507
310700
  const maxCostPerRunMode = api.pluginConfig?.maxCostPerRunMode === "strict" ? "strict" : "graceful";
310508
310701
  if (maxCostPerRunUsd !== void 0) {
310509
310702
  api.logger.info(
package/dist/index.d.ts CHANGED
@@ -1353,7 +1353,9 @@ type ProxyOptions = {
1353
1353
  cacheConfig?: ResponseCacheConfig;
1354
1354
  /**
1355
1355
  * Maximum total spend (in USD) per session run.
1356
- * Default: undefined (no limit). Example: 0.5 = $0.50 per session.
1356
+ * Default: undefined (no limit). Example: 0.5 = $0.50 per session. A positive cap
1357
+ * covers /v1/chat/completions and /v1/messages; 0 refuses every paid call on every
1358
+ * endpoint.
1357
1359
  */
1358
1360
  maxCostPerRunUsd?: number;
1359
1361
  /**