@blockrun/clawrouter 0.12.315 → 0.12.316

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
@@ -60293,6 +60293,7 @@ var init_payment_chain = __esm({
60293
60293
  import * as fs from "fs";
60294
60294
  import * as path from "path";
60295
60295
  import { homedir as homedir2 } from "os";
60296
+ import { randomUUID } from "crypto";
60296
60297
  function normalizePayee(value) {
60297
60298
  return EVM_ADDRESS.test(value) ? value.toLowerCase() : value;
60298
60299
  }
@@ -60318,6 +60319,15 @@ function cloneLimits(limits) {
60318
60319
  }
60319
60320
  return clone2;
60320
60321
  }
60322
+ function recordKey(r2) {
60323
+ return r2.id ?? `${r2.timestamp}|${r2.amount}|${r2.model ?? ""}|${r2.action ?? ""}`;
60324
+ }
60325
+ function mergeSpendHistory(a, b) {
60326
+ const byKey = /* @__PURE__ */ new Map();
60327
+ for (const r2 of a) byKey.set(recordKey(r2), r2);
60328
+ for (const r2 of b) if (!byKey.has(recordKey(r2))) byKey.set(recordKey(r2), r2);
60329
+ return [...byKey.values()].sort((x, y) => x.timestamp - y.timestamp);
60330
+ }
60321
60331
  function canonicalLimits(limits) {
60322
60332
  return JSON.stringify(
60323
60333
  Object.fromEntries(Object.entries(limits).sort(([a], [b]) => a < b ? -1 : 1))
@@ -60526,7 +60536,8 @@ var init_spend_control = __esm({
60526
60536
  timestamp: r2.timestamp,
60527
60537
  amount: r2.amount,
60528
60538
  model: typeof r2.model === "string" ? r2.model : void 0,
60529
- action: typeof r2.action === "string" ? r2.action : void 0
60539
+ action: typeof r2.action === "string" ? r2.action : void 0,
60540
+ ...typeof r2.id === "string" && r2.id !== "" ? { id: r2.id } : {}
60530
60541
  });
60531
60542
  }
60532
60543
  }
@@ -60800,6 +60811,9 @@ var init_spend_control = __esm({
60800
60811
  };
60801
60812
  }
60802
60813
  const now2 = this.now();
60814
+ if (this.limits.hourly !== void 0 || this.limits.daily !== void 0) {
60815
+ this.syncHistory();
60816
+ }
60803
60817
  if (this.limits.perRequest !== void 0) {
60804
60818
  if (estimatedCost3 > this.limits.perRequest) {
60805
60819
  return {
@@ -60862,7 +60876,8 @@ var init_spend_control = __esm({
60862
60876
  timestamp: this.now(),
60863
60877
  amount,
60864
60878
  model: metadata?.model,
60865
- action: metadata?.action
60879
+ action: metadata?.action,
60880
+ id: randomUUID()
60866
60881
  };
60867
60882
  this.history.push(record2);
60868
60883
  this.sessionSpent += amount;
@@ -60993,6 +61008,32 @@ var init_spend_control = __esm({
60993
61008
  this.sessionSpent = 0;
60994
61009
  this.sessionCalls = 0;
60995
61010
  }
61011
+ /**
61012
+ * Fold in spend that other processes recorded to the same spending.json.
61013
+ *
61014
+ * The hourly and daily windows are per wallet, not per process, but each
61015
+ * process used to read the file once at startup and then trust its own copy:
61016
+ * N proxies started on one wallet each let the full window through, and the
61017
+ * last writer's history replaced the others' on disk (GHSA-9xv2-9567-rxrw).
61018
+ * Re-reading before every amount check and every write closes that for
61019
+ * anything not signed in the same instant. Two processes checking within
61020
+ * one signing round trip of each other can still both pass; reservations
61021
+ * are per process by design (see reserve()).
61022
+ *
61023
+ * A read failure keeps the ledger this instance already has: a file we
61024
+ * cannot read is no reason to forget spend we know about.
61025
+ */
61026
+ syncHistory() {
61027
+ let data;
61028
+ try {
61029
+ data = this.storage.load();
61030
+ } catch {
61031
+ return;
61032
+ }
61033
+ if (!data || data.history.length === 0) return;
61034
+ this.history = mergeSpendHistory(this.history, data.history);
61035
+ this.cleanup();
61036
+ }
60996
61037
  cleanup() {
60997
61038
  const cutoff = this.now() - DAY_MS;
60998
61039
  this.history = this.history.filter((r2) => r2.timestamp >= cutoff);
@@ -61002,6 +61043,7 @@ var init_spend_control = __esm({
61002
61043
  return;
61003
61044
  }
61004
61045
  if (!this.limitsDirty && this.storage.saveHistory) {
61046
+ this.syncHistory();
61005
61047
  this.storage.saveHistory([...this.history]);
61006
61048
  return;
61007
61049
  }
@@ -90516,6 +90558,8 @@ var init_session_spend = __esm({
90516
90558
  signedMicros = 0n;
90517
90559
  /** Each signature this request made, in order, at the amount that still counts. */
90518
90560
  signedLog = [];
90561
+ /** API-key rail: the latest dispatch's charge was reported by the gateway and recorded. */
90562
+ lastDispatchCharged = false;
90519
90563
  released = false;
90520
90564
  /**
90521
90565
  * Strict mode: admit the request only if the session's spend, plus what its
@@ -90605,13 +90649,32 @@ var init_session_spend = __esm({
90605
90649
  this.signedMicros += delta;
90606
90650
  this.store.addSessionCost(this.sessionId, delta);
90607
90651
  }
90652
+ /**
90653
+ * API-key rail: a dispatch is about to go out. Its charge, if the gateway
90654
+ * reports one, belongs to it alone — an earlier attempt's reported charge
90655
+ * must not stand in for this one's estimate.
90656
+ */
90657
+ beginDispatch() {
90658
+ this.lastDispatchCharged = false;
90659
+ }
90660
+ /**
90661
+ * API-key rail: the gateway reported what it charged for the latest
90662
+ * dispatch (`x-blockrun-cost-usd`), on whatever status. It is spend now.
90663
+ */
90664
+ recordCharged(chargedMicros) {
90665
+ this.lastDispatchCharged = true;
90666
+ if (chargedMicros <= 0n) return;
90667
+ this.store.addSessionCost(this.sessionId, chargedMicros);
90668
+ this.shrinkHold(chargedMicros);
90669
+ }
90608
90670
  /**
90609
90671
  * An attempt succeeded. When nothing was signed for this request (the API
90610
- * key rail), the local estimate is the only record of the spend. When a
90611
- * payment was signed, it is already recorded at its real amount.
90672
+ * key rail), the local estimate is the only record of the spend — unless the
90673
+ * gateway reported the winning dispatch's charge, which is already recorded.
90674
+ * When a payment was signed, it is already recorded at its real amount.
90612
90675
  */
90613
90676
  recordSuccess(estimateMicros) {
90614
- if (this.signedLog.length > 0 || estimateMicros <= 0n) return;
90677
+ if (this.signedLog.length > 0 || this.lastDispatchCharged || estimateMicros <= 0n) return;
90615
90678
  this.store.addSessionCost(this.sessionId, estimateMicros);
90616
90679
  this.shrinkHold(estimateMicros);
90617
90680
  }
@@ -109156,7 +109219,7 @@ import * as path4 from "path";
109156
109219
  import * as os3 from "os";
109157
109220
  import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey2, sign as ed25519Sign } from "crypto";
109158
109221
  import { AsyncLocalStorage } from "async_hooks";
109159
- import { randomUUID } from "crypto";
109222
+ import { randomUUID as randomUUID2 } from "crypto";
109160
109223
  import * as fs6 from "fs";
109161
109224
  import * as path5 from "path";
109162
109225
  import * as fs7 from "fs";
@@ -111696,7 +111759,7 @@ function lockChannelFile(file2) {
111696
111759
  if (registry22.locks.has(file2)) return void 0;
111697
111760
  const lock = `${file2}.lock`;
111698
111761
  fs6.mkdirSync(path5.dirname(lock), { recursive: true, mode: 448 });
111699
- const token = randomUUID();
111762
+ const token = randomUUID2();
111700
111763
  for (let attempt = 0; attempt < 2; attempt += 1) {
111701
111764
  const tmp = `${lock}.${process.pid}.${token}.tmp`;
111702
111765
  try {
@@ -111916,7 +111979,7 @@ function withDepositBlockhash(paymentRequired, blockhash2) {
111916
111979
  function withPaymentIdentifier(paymentRequired) {
111917
111980
  const declared = paymentRequired.extensions?.[PAYMENT_IDENTIFIER];
111918
111981
  if (typeof declared?.info?.required !== "boolean") return paymentRequired;
111919
- const id2 = `pay_${randomUUID().replace(/-/g, "")}`;
111982
+ const id2 = `pay_${randomUUID2().replace(/-/g, "")}`;
111920
111983
  return {
111921
111984
  ...paymentRequired,
111922
111985
  extensions: { ...paymentRequired.extensions, [PAYMENT_IDENTIFIER]: { ...declared, info: { ...declared.info, id: id2 } } }
@@ -120408,7 +120471,7 @@ var init_dist2 = __esm({
120408
120471
  fsyncDirectory(dir);
120409
120472
  return;
120410
120473
  }
120411
- const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
120474
+ const tmp = `${this.file}.${process.pid}.${randomUUID2()}.tmp`;
120412
120475
  const fd = fs6.openSync(tmp, "w", 384);
120413
120476
  try {
120414
120477
  fs6.writeSync(fd, JSON.stringify({ version: 1, intents }, null, 2));
@@ -157476,6 +157539,26 @@ function withZeroCapGuard(inner, isFree) {
157476
157539
  return inner(input2, init2);
157477
157540
  };
157478
157541
  }
157542
+ function withSessionCostCap(inner) {
157543
+ return async (input2, init2) => {
157544
+ const store = paymentStore.getStore();
157545
+ const spend = store?.sessionSpend;
157546
+ const published = store?.estimatedUsd;
157547
+ if (spend?.isStrict && published !== void 0) {
157548
+ const attemptMicros = usdToMicros(published);
157549
+ if (!spend.coverPayment(attemptMicros)) {
157550
+ throw new CostCapError(
157551
+ `ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`
157552
+ );
157553
+ }
157554
+ }
157555
+ if (published !== void 0) spend?.beginDispatch();
157556
+ const response = await inner(input2, init2);
157557
+ const charged = gatewaySettledCostUsd(response);
157558
+ if (spend && charged !== void 0) spend.recordCharged(usdToMicros(charged));
157559
+ return response;
157560
+ };
157561
+ }
157479
157562
  function isMessagesPath(url3) {
157480
157563
  return url3 === "/v1/messages" || (url3?.startsWith("/v1/messages?") ?? false);
157481
157564
  }
@@ -157915,15 +157998,17 @@ async function startProxy(options) {
157915
157998
  const { freeIds } = catalog.current();
157916
157999
  return freeIds.has(resolveModelAlias(model)) || [...freeIds].some((id2) => toUpstreamModelId(id2) === model);
157917
158000
  };
157918
- const payFetch = authMode === "api-key" ? withSpendPolicy(
157919
- options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
157920
- options.spendControl ?? getSharedSpendControl(),
157921
- () => {
157922
- const store = paymentStore.getStore();
157923
- const published = store?.estimatedUsd;
157924
- if (store) store.estimatedUsd = void 0;
157925
- return published;
157926
- }
158001
+ const payFetch = authMode === "api-key" ? withSessionCostCap(
158002
+ withSpendPolicy(
158003
+ options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
158004
+ options.spendControl ?? getSharedSpendControl(),
158005
+ () => {
158006
+ const store = paymentStore.getStore();
158007
+ const published = store?.estimatedUsd;
158008
+ if (store) store.estimatedUsd = void 0;
158009
+ return published;
158010
+ }
158011
+ )
157927
158012
  ) : createPayFetchWithPreAuth(fetch, x402, void 0, {
157928
158013
  skipPreAuth: paymentChain === "solana",
157929
158014
  // Per-request cost estimate so pre-auth is only reused when the cached
@@ -313558,7 +313643,7 @@ import {
313558
313643
  } from "fs";
313559
313644
  import { readFile as readFileAsync } from "fs/promises";
313560
313645
  import { homedir as homedir16 } from "os";
313561
- import { randomUUID as randomUUID2 } from "crypto";
313646
+ import { randomUUID as randomUUID3 } from "crypto";
313562
313647
  import { join as join20 } from "path";
313563
313648
  async function waitForProxyHealth(port, timeoutMs = 3e3) {
313564
313649
  const start = Date.now();
@@ -313573,7 +313658,7 @@ async function waitForProxyHealth(port, timeoutMs = 3e3) {
313573
313658
  return false;
313574
313659
  }
313575
313660
  function writePrivateJsonSync(path8, value) {
313576
- const temporary = `${path8}.tmp.${randomUUID2()}`;
313661
+ const temporary = `${path8}.tmp.${randomUUID3()}`;
313577
313662
  try {
313578
313663
  writeFileSync8(temporary, JSON.stringify(value, null, 2), { mode: 384 });
313579
313664
  renameSync3(temporary, path8);
package/dist/index.d.ts CHANGED
@@ -855,6 +855,12 @@ interface SpendRecord {
855
855
  amount: number;
856
856
  model?: string;
857
857
  action?: string;
858
+ /**
859
+ * Unique per record, so ledgers written by separate processes sharing one
860
+ * spending.json can be merged without double-counting. Absent on records
861
+ * written before it existed; those merge on their content.
862
+ */
863
+ id?: string;
858
864
  }
859
865
  interface SpendingStatus {
860
866
  limits: SpendLimits;
@@ -1044,6 +1050,22 @@ declare class SpendControl {
1044
1050
  * windows are deliberately untouched.
1045
1051
  */
1046
1052
  resetSession(): void;
1053
+ /**
1054
+ * Fold in spend that other processes recorded to the same spending.json.
1055
+ *
1056
+ * The hourly and daily windows are per wallet, not per process, but each
1057
+ * process used to read the file once at startup and then trust its own copy:
1058
+ * N proxies started on one wallet each let the full window through, and the
1059
+ * last writer's history replaced the others' on disk (GHSA-9xv2-9567-rxrw).
1060
+ * Re-reading before every amount check and every write closes that for
1061
+ * anything not signed in the same instant. Two processes checking within
1062
+ * one signing round trip of each other can still both pass; reservations
1063
+ * are per process by design (see reserve()).
1064
+ *
1065
+ * A read failure keeps the ledger this instance already has: a file we
1066
+ * cannot read is no reason to forget spend we know about.
1067
+ */
1068
+ private syncHistory;
1047
1069
  private cleanup;
1048
1070
  private save;
1049
1071
  private load;
package/dist/index.js CHANGED
@@ -84776,7 +84776,7 @@ import * as path4 from "path";
84776
84776
  import * as os3 from "os";
84777
84777
  import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey2, sign as ed25519Sign } from "crypto";
84778
84778
  import { AsyncLocalStorage } from "async_hooks";
84779
- import { randomUUID } from "crypto";
84779
+ import { randomUUID as randomUUID2 } from "crypto";
84780
84780
  import * as fs6 from "fs";
84781
84781
  import * as path5 from "path";
84782
84782
  import * as fs7 from "fs";
@@ -87316,7 +87316,7 @@ function lockChannelFile(file2) {
87316
87316
  if (registry22.locks.has(file2)) return void 0;
87317
87317
  const lock = `${file2}.lock`;
87318
87318
  fs6.mkdirSync(path5.dirname(lock), { recursive: true, mode: 448 });
87319
- const token = randomUUID();
87319
+ const token = randomUUID2();
87320
87320
  for (let attempt = 0; attempt < 2; attempt += 1) {
87321
87321
  const tmp = `${lock}.${process.pid}.${token}.tmp`;
87322
87322
  try {
@@ -87536,7 +87536,7 @@ function withDepositBlockhash(paymentRequired, blockhash2) {
87536
87536
  function withPaymentIdentifier(paymentRequired) {
87537
87537
  const declared = paymentRequired.extensions?.[PAYMENT_IDENTIFIER];
87538
87538
  if (typeof declared?.info?.required !== "boolean") return paymentRequired;
87539
- const id2 = `pay_${randomUUID().replace(/-/g, "")}`;
87539
+ const id2 = `pay_${randomUUID2().replace(/-/g, "")}`;
87540
87540
  return {
87541
87541
  ...paymentRequired,
87542
87542
  extensions: { ...paymentRequired.extensions, [PAYMENT_IDENTIFIER]: { ...declared, info: { ...declared.info, id: id2 } } }
@@ -96028,7 +96028,7 @@ var init_dist = __esm({
96028
96028
  fsyncDirectory(dir);
96029
96029
  return;
96030
96030
  }
96031
- const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
96031
+ const tmp = `${this.file}.${process.pid}.${randomUUID2()}.tmp`;
96032
96032
  const fd = fs6.openSync(tmp, "w", 384);
96033
96033
  try {
96034
96034
  fs6.writeSync(fd, JSON.stringify({ version: 1, intents }, null, 2));
@@ -282545,6 +282545,7 @@ function resolveMaxTokens(parsed, fallback2 = DEFAULT_MAX_TOKENS) {
282545
282545
  import * as fs from "fs";
282546
282546
  import * as path from "path";
282547
282547
  import { homedir as homedir2 } from "os";
282548
+ import { randomUUID } from "crypto";
282548
282549
 
282549
282550
  // src/payment-chain.ts
282550
282551
  var PAYMENT_CHAINS = ["base", "solana", "arc"];
@@ -282617,6 +282618,15 @@ function cloneLimits(limits) {
282617
282618
  }
282618
282619
  return clone2;
282619
282620
  }
282621
+ function recordKey(r2) {
282622
+ return r2.id ?? `${r2.timestamp}|${r2.amount}|${r2.model ?? ""}|${r2.action ?? ""}`;
282623
+ }
282624
+ function mergeSpendHistory(a, b) {
282625
+ const byKey = /* @__PURE__ */ new Map();
282626
+ for (const r2 of a) byKey.set(recordKey(r2), r2);
282627
+ for (const r2 of b) if (!byKey.has(recordKey(r2))) byKey.set(recordKey(r2), r2);
282628
+ return [...byKey.values()].sort((x, y) => x.timestamp - y.timestamp);
282629
+ }
282620
282630
  function canonicalLimits(limits) {
282621
282631
  return JSON.stringify(
282622
282632
  Object.fromEntries(Object.entries(limits).sort(([a], [b]) => a < b ? -1 : 1))
@@ -282672,7 +282682,8 @@ var FileSpendControlStorage = class {
282672
282682
  timestamp: r2.timestamp,
282673
282683
  amount: r2.amount,
282674
282684
  model: typeof r2.model === "string" ? r2.model : void 0,
282675
- action: typeof r2.action === "string" ? r2.action : void 0
282685
+ action: typeof r2.action === "string" ? r2.action : void 0,
282686
+ ...typeof r2.id === "string" && r2.id !== "" ? { id: r2.id } : {}
282676
282687
  });
282677
282688
  }
282678
282689
  }
@@ -282946,6 +282957,9 @@ var SpendControl = class {
282946
282957
  };
282947
282958
  }
282948
282959
  const now2 = this.now();
282960
+ if (this.limits.hourly !== void 0 || this.limits.daily !== void 0) {
282961
+ this.syncHistory();
282962
+ }
282949
282963
  if (this.limits.perRequest !== void 0) {
282950
282964
  if (estimatedCost3 > this.limits.perRequest) {
282951
282965
  return {
@@ -283008,7 +283022,8 @@ var SpendControl = class {
283008
283022
  timestamp: this.now(),
283009
283023
  amount,
283010
283024
  model: metadata?.model,
283011
- action: metadata?.action
283025
+ action: metadata?.action,
283026
+ id: randomUUID()
283012
283027
  };
283013
283028
  this.history.push(record2);
283014
283029
  this.sessionSpent += amount;
@@ -283139,6 +283154,32 @@ var SpendControl = class {
283139
283154
  this.sessionSpent = 0;
283140
283155
  this.sessionCalls = 0;
283141
283156
  }
283157
+ /**
283158
+ * Fold in spend that other processes recorded to the same spending.json.
283159
+ *
283160
+ * The hourly and daily windows are per wallet, not per process, but each
283161
+ * process used to read the file once at startup and then trust its own copy:
283162
+ * N proxies started on one wallet each let the full window through, and the
283163
+ * last writer's history replaced the others' on disk (GHSA-9xv2-9567-rxrw).
283164
+ * Re-reading before every amount check and every write closes that for
283165
+ * anything not signed in the same instant. Two processes checking within
283166
+ * one signing round trip of each other can still both pass; reservations
283167
+ * are per process by design (see reserve()).
283168
+ *
283169
+ * A read failure keeps the ledger this instance already has: a file we
283170
+ * cannot read is no reason to forget spend we know about.
283171
+ */
283172
+ syncHistory() {
283173
+ let data;
283174
+ try {
283175
+ data = this.storage.load();
283176
+ } catch {
283177
+ return;
283178
+ }
283179
+ if (!data || data.history.length === 0) return;
283180
+ this.history = mergeSpendHistory(this.history, data.history);
283181
+ this.cleanup();
283182
+ }
283142
283183
  cleanup() {
283143
283184
  const cutoff = this.now() - DAY_MS;
283144
283185
  this.history = this.history.filter((r2) => r2.timestamp >= cutoff);
@@ -283148,6 +283189,7 @@ var SpendControl = class {
283148
283189
  return;
283149
283190
  }
283150
283191
  if (!this.limitsDirty && this.storage.saveHistory) {
283192
+ this.syncHistory();
283151
283193
  this.storage.saveHistory([...this.history]);
283152
283194
  return;
283153
283195
  }
@@ -290027,6 +290069,8 @@ var SessionSpend = class _SessionSpend {
290027
290069
  signedMicros = 0n;
290028
290070
  /** Each signature this request made, in order, at the amount that still counts. */
290029
290071
  signedLog = [];
290072
+ /** API-key rail: the latest dispatch's charge was reported by the gateway and recorded. */
290073
+ lastDispatchCharged = false;
290030
290074
  released = false;
290031
290075
  /**
290032
290076
  * Strict mode: admit the request only if the session's spend, plus what its
@@ -290116,13 +290160,32 @@ var SessionSpend = class _SessionSpend {
290116
290160
  this.signedMicros += delta;
290117
290161
  this.store.addSessionCost(this.sessionId, delta);
290118
290162
  }
290163
+ /**
290164
+ * API-key rail: a dispatch is about to go out. Its charge, if the gateway
290165
+ * reports one, belongs to it alone — an earlier attempt's reported charge
290166
+ * must not stand in for this one's estimate.
290167
+ */
290168
+ beginDispatch() {
290169
+ this.lastDispatchCharged = false;
290170
+ }
290171
+ /**
290172
+ * API-key rail: the gateway reported what it charged for the latest
290173
+ * dispatch (`x-blockrun-cost-usd`), on whatever status. It is spend now.
290174
+ */
290175
+ recordCharged(chargedMicros) {
290176
+ this.lastDispatchCharged = true;
290177
+ if (chargedMicros <= 0n) return;
290178
+ this.store.addSessionCost(this.sessionId, chargedMicros);
290179
+ this.shrinkHold(chargedMicros);
290180
+ }
290119
290181
  /**
290120
290182
  * An attempt succeeded. When nothing was signed for this request (the API
290121
- * key rail), the local estimate is the only record of the spend. When a
290122
- * payment was signed, it is already recorded at its real amount.
290183
+ * key rail), the local estimate is the only record of the spend — unless the
290184
+ * gateway reported the winning dispatch's charge, which is already recorded.
290185
+ * When a payment was signed, it is already recorded at its real amount.
290123
290186
  */
290124
290187
  recordSuccess(estimateMicros) {
290125
- if (this.signedLog.length > 0 || estimateMicros <= 0n) return;
290188
+ if (this.signedLog.length > 0 || this.lastDispatchCharged || estimateMicros <= 0n) return;
290126
290189
  this.store.addSessionCost(this.sessionId, estimateMicros);
290127
290190
  this.shrinkHold(estimateMicros);
290128
290191
  }
@@ -293825,6 +293888,26 @@ function withZeroCapGuard(inner, isFree) {
293825
293888
  return inner(input2, init2);
293826
293889
  };
293827
293890
  }
293891
+ function withSessionCostCap(inner) {
293892
+ return async (input2, init2) => {
293893
+ const store = paymentStore.getStore();
293894
+ const spend = store?.sessionSpend;
293895
+ const published = store?.estimatedUsd;
293896
+ if (spend?.isStrict && published !== void 0) {
293897
+ const attemptMicros = usdToMicros(published);
293898
+ if (!spend.coverPayment(attemptMicros)) {
293899
+ throw new CostCapError(
293900
+ `ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`
293901
+ );
293902
+ }
293903
+ }
293904
+ if (published !== void 0) spend?.beginDispatch();
293905
+ const response = await inner(input2, init2);
293906
+ const charged = gatewaySettledCostUsd(response);
293907
+ if (spend && charged !== void 0) spend.recordCharged(usdToMicros(charged));
293908
+ return response;
293909
+ };
293910
+ }
293828
293911
  function isMessagesPath(url3) {
293829
293912
  return url3 === "/v1/messages" || (url3?.startsWith("/v1/messages?") ?? false);
293830
293913
  }
@@ -294264,15 +294347,17 @@ async function startProxy(options) {
294264
294347
  const { freeIds } = catalog.current();
294265
294348
  return freeIds.has(resolveModelAlias(model)) || [...freeIds].some((id2) => toUpstreamModelId(id2) === model);
294266
294349
  };
294267
- const payFetch = authMode === "api-key" ? withSpendPolicy(
294268
- options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
294269
- options.spendControl ?? getSharedSpendControl(),
294270
- () => {
294271
- const store = paymentStore.getStore();
294272
- const published = store?.estimatedUsd;
294273
- if (store) store.estimatedUsd = void 0;
294274
- return published;
294275
- }
294350
+ const payFetch = authMode === "api-key" ? withSessionCostCap(
294351
+ withSpendPolicy(
294352
+ options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
294353
+ options.spendControl ?? getSharedSpendControl(),
294354
+ () => {
294355
+ const store = paymentStore.getStore();
294356
+ const published = store?.estimatedUsd;
294357
+ if (store) store.estimatedUsd = void 0;
294358
+ return published;
294359
+ }
294360
+ )
294276
294361
  ) : createPayFetchWithPreAuth(fetch, x402, void 0, {
294277
294362
  skipPreAuth: paymentChain === "solana",
294278
294363
  // Per-request cost estimate so pre-auth is only reused when the cached
@@ -298302,7 +298387,7 @@ import {
298302
298387
  } from "fs";
298303
298388
  import { readFile as readFileAsync } from "fs/promises";
298304
298389
  import { homedir as homedir15 } from "os";
298305
- import { randomUUID as randomUUID2 } from "crypto";
298390
+ import { randomUUID as randomUUID3 } from "crypto";
298306
298391
  import { join as join19 } from "path";
298307
298392
  init_accounts();
298308
298393
 
@@ -310660,7 +310745,7 @@ async function waitForProxyHealth(port, timeoutMs = 3e3) {
310660
310745
  return false;
310661
310746
  }
310662
310747
  function writePrivateJsonSync(path8, value) {
310663
- const temporary = `${path8}.tmp.${randomUUID2()}`;
310748
+ const temporary = `${path8}.tmp.${randomUUID3()}`;
310664
310749
  try {
310665
310750
  writeFileSync8(temporary, JSON.stringify(value, null, 2), { mode: 384 });
310666
310751
  renameSync3(temporary, path8);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/clawrouter",
3
- "version": "0.12.315",
3
+ "version": "0.12.316",
4
4
  "description": "Smart LLM router — save 84% on inference costs. 91 models (8 free). Pay by credit card (API key) or USDC (x402 wallet).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",