@blockrun/clawrouter 0.12.297 → 0.12.299

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
@@ -6758,7 +6758,7 @@ var init_api_key = __esm({
6758
6758
  HINTS = {
6759
6759
  401: `Check BLOCKRUN_API_KEY, or mint a new key at ${PORTAL_KEYS_URL}.`,
6760
6760
  402: `Top up your BlockRun credit at ${PORTAL_CREDITS_URL}.`,
6761
- 404: `api.blockrun.ai does not serve this endpoint. Chat, Anthropic-shaped messages, images, speech, video and the partner APIs (Surf, Exa, prediction markets, phone lookup) all work on an API key. The wallet-only exceptions are the routes that bind a lease or a position to a payer address \u2014 buying/renewing/releasing phone numbers, and Polymarket trading \u2014 which need a wallet to own the thing being bought. For those, unset BLOCKRUN_API_KEY and run "clawrouter logout".`
6761
+ 404: `api.blockrun.ai does not serve this endpoint. Chat, Anthropic-shaped messages, images, speech, video and the partner APIs (Exa, prediction markets, phone lookup) all work on an API key. The wallet-only exceptions are the routes that bind a lease or a position to a payer address \u2014 buying/renewing/releasing phone numbers, and Polymarket trading \u2014 which need a wallet to own the thing being bought. For those, unset BLOCKRUN_API_KEY and run "clawrouter logout".`
6762
6762
  };
6763
6763
  }
6764
6764
  });
@@ -67263,7 +67263,7 @@ var require_websocket = __commonJS({
67263
67263
  var net3 = __require("net");
67264
67264
  var tls2 = __require("tls");
67265
67265
  var { randomBytes: randomBytes9, createHash: createHash6 } = __require("crypto");
67266
- var { Duplex, Readable: Readable3 } = __require("stream");
67266
+ var { Duplex, Readable: Readable4 } = __require("stream");
67267
67267
  var { URL: URL3 } = __require("url");
67268
67268
  var PerMessageDeflate2 = require_permessage_deflate();
67269
67269
  var Receiver2 = require_receiver();
@@ -104625,6 +104625,11 @@ ${lines.join("\n")}`;
104625
104625
  });
104626
104626
 
104627
104627
  // src/local-guard.ts
104628
+ import { request as httpRequest } from "http";
104629
+ import { request as httpsRequest } from "https";
104630
+ import { lookup as dnsLookup } from "dns/promises";
104631
+ import { isIP } from "net";
104632
+ import { Readable } from "stream";
104628
104633
  import { closeSync as closeSync3, fstatSync as fstatSync2, openSync as openSync3, readSync as readSync2, realpathSync } from "fs";
104629
104634
  import { homedir as homedir11 } from "os";
104630
104635
  import { join as join15 } from "path";
@@ -104701,18 +104706,84 @@ function isBlockedSsrfHost(hostname) {
104701
104706
  }
104702
104707
  return false;
104703
104708
  }
104709
+ async function resolvePublicAddresses(hostname, resolve2 = systemResolver) {
104710
+ const h = hostname.replace(/^\[/, "").replace(/\]$/, "");
104711
+ const family = isIP(h);
104712
+ const addrs = family ? [{ address: h, family }] : await resolve2(h);
104713
+ if (addrs.length === 0) throw new Error(`could not resolve ${hostname}`);
104714
+ const blocked = addrs.find((a) => isBlockedSsrfHost(a.address));
104715
+ if (blocked) {
104716
+ throw new Error(
104717
+ `refusing to fetch ${hostname}: it resolves to a private/loopback/metadata address (${blocked.address})`
104718
+ );
104719
+ }
104720
+ return addrs;
104721
+ }
104722
+ function pinnedLookup(addrs) {
104723
+ return (_hostname, options, callback) => {
104724
+ if (options.all) {
104725
+ callback(null, addrs);
104726
+ } else {
104727
+ callback(null, addrs[0].address, addrs[0].family);
104728
+ }
104729
+ };
104730
+ }
104731
+ function pinnedFetch(url2, addrs, init2 = {}) {
104732
+ const method = (init2.method ?? "GET").toUpperCase();
104733
+ const body = init2.body;
104734
+ if (body != null && typeof body !== "string" && !(body instanceof Uint8Array)) {
104735
+ return Promise.reject(new TypeError("pinnedFetch supports only string or byte bodies"));
104736
+ }
104737
+ const headers = Object.fromEntries(new Headers(init2.headers));
104738
+ const send = url2.protocol === "https:" ? httpsRequest : httpRequest;
104739
+ return new Promise((resolve2, reject) => {
104740
+ const req = send(
104741
+ url2,
104742
+ { method, headers, lookup: pinnedLookup(addrs), signal: init2.signal ?? void 0 },
104743
+ (res) => {
104744
+ const status2 = res.statusCode ?? 0;
104745
+ if (status2 < 200 || status2 > 599) {
104746
+ res.destroy();
104747
+ reject(new Error(`unexpected HTTP status ${status2} from ${url2.host}`));
104748
+ return;
104749
+ }
104750
+ const resHeaders = new Headers();
104751
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
104752
+ resHeaders.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
104753
+ }
104754
+ const noBody = method === "HEAD" || NULL_BODY_STATUSES.has(status2);
104755
+ if (noBody) res.resume();
104756
+ resolve2(
104757
+ new Response(noBody ? null : Readable.toWeb(res), {
104758
+ status: status2,
104759
+ statusText: res.statusMessage,
104760
+ headers: resHeaders
104761
+ })
104762
+ );
104763
+ }
104764
+ );
104765
+ req.on("error", reject);
104766
+ req.end(body ?? void 0);
104767
+ });
104768
+ }
104704
104769
  async function ssrfSafeFetch(url2, init2 = {}, maxHops = 5) {
104705
- const { allowPrivate, ...fetchInit } = init2;
104770
+ const { allowPrivate, viaUpstreamProxy, resolve: resolve2, ...fetchInit } = init2;
104706
104771
  let current = url2;
104707
104772
  for (let hop = 0; hop <= maxHops; hop++) {
104708
104773
  const u = new URL(current);
104709
104774
  if (u.protocol !== "http:" && u.protocol !== "https:") {
104710
104775
  throw new Error(`refusing to fetch non-http(s) URL (${u.protocol})`);
104711
104776
  }
104712
- if (!allowPrivate && isBlockedSsrfHost(u.hostname)) {
104713
- throw new Error(`refusing to fetch a private/loopback/metadata address: ${u.hostname}`);
104777
+ let res;
104778
+ if (allowPrivate) {
104779
+ res = await fetch(current, { ...fetchInit, redirect: "manual" });
104780
+ } else {
104781
+ if (isBlockedSsrfHost(u.hostname)) {
104782
+ throw new Error(`refusing to fetch a private/loopback/metadata address: ${u.hostname}`);
104783
+ }
104784
+ const addrs = await resolvePublicAddresses(u.hostname, resolve2);
104785
+ res = viaUpstreamProxy ? await fetch(current, { ...fetchInit, redirect: "manual" }) : await pinnedFetch(u, addrs, fetchInit);
104714
104786
  }
104715
- const res = await fetch(current, { ...fetchInit, redirect: "manual" });
104716
104787
  if (res.status >= 300 && res.status < 400) {
104717
104788
  const loc = res.headers.get("location");
104718
104789
  if (!loc) return res;
@@ -104751,11 +104822,13 @@ function readLocalImageAsDataUri(filePath) {
104751
104822
  closeSync3(fd);
104752
104823
  }
104753
104824
  }
104754
- var METADATA_HOSTS, MAX_LOCAL_IMAGE_BYTES, IMAGE_SIGNATURES;
104825
+ var METADATA_HOSTS, systemResolver, NULL_BODY_STATUSES, MAX_LOCAL_IMAGE_BYTES, IMAGE_SIGNATURES;
104755
104826
  var init_local_guard = __esm({
104756
104827
  "src/local-guard.ts"() {
104757
104828
  "use strict";
104758
104829
  METADATA_HOSTS = /* @__PURE__ */ new Set(["metadata", "metadata.goog", "instance-data"]);
104830
+ systemResolver = (hostname) => dnsLookup(hostname, { all: true, verbatim: true });
104831
+ NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
104759
104832
  MAX_LOCAL_IMAGE_BYTES = 25 * 1024 * 1024;
104760
104833
  IMAGE_SIGNATURES = [
104761
104834
  {
@@ -108278,13 +108351,13 @@ var require_util2 = __commonJS({
108278
108351
  function TAOCheck() {
108279
108352
  return "success";
108280
108353
  }
108281
- function appendFetchMetadata(httpRequest) {
108282
- if (!isURLPotentiallyTrustworthy(requestCurrentURL(httpRequest))) {
108354
+ function appendFetchMetadata(httpRequest2) {
108355
+ if (!isURLPotentiallyTrustworthy(requestCurrentURL(httpRequest2))) {
108283
108356
  return;
108284
108357
  }
108285
108358
  let header = null;
108286
- header = httpRequest.mode;
108287
- httpRequest.headersList.set("sec-fetch-mode", header, true);
108359
+ header = httpRequest2.mode;
108360
+ httpRequest2.headersList.set("sec-fetch-mode", header, true);
108288
108361
  }
108289
108362
  function appendRequestOriginHeader(request2) {
108290
108363
  let serializedOrigin = request2.origin;
@@ -120163,7 +120236,7 @@ var require_readable = __commonJS({
120163
120236
  "use strict";
120164
120237
  var assert10 = __require("assert");
120165
120238
  var { addAbortListener } = __require("events");
120166
- var { Readable: Readable3 } = __require("stream");
120239
+ var { Readable: Readable4 } = __require("stream");
120167
120240
  var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors();
120168
120241
  var util5 = require_util();
120169
120242
  var kConsume = /* @__PURE__ */ Symbol("kConsume");
@@ -120176,7 +120249,7 @@ var require_readable = __commonJS({
120176
120249
  var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
120177
120250
  var noop2 = () => {
120178
120251
  };
120179
- var BodyReadable = class extends Readable3 {
120252
+ var BodyReadable = class extends Readable4 {
120180
120253
  /**
120181
120254
  * @param {object} opts
120182
120255
  * @param {(this: Readable, size: number) => void} opts.resume
@@ -120575,7 +120648,7 @@ var require_api_request = __commonJS({
120575
120648
  "use strict";
120576
120649
  var assert10 = __require("assert");
120577
120650
  var { AsyncResource } = __require("async_hooks");
120578
- var { Readable: Readable3 } = require_readable();
120651
+ var { Readable: Readable4 } = require_readable();
120579
120652
  var { InvalidArgumentError, RequestAbortedError } = require_errors();
120580
120653
  var util5 = require_util();
120581
120654
  function noop2() {
@@ -120661,7 +120734,7 @@ var require_api_request = __commonJS({
120661
120734
  const parsedHeaders = headers;
120662
120735
  const contentType = parsedHeaders?.["content-type"];
120663
120736
  const contentLength = parsedHeaders?.["content-length"];
120664
- const res = new Readable3({
120737
+ const res = new Readable4({
120665
120738
  resume: () => controller.resume(),
120666
120739
  abort: (reason) => controller.abort(reason),
120667
120740
  contentType,
@@ -121037,7 +121110,7 @@ var require_api_pipeline = __commonJS({
121037
121110
  "node_modules/undici/lib/api/api-pipeline.js"(exports, module) {
121038
121111
  "use strict";
121039
121112
  var {
121040
- Readable: Readable3,
121113
+ Readable: Readable4,
121041
121114
  Duplex,
121042
121115
  PassThrough
121043
121116
  } = __require("stream");
@@ -121054,7 +121127,7 @@ var require_api_pipeline = __commonJS({
121054
121127
  function noop2() {
121055
121128
  }
121056
121129
  var kResume = /* @__PURE__ */ Symbol("resume");
121057
- var PipelineRequest = class extends Readable3 {
121130
+ var PipelineRequest = class extends Readable4 {
121058
121131
  constructor() {
121059
121132
  super({ autoDestroy: true });
121060
121133
  this[kResume] = null;
@@ -121072,7 +121145,7 @@ var require_api_pipeline = __commonJS({
121072
121145
  callback(err);
121073
121146
  }
121074
121147
  };
121075
- var PipelineResponse = class extends Readable3 {
121148
+ var PipelineResponse = class extends Readable4 {
121076
121149
  constructor(resume2) {
121077
121150
  super({ autoDestroy: true });
121078
121151
  this[kResume] = resume2;
@@ -124126,7 +124199,7 @@ var require_dump = __commonJS({
124126
124199
  var require_dns = __commonJS({
124127
124200
  "node_modules/undici/lib/interceptor/dns.js"(exports, module) {
124128
124201
  "use strict";
124129
- var { isIP: isIP2 } = __require("net");
124202
+ var { isIP: isIP3 } = __require("net");
124130
124203
  var { lookup } = __require("dns");
124131
124204
  var DecoratorHandler = require_decorator_handler();
124132
124205
  var { InvalidArgumentError, InformationalError } = require_errors();
@@ -124543,7 +124616,7 @@ var require_dns = __commonJS({
124543
124616
  return dispatch(origDispatchOpts, handler);
124544
124617
  }
124545
124618
  const origin2 = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
124546
- if (isIP2(origin2.hostname) !== 0) {
124619
+ if (isIP3(origin2.hostname) !== 0) {
124547
124620
  return dispatch(origDispatchOpts, handler);
124548
124621
  }
124549
124622
  instance.runLookup(origin2, origDispatchOpts, (err, newOrigin) => {
@@ -126614,7 +126687,7 @@ var require_cache2 = __commonJS({
126614
126687
  "node_modules/undici/lib/interceptor/cache.js"(exports, module) {
126615
126688
  "use strict";
126616
126689
  var assert10 = __require("assert");
126617
- var { Readable: Readable3 } = __require("stream");
126690
+ var { Readable: Readable4 } = __require("stream");
126618
126691
  var util5 = require_util();
126619
126692
  var CacheHandler = require_cache_handler();
126620
126693
  var MemoryCacheStore = require_memory_cache_store();
@@ -126810,7 +126883,7 @@ var require_cache2 = __commonJS({
126810
126883
  return dispatch(opts, new CacheHandler(globalOpts, cacheKey3, handler));
126811
126884
  }
126812
126885
  function sendCachedValue(handler, opts, result, age, context, isStale2) {
126813
- const stream4 = util5.isStream(result.body) ? result.body : Readable3.from(result.body ?? []);
126886
+ const stream4 = util5.isStream(result.body) ? result.body : Readable4.from(result.body ?? []);
126814
126887
  assert10(!stream4.destroyed, "stream should not be destroyed");
126815
126888
  assert10(!stream4.readableDidRead, "stream should not be readableDidRead");
126816
126889
  let aborted = false;
@@ -130275,7 +130348,7 @@ var require_fetch = __commonJS({
130275
130348
  subresourceSet
130276
130349
  } = require_constants3();
130277
130350
  var EE = __require("events");
130278
- var { Readable: Readable3, pipeline: pipeline2, finished: finished2, isErrored, isReadable } = __require("stream");
130351
+ var { Readable: Readable4, pipeline: pipeline2, finished: finished2, isErrored, isReadable } = __require("stream");
130279
130352
  var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
130280
130353
  var { SocketError } = require_errors();
130281
130354
  var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
@@ -130904,90 +130977,90 @@ var require_fetch = __commonJS({
130904
130977
  async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
130905
130978
  const request2 = fetchParams.request;
130906
130979
  let httpFetchParams = null;
130907
- let httpRequest = null;
130980
+ let httpRequest2 = null;
130908
130981
  let response = null;
130909
130982
  const httpCache = null;
130910
130983
  const revalidatingFlag = false;
130911
130984
  if (request2.window === "no-window" && request2.redirect === "error") {
130912
130985
  httpFetchParams = fetchParams;
130913
- httpRequest = request2;
130986
+ httpRequest2 = request2;
130914
130987
  } else {
130915
130988
  if (request2.body?.source != null) {
130916
- httpRequest = cloneRequest(request2);
130989
+ httpRequest2 = cloneRequest(request2);
130917
130990
  } else {
130918
- httpRequest = cloneRequest({ ...request2, body: null });
130919
- httpRequest.body = request2.body;
130991
+ httpRequest2 = cloneRequest({ ...request2, body: null });
130992
+ httpRequest2.body = request2.body;
130920
130993
  }
130921
130994
  httpFetchParams = { ...fetchParams };
130922
- httpFetchParams.request = httpRequest;
130995
+ httpFetchParams.request = httpRequest2;
130923
130996
  }
130924
130997
  const includeCredentials = request2.credentials === "include" || request2.credentials === "same-origin" && request2.responseTainting === "basic";
130925
- const contentLength = httpRequest.body ? httpRequest.body.length : null;
130998
+ const contentLength = httpRequest2.body ? httpRequest2.body.length : null;
130926
130999
  let contentLengthHeaderValue = null;
130927
- if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
131000
+ if (httpRequest2.body == null && ["POST", "PUT"].includes(httpRequest2.method)) {
130928
131001
  contentLengthHeaderValue = "0";
130929
131002
  }
130930
131003
  if (contentLength != null) {
130931
131004
  contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
130932
131005
  }
130933
- if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
130934
- httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
131006
+ if (contentLengthHeaderValue != null && !httpRequest2.headersList.contains("content-length", true)) {
131007
+ httpRequest2.headersList.append("content-length", contentLengthHeaderValue, true);
130935
131008
  }
130936
- if (contentLength != null && httpRequest.keepalive) {
131009
+ if (contentLength != null && httpRequest2.keepalive) {
130937
131010
  }
130938
- if (webidl.is.URL(httpRequest.referrer)) {
130939
- httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
131011
+ if (webidl.is.URL(httpRequest2.referrer)) {
131012
+ httpRequest2.headersList.append("referer", isomorphicEncode(httpRequest2.referrer.href), true);
130940
131013
  }
130941
- appendRequestOriginHeader(httpRequest);
130942
- appendFetchMetadata(httpRequest);
130943
- if (!httpRequest.headersList.contains("user-agent", true)) {
130944
- httpRequest.headersList.append("user-agent", defaultUserAgent, true);
131014
+ appendRequestOriginHeader(httpRequest2);
131015
+ appendFetchMetadata(httpRequest2);
131016
+ if (!httpRequest2.headersList.contains("user-agent", true)) {
131017
+ httpRequest2.headersList.append("user-agent", defaultUserAgent, true);
130945
131018
  }
130946
- if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) {
130947
- httpRequest.cache = "no-store";
131019
+ if (httpRequest2.cache === "default" && (httpRequest2.headersList.contains("if-modified-since", true) || httpRequest2.headersList.contains("if-none-match", true) || httpRequest2.headersList.contains("if-unmodified-since", true) || httpRequest2.headersList.contains("if-match", true) || httpRequest2.headersList.contains("if-range", true))) {
131020
+ httpRequest2.cache = "no-store";
130948
131021
  }
130949
- if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) {
130950
- httpRequest.headersList.append("cache-control", "max-age=0", true);
131022
+ if (httpRequest2.cache === "no-cache" && !httpRequest2.preventNoCacheCacheControlHeaderModification && !httpRequest2.headersList.contains("cache-control", true)) {
131023
+ httpRequest2.headersList.append("cache-control", "max-age=0", true);
130951
131024
  }
130952
- if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
130953
- if (!httpRequest.headersList.contains("pragma", true)) {
130954
- httpRequest.headersList.append("pragma", "no-cache", true);
131025
+ if (httpRequest2.cache === "no-store" || httpRequest2.cache === "reload") {
131026
+ if (!httpRequest2.headersList.contains("pragma", true)) {
131027
+ httpRequest2.headersList.append("pragma", "no-cache", true);
130955
131028
  }
130956
- if (!httpRequest.headersList.contains("cache-control", true)) {
130957
- httpRequest.headersList.append("cache-control", "no-cache", true);
131029
+ if (!httpRequest2.headersList.contains("cache-control", true)) {
131030
+ httpRequest2.headersList.append("cache-control", "no-cache", true);
130958
131031
  }
130959
131032
  }
130960
- if (httpRequest.headersList.contains("range", true)) {
130961
- httpRequest.headersList.append("accept-encoding", "identity", true);
131033
+ if (httpRequest2.headersList.contains("range", true)) {
131034
+ httpRequest2.headersList.append("accept-encoding", "identity", true);
130962
131035
  }
130963
- if (!httpRequest.headersList.contains("accept-encoding", true)) {
130964
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
130965
- httpRequest.headersList.append("accept-encoding", "br, gzip, deflate, zstd", true);
131036
+ if (!httpRequest2.headersList.contains("accept-encoding", true)) {
131037
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest2))) {
131038
+ httpRequest2.headersList.append("accept-encoding", "br, gzip, deflate, zstd", true);
130966
131039
  } else {
130967
- httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
131040
+ httpRequest2.headersList.append("accept-encoding", "gzip, deflate", true);
130968
131041
  }
130969
131042
  }
130970
- httpRequest.headersList.delete("host", true);
131043
+ httpRequest2.headersList.delete("host", true);
130971
131044
  if (includeCredentials) {
130972
- if (!httpRequest.headersList.contains("authorization", true)) {
131045
+ if (!httpRequest2.headersList.contains("authorization", true)) {
130973
131046
  let authorizationValue = null;
130974
- if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
130975
- } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
130976
- const { username, password } = requestCurrentURL(httpRequest);
131047
+ if (hasAuthenticationEntry(httpRequest2) && (httpRequest2.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest2)))) {
131048
+ } else if (includesCredentials(requestCurrentURL(httpRequest2)) && isAuthenticationFetch) {
131049
+ const { username, password } = requestCurrentURL(httpRequest2);
130977
131050
  authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
130978
131051
  }
130979
131052
  if (authorizationValue !== null) {
130980
- httpRequest.headersList.append("Authorization", authorizationValue, false);
131053
+ httpRequest2.headersList.append("Authorization", authorizationValue, false);
130981
131054
  }
130982
131055
  }
130983
131056
  }
130984
131057
  if (httpCache == null) {
130985
- httpRequest.cache = "no-store";
131058
+ httpRequest2.cache = "no-store";
130986
131059
  }
130987
- if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") {
131060
+ if (httpRequest2.cache !== "no-store" && httpRequest2.cache !== "reload") {
130988
131061
  }
130989
131062
  if (response == null) {
130990
- if (httpRequest.cache === "only-if-cached") {
131063
+ if (httpRequest2.cache === "only-if-cached") {
130991
131064
  return makeNetworkError("only if cached");
130992
131065
  }
130993
131066
  const forwardResponse = await httpNetworkFetch(
@@ -130995,7 +131068,7 @@ var require_fetch = __commonJS({
130995
131068
  includeCredentials,
130996
131069
  isNewConnectionFetch
130997
131070
  );
130998
- if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
131071
+ if (!safeMethodsSet.has(httpRequest2.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
130999
131072
  }
131000
131073
  if (revalidatingFlag && forwardResponse.status === 304) {
131001
131074
  }
@@ -131003,12 +131076,12 @@ var require_fetch = __commonJS({
131003
131076
  response = forwardResponse;
131004
131077
  }
131005
131078
  }
131006
- response.urlList = [...httpRequest.urlList];
131007
- if (httpRequest.headersList.contains("range", true)) {
131079
+ response.urlList = [...httpRequest2.urlList];
131080
+ if (httpRequest2.headersList.contains("range", true)) {
131008
131081
  response.rangeRequested = true;
131009
131082
  }
131010
131083
  response.requestIncludesCredentials = includeCredentials;
131011
- if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
131084
+ if (response.status === 401 && httpRequest2.responseTainting !== "cors" && includeCredentials && (request2.useURLCredentials !== void 0 || isTraversableNavigable(request2.traversableForUserPrompts))) {
131012
131085
  if (request2.body != null) {
131013
131086
  if (request2.body.source == null) {
131014
131087
  return response;
@@ -131305,7 +131378,7 @@ var require_fetch = __commonJS({
131305
131378
  }
131306
131379
  }
131307
131380
  }
131308
- this.body = new Readable3({ read: () => controller.resume() });
131381
+ this.body = new Readable4({ read: () => controller.resume() });
131309
131382
  const onError = (err) => this.onResponseError(controller, err);
131310
131383
  resolve2({
131311
131384
  status: status2,
@@ -137039,7 +137112,7 @@ var init_v1 = __esm({
137039
137112
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
137040
137113
  import { createHmac } from "crypto";
137041
137114
  import { createServer } from "http";
137042
- import { finished, Readable } from "stream";
137115
+ import { finished, Readable as Readable2 } from "stream";
137043
137116
  import { pipeline } from "stream/promises";
137044
137117
  import { homedir as homedir13 } from "os";
137045
137118
  import { join as join17 } from "path";
@@ -137855,8 +137928,7 @@ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPayment
137855
137928
  const isBlockrunExa = req.url?.startsWith("/v1/exa/") ?? false;
137856
137929
  const isModalSandbox = req.url?.startsWith("/v1/modal/") ?? false;
137857
137930
  const isPhone = (req.url?.startsWith("/v1/phone/") ?? false) || (req.url?.startsWith("/v1/voice/") ?? false);
137858
- const isSurf = req.url?.startsWith("/v1/surf/") ?? false;
137859
- const requestLabel = isBlockrunExa ? "BlockRun Exa" : isModalSandbox ? "Modal Sandbox" : isPhone ? "Phone/Voice" : isSurf ? "Surf" : "Partner";
137931
+ const requestLabel = isBlockrunExa ? "BlockRun Exa" : isModalSandbox ? "Modal Sandbox" : isPhone ? "Phone/Voice" : "Partner";
137860
137932
  const bodyChunks = [];
137861
137933
  for await (const chunk of req) {
137862
137934
  bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
@@ -137896,7 +137968,7 @@ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPayment
137896
137968
  if (accountPassthrough) {
137897
137969
  if (upstream.body) {
137898
137970
  await pipeline(
137899
- Readable.fromWeb(upstream.body),
137971
+ Readable2.fromWeb(upstream.body),
137900
137972
  res,
137901
137973
  { signal: clientAbort.signal }
137902
137974
  );
@@ -137927,14 +137999,14 @@ async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPayment
137927
137999
  logUsage({
137928
138000
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
137929
138001
  ...blockrunRequestId(upstream) ? { requestId: blockrunRequestId(upstream) } : {},
137930
- model: isBlockrunExa ? "blockrun-exa" : isModalSandbox ? "modal-sandbox" : isPhone ? (req.url ?? "").replace(/^\/v1\//, "").split("?")[0] : isSurf ? (req.url ?? "").replace(/^\/v1\//, "").split("?")[0] : "partner",
137931
- tier: isPhone ? "PHONE" : isSurf ? "SURF" : "PARTNER",
138002
+ model: isBlockrunExa ? "blockrun-exa" : isModalSandbox ? "modal-sandbox" : isPhone ? (req.url ?? "").replace(/^\/v1\//, "").split("?")[0] : "partner",
138003
+ tier: isPhone ? "PHONE" : "PARTNER",
137932
138004
  cost: requestCost,
137933
138005
  baselineCost: requestCost,
137934
138006
  savings: 0,
137935
138007
  latencyMs,
137936
138008
  partnerId: (req.url?.split("?")[0] ?? "").replace(/^\/v1\//, "").replace(/\//g, "_") || "unknown",
137937
- service: isBlockrunExa ? "web_search" : isModalSandbox ? "modal" : isPhone ? "phone" : isSurf ? "surf" : "partner"
138009
+ service: isBlockrunExa ? "web_search" : isModalSandbox ? "modal" : isPhone ? "phone" : "partner"
137938
138010
  }).catch(() => {
137939
138011
  });
137940
138012
  }
@@ -138832,7 +138904,8 @@ async function startProxy(options) {
138832
138904
  } else if (val.startsWith("https://") || val.startsWith("http://")) {
138833
138905
  const imgResp = await ssrfSafeFetch(val, {
138834
138906
  signal: clientAbort.signal,
138835
- allowPrivate: process.env.CLAWROUTER_ALLOW_PRIVATE_FETCH === "1"
138907
+ allowPrivate: process.env.CLAWROUTER_ALLOW_PRIVATE_FETCH === "1",
138908
+ viaUpstreamProxy: Boolean(upstreamProxy)
138836
138909
  });
138837
138910
  if (!imgResp.ok)
138838
138911
  throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);
@@ -139209,7 +139282,7 @@ async function startProxy(options) {
139209
139282
  }
139210
139283
  const isVerbatimGatewayPath = req.url === "/v1/messages" || (req.url?.startsWith("/v1/messages?") ?? false) || req.url === "/v1/audio/speech" || (req.url?.startsWith("/v1/audio/speech?") ?? false);
139211
139284
  if (isVerbatimGatewayPath || req.url?.match(
139212
- /^\/v1\/(?:partner|pm|exa|modal|stocks|usstock|crypto|fx|commodity|phone|voice|surf)\//
139285
+ /^\/v1\/(?:partner|pm|exa|modal|stocks|usstock|crypto|fx|commodity|phone|voice)\//
139213
139286
  )) {
139214
139287
  try {
139215
139288
  await proxyPaidApiRequest(
@@ -139274,7 +139347,7 @@ async function startProxy(options) {
139274
139347
  res.end(
139275
139348
  JSON.stringify({
139276
139349
  error: {
139277
- message: `ClawRouter does not proxy ${req.url}. It serves /v1/chat/completions, /v1/messages, /v1/models, /v1/images/generations, /v1/images/image2image, /v1/videos/generations, /v1/audio/generations, /v1/audio/speech, and the partner prefixes /v1/{partner,pm,exa,modal,stocks,usstock,crypto,fx,commodity,phone,voice,surf}/. If BlockRun serves this endpoint, call it directly against the gateway.`,
139350
+ message: `ClawRouter does not proxy ${req.url}. It serves /v1/chat/completions, /v1/messages, /v1/models, /v1/images/generations, /v1/images/image2image, /v1/videos/generations, /v1/audio/generations, /v1/audio/speech, and the partner prefixes /v1/{partner,pm,exa,modal,stocks,usstock,crypto,fx,commodity,phone,voice}/. If BlockRun serves this endpoint, call it directly against the gateway.`,
139278
139351
  type: "invalid_request_error",
139279
139352
  code: "unsupported_endpoint"
139280
139353
  }
@@ -159685,7 +159758,7 @@ var init_readBlob = __esm({
159685
159758
 
159686
159759
  // node_modules/axios/lib/helpers/formDataToStream.js
159687
159760
  import util2 from "util";
159688
- import { Readable as Readable2 } from "stream";
159761
+ import { Readable as Readable3 } from "stream";
159689
159762
  var BOUNDARY_ALPHABET, textEncoder, CRLF, CRLF_BYTES, CRLF_BYTES_COUNT, FormDataPart, formDataToStream, formDataToStream_default;
159690
159763
  var init_formDataToStream = __esm({
159691
159764
  "node_modules/axios/lib/helpers/formDataToStream.js"() {
@@ -159765,7 +159838,7 @@ var init_formDataToStream = __esm({
159765
159838
  computedHeaders["Content-Length"] = contentLength;
159766
159839
  }
159767
159840
  headersHandler && headersHandler(computedHeaders);
159768
- return Readable2.from(
159841
+ return Readable3.from(
159769
159842
  (async function* () {
159770
159843
  for (const part of parts) {
159771
159844
  yield boundaryBytes;
@@ -287770,6 +287843,7 @@ ClawRouter v${VERSION} - Smart LLM Router
287770
287843
 
287771
287844
  Usage:
287772
287845
  clawrouter [options]
287846
+ clawrouter update # Update ClawRouter in place
287773
287847
  clawrouter login [brk_...] # Use a BlockRun API key (card-funded credit)
287774
287848
  clawrouter logout # Forget the API key and go back to the wallet
287775
287849
  clawrouter status # Live proxy status (wallet, balance, chain)
@@ -287812,6 +287886,8 @@ Query Commands (talk to running proxy on localhost:${getProxyPort()}):
287812
287886
  cache Response cache stats (hit rate, size)
287813
287887
 
287814
287888
  Management Commands:
287889
+ update Update the OpenClaw plugin and this global CLI in one step.
287890
+ Backs up wallet/config state and rolls back on failure.
287815
287891
  setup Finish OpenClaw integration (run after npm install -g).
287816
287892
  Registers ClawRouter as a plugin, syncs the model allowlist,
287817
287893
  and writes the auth profile. Idempotent \u2014 safe to re-run.
@@ -288540,6 +288616,79 @@ async function cmdSetup() {
288540
288616
  Then verify in your bot: /models \u2014 you should see ${VISIBLE_OPENCLAW_MODELS2.length} BlockRun models.`
288541
288617
  );
288542
288618
  }
288619
+ async function cmdUpdate() {
288620
+ const { execFileSync } = await import("child_process");
288621
+ const { copyFileSync: copyFileSync2, existsSync: existsSync9, mkdtempSync, realpathSync: realpathSync2, rmSync } = await import("fs");
288622
+ const { tmpdir } = await import("os");
288623
+ const { dirname: dirname6, join: join21, relative, isAbsolute } = await import("path");
288624
+ const { fileURLToPath: fileURLToPath2 } = await import("url");
288625
+ const isWindows = process.platform === "win32";
288626
+ const packageRoot = dirname6(dirname6(fileURLToPath2(import.meta.url)));
288627
+ const scriptName = isWindows ? "update.ps1" : "update.sh";
288628
+ const updateScript = join21(packageRoot, "scripts", scriptName);
288629
+ const exitStatus = (error) => typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" ? error.status : 1;
288630
+ if (!existsSync9(updateScript)) {
288631
+ console.error("\u2717 The bundled updater is missing from this ClawRouter installation.");
288632
+ console.error(
288633
+ isWindows ? " Update manually: iwr -useb https://blockrun.ai/ClawRouter-update.ps1 | iex" : " Update manually: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"
288634
+ );
288635
+ process.exitCode = 1;
288636
+ return;
288637
+ }
288638
+ console.log(`\u{1F99E} ClawRouter update (v${VERSION})
288639
+ `);
288640
+ const tempDir = mkdtempSync(join21(tmpdir(), "clawrouter-update-"));
288641
+ try {
288642
+ const script = join21(tempDir, scriptName);
288643
+ copyFileSync2(updateScript, script);
288644
+ if (isWindows) {
288645
+ execFileSync(
288646
+ "powershell.exe",
288647
+ ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script],
288648
+ { stdio: "inherit", env: process.env }
288649
+ );
288650
+ } else {
288651
+ execFileSync("bash", [script], { stdio: "inherit", env: process.env });
288652
+ }
288653
+ } catch (error) {
288654
+ process.exitCode = exitStatus(error);
288655
+ return;
288656
+ } finally {
288657
+ rmSync(tempDir, { recursive: true, force: true });
288658
+ }
288659
+ let globalRoot;
288660
+ try {
288661
+ globalRoot = execFileSync("npm", ["root", "-g"], {
288662
+ encoding: "utf8",
288663
+ shell: isWindows,
288664
+ stdio: ["ignore", "pipe", "ignore"]
288665
+ }).trim();
288666
+ } catch {
288667
+ return;
288668
+ }
288669
+ let fromGlobal;
288670
+ try {
288671
+ const rel = relative(realpathSync2(globalRoot), realpathSync2(packageRoot));
288672
+ fromGlobal = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
288673
+ } catch {
288674
+ return;
288675
+ }
288676
+ if (!fromGlobal) return;
288677
+ const installSpec = process.env.BLOCKRUN_CLAWROUTER_INSTALL_SPEC || "@blockrun/clawrouter@latest";
288678
+ console.log(`
288679
+ \u2192 Updating global CLI (npm install -g ${installSpec})...`);
288680
+ try {
288681
+ execFileSync("npm", ["install", "-g", installSpec], {
288682
+ stdio: "inherit",
288683
+ shell: isWindows,
288684
+ env: process.env
288685
+ });
288686
+ console.log(" \u2713 Global CLI updated");
288687
+ } catch {
288688
+ console.warn(" \u26A0 Plugin updated, but the global CLI could not be refreshed.");
288689
+ console.warn(` Run manually: npm install -g ${installSpec}`);
288690
+ }
288691
+ }
288543
288692
  function parseArgs(args) {
288544
288693
  const result = {
288545
288694
  version: false,
@@ -288565,6 +288714,7 @@ function parseArgs(args) {
288565
288714
  reconcileDays: 7,
288566
288715
  queryCache: false,
288567
288716
  setup: false,
288717
+ update: false,
288568
288718
  share: false,
288569
288719
  shareTarget: void 0,
288570
288720
  sharePreset: void 0,
@@ -288665,6 +288815,8 @@ function parseArgs(args) {
288665
288815
  result.noReuse = true;
288666
288816
  } else if (arg === "setup") {
288667
288817
  result.setup = true;
288818
+ } else if (arg === "update" && i === 0) {
288819
+ result.update = true;
288668
288820
  } else if (arg === "phone") {
288669
288821
  result.phone = true;
288670
288822
  const next = args[i + 1];
@@ -288802,6 +288954,10 @@ async function main() {
288802
288954
  await cmdSetup();
288803
288955
  process.exit(0);
288804
288956
  }
288957
+ if (args.update) {
288958
+ await cmdUpdate();
288959
+ return;
288960
+ }
288805
288961
  if (args.policy) {
288806
288962
  const result = runPolicyCommand(args.policyArgs);
288807
288963
  if (result.isError) {