vapi-network 0.15.0 → 0.15.2

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/index.js CHANGED
@@ -10194,6 +10194,7 @@ __export(src_exports, {
10194
10194
  NATIVE_ETH_FEE_MARGIN_PERCENT: () => NATIVE_ETH_FEE_MARGIN_PERCENT,
10195
10195
  NATIVE_ETH_L1_FEE_FALLBACK_WEI: () => NATIVE_ETH_L1_FEE_FALLBACK_WEI,
10196
10196
  NETWORKS: () => NETWORKS,
10197
+ NetworkGuardError: () => NetworkGuardError,
10197
10198
  ONRAMP_FALLBACK_INSTRUCTIONS: () => ONRAMP_FALLBACK_INSTRUCTIONS,
10198
10199
  ONRAMP_NETWORK: () => ONRAMP_NETWORK,
10199
10200
  PASSPHRASE_ENVIRONMENT_VARIABLE: () => PASSPHRASE_ENVIRONMENT_VARIABLE,
@@ -10300,6 +10301,7 @@ __export(src_exports, {
10300
10301
  deleteSwarmFile: () => deleteSwarmFile,
10301
10302
  deriveEvmPrivateKey: () => deriveEvmPrivateKey,
10302
10303
  deriveSolanaPrivateKey: () => deriveSolanaPrivateKey,
10304
+ describeNetworkFailure: () => describeNetworkFailure,
10303
10305
  deviceName: () => deviceName,
10304
10306
  discardBody: () => discardBody,
10305
10307
  discover: () => discover,
@@ -44313,7 +44315,7 @@ async function assertPublicUrl(url2, options) {
44313
44315
  options.timeoutMs ?? 5e3
44314
44316
  );
44315
44317
  } catch {
44316
- throw guardError(url2);
44318
+ throw guardError(url2, "unresolved");
44317
44319
  }
44318
44320
  if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
44319
44321
  throw guardError(url2);
@@ -44468,10 +44470,67 @@ function isNonPublicIpv6(hextets) {
44468
44470
  const isDocumentation = first === 8193 && hextets[1] === 3512;
44469
44471
  return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
44470
44472
  }
44471
- function guardError(url2) {
44472
- return new Error(
44473
- `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
44473
+ var NetworkGuardError = class extends Error {
44474
+ constructor(message, reason) {
44475
+ super(message);
44476
+ this.reason = reason;
44477
+ this.name = "NetworkGuardError";
44478
+ }
44479
+ reason;
44480
+ };
44481
+ function guardError(url2, reason = "blocked") {
44482
+ return new NetworkGuardError(
44483
+ `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`,
44484
+ reason
44485
+ );
44486
+ }
44487
+ var PROXY_VARIABLES = {
44488
+ "https:": ["HTTPS_PROXY", "https_proxy"],
44489
+ "http:": ["HTTP_PROXY", "http_proxy"]
44490
+ };
44491
+ var SYSTEM_ERROR_CODE = /^[A-Z][A-Z0-9_]{1,39}$/u;
44492
+ function describeNetworkFailure(error61, url2, env = process.env) {
44493
+ const host = url2.host;
44494
+ let reason;
44495
+ const guard = guardReason(error61);
44496
+ if (guard !== void 0) {
44497
+ reason = guard === "unresolved" ? `the DNS lookup for ${host} failed` : `${host} is not a public address`;
44498
+ } else if (isTimeout(error61)) {
44499
+ reason = `the connection to ${host} timed out`;
44500
+ } else {
44501
+ const code = systemErrorCode(error61);
44502
+ reason = `could not connect to ${host}${code === void 0 ? "" : ` (${code})`}`;
44503
+ }
44504
+ const proxy = (PROXY_VARIABLES[url2.protocol] ?? []).find(
44505
+ (name) => (env[name] ?? "").trim() !== ""
44474
44506
  );
44507
+ let hint = "";
44508
+ if (proxy !== void 0) {
44509
+ if (env.NODE_USE_ENV_PROXY !== "1") {
44510
+ hint = ` ${proxy} is set, but Node.js uses it only with NODE_USE_ENV_PROXY=1 (Node.js 22.21 or later): run the command again with NODE_USE_ENV_PROXY=1.`;
44511
+ } else if (guard === "unresolved") {
44512
+ hint = ` vapi looks ${host} up on this machine before it uses the proxy in ${proxy}, so the name must resolve here too.`;
44513
+ } else if (guard === void 0) {
44514
+ hint = ` NODE_USE_ENV_PROXY=1 and ${proxy} are set, so the proxy may have refused the connection.`;
44515
+ }
44516
+ }
44517
+ return `${reason}.${hint}`;
44518
+ }
44519
+ function guardReason(error61) {
44520
+ if (!(error61 instanceof Error) || error61.name !== "NetworkGuardError") return void 0;
44521
+ const reason = error61.reason;
44522
+ return reason === "blocked" || reason === "unresolved" ? reason : void 0;
44523
+ }
44524
+ function isTimeout(error61) {
44525
+ return error61 instanceof Error && (error61.name === "TimeoutError" || error61.name === "AbortError");
44526
+ }
44527
+ function systemErrorCode(error61) {
44528
+ for (let current = error61, depth = 0; current instanceof Error && depth < 3; depth += 1) {
44529
+ const code = current.code;
44530
+ if (typeof code === "string" && SYSTEM_ERROR_CODE.test(code)) return code;
44531
+ current = current.cause;
44532
+ }
44533
+ return void 0;
44475
44534
  }
44476
44535
 
44477
44536
  // ../core/src/networks.ts
@@ -47606,12 +47665,12 @@ async function removeStaleLock(path) {
47606
47665
  const pid = lockOwnerPid(owner);
47607
47666
  if (pid !== void 0 && processIsAlive(pid)) return;
47608
47667
  await atomicFileTestHooks?.beforeStaleLockBreak?.(path);
47609
- await removeOwnedLock(path, [owner]);
47668
+ await removeOwnedLock(path, [owner], true);
47610
47669
  } catch (error61) {
47611
47670
  if (!hasCode(error61, "ENOENT")) throw error61;
47612
47671
  }
47613
47672
  }
47614
- async function removeOwnedLock(path, owners) {
47673
+ async function removeOwnedLock(path, owners, staleDeadOwner = false) {
47615
47674
  const tombPath = `${path}.stale.${randomBytes2(16).toString("hex")}`;
47616
47675
  try {
47617
47676
  await rename(path, tombPath);
@@ -47620,7 +47679,7 @@ async function removeOwnedLock(path, owners) {
47620
47679
  await removeOwnedTombs(path, owners);
47621
47680
  const currentOwner = await readFile(path, "utf8").catch(() => void 0);
47622
47681
  if (currentOwner !== void 0 && owners.includes(currentOwner)) {
47623
- await removeOwnedLock(path, owners);
47682
+ await removeOwnedLock(path, owners, staleDeadOwner);
47624
47683
  }
47625
47684
  return;
47626
47685
  }
@@ -47629,6 +47688,7 @@ async function removeOwnedLock(path, owners) {
47629
47688
  let pendingError;
47630
47689
  let renamedOwner;
47631
47690
  try {
47691
+ await atomicFileTestHooks?.afterLockRename?.(tombPath);
47632
47692
  renamedOwner = await readFile(tombPath, "utf8");
47633
47693
  if (!owners.includes(renamedOwner) && !lockOwnerReleased(renamedOwner)) {
47634
47694
  await atomicFileTestHooks?.afterMismatchedLockRename?.(path);
@@ -47637,6 +47697,7 @@ async function removeOwnedLock(path, owners) {
47637
47697
  await atomicFileTestHooks?.afterMismatchedLockRestore?.(path);
47638
47698
  }
47639
47699
  } catch (error61) {
47700
+ if (hasCode(error61, "ENOENT")) return;
47640
47701
  pendingError = error61;
47641
47702
  }
47642
47703
  try {
@@ -47645,7 +47706,7 @@ async function removeOwnedLock(path, owners) {
47645
47706
  } catch (error61) {
47646
47707
  if (!tombUnlinkTolerated(
47647
47708
  error61,
47648
- renamedOwner !== void 0 && lockOwnerReleased(renamedOwner) && owners.includes(renamedOwner)
47709
+ renamedOwner !== void 0 && (lockOwnerReleased(renamedOwner) || staleDeadOwner) && owners.includes(renamedOwner)
47649
47710
  ) && pendingError === void 0) {
47650
47711
  pendingError = error61;
47651
47712
  }
@@ -48876,7 +48937,7 @@ async function withCredentialLockFile(lockPath, operation) {
48876
48937
  try {
48877
48938
  return await operation();
48878
48939
  } finally {
48879
- await handle.close();
48940
+ await handle.close().catch(() => void 0);
48880
48941
  await unlink2(lockPath).catch(() => void 0);
48881
48942
  }
48882
48943
  }
@@ -48940,16 +49001,25 @@ function withBearer(init, accessToken) {
48940
49001
  async function safeFetch(fetchImpl, input2, init) {
48941
49002
  try {
48942
49003
  return await fetchImpl(input2, init);
48943
- } catch {
48944
- throw httpError("The vAPI agent link request failed.");
49004
+ } catch (error61) {
49005
+ throw httpError(`The vAPI agent link request failed: ${networkFailure(error61, input2)}`);
48945
49006
  }
48946
49007
  }
48947
49008
  async function safeAgentFetch(fetchImpl, input2, init) {
48948
49009
  try {
48949
49010
  return await fetchImpl(input2, init);
49011
+ } catch (error61) {
49012
+ throw httpError(`The vAPI agent request failed: ${networkFailure(error61, input2)}`);
49013
+ }
49014
+ }
49015
+ function networkFailure(error61, input2) {
49016
+ let url2;
49017
+ try {
49018
+ url2 = new URL(input2 instanceof Request ? input2.url : input2);
48950
49019
  } catch {
48951
- throw httpError("The vAPI agent request failed.");
49020
+ return "the request did not reach vAPI.";
48952
49021
  }
49022
+ return describeNetworkFailure(error61, url2);
48953
49023
  }
48954
49024
  function deviceAuthorizationError(status, payload) {
48955
49025
  const error61 = stringField(payload, "error");
@@ -71746,7 +71816,7 @@ async function withVaultLock(path, operation) {
71746
71816
  try {
71747
71817
  return await operation();
71748
71818
  } finally {
71749
- await handle.close();
71819
+ await handle.close().catch(() => void 0);
71750
71820
  await unlink4(lockPath).catch(() => void 0);
71751
71821
  }
71752
71822
  }
@@ -74643,7 +74713,7 @@ async function withRegistryLock(path, operation) {
74643
74713
  try {
74644
74714
  return await operation();
74645
74715
  } finally {
74646
- await handle.close();
74716
+ await handle.close().catch(() => void 0);
74647
74717
  await unlink7(lockPath).catch(() => void 0);
74648
74718
  }
74649
74719
  }
@@ -75534,7 +75604,7 @@ async function withLedgerLock(path, operation) {
75534
75604
  try {
75535
75605
  return await operation();
75536
75606
  } finally {
75537
- await handle.close();
75607
+ await handle.close().catch(() => void 0);
75538
75608
  await unlink9(lockPath).catch(() => void 0);
75539
75609
  }
75540
75610
  }
@@ -75834,13 +75904,32 @@ async function transferBetweenAccounts(args) {
75834
75904
  if (existing !== void 0 && existing.transfer?.status !== "failed") {
75835
75905
  throw transferError("authorization_invalid");
75836
75906
  }
75837
- await appendTransferReceipt(context, request, {
75838
- receiptId,
75839
- status: "unknown",
75840
- txHash: null,
75841
- replayed: false,
75842
- reservedOn
75843
- });
75907
+ try {
75908
+ await appendTransferReceipt(context, request, {
75909
+ receiptId,
75910
+ status: "unknown",
75911
+ txHash: null,
75912
+ replayed: false,
75913
+ reservedOn
75914
+ });
75915
+ } catch (error61) {
75916
+ let persisted;
75917
+ try {
75918
+ persisted = await findTransferReceipt(context, nonce);
75919
+ } catch {
75920
+ authorizationPersisted = true;
75921
+ }
75922
+ if (persisted !== void 0 && persisted.transfer?.status !== "failed") {
75923
+ authorizationPersisted = true;
75924
+ }
75925
+ if (!authorizationPersisted) throw error61;
75926
+ return transferResult(context, {
75927
+ status: "unknown",
75928
+ txHash: null,
75929
+ nonce: request.authorization.nonce,
75930
+ replayed: false
75931
+ });
75932
+ }
75844
75933
  try {
75845
75934
  await syncReceipts(context.receiptsPath);
75846
75935
  } catch (error61) {
@@ -79145,7 +79234,7 @@ function createRunBudget(args) {
79145
79234
  import { mkdir as mkdir15, writeFile as writeFile7 } from "node:fs/promises";
79146
79235
  import { arch, platform, release } from "node:os";
79147
79236
  import { join as join14 } from "node:path";
79148
- var VAPI_CLIENT_VERSION = "0.15.0";
79237
+ var VAPI_CLIENT_VERSION = "0.15.2";
79149
79238
  async function createSupportReport(options) {
79150
79239
  const message = options.message.trim();
79151
79240
  if (!message) throw new Error("Support report message must not be empty.");
@@ -80948,26 +81037,28 @@ async function ensureBalanceRouterKey(deps, paidLink) {
80948
81037
  if (!parsed.success) {
80949
81038
  throw new RouterClientError("http", "The Router balance key response was invalid.");
80950
81039
  }
80951
- const currentLink = await linkedWallet(deps);
80952
- if (!sameAgentLink(currentLink, paidLink)) {
80953
- throw new RouterClientError(
80954
- "http",
80955
- "The agent link changed while fetching the Router balance key."
80956
- );
80957
- }
80958
- const returnedBase = validRouterBaseUrl(parsed.data.router_base_url);
80959
- const expectedBase = validRouterBaseUrl(link3.routerBaseUrl ?? DEFAULT_ROUTER_BASE_URL);
80960
- if (returnedBase !== expectedBase) {
80961
- throw new RouterClientError(
80962
- "http",
80963
- "The Router balance key response named an unexpected Router base URL."
80964
- );
80965
- }
80966
- try {
80967
- await deps.secrets.set(account, parsed.data.router_key);
80968
- } catch {
80969
- throw new RouterClientError("http", "The Router balance key could not be stored safely.");
80970
- }
81040
+ await withCredentialPublishLock(deps.wallets, deps.wallet, async () => {
81041
+ const currentLink = await linkedWallet(deps);
81042
+ if (!sameAgentLink(currentLink, paidLink)) {
81043
+ throw new RouterClientError(
81044
+ "http",
81045
+ "The agent link changed while fetching the Router balance key."
81046
+ );
81047
+ }
81048
+ const returnedBase = validRouterBaseUrl(parsed.data.router_base_url);
81049
+ const expectedBase = validRouterBaseUrl(link3.routerBaseUrl ?? DEFAULT_ROUTER_BASE_URL);
81050
+ if (returnedBase !== expectedBase) {
81051
+ throw new RouterClientError(
81052
+ "http",
81053
+ "The Router balance key response named an unexpected Router base URL."
81054
+ );
81055
+ }
81056
+ try {
81057
+ await deps.secrets.set(account, parsed.data.router_key);
81058
+ } catch {
81059
+ throw new RouterClientError("http", "The Router balance key could not be stored safely.");
81060
+ }
81061
+ });
80971
81062
  }
80972
81063
  );
80973
81064
  }
@@ -81008,12 +81099,14 @@ async function routerBalanceCredentialSnapshot(deps) {
81008
81099
  async function removeRejectedBalanceKey(deps, rejected) {
81009
81100
  if (!deps.secrets.available) return;
81010
81101
  await withAgentCredentialLock(deps.wallets, rejected.clientId, async () => {
81011
- const link3 = await linkedWallet(deps);
81012
- if (link3.clientId !== rejected.clientId) return;
81013
- const account = agentSecretAccounts(deps.wallet).routerBalance;
81014
- if (await deps.secrets.get(account) === rejected.routerKey) {
81015
- await deps.secrets.remove(account);
81016
- }
81102
+ await withCredentialPublishLock(deps.wallets, deps.wallet, async () => {
81103
+ const link3 = await linkedWallet(deps);
81104
+ if (link3.clientId !== rejected.clientId) return;
81105
+ const account = agentSecretAccounts(deps.wallet).routerBalance;
81106
+ if (await deps.secrets.get(account) === rejected.routerKey) {
81107
+ await deps.secrets.remove(account);
81108
+ }
81109
+ });
81017
81110
  });
81018
81111
  }
81019
81112
  async function routerAccessToken(deps) {
@@ -81101,32 +81194,34 @@ async function rotateRouterKey(deps) {
81101
81194
  validRouterBaseUrl(parsed.data.router_base_url);
81102
81195
  try {
81103
81196
  await withAgentCredentialLock(deps.wallets, link3.clientId, async () => {
81104
- const currentLink = await linkedWallet(deps);
81105
- if (!sameAgentLink(currentLink, link3)) {
81106
- throw new RouterClientError("http", "The agent link changed during Router key rotation.");
81107
- }
81108
- const account = agentSecretAccounts(deps.wallet).routerStake;
81109
- let previousKey;
81110
- try {
81111
- previousKey = await deps.secrets.get(account);
81112
- await deps.secrets.set(account, parsed.data.router_key);
81113
- } catch {
81114
- throw new RouterClientError("http", "The Router key could not be stored safely.");
81115
- }
81116
- try {
81117
- await deps.wallets.setLink(deps.wallet, {
81118
- ...currentLink,
81119
- routerBaseUrl: parsed.data.router_base_url
81120
- });
81121
- } catch {
81197
+ await withCredentialPublishLock(deps.wallets, deps.wallet, async () => {
81198
+ const currentLink = await linkedWallet(deps);
81199
+ if (!sameAgentLink(currentLink, link3)) {
81200
+ throw new RouterClientError("http", "The agent link changed during Router key rotation.");
81201
+ }
81202
+ const account = agentSecretAccounts(deps.wallet).routerStake;
81203
+ let previousKey;
81122
81204
  try {
81123
- if (previousKey === void 0) await deps.secrets.remove(account);
81124
- else await deps.secrets.set(account, previousKey);
81205
+ previousKey = await deps.secrets.get(account);
81206
+ await deps.secrets.set(account, parsed.data.router_key);
81125
81207
  } catch {
81126
- await deps.wallets.clearLink(deps.wallet).catch(() => void 0);
81208
+ throw new RouterClientError("http", "The Router key could not be stored safely.");
81127
81209
  }
81128
- throw new RouterClientError("http", "The Router key could not be stored safely.");
81129
- }
81210
+ try {
81211
+ await deps.wallets.setLink(deps.wallet, {
81212
+ ...currentLink,
81213
+ routerBaseUrl: parsed.data.router_base_url
81214
+ });
81215
+ } catch {
81216
+ try {
81217
+ if (previousKey === void 0) await deps.secrets.remove(account);
81218
+ else await deps.secrets.set(account, previousKey);
81219
+ } catch {
81220
+ await deps.wallets.clearLink(deps.wallet).catch(() => void 0);
81221
+ }
81222
+ throw new RouterClientError("http", "The Router key could not be stored safely.");
81223
+ }
81224
+ });
81130
81225
  });
81131
81226
  } catch (error61) {
81132
81227
  if (error61 instanceof RouterClientError) throw error61;
@@ -86674,34 +86769,48 @@ async function searchDocs(query, options = {}) {
86674
86769
  throw new DocsError("invalid_input", "Search limit must be a positive integer.");
86675
86770
  }
86676
86771
  const origin = resolveDocsOrigin(options.env);
86677
- const { text: body } = await requestText(
86678
- new URL("/~gitbook/mcp", origin),
86679
- {
86680
- method: "POST",
86681
- headers: {
86682
- "content-type": "application/json",
86683
- accept: "application/json, text/event-stream"
86684
- },
86685
- body: JSON.stringify({
86686
- jsonrpc: "2.0",
86687
- id: 1,
86688
- method: "tools/call",
86689
- params: { name: "searchDocumentation", arguments: { query: normalized } }
86690
- })
86772
+ const requestOptions2 = {
86773
+ operation: "search",
86774
+ origin,
86775
+ timeoutMs: options.timeoutMs ?? SEARCH_TIMEOUT_MS,
86776
+ fetchImpl: options.fetchImpl
86777
+ };
86778
+ const searchRequest = (name, args) => ({
86779
+ method: "POST",
86780
+ headers: {
86781
+ "content-type": "application/json",
86782
+ accept: "application/json, text/event-stream"
86691
86783
  },
86692
- {
86693
- operation: "search",
86694
- origin,
86695
- timeoutMs: options.timeoutMs ?? SEARCH_TIMEOUT_MS,
86696
- fetchImpl: options.fetchImpl
86697
- }
86698
- );
86699
- const payload = parseSearchEnvelope(body);
86700
- const blocks = searchTextBlocks(payload);
86701
- const results = blocks.flatMap((block) => {
86702
- const parsed = parseSearchBlock(block);
86703
- return parsed === void 0 ? [] : [parsed];
86784
+ body: JSON.stringify({
86785
+ jsonrpc: "2.0",
86786
+ id: 1,
86787
+ method: "tools/call",
86788
+ params: { name, arguments: args }
86789
+ })
86704
86790
  });
86791
+ let results;
86792
+ try {
86793
+ const { text: body } = await requestText(
86794
+ new URL("/mcp", origin),
86795
+ searchRequest("search_docs", {
86796
+ query: normalized,
86797
+ ...options.limit === void 0 ? {} : { limit: Math.min(options.limit, 10) }
86798
+ }),
86799
+ { ...requestOptions2, notFoundOn404: true, notFoundOn405: true }
86800
+ );
86801
+ results = parseSiteSearch(searchTextBlocks(parseSearchEnvelope(body)), origin);
86802
+ } catch (error61) {
86803
+ if (!(error61 instanceof DocsError && error61.code === "not_found")) throw error61;
86804
+ const { text: body } = await requestText(
86805
+ new URL("/~gitbook/mcp", origin),
86806
+ searchRequest("searchDocumentation", { query: normalized }),
86807
+ requestOptions2
86808
+ );
86809
+ results = searchTextBlocks(parseSearchEnvelope(body)).flatMap((block) => {
86810
+ const parsed = parseSearchBlock(block);
86811
+ return parsed === void 0 ? [] : [parsed];
86812
+ });
86813
+ }
86705
86814
  return { results: options.limit === void 0 ? results : results.slice(0, options.limit) };
86706
86815
  }
86707
86816
  async function readDocs(pageUrlOrPath, options = {}) {
@@ -86729,7 +86838,7 @@ async function readDocs(pageUrlOrPath, options = {}) {
86729
86838
  }
86730
86839
  async function readFirstMarkdown(page, options) {
86731
86840
  const path = page.pathname.replace(/\/+$/u, "");
86732
- const candidates = path ? [`${path}.md`, `${path}/readme.md`] : ["/readme.md"];
86841
+ const candidates = path ? [`${path}.md`, `${path}/readme.md`] : ["/index.md", "/readme.md"];
86733
86842
  for (const pathname of candidates) {
86734
86843
  const candidate = new URL(page);
86735
86844
  candidate.pathname = pathname;
@@ -86753,17 +86862,32 @@ async function askDocs(question, options = {}) {
86753
86862
  const origin = resolveDocsOrigin(options.env);
86754
86863
  const url2 = new URL("/readme.md", origin);
86755
86864
  url2.searchParams.set("ask", normalized);
86756
- const { text: markdown } = await requestText(
86757
- url2,
86758
- { method: "GET", headers: { accept: "text/markdown" } },
86759
- {
86760
- operation: "ask",
86761
- origin,
86762
- timeoutMs: options.timeoutMs ?? ASK_TIMEOUT_MS,
86763
- fetchImpl: options.fetchImpl
86764
- }
86765
- );
86766
- return parseAnswer(markdown);
86865
+ try {
86866
+ const { text: markdown } = await requestText(
86867
+ url2,
86868
+ { method: "GET", headers: { accept: "text/markdown" } },
86869
+ {
86870
+ operation: "ask",
86871
+ origin,
86872
+ timeoutMs: options.timeoutMs ?? ASK_TIMEOUT_MS,
86873
+ fetchImpl: options.fetchImpl,
86874
+ notFoundOn404: true
86875
+ }
86876
+ );
86877
+ return parseAnswer(markdown);
86878
+ } catch (error61) {
86879
+ if (!(error61 instanceof DocsError && error61.code === "not_found")) throw error61;
86880
+ }
86881
+ const { results } = await searchDocs(normalized, { ...options, limit: 3 });
86882
+ if (results.length === 0) return { answer: "No matching documentation found.", sources: [] };
86883
+ return {
86884
+ answer: [
86885
+ "These are the closest sections of the docs; the new docs site has no assistant.",
86886
+ "",
86887
+ ...results.map(({ title, url: url3, excerpt }) => `- [${title}](${url3}): ${excerpt}`)
86888
+ ].join("\n"),
86889
+ sources: results.map(({ title, url: url3 }) => ({ title, url: url3 }))
86890
+ };
86767
86891
  }
86768
86892
  function nonEmpty(value, label) {
86769
86893
  const normalized = value.trim();
@@ -86835,7 +86959,7 @@ async function requestText(requestUrl2, init, options) {
86835
86959
  assertAllowedUrl(next, options.origin);
86836
86960
  url2 = next;
86837
86961
  }
86838
- if (options.notFoundOn404 && response.status === 404) {
86962
+ if (options.notFoundOn404 && response.status === 404 || options.notFoundOn405 && response.status === 405) {
86839
86963
  throw new DocsError("not_found", `Documentation page not found: ${url2.href}`);
86840
86964
  }
86841
86965
  if (!response.ok) {
@@ -86940,12 +87064,40 @@ function searchTextBlocks(payload) {
86940
87064
  throw new DocsError("bad_response", `The documentation search returned an error${message}`);
86941
87065
  }
86942
87066
  const result = asRecord(envelope?.result);
87067
+ if (result?.isError === true) {
87068
+ throw new DocsError("bad_response", "The documentation search tool returned an error.");
87069
+ }
86943
87070
  if (!Array.isArray(result?.content)) throw invalidSearchResponse();
86944
87071
  return result.content.flatMap((item) => {
86945
87072
  const block = asRecord(item);
86946
87073
  return block?.type === "text" && typeof block.text === "string" ? [block.text] : [];
86947
87074
  });
86948
87075
  }
87076
+ function parseSiteSearch(blocks, origin) {
87077
+ if (blocks.length === 0) throw invalidSearchResponse();
87078
+ return blocks.flatMap((block) => {
87079
+ const items = parseJson2(block);
87080
+ if (!Array.isArray(items)) throw invalidSearchResponse();
87081
+ return items.map((item) => {
87082
+ const entry = asRecord(item);
87083
+ if (typeof entry?.title !== "string" || typeof entry.url !== "string" || typeof entry.heading !== "string" || typeof entry.snippet !== "string") {
87084
+ throw invalidSearchResponse();
87085
+ }
87086
+ let url2;
87087
+ try {
87088
+ url2 = new URL(entry.url, origin);
87089
+ } catch {
87090
+ throw invalidSearchResponse();
87091
+ }
87092
+ assertAllowedUrl(url2, origin);
87093
+ return {
87094
+ title: entry.heading ? `${entry.title} \u203A ${entry.heading}` : entry.title,
87095
+ url: url2.href,
87096
+ excerpt: entry.snippet
87097
+ };
87098
+ });
87099
+ });
87100
+ }
86949
87101
  function parseSearchBlock(block) {
86950
87102
  const match = /^Title:\s*([^\r\n]+)\r?\nLink:\s*([^\r\n]+)\r?\nContent:\s*([\s\S]*)$/u.exec(
86951
87103
  block.trim()
@@ -103889,7 +104041,7 @@ async function readProcessStdin() {
103889
104041
  }
103890
104042
 
103891
104043
  // ../cli/src/version.ts
103892
- var CLI_VERSION = "0.15.0";
104044
+ var CLI_VERSION = "0.15.2";
103893
104045
 
103894
104046
  // ../cli/src/status.ts
103895
104047
  async function statusCommand(argv, json2, io, dependencies) {
@@ -107677,6 +107829,10 @@ ${RUN_USAGE}`
107677
107829
  ${RUN_USAGE}`);
107678
107830
  }
107679
107831
  const environment = getEnvironment(dependencies);
107832
+ const runIo = resultFile === void 0 ? io : {
107833
+ stdout: (message) => io.stdout(redactDetachedRunText(message, environment)),
107834
+ stderr: (message) => io.stderr(redactDetachedRunText(message, environment))
107835
+ };
107680
107836
  const configuredRunId = environmentRunId(environment, "VAPI_RUN_ID");
107681
107837
  const parentRunId = environmentRunId(environment, "VAPI_PARENT_RUN_ID");
107682
107838
  const paths = getVapiPaths();
@@ -107688,8 +107844,8 @@ ${RUN_USAGE}`);
107688
107844
  if (resultFile !== void 0) {
107689
107845
  await writeJsonAtomic(resultFile, { v: 1, exitCode: 1, result: result2 }, { mode: 384 });
107690
107846
  }
107691
- if (json2) io.stdout(JSON.stringify(result2));
107692
- else io.stderr(message);
107847
+ if (json2) runIo.stdout(JSON.stringify(result2));
107848
+ else runIo.stderr(message);
107693
107849
  return 1;
107694
107850
  }
107695
107851
  const runId = configuredRunId ?? createRunId();
@@ -107753,42 +107909,48 @@ ${RUN_USAGE}`);
107753
107909
  ...runMeta === void 0 ? {} : { runMeta },
107754
107910
  approvals: "tty",
107755
107911
  json: json2,
107756
- io,
107912
+ io: runIo,
107757
107913
  dependencies
107758
107914
  });
107759
107915
  const execute = dependencies.agent?.runAgent ?? runAgent;
107760
107916
  const executed = await execute(task, runDependencies);
107761
107917
  const result = resultFile === void 0 ? executed : redactAgentRunResult(executed, environment);
107762
- if (!json2) printAgentRefills(result, io);
107918
+ if (!json2) printAgentRefills(result, runIo, io);
107763
107919
  const exitCode = result.stoppedBecause.reason === "finished" ? 0 : 1;
107764
107920
  if (resultFile !== void 0) {
107765
107921
  await writeJsonAtomic(resultFile, { v: 1, exitCode, result }, { mode: 384 });
107766
107922
  }
107767
107923
  if (json2) {
107768
- io.stdout(JSON.stringify(result));
107924
+ io.stdout(
107925
+ JSON.stringify(resultFile === void 0 ? result : redactAgentRunResult(result, environment))
107926
+ );
107769
107927
  } else if (result.stoppedBecause.reason === "finished") {
107770
- io.stdout(result.answer ?? "");
107928
+ runIo.stdout(result.answer ?? "");
107771
107929
  } else {
107772
- io.stderr(result.stoppedBecause.detail ?? result.stoppedBecause.reason);
107930
+ runIo.stderr(result.stoppedBecause.detail ?? result.stoppedBecause.reason);
107773
107931
  }
107774
107932
  return exitCode;
107775
107933
  }
107934
+ var SETTLEMENT_HASH = /^0x[0-9a-fA-F]{64}$/u;
107776
107935
  function redactAgentRunResult(executed, environment) {
107777
107936
  const result = redactDetachedRunValue(executed, environment);
107778
107937
  for (const [index2, refill] of (executed.refills ?? []).entries()) {
107779
107938
  const transaction2 = refill.receipt.transaction;
107780
107939
  const redacted = result.refills?.[index2];
107781
- if (redacted !== void 0 && transaction2 !== void 0 && /^0x[0-9a-fA-F]{64}$/u.test(transaction2)) {
107940
+ if (redacted !== void 0 && transaction2 !== void 0 && SETTLEMENT_HASH.test(transaction2)) {
107782
107941
  redacted.receipt.transaction = transaction2;
107783
107942
  }
107784
107943
  }
107785
107944
  return result;
107786
107945
  }
107787
- function printAgentRefills(result, io) {
107946
+ function printAgentRefills(result, io, settlementHashIo = io) {
107788
107947
  for (const refill of result.refills ?? []) {
107789
107948
  io.stderr(`Receipt: ${refill.receipt.id}`);
107790
- if (refill.receipt.transaction !== void 0)
107791
- io.stderr(`Transaction: ${refill.receipt.transaction}`);
107949
+ const transaction2 = refill.receipt.transaction;
107950
+ if (transaction2 !== void 0) {
107951
+ const output4 = SETTLEMENT_HASH.test(transaction2) ? settlementHashIo : io;
107952
+ output4.stderr(`Transaction: ${transaction2}`);
107953
+ }
107792
107954
  for (const warning of refill.warnings ?? []) io.stderr(warning.message);
107793
107955
  }
107794
107956
  }
@@ -112389,12 +112551,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
112389
112551
  exitCode = 0;
112390
112552
  break;
112391
112553
  case "agent":
112392
- exitCode = await agentCommand(
112393
- args.slice(1),
112394
- json2,
112395
- args[1] === "run" && args.includes("--bundle-env") ? io : runIo,
112396
- dependencies
112397
- );
112554
+ exitCode = await agentCommand(args.slice(1), json2, io, dependencies);
112398
112555
  break;
112399
112556
  case "dashboard":
112400
112557
  await dashboardCommand(args.slice(1), json2, io, dependencies);