@blockrun/clawrouter 0.12.315 → 0.12.317

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,31 @@ function cloneLimits(limits) {
60318
60319
  }
60319
60320
  return clone2;
60320
60321
  }
60322
+ function mergeSpendHistory(a, b) {
60323
+ const merged = [];
60324
+ const ids = /* @__PURE__ */ new Set();
60325
+ const legacyKept = /* @__PURE__ */ new Map();
60326
+ for (const ledger2 of [a, b]) {
60327
+ const legacySeen = /* @__PURE__ */ new Map();
60328
+ for (const r2 of ledger2) {
60329
+ if (r2.id !== void 0) {
60330
+ if (!ids.has(r2.id)) {
60331
+ ids.add(r2.id);
60332
+ merged.push(r2);
60333
+ }
60334
+ continue;
60335
+ }
60336
+ const key3 = `${r2.timestamp}|${r2.amount}|${r2.model ?? ""}|${r2.action ?? ""}`;
60337
+ const nth = (legacySeen.get(key3) ?? 0) + 1;
60338
+ legacySeen.set(key3, nth);
60339
+ if (nth > (legacyKept.get(key3) ?? 0)) {
60340
+ legacyKept.set(key3, nth);
60341
+ merged.push(r2);
60342
+ }
60343
+ }
60344
+ }
60345
+ return merged.sort((x, y) => x.timestamp - y.timestamp);
60346
+ }
60321
60347
  function canonicalLimits(limits) {
60322
60348
  return JSON.stringify(
60323
60349
  Object.fromEntries(Object.entries(limits).sort(([a], [b]) => a < b ? -1 : 1))
@@ -60526,7 +60552,8 @@ var init_spend_control = __esm({
60526
60552
  timestamp: r2.timestamp,
60527
60553
  amount: r2.amount,
60528
60554
  model: typeof r2.model === "string" ? r2.model : void 0,
60529
- action: typeof r2.action === "string" ? r2.action : void 0
60555
+ action: typeof r2.action === "string" ? r2.action : void 0,
60556
+ ...typeof r2.id === "string" && r2.id !== "" ? { id: r2.id } : {}
60530
60557
  });
60531
60558
  }
60532
60559
  }
@@ -60800,6 +60827,9 @@ var init_spend_control = __esm({
60800
60827
  };
60801
60828
  }
60802
60829
  const now2 = this.now();
60830
+ if (this.limits.hourly !== void 0 || this.limits.daily !== void 0) {
60831
+ this.syncHistory();
60832
+ }
60803
60833
  if (this.limits.perRequest !== void 0) {
60804
60834
  if (estimatedCost3 > this.limits.perRequest) {
60805
60835
  return {
@@ -60862,7 +60892,8 @@ var init_spend_control = __esm({
60862
60892
  timestamp: this.now(),
60863
60893
  amount,
60864
60894
  model: metadata?.model,
60865
- action: metadata?.action
60895
+ action: metadata?.action,
60896
+ id: randomUUID()
60866
60897
  };
60867
60898
  this.history.push(record2);
60868
60899
  this.sessionSpent += amount;
@@ -60993,6 +61024,32 @@ var init_spend_control = __esm({
60993
61024
  this.sessionSpent = 0;
60994
61025
  this.sessionCalls = 0;
60995
61026
  }
61027
+ /**
61028
+ * Fold in spend that other processes recorded to the same spending.json.
61029
+ *
61030
+ * The hourly and daily windows are per wallet, not per process, but each
61031
+ * process used to read the file once at startup and then trust its own copy:
61032
+ * N proxies started on one wallet each let the full window through, and the
61033
+ * last writer's history replaced the others' on disk (GHSA-9xv2-9567-rxrw).
61034
+ * Re-reading before every amount check and every write closes that for
61035
+ * anything not signed in the same instant. Two processes checking within
61036
+ * one signing round trip of each other can still both pass; reservations
61037
+ * are per process by design (see reserve()).
61038
+ *
61039
+ * A read failure keeps the ledger this instance already has: a file we
61040
+ * cannot read is no reason to forget spend we know about.
61041
+ */
61042
+ syncHistory() {
61043
+ let data;
61044
+ try {
61045
+ data = this.storage.load();
61046
+ } catch {
61047
+ return;
61048
+ }
61049
+ if (!data || data.history.length === 0) return;
61050
+ this.history = mergeSpendHistory(this.history, data.history);
61051
+ this.cleanup();
61052
+ }
60996
61053
  cleanup() {
60997
61054
  const cutoff = this.now() - DAY_MS;
60998
61055
  this.history = this.history.filter((r2) => r2.timestamp >= cutoff);
@@ -61002,6 +61059,7 @@ var init_spend_control = __esm({
61002
61059
  return;
61003
61060
  }
61004
61061
  if (!this.limitsDirty && this.storage.saveHistory) {
61062
+ this.syncHistory();
61005
61063
  this.storage.saveHistory([...this.history]);
61006
61064
  return;
61007
61065
  }
@@ -90516,6 +90574,8 @@ var init_session_spend = __esm({
90516
90574
  signedMicros = 0n;
90517
90575
  /** Each signature this request made, in order, at the amount that still counts. */
90518
90576
  signedLog = [];
90577
+ /** API-key rail: the latest dispatch's charge was reported by the gateway and recorded. */
90578
+ lastDispatchCharged = false;
90519
90579
  released = false;
90520
90580
  /**
90521
90581
  * Strict mode: admit the request only if the session's spend, plus what its
@@ -90605,13 +90665,32 @@ var init_session_spend = __esm({
90605
90665
  this.signedMicros += delta;
90606
90666
  this.store.addSessionCost(this.sessionId, delta);
90607
90667
  }
90668
+ /**
90669
+ * API-key rail: a dispatch is about to go out. Its charge, if the gateway
90670
+ * reports one, belongs to it alone — an earlier attempt's reported charge
90671
+ * must not stand in for this one's estimate.
90672
+ */
90673
+ beginDispatch() {
90674
+ this.lastDispatchCharged = false;
90675
+ }
90676
+ /**
90677
+ * API-key rail: the gateway reported what it charged for the latest
90678
+ * dispatch (`x-blockrun-cost-usd`), on whatever status. It is spend now.
90679
+ */
90680
+ recordCharged(chargedMicros) {
90681
+ this.lastDispatchCharged = true;
90682
+ if (chargedMicros <= 0n) return;
90683
+ this.store.addSessionCost(this.sessionId, chargedMicros);
90684
+ this.shrinkHold(chargedMicros);
90685
+ }
90608
90686
  /**
90609
90687
  * 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.
90688
+ * key rail), the local estimate is the only record of the spend — unless the
90689
+ * gateway reported the winning dispatch's charge, which is already recorded.
90690
+ * When a payment was signed, it is already recorded at its real amount.
90612
90691
  */
90613
90692
  recordSuccess(estimateMicros) {
90614
- if (this.signedLog.length > 0 || estimateMicros <= 0n) return;
90693
+ if (this.signedLog.length > 0 || this.lastDispatchCharged || estimateMicros <= 0n) return;
90615
90694
  this.store.addSessionCost(this.sessionId, estimateMicros);
90616
90695
  this.shrinkHold(estimateMicros);
90617
90696
  }
@@ -91725,12 +91804,19 @@ var init_session = __esm({
91725
91804
  });
91726
91805
 
91727
91806
  // src/updater.ts
91807
+ function versionCore(version31) {
91808
+ const core = version31.split(/[+-]/, 1)[0] ?? "";
91809
+ return core.split(".").map((part) => {
91810
+ const value = Number(part);
91811
+ return Number.isFinite(value) ? value : 0;
91812
+ });
91813
+ }
91728
91814
  function compareSemver(a, b) {
91729
- const pa = a.split(".").map(Number);
91730
- const pb = b.split(".").map(Number);
91815
+ const pa = versionCore(a);
91816
+ const pb = versionCore(b);
91731
91817
  for (let i = 0; i < 3; i++) {
91732
- if ((pa[i] || 0) > (pb[i] || 0)) return 1;
91733
- if ((pa[i] || 0) < (pb[i] || 0)) return -1;
91818
+ if ((pa[i] ?? 0) > (pb[i] ?? 0)) return 1;
91819
+ if ((pa[i] ?? 0) < (pb[i] ?? 0)) return -1;
91734
91820
  }
91735
91821
  return 0;
91736
91822
  }
@@ -109156,7 +109242,7 @@ import * as path4 from "path";
109156
109242
  import * as os3 from "os";
109157
109243
  import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey2, sign as ed25519Sign } from "crypto";
109158
109244
  import { AsyncLocalStorage } from "async_hooks";
109159
- import { randomUUID } from "crypto";
109245
+ import { randomUUID as randomUUID2 } from "crypto";
109160
109246
  import * as fs6 from "fs";
109161
109247
  import * as path5 from "path";
109162
109248
  import * as fs7 from "fs";
@@ -111696,7 +111782,7 @@ function lockChannelFile(file2) {
111696
111782
  if (registry22.locks.has(file2)) return void 0;
111697
111783
  const lock = `${file2}.lock`;
111698
111784
  fs6.mkdirSync(path5.dirname(lock), { recursive: true, mode: 448 });
111699
- const token = randomUUID();
111785
+ const token = randomUUID2();
111700
111786
  for (let attempt = 0; attempt < 2; attempt += 1) {
111701
111787
  const tmp = `${lock}.${process.pid}.${token}.tmp`;
111702
111788
  try {
@@ -111916,7 +112002,7 @@ function withDepositBlockhash(paymentRequired, blockhash2) {
111916
112002
  function withPaymentIdentifier(paymentRequired) {
111917
112003
  const declared = paymentRequired.extensions?.[PAYMENT_IDENTIFIER];
111918
112004
  if (typeof declared?.info?.required !== "boolean") return paymentRequired;
111919
- const id2 = `pay_${randomUUID().replace(/-/g, "")}`;
112005
+ const id2 = `pay_${randomUUID2().replace(/-/g, "")}`;
111920
112006
  return {
111921
112007
  ...paymentRequired,
111922
112008
  extensions: { ...paymentRequired.extensions, [PAYMENT_IDENTIFIER]: { ...declared, info: { ...declared.info, id: id2 } } }
@@ -120408,7 +120494,7 @@ var init_dist2 = __esm({
120408
120494
  fsyncDirectory(dir);
120409
120495
  return;
120410
120496
  }
120411
- const tmp = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
120497
+ const tmp = `${this.file}.${process.pid}.${randomUUID2()}.tmp`;
120412
120498
  const fd = fs6.openSync(tmp, "w", 384);
120413
120499
  try {
120414
120500
  fs6.writeSync(fd, JSON.stringify({ version: 1, intents }, null, 2));
@@ -157476,6 +157562,26 @@ function withZeroCapGuard(inner, isFree) {
157476
157562
  return inner(input2, init2);
157477
157563
  };
157478
157564
  }
157565
+ function withSessionCostCap(inner) {
157566
+ return async (input2, init2) => {
157567
+ const store = paymentStore.getStore();
157568
+ const spend = store?.sessionSpend;
157569
+ const published = store?.estimatedUsd;
157570
+ if (spend?.isStrict && published !== void 0) {
157571
+ const attemptMicros = usdToMicros(published);
157572
+ if (!spend.coverPayment(attemptMicros)) {
157573
+ throw new CostCapError(
157574
+ `ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`
157575
+ );
157576
+ }
157577
+ }
157578
+ if (published !== void 0) spend?.beginDispatch();
157579
+ const response = await inner(input2, init2);
157580
+ const charged = gatewaySettledCostUsd(response);
157581
+ if (spend && charged !== void 0) spend.recordCharged(usdToMicros(charged));
157582
+ return response;
157583
+ };
157584
+ }
157479
157585
  function isMessagesPath(url3) {
157480
157586
  return url3 === "/v1/messages" || (url3?.startsWith("/v1/messages?") ?? false);
157481
157587
  }
@@ -157915,15 +158021,17 @@ async function startProxy(options) {
157915
158021
  const { freeIds } = catalog.current();
157916
158022
  return freeIds.has(resolveModelAlias(model)) || [...freeIds].some((id2) => toUpstreamModelId(id2) === model);
157917
158023
  };
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
- }
158024
+ const payFetch = authMode === "api-key" ? withSessionCostCap(
158025
+ withSpendPolicy(
158026
+ options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
158027
+ options.spendControl ?? getSharedSpendControl(),
158028
+ () => {
158029
+ const store = paymentStore.getStore();
158030
+ const published = store?.estimatedUsd;
158031
+ if (store) store.estimatedUsd = void 0;
158032
+ return published;
158033
+ }
158034
+ )
157927
158035
  ) : createPayFetchWithPreAuth(fetch, x402, void 0, {
157928
158036
  skipPreAuth: paymentChain === "solana",
157929
158037
  // Per-request cost estimate so pre-auth is only reused when the cached
@@ -313558,7 +313666,7 @@ import {
313558
313666
  } from "fs";
313559
313667
  import { readFile as readFileAsync } from "fs/promises";
313560
313668
  import { homedir as homedir16 } from "os";
313561
- import { randomUUID as randomUUID2 } from "crypto";
313669
+ import { randomUUID as randomUUID3 } from "crypto";
313562
313670
  import { join as join20 } from "path";
313563
313671
  async function waitForProxyHealth(port, timeoutMs = 3e3) {
313564
313672
  const start = Date.now();
@@ -313573,7 +313681,7 @@ async function waitForProxyHealth(port, timeoutMs = 3e3) {
313573
313681
  return false;
313574
313682
  }
313575
313683
  function writePrivateJsonSync(path8, value) {
313576
- const temporary = `${path8}.tmp.${randomUUID2()}`;
313684
+ const temporary = `${path8}.tmp.${randomUUID3()}`;
313577
313685
  try {
313578
313686
  writeFileSync8(temporary, JSON.stringify(value, null, 2), { mode: 384 });
313579
313687
  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,31 @@ function cloneLimits(limits) {
282617
282618
  }
282618
282619
  return clone2;
282619
282620
  }
282621
+ function mergeSpendHistory(a, b) {
282622
+ const merged = [];
282623
+ const ids = /* @__PURE__ */ new Set();
282624
+ const legacyKept = /* @__PURE__ */ new Map();
282625
+ for (const ledger2 of [a, b]) {
282626
+ const legacySeen = /* @__PURE__ */ new Map();
282627
+ for (const r2 of ledger2) {
282628
+ if (r2.id !== void 0) {
282629
+ if (!ids.has(r2.id)) {
282630
+ ids.add(r2.id);
282631
+ merged.push(r2);
282632
+ }
282633
+ continue;
282634
+ }
282635
+ const key3 = `${r2.timestamp}|${r2.amount}|${r2.model ?? ""}|${r2.action ?? ""}`;
282636
+ const nth = (legacySeen.get(key3) ?? 0) + 1;
282637
+ legacySeen.set(key3, nth);
282638
+ if (nth > (legacyKept.get(key3) ?? 0)) {
282639
+ legacyKept.set(key3, nth);
282640
+ merged.push(r2);
282641
+ }
282642
+ }
282643
+ }
282644
+ return merged.sort((x, y) => x.timestamp - y.timestamp);
282645
+ }
282620
282646
  function canonicalLimits(limits) {
282621
282647
  return JSON.stringify(
282622
282648
  Object.fromEntries(Object.entries(limits).sort(([a], [b]) => a < b ? -1 : 1))
@@ -282672,7 +282698,8 @@ var FileSpendControlStorage = class {
282672
282698
  timestamp: r2.timestamp,
282673
282699
  amount: r2.amount,
282674
282700
  model: typeof r2.model === "string" ? r2.model : void 0,
282675
- action: typeof r2.action === "string" ? r2.action : void 0
282701
+ action: typeof r2.action === "string" ? r2.action : void 0,
282702
+ ...typeof r2.id === "string" && r2.id !== "" ? { id: r2.id } : {}
282676
282703
  });
282677
282704
  }
282678
282705
  }
@@ -282946,6 +282973,9 @@ var SpendControl = class {
282946
282973
  };
282947
282974
  }
282948
282975
  const now2 = this.now();
282976
+ if (this.limits.hourly !== void 0 || this.limits.daily !== void 0) {
282977
+ this.syncHistory();
282978
+ }
282949
282979
  if (this.limits.perRequest !== void 0) {
282950
282980
  if (estimatedCost3 > this.limits.perRequest) {
282951
282981
  return {
@@ -283008,7 +283038,8 @@ var SpendControl = class {
283008
283038
  timestamp: this.now(),
283009
283039
  amount,
283010
283040
  model: metadata?.model,
283011
- action: metadata?.action
283041
+ action: metadata?.action,
283042
+ id: randomUUID()
283012
283043
  };
283013
283044
  this.history.push(record2);
283014
283045
  this.sessionSpent += amount;
@@ -283139,6 +283170,32 @@ var SpendControl = class {
283139
283170
  this.sessionSpent = 0;
283140
283171
  this.sessionCalls = 0;
283141
283172
  }
283173
+ /**
283174
+ * Fold in spend that other processes recorded to the same spending.json.
283175
+ *
283176
+ * The hourly and daily windows are per wallet, not per process, but each
283177
+ * process used to read the file once at startup and then trust its own copy:
283178
+ * N proxies started on one wallet each let the full window through, and the
283179
+ * last writer's history replaced the others' on disk (GHSA-9xv2-9567-rxrw).
283180
+ * Re-reading before every amount check and every write closes that for
283181
+ * anything not signed in the same instant. Two processes checking within
283182
+ * one signing round trip of each other can still both pass; reservations
283183
+ * are per process by design (see reserve()).
283184
+ *
283185
+ * A read failure keeps the ledger this instance already has: a file we
283186
+ * cannot read is no reason to forget spend we know about.
283187
+ */
283188
+ syncHistory() {
283189
+ let data;
283190
+ try {
283191
+ data = this.storage.load();
283192
+ } catch {
283193
+ return;
283194
+ }
283195
+ if (!data || data.history.length === 0) return;
283196
+ this.history = mergeSpendHistory(this.history, data.history);
283197
+ this.cleanup();
283198
+ }
283142
283199
  cleanup() {
283143
283200
  const cutoff = this.now() - DAY_MS;
283144
283201
  this.history = this.history.filter((r2) => r2.timestamp >= cutoff);
@@ -283148,6 +283205,7 @@ var SpendControl = class {
283148
283205
  return;
283149
283206
  }
283150
283207
  if (!this.limitsDirty && this.storage.saveHistory) {
283208
+ this.syncHistory();
283151
283209
  this.storage.saveHistory([...this.history]);
283152
283210
  return;
283153
283211
  }
@@ -290027,6 +290085,8 @@ var SessionSpend = class _SessionSpend {
290027
290085
  signedMicros = 0n;
290028
290086
  /** Each signature this request made, in order, at the amount that still counts. */
290029
290087
  signedLog = [];
290088
+ /** API-key rail: the latest dispatch's charge was reported by the gateway and recorded. */
290089
+ lastDispatchCharged = false;
290030
290090
  released = false;
290031
290091
  /**
290032
290092
  * Strict mode: admit the request only if the session's spend, plus what its
@@ -290116,13 +290176,32 @@ var SessionSpend = class _SessionSpend {
290116
290176
  this.signedMicros += delta;
290117
290177
  this.store.addSessionCost(this.sessionId, delta);
290118
290178
  }
290179
+ /**
290180
+ * API-key rail: a dispatch is about to go out. Its charge, if the gateway
290181
+ * reports one, belongs to it alone — an earlier attempt's reported charge
290182
+ * must not stand in for this one's estimate.
290183
+ */
290184
+ beginDispatch() {
290185
+ this.lastDispatchCharged = false;
290186
+ }
290187
+ /**
290188
+ * API-key rail: the gateway reported what it charged for the latest
290189
+ * dispatch (`x-blockrun-cost-usd`), on whatever status. It is spend now.
290190
+ */
290191
+ recordCharged(chargedMicros) {
290192
+ this.lastDispatchCharged = true;
290193
+ if (chargedMicros <= 0n) return;
290194
+ this.store.addSessionCost(this.sessionId, chargedMicros);
290195
+ this.shrinkHold(chargedMicros);
290196
+ }
290119
290197
  /**
290120
290198
  * 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.
290199
+ * key rail), the local estimate is the only record of the spend — unless the
290200
+ * gateway reported the winning dispatch's charge, which is already recorded.
290201
+ * When a payment was signed, it is already recorded at its real amount.
290123
290202
  */
290124
290203
  recordSuccess(estimateMicros) {
290125
- if (this.signedLog.length > 0 || estimateMicros <= 0n) return;
290204
+ if (this.signedLog.length > 0 || this.lastDispatchCharged || estimateMicros <= 0n) return;
290126
290205
  this.store.addSessionCost(this.sessionId, estimateMicros);
290127
290206
  this.shrinkHold(estimateMicros);
290128
290207
  }
@@ -291163,12 +291242,19 @@ function hashRequestContent(lastUserContent, toolCallNames) {
291163
291242
  // src/updater.ts
291164
291243
  var NPM_REGISTRY = "https://registry.npmjs.org/@blockrun/clawrouter/latest";
291165
291244
  var CHECK_TIMEOUT_MS = 5e3;
291245
+ function versionCore(version31) {
291246
+ const core = version31.split(/[+-]/, 1)[0] ?? "";
291247
+ return core.split(".").map((part) => {
291248
+ const value = Number(part);
291249
+ return Number.isFinite(value) ? value : 0;
291250
+ });
291251
+ }
291166
291252
  function compareSemver(a, b) {
291167
- const pa = a.split(".").map(Number);
291168
- const pb = b.split(".").map(Number);
291253
+ const pa = versionCore(a);
291254
+ const pb = versionCore(b);
291169
291255
  for (let i = 0; i < 3; i++) {
291170
- if ((pa[i] || 0) > (pb[i] || 0)) return 1;
291171
- if ((pa[i] || 0) < (pb[i] || 0)) return -1;
291256
+ if ((pa[i] ?? 0) > (pb[i] ?? 0)) return 1;
291257
+ if ((pa[i] ?? 0) < (pb[i] ?? 0)) return -1;
291172
291258
  }
291173
291259
  return 0;
291174
291260
  }
@@ -293825,6 +293911,26 @@ function withZeroCapGuard(inner, isFree) {
293825
293911
  return inner(input2, init2);
293826
293912
  };
293827
293913
  }
293914
+ function withSessionCostCap(inner) {
293915
+ return async (input2, init2) => {
293916
+ const store = paymentStore.getStore();
293917
+ const spend = store?.sessionSpend;
293918
+ const published = store?.estimatedUsd;
293919
+ if (spend?.isStrict && published !== void 0) {
293920
+ const attemptMicros = usdToMicros(published);
293921
+ if (!spend.coverPayment(attemptMicros)) {
293922
+ throw new CostCapError(
293923
+ `ClawRouter cost cap exceeded: dispatching an estimated $${microsToUsd(attemptMicros).toFixed(6)} would push this session past its maxCostPerRun limit`
293924
+ );
293925
+ }
293926
+ }
293927
+ if (published !== void 0) spend?.beginDispatch();
293928
+ const response = await inner(input2, init2);
293929
+ const charged = gatewaySettledCostUsd(response);
293930
+ if (spend && charged !== void 0) spend.recordCharged(usdToMicros(charged));
293931
+ return response;
293932
+ };
293933
+ }
293828
293934
  function isMessagesPath(url3) {
293829
293935
  return url3 === "/v1/messages" || (url3?.startsWith("/v1/messages?") ?? false);
293830
293936
  }
@@ -294264,15 +294370,17 @@ async function startProxy(options) {
294264
294370
  const { freeIds } = catalog.current();
294265
294371
  return freeIds.has(resolveModelAlias(model)) || [...freeIds].some((id2) => toUpstreamModelId(id2) === model);
294266
294372
  };
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
- }
294373
+ const payFetch = authMode === "api-key" ? withSessionCostCap(
294374
+ withSpendPolicy(
294375
+ options.maxCostPerRunUsd === 0 ? withZeroCapGuard(keyFetch, isFreeForCap) : keyFetch,
294376
+ options.spendControl ?? getSharedSpendControl(),
294377
+ () => {
294378
+ const store = paymentStore.getStore();
294379
+ const published = store?.estimatedUsd;
294380
+ if (store) store.estimatedUsd = void 0;
294381
+ return published;
294382
+ }
294383
+ )
294276
294384
  ) : createPayFetchWithPreAuth(fetch, x402, void 0, {
294277
294385
  skipPreAuth: paymentChain === "solana",
294278
294386
  // Per-request cost estimate so pre-auth is only reused when the cached
@@ -298302,7 +298410,7 @@ import {
298302
298410
  } from "fs";
298303
298411
  import { readFile as readFileAsync } from "fs/promises";
298304
298412
  import { homedir as homedir15 } from "os";
298305
- import { randomUUID as randomUUID2 } from "crypto";
298413
+ import { randomUUID as randomUUID3 } from "crypto";
298306
298414
  import { join as join19 } from "path";
298307
298415
  init_accounts();
298308
298416
 
@@ -310660,7 +310768,7 @@ async function waitForProxyHealth(port, timeoutMs = 3e3) {
310660
310768
  return false;
310661
310769
  }
310662
310770
  function writePrivateJsonSync(path8, value) {
310663
- const temporary = `${path8}.tmp.${randomUUID2()}`;
310771
+ const temporary = `${path8}.tmp.${randomUUID3()}`;
310664
310772
  try {
310665
310773
  writeFileSync8(temporary, JSON.stringify(value, null, 2), { mode: 384 });
310666
310774
  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.317",
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",