@zeroxyz/sdk 0.9.0 → 0.10.0

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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  var viem = require('viem');
4
4
  var accounts = require('viem/accounts');
5
+ var chains = require('viem/chains');
5
6
  var relaySdk = require('@relayprotocol/relay-sdk');
6
7
  var client$1 = require('@x402/core/client');
7
8
  var http = require('@x402/core/http');
@@ -10,7 +11,6 @@ var signInWithX = require('@x402/extensions/sign-in-with-x');
10
11
  var fetch = require('@x402/fetch');
11
12
  var mppx = require('mppx');
12
13
  var client$2 = require('mppx/client');
13
- var chains = require('viem/chains');
14
14
  var crypto$1 = require('crypto');
15
15
  var zod = require('zod');
16
16
 
@@ -45,6 +45,28 @@ var createManagedAccount = (client, address) => accounts.toAccount({
45
45
  return await serialize(transaction, viem.parseSignature(signature));
46
46
  }
47
47
  });
48
+ var USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
49
+ var USDC_TEMPO = "0x20c000000000000000000000b9537d11c60e8b50";
50
+ var TEMPO_CHAIN_ID = 4217;
51
+ var baseChain = chains.base;
52
+ var tempoChain = {
53
+ id: TEMPO_CHAIN_ID,
54
+ name: "Tempo",
55
+ nativeCurrency: { name: "USD", symbol: "USD", decimals: 18 },
56
+ rpcUrls: {
57
+ default: { http: ["https://rpc.tempo.xyz"] }
58
+ }
59
+ };
60
+ var ERC20_BALANCE_ABI = [
61
+ {
62
+ inputs: [{ name: "account", type: "address" }],
63
+ name: "balanceOf",
64
+ outputs: [{ name: "", type: "uint256" }],
65
+ stateMutability: "view",
66
+ type: "function"
67
+ }
68
+ ];
69
+ var USDC_DECIMALS = 6;
48
70
 
49
71
  // src/errors.ts
50
72
  var ZeroError = class extends Error {
@@ -73,6 +95,25 @@ var ZeroAuthError = class extends ZeroError {
73
95
  this.name = "ZeroAuthError";
74
96
  }
75
97
  };
98
+ var ZeroAgentAuthError = class extends ZeroError {
99
+ status;
100
+ body;
101
+ constructor(message, init) {
102
+ super("auth_error", message, { cause: init.cause });
103
+ this.name = "ZeroAgentAuthError";
104
+ this.status = init.status;
105
+ this.body = init.body;
106
+ }
107
+ // The error code the SERVER sent, distinct from ZeroError's `code`
108
+ // discriminator. WorkOS error bodies carry {code, message}; OAuth-style
109
+ // ones carry {error}.
110
+ get serverCode() {
111
+ const body = this.body;
112
+ if (typeof body?.code === "string") return body.code;
113
+ if (typeof body?.error === "string") return body.error;
114
+ return null;
115
+ }
116
+ };
76
117
  var ZeroPaymentError = class extends ZeroError {
77
118
  constructor(message, options) {
78
119
  super("payment_error", message, options);
@@ -432,15 +473,15 @@ var networkToChain = (network) => {
432
473
  var MAX_PAY_RE = /^[0-9]+(\.[0-9]{1,6})?$/;
433
474
  var UINT_RE = /^[0-9]+$/;
434
475
  var MAX_AMOUNT_DIGITS = 30;
435
- var USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
436
- var USDC_TEMPO = "0x20c000000000000000000000b9537d11c60e8b50";
476
+ var USDC_BASE2 = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
477
+ var USDC_TEMPO2 = "0x20c000000000000000000000b9537d11c60e8b50";
437
478
  var PATHUSD_TEMPO = "0x20c0000000000000000000000000000000000000";
438
479
  var BASE_CHAIN_ID = 8453;
439
- var TEMPO_CHAIN_ID = 4217;
480
+ var TEMPO_CHAIN_ID2 = 4217;
440
481
  var TEMPO_TESTNET_CHAIN_ID = 42431;
441
482
  var DEFAULT_PREFUND = "1";
442
- var tempoChain = {
443
- id: TEMPO_CHAIN_ID,
483
+ var tempoChain2 = {
484
+ id: TEMPO_CHAIN_ID2,
444
485
  name: "Tempo",
445
486
  nativeCurrency: { name: "USD", symbol: "USD", decimals: 18 },
446
487
  rpcUrls: { default: { http: ["https://rpc.tempo.xyz"] } }
@@ -451,7 +492,7 @@ var tempoTestnetChain = {
451
492
  nativeCurrency: { name: "USD", symbol: "USD", decimals: 18 },
452
493
  rpcUrls: { default: { http: ["https://rpc.moderato.tempo.xyz"] } }
453
494
  };
454
- var ERC20_BALANCE_ABI = [
495
+ var ERC20_BALANCE_ABI2 = [
455
496
  {
456
497
  inputs: [{ name: "account", type: "address" }],
457
498
  name: "balanceOf",
@@ -480,7 +521,7 @@ var resolveDefaultPrefund = (displayCostAmount) => {
480
521
  var isUintString = (v) => typeof v === "string" && v.length > 0 && v.length <= MAX_AMOUNT_DIGITS && UINT_RE.test(v);
481
522
  var coerceTempoChainId = (raw) => {
482
523
  const id = typeof raw === "number" && Number.isFinite(raw) ? raw : typeof raw === "string" && /^-?[0-9]+$/.test(raw) ? Number(raw) : null;
483
- if (id === TEMPO_CHAIN_ID) return { id, chain: "tempo" };
524
+ if (id === TEMPO_CHAIN_ID2) return { id, chain: "tempo" };
484
525
  if (id === TEMPO_TESTNET_CHAIN_ID) return { id, chain: "tempo-testnet" };
485
526
  return null;
486
527
  };
@@ -967,7 +1008,7 @@ var Payments = class {
967
1008
  );
968
1009
  if (!coerced) {
969
1010
  throw new ZeroPaymentError(
970
- `MPP challenge has missing or unsupported chainId (expected ${TEMPO_CHAIN_ID} or ${TEMPO_TESTNET_CHAIN_ID})`
1011
+ `MPP challenge has missing or unsupported chainId (expected ${TEMPO_CHAIN_ID2} or ${TEMPO_TESTNET_CHAIN_ID})`
971
1012
  );
972
1013
  }
973
1014
  const tempoBalance = await this.readUsdcBalance(
@@ -1011,9 +1052,9 @@ var Payments = class {
1011
1052
  });
1012
1053
  const quote = await relaySdk.getClient().actions.getQuote({
1013
1054
  chainId: BASE_CHAIN_ID,
1014
- toChainId: TEMPO_CHAIN_ID,
1015
- currency: USDC_BASE,
1016
- toCurrency: USDC_TEMPO,
1055
+ toChainId: TEMPO_CHAIN_ID2,
1056
+ currency: USDC_BASE2,
1057
+ toCurrency: USDC_TEMPO2,
1017
1058
  amount: bridgeAmount.toString(),
1018
1059
  tradeType: "EXACT_INPUT",
1019
1060
  user: account.address,
@@ -1044,7 +1085,7 @@ var Payments = class {
1044
1085
  // Tempo tx hash on the Base transport.
1045
1086
  chains: [
1046
1087
  relaySdk.convertViemChainToRelayChain(chains.base),
1047
- relaySdk.convertViemChainToRelayChain(tempoChain)
1088
+ relaySdk.convertViemChainToRelayChain(tempoChain2)
1048
1089
  ]
1049
1090
  });
1050
1091
  this.relayInitialized = true;
@@ -1053,14 +1094,14 @@ var Payments = class {
1053
1094
  const { viemChain, token } = (() => {
1054
1095
  switch (chain) {
1055
1096
  case "base":
1056
- return { viemChain: chains.base, token: USDC_BASE };
1097
+ return { viemChain: chains.base, token: USDC_BASE2 };
1057
1098
  case "base-sepolia":
1058
1099
  return {
1059
1100
  viemChain: chains.baseSepolia,
1060
1101
  token: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
1061
1102
  };
1062
1103
  case "tempo":
1063
- return { viemChain: tempoChain, token: USDC_TEMPO };
1104
+ return { viemChain: tempoChain2, token: USDC_TEMPO2 };
1064
1105
  case "tempo-testnet":
1065
1106
  return { viemChain: tempoTestnetChain, token: PATHUSD_TEMPO };
1066
1107
  }
@@ -1068,7 +1109,7 @@ var Payments = class {
1068
1109
  const client = viem.createPublicClient({ chain: viemChain, transport: viem.http() });
1069
1110
  return await client.readContract({
1070
1111
  address: token,
1071
- abi: ERC20_BALANCE_ABI,
1112
+ abi: ERC20_BALANCE_ABI2,
1072
1113
  functionName: "balanceOf",
1073
1114
  args: [address]
1074
1115
  });
@@ -1118,7 +1159,7 @@ var Payments = class {
1118
1159
  }
1119
1160
  if (!coercedChainId) {
1120
1161
  throw buildOrphanFromChannelEntry(
1121
- `MPP session challenge has unsupported chainId (expected ${TEMPO_CHAIN_ID} or ${TEMPO_TESTNET_CHAIN_ID}); channel ${channelId} is open and requires reconciliation.`
1162
+ `MPP session challenge has unsupported chainId (expected ${TEMPO_CHAIN_ID2} or ${TEMPO_TESTNET_CHAIN_ID}); channel ${channelId} is open and requires reconciliation.`
1122
1163
  );
1123
1164
  }
1124
1165
  const receipt = readSessionReceipt(response);
@@ -1438,16 +1479,89 @@ var extractUpstreamErrorMessage = (body) => {
1438
1479
  }
1439
1480
  return void 0;
1440
1481
  };
1482
+ var extractFieldName = (message) => {
1483
+ const patterns = [
1484
+ /(?:field|param(?:eter)?|property|key)[:\s]+["'`]?([a-z0-9_.[\]-]+)["'`]?/i,
1485
+ /["'`]([a-z0-9_.[\]-]+)["'`]\s*(?:is\s+)?(?:required|missing|expected)/i,
1486
+ // Quotes REQUIRED here — an unquoted token after "required"/"missing"
1487
+ // is usually a generic noun ("required parameters", "missing fields"),
1488
+ // not a field name. Only trust it when the seller quoted it.
1489
+ /(?:required|missing|expected)[:\s]+["'`]([a-z0-9_.[\]-]+)["'`]/i
1490
+ ];
1491
+ for (const p of patterns) {
1492
+ const match = message.match(p);
1493
+ if (match?.[1]) return match[1];
1494
+ }
1495
+ return void 0;
1496
+ };
1497
+ var extractAllowedMethod = (text) => {
1498
+ const listed = text.match(
1499
+ /allowed[^[]*\[\s*["'`]?(GET|POST|PUT|PATCH|DELETE|HEAD)/i
1500
+ );
1501
+ if (listed?.[1]) return listed[1].toUpperCase();
1502
+ const useVerb = text.match(/\buse\s+(GET|POST|PUT|PATCH|DELETE|HEAD)\b/i);
1503
+ if (useVerb?.[1]) return useVerb[1].toUpperCase();
1504
+ return void 0;
1505
+ };
1506
+ var extractUnrecognizedKeys = (bodyRaw) => {
1507
+ if (!bodyRaw) return [];
1508
+ const parsed = tryParseJson(bodyRaw);
1509
+ if (parsed === null || typeof parsed !== "object") return [];
1510
+ const out = [];
1511
+ const visit = (node) => {
1512
+ if (!node || typeof node !== "object") return;
1513
+ const o = node;
1514
+ if (Array.isArray(o.keys)) {
1515
+ for (const k of o.keys) if (typeof k === "string") out.push(k);
1516
+ }
1517
+ for (const v of Object.values(o)) {
1518
+ if (Array.isArray(v)) v.forEach(visit);
1519
+ else if (v && typeof v === "object") visit(v);
1520
+ }
1521
+ };
1522
+ visit(parsed);
1523
+ return [...new Set(out)].slice(0, 8);
1524
+ };
1525
+ var computeFixHint = (status, message, bodyRaw) => {
1526
+ if (status < 400 || status >= 500) return void 0;
1527
+ const hay = `${message ?? ""} ${bodyRaw ?? ""}`.toLowerCase();
1528
+ if (status === 405 || /method not allowed|method_not_allowed/.test(hay)) {
1529
+ const allowed = extractAllowedMethod(`${bodyRaw ?? ""} ${message ?? ""}`);
1530
+ return allowed ? `the endpoint expects ${allowed}, not the method you used \u2014 retry with -X ${allowed}` : "the endpoint rejected this HTTP method \u2014 check the capability's method (`zero get <slug>`) and retry with the right -X";
1531
+ }
1532
+ if (/invalid json|not valid json|malformed|unexpected token|json ?parse|could not parse|failed to parse|jsondecode/.test(
1533
+ hay
1534
+ )) {
1535
+ return "the request body isn't valid JSON \u2014 check quoting/escaping (single-quote the -d value or use @file), then retry";
1536
+ }
1537
+ if (/unrecognized[_ ]?key|unexpected key|unknown (field|key|propert)|additional (?:propert|field)|not allowed in object/.test(
1538
+ hay
1539
+ )) {
1540
+ const keys = extractUnrecognizedKeys(bodyRaw ?? null);
1541
+ return keys.length ? `remove the unexpected field(s) ${keys.map((k) => `'${k}'`).join(", ")} from the request body, then retry` : "the request body has fields the capability doesn't accept \u2014 send only the documented fields, then retry";
1542
+ }
1543
+ if (status === 415 || /content-?type|unsupported media|media type/.test(hay)) {
1544
+ return "set the Content-Type header to what the capability expects (usually application/json), then retry";
1545
+ }
1546
+ if (/required|missing|must (include|provide|have|contain)|is expected/.test(hay)) {
1547
+ const field = extractFieldName(message ?? "");
1548
+ return field ? `add the required field '${field}' to the request body, then retry` : "the request is missing one or more required fields \u2014 check the capability schema (`zero get <slug>`), then retry";
1549
+ }
1550
+ return void 0;
1551
+ };
1441
1552
  var buildUpstreamError = (status, bodyRaw, bodyEncoding) => {
1442
1553
  if (status >= 200 && status < 300) return void 0;
1443
1554
  if (bodyRaw === null || bodyRaw.length === 0) return void 0;
1444
1555
  if (bodyEncoding === "base64") return void 0;
1445
1556
  const snippet = bodyRaw.slice(0, ERROR_SNIPPET_BYTES);
1557
+ const message = extractUpstreamErrorMessage(bodyRaw);
1558
+ const fixHint = computeFixHint(status, message, bodyRaw);
1446
1559
  return {
1447
1560
  status,
1448
- message: extractUpstreamErrorMessage(bodyRaw),
1561
+ message,
1449
1562
  snippetHash: crypto$1.createHash("sha256").update(snippet).digest("hex"),
1450
- snippetLength: snippet.length
1563
+ snippetLength: snippet.length,
1564
+ ...fixHint && { fixHint }
1451
1565
  };
1452
1566
  };
1453
1567
  var computeOutcome = (status, payment, warnings) => {
@@ -1838,77 +1952,64 @@ var clientFetch = async (client, url, opts = {}) => {
1838
1952
 
1839
1953
  // package.json
1840
1954
  var package_default = {
1841
- version: "0.9.0"};
1955
+ version: "0.10.0"};
1842
1956
 
1843
1957
  // src/version.ts
1844
1958
  var SDK_VERSION = package_default.version;
1845
- var userWalletDtoSchema = zod.z.object({
1846
- walletAddress: zod.z.string(),
1847
- source: zod.z.enum(["self_custody", "privy_embedded"]),
1848
- isPrimary: zod.z.boolean(),
1849
- linkedAt: zod.z.union([zod.z.string(), zod.z.date()]).nullable().optional(),
1850
- delegationGranted: zod.z.boolean(),
1851
- signerQuorumId: zod.z.string().nullable(),
1852
- // Per-transaction USDC cap in base units (6 dp). null = unlimited, 0 = free-only.
1853
- maxTransactionUsdcBaseUnits: zod.z.number().int().nullable()
1854
- });
1855
- var welcomeBonusSummarySchema = zod.z.object({
1856
- status: zod.z.string(),
1857
- amountUsd: zod.z.number()
1858
- });
1859
- var internalUserDtoSchema = zod.z.object({
1959
+ var agentAuthMetadataSchema = zod.z.object({
1960
+ token_endpoint: zod.z.string().optional(),
1961
+ agent_auth: zod.z.object({
1962
+ identity_endpoint: zod.z.string(),
1963
+ claim_endpoint: zod.z.string().optional()
1964
+ }).loose()
1965
+ }).loose();
1966
+ var identityEnvelopeSchema = zod.z.object({
1860
1967
  id: zod.z.string(),
1861
- email: zod.z.string().nullable(),
1862
- createdAt: zod.z.union([zod.z.string(), zod.z.date()]).optional(),
1863
- lastLoginAt: zod.z.union([zod.z.string(), zod.z.date()]).nullable().optional(),
1864
- onboardingCompleted: zod.z.boolean().optional(),
1865
- delegationGranted: zod.z.boolean().optional(),
1866
- wallets: zod.z.array(userWalletDtoSchema).optional(),
1867
- balance: zod.z.object({ amount: zod.z.string(), asset: zod.z.string() }).nullable().optional(),
1868
- welcomeBonus: welcomeBonusSummarySchema.nullable().optional()
1869
- });
1870
- var publicUserDtoSchema = zod.z.object({
1871
- user: zod.z.object({
1872
- id: zod.z.string(),
1873
- email: zod.z.string().nullable()
1874
- }),
1875
- walletAddress: zod.z.string().nullable(),
1876
- balance: zod.z.object({ amount: zod.z.string(), asset: zod.z.string() }).nullable(),
1877
- welcomeBonus: welcomeBonusSummarySchema.nullable()
1878
- });
1879
- var signResponseSchema = zod.z.object({
1880
- signature: zod.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be 0x-prefixed hex"),
1881
- walletAddress: zod.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be 0x-prefixed 40-char hex address")
1882
- });
1883
-
1884
- // src/schemas/device.ts
1885
- var deviceStartResponseSchema = zod.z.object({
1886
- deviceCode: zod.z.string(),
1887
- userCode: zod.z.string(),
1888
- verificationUri: zod.z.string(),
1889
- pollInterval: zod.z.number(),
1890
- expiresAt: zod.z.number()
1891
- });
1892
- var devicePollResponseSchema = zod.z.union([
1893
- // userCode + verificationUri are optional: older API deployments don't
1894
- // echo them on pending.
1895
- zod.z.object({
1896
- error: zod.z.literal("authorization_pending"),
1897
- userCode: zod.z.string().optional(),
1898
- verificationUri: zod.z.string().optional()
1899
- }),
1900
- zod.z.object({ error: zod.z.literal("expired_token") }),
1901
- zod.z.object({
1902
- accessToken: zod.z.string(),
1903
- refreshToken: zod.z.string(),
1904
- expiresIn: zod.z.number(),
1905
- user: internalUserDtoSchema
1906
- })
1907
- ]);
1908
- var sessionExchangeResponseSchema = zod.z.object({
1909
- token: zod.z.string(),
1910
- expiresAt: zod.z.number()
1911
- });
1968
+ identity: zod.z.object({
1969
+ assertion: zod.z.string(),
1970
+ expires_at: zod.z.string().optional(),
1971
+ refresh_token: zod.z.object({ value: zod.z.string() }).loose().optional()
1972
+ }).loose(),
1973
+ claim: zod.z.object({
1974
+ token: zod.z.string().optional(),
1975
+ expires_at: zod.z.string().optional()
1976
+ }).loose().optional()
1977
+ }).loose().transform((raw) => ({
1978
+ registrationId: raw.id,
1979
+ identityAssertion: raw.identity.assertion,
1980
+ assertionExpires: raw.identity.expires_at ?? null,
1981
+ refreshToken: raw.identity.refresh_token?.value ?? null,
1982
+ claimToken: raw.claim?.token ?? null,
1983
+ claimTokenExpires: raw.claim?.expires_at ?? null
1984
+ }));
1985
+ var agentTokenResponseSchema = zod.z.object({ access_token: zod.z.string() }).loose().transform((raw) => ({ accessToken: raw.access_token }));
1986
+ var startClaimResponseSchema = zod.z.object({
1987
+ attempt: zod.z.object({
1988
+ verification_uri: zod.z.string(),
1989
+ expires_at: zod.z.string().optional()
1990
+ }).loose()
1991
+ }).loose().transform((raw) => ({
1992
+ verificationUri: raw.attempt.verification_uri,
1993
+ expiresAt: raw.attempt.expires_at ?? null
1994
+ }));
1995
+ var completeClaimResponseSchema = zod.z.object({
1996
+ identity: zod.z.object({
1997
+ assertion: zod.z.string(),
1998
+ expires_at: zod.z.string().optional(),
1999
+ refresh_token: zod.z.object({ value: zod.z.string() }).loose().optional()
2000
+ }).loose()
2001
+ }).loose().transform((raw) => ({
2002
+ identityAssertion: raw.identity.assertion,
2003
+ assertionExpires: raw.identity.expires_at ?? null,
2004
+ refreshToken: raw.identity.refresh_token?.value ?? null
2005
+ }));
2006
+ var agentZeroSessionSchema = zod.z.object({
2007
+ accessToken: zod.z.string(),
2008
+ refreshToken: zod.z.string(),
2009
+ expiresIn: zod.z.number(),
2010
+ user: zod.z.object({ id: zod.z.string() }).loose(),
2011
+ walletAddress: zod.z.string().optional()
2012
+ }).loose();
1912
2013
  var refreshResponseSchema = zod.z.object({
1913
2014
  accessToken: zod.z.string(),
1914
2015
  refreshToken: zod.z.string()
@@ -2144,6 +2245,267 @@ var request = async (client, opts, schema) => {
2144
2245
  });
2145
2246
  };
2146
2247
 
2248
+ // src/namespaces/auth-agent.ts
2249
+ var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
2250
+ var trimSlash = (value) => value.replace(/\/$/, "");
2251
+ var wrapNetworkError = (url, err) => {
2252
+ const cause = err?.cause;
2253
+ const causeMessage = cause instanceof Error ? cause.code ?? cause.message : err instanceof Error ? err.message : String(err);
2254
+ return new ZeroAgentAuthError(`Could not reach ${url} (${causeMessage})`, {
2255
+ status: 0,
2256
+ cause: err
2257
+ });
2258
+ };
2259
+ var AuthAgent = class {
2260
+ constructor(client) {
2261
+ this.client = client;
2262
+ }
2263
+ endpointsPromise = null;
2264
+ // Fully autonomous signup: register anonymously at the AuthKit domain,
2265
+ // exchange the identity assertion for a WorkOS access token, exchange that
2266
+ // for a Zero session. The claim token and identity assertion are returned
2267
+ // exactly once — the caller persists them.
2268
+ signup = async () => {
2269
+ const registration = await this.register();
2270
+ const token = await this.exchangeAssertion(registration.identityAssertion);
2271
+ const session = await this.exchangeAtZero(token.accessToken);
2272
+ return { registration, session };
2273
+ };
2274
+ register = async () => {
2275
+ const endpoints = await this.endpoints();
2276
+ return this.postJson(
2277
+ endpoints.identityEndpoint,
2278
+ { type: "anonymous" },
2279
+ identityEnvelopeSchema
2280
+ );
2281
+ };
2282
+ exchangeAssertion = async (identityAssertion) => {
2283
+ const endpoints = await this.endpoints();
2284
+ return this.postForm(
2285
+ endpoints.tokenEndpoint,
2286
+ { grant_type: JWT_BEARER_GRANT_TYPE, assertion: identityAssertion },
2287
+ agentTokenResponseSchema
2288
+ );
2289
+ };
2290
+ // POST /v1/auth/agent/exchange — WorkOS agent access token → Zero session
2291
+ // pair (+ the implicitly provisioned wallet address). The post-claim token
2292
+ // goes through here too: the server binds the claiming human.
2293
+ exchangeAtZero = (accessToken, opts = {}) => request(
2294
+ this.client,
2295
+ {
2296
+ method: "POST",
2297
+ path: "/v1/auth/agent/exchange",
2298
+ body: { accessToken },
2299
+ signal: opts.signal
2300
+ },
2301
+ agentZeroSessionSchema
2302
+ );
2303
+ // Mint a claim attempt. The human opens the returned verification URI,
2304
+ // signs in as `email`, and the page shows THEM a pairing code to read back
2305
+ // to the agent — completeClaim() submits it.
2306
+ startClaim = async (input) => {
2307
+ const endpoints = await this.endpoints();
2308
+ if (!endpoints.claimEndpoint) {
2309
+ throw new ZeroAgentAuthError(
2310
+ "The authorization server advertises no claim endpoint.",
2311
+ { status: 0 }
2312
+ );
2313
+ }
2314
+ return this.postJson(
2315
+ endpoints.claimEndpoint,
2316
+ {
2317
+ type: "service_auth",
2318
+ claim_token: input.claimToken,
2319
+ login_hint: input.email
2320
+ },
2321
+ startClaimResponseSchema
2322
+ );
2323
+ };
2324
+ // Submit the pairing code the human read off the hosted page. Terminal
2325
+ // states map to a typed result; anything unexpected throws.
2326
+ completeClaim = async (input) => {
2327
+ const endpoints = await this.endpoints();
2328
+ if (!endpoints.claimEndpoint) {
2329
+ throw new ZeroAgentAuthError(
2330
+ "The authorization server advertises no claim endpoint.",
2331
+ { status: 0 }
2332
+ );
2333
+ }
2334
+ try {
2335
+ const identity = await this.postJson(
2336
+ `${endpoints.claimEndpoint}/complete`,
2337
+ { claim_token: input.claimToken, user_code: input.userCode },
2338
+ completeClaimResponseSchema
2339
+ );
2340
+ return { status: "ok", ...identity };
2341
+ } catch (err) {
2342
+ if (err instanceof ZeroAgentAuthError && err.serverCode) {
2343
+ if (err.serverCode === "claim_not_confirmed") {
2344
+ return { status: "not_confirmed" };
2345
+ }
2346
+ if (err.serverCode === "invalid_user_code") {
2347
+ return { status: "invalid_code" };
2348
+ }
2349
+ if ([
2350
+ "user_code_expired",
2351
+ "claim_expired",
2352
+ "claim_revoked",
2353
+ "already_claimed",
2354
+ "claim_denied"
2355
+ ].includes(err.serverCode)) {
2356
+ return { status: "expired", code: err.serverCode };
2357
+ }
2358
+ }
2359
+ throw err;
2360
+ }
2361
+ };
2362
+ // Resolve (and cache) the agent-auth endpoints via discovery.
2363
+ endpoints = () => {
2364
+ if (!this.endpointsPromise) {
2365
+ this.endpointsPromise = this.discover().catch((err) => {
2366
+ this.endpointsPromise = null;
2367
+ throw err;
2368
+ });
2369
+ }
2370
+ return this.endpointsPromise;
2371
+ };
2372
+ discover = async () => {
2373
+ const resource = await this.getJson(
2374
+ `${trimSlash(this.client.baseUrl)}/.well-known/oauth-protected-resource`
2375
+ );
2376
+ let lastError = null;
2377
+ for (const server of resource.authorization_servers ?? []) {
2378
+ try {
2379
+ const raw = await this.getJson(
2380
+ `${trimSlash(server)}/.well-known/oauth-authorization-server`
2381
+ );
2382
+ const metadata = agentAuthMetadataSchema.parse(raw);
2383
+ return {
2384
+ authorizationServer: trimSlash(server),
2385
+ identityEndpoint: metadata.agent_auth.identity_endpoint,
2386
+ claimEndpoint: metadata.agent_auth.claim_endpoint ?? null,
2387
+ tokenEndpoint: metadata.token_endpoint ?? `${trimSlash(server)}/oauth2/token`
2388
+ };
2389
+ } catch (err) {
2390
+ lastError = err;
2391
+ }
2392
+ }
2393
+ throw new ZeroAgentAuthError(
2394
+ "No authorization server with an agent_auth block found \u2014 agent registration is not enabled for this service.",
2395
+ { status: 0, cause: lastError }
2396
+ );
2397
+ };
2398
+ getJson = async (url) => {
2399
+ const response = await this.client.fetchImpl(url).catch((err) => {
2400
+ throw wrapNetworkError(url, err);
2401
+ });
2402
+ if (!response.ok) {
2403
+ throw new ZeroAgentAuthError(`GET ${url} failed (${response.status})`, {
2404
+ status: response.status
2405
+ });
2406
+ }
2407
+ return await response.json();
2408
+ };
2409
+ postJson = (url, body, schema) => this.post(url, "application/json", JSON.stringify(body), schema);
2410
+ postForm = (url, fields, schema) => this.post(
2411
+ url,
2412
+ "application/x-www-form-urlencoded",
2413
+ new URLSearchParams(fields).toString(),
2414
+ schema
2415
+ );
2416
+ post = async (url, contentType, body, schema) => {
2417
+ const response = await this.client.fetchImpl(url, {
2418
+ method: "POST",
2419
+ headers: { "content-type": contentType },
2420
+ body
2421
+ }).catch((err) => {
2422
+ throw wrapNetworkError(url, err);
2423
+ });
2424
+ const text = await response.text();
2425
+ let parsed = null;
2426
+ try {
2427
+ parsed = text ? JSON.parse(text) : null;
2428
+ } catch {
2429
+ }
2430
+ if (!response.ok) {
2431
+ const errBody = parsed;
2432
+ const code = errBody?.code ?? errBody?.error;
2433
+ throw new ZeroAgentAuthError(
2434
+ `Agent auth request to ${url} failed (${response.status}${typeof code === "string" ? `: ${code}` : ""})`,
2435
+ { status: response.status, body: parsed ?? text }
2436
+ );
2437
+ }
2438
+ return schema.parse(parsed);
2439
+ };
2440
+ };
2441
+ var userWalletDtoSchema = zod.z.object({
2442
+ walletAddress: zod.z.string(),
2443
+ source: zod.z.enum(["self_custody", "privy_embedded"]),
2444
+ isPrimary: zod.z.boolean(),
2445
+ linkedAt: zod.z.union([zod.z.string(), zod.z.date()]).nullable().optional(),
2446
+ delegationGranted: zod.z.boolean(),
2447
+ signerQuorumId: zod.z.string().nullable(),
2448
+ // Per-transaction USDC cap in base units (6 dp). null = unlimited, 0 = free-only.
2449
+ maxTransactionUsdcBaseUnits: zod.z.number().int().nullable()
2450
+ });
2451
+ var welcomeBonusSummarySchema = zod.z.object({
2452
+ status: zod.z.string(),
2453
+ amountUsd: zod.z.number()
2454
+ });
2455
+ var internalUserDtoSchema = zod.z.object({
2456
+ id: zod.z.string(),
2457
+ email: zod.z.string().nullable(),
2458
+ createdAt: zod.z.union([zod.z.string(), zod.z.date()]).optional(),
2459
+ lastLoginAt: zod.z.union([zod.z.string(), zod.z.date()]).nullable().optional(),
2460
+ onboardingCompleted: zod.z.boolean().optional(),
2461
+ delegationGranted: zod.z.boolean().optional(),
2462
+ wallets: zod.z.array(userWalletDtoSchema).optional(),
2463
+ balance: zod.z.object({ amount: zod.z.string(), asset: zod.z.string() }).nullable().optional(),
2464
+ welcomeBonus: welcomeBonusSummarySchema.nullable().optional()
2465
+ });
2466
+ var publicUserDtoSchema = zod.z.object({
2467
+ user: zod.z.object({
2468
+ id: zod.z.string(),
2469
+ email: zod.z.string().nullable()
2470
+ }),
2471
+ walletAddress: zod.z.string().nullable(),
2472
+ balance: zod.z.object({ amount: zod.z.string(), asset: zod.z.string() }).nullable(),
2473
+ welcomeBonus: welcomeBonusSummarySchema.nullable()
2474
+ });
2475
+ var signResponseSchema = zod.z.object({
2476
+ signature: zod.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be 0x-prefixed hex"),
2477
+ walletAddress: zod.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be 0x-prefixed 40-char hex address")
2478
+ });
2479
+
2480
+ // src/schemas/device.ts
2481
+ var deviceStartResponseSchema = zod.z.object({
2482
+ deviceCode: zod.z.string(),
2483
+ userCode: zod.z.string(),
2484
+ verificationUri: zod.z.string(),
2485
+ pollInterval: zod.z.number(),
2486
+ expiresAt: zod.z.number()
2487
+ });
2488
+ var devicePollResponseSchema = zod.z.union([
2489
+ // userCode + verificationUri are optional: older API deployments don't
2490
+ // echo them on pending.
2491
+ zod.z.object({
2492
+ error: zod.z.literal("authorization_pending"),
2493
+ userCode: zod.z.string().optional(),
2494
+ verificationUri: zod.z.string().optional()
2495
+ }),
2496
+ zod.z.object({ error: zod.z.literal("expired_token") }),
2497
+ zod.z.object({
2498
+ accessToken: zod.z.string(),
2499
+ refreshToken: zod.z.string(),
2500
+ expiresIn: zod.z.number(),
2501
+ user: internalUserDtoSchema
2502
+ })
2503
+ ]);
2504
+ var sessionExchangeResponseSchema = zod.z.object({
2505
+ token: zod.z.string(),
2506
+ expiresAt: zod.z.number()
2507
+ });
2508
+
2147
2509
  // src/namespaces/auth-device.ts
2148
2510
  var AuthDevice = class {
2149
2511
  constructor(client) {
@@ -2205,8 +2567,10 @@ var repackageSignFailure = (err, op) => {
2205
2567
  var Auth = class {
2206
2568
  constructor(client) {
2207
2569
  this.client = client;
2570
+ this.agent = new AuthAgent(client);
2208
2571
  this.device = new AuthDevice(client);
2209
2572
  }
2573
+ agent;
2210
2574
  device;
2211
2575
  // The internal (web-app facing) user profile. Richer than profile(): full
2212
2576
  // wallet list with per-wallet delegation/signer/limit metadata.
@@ -2413,8 +2777,12 @@ var createBugReportResponseSchema = zod.z.object({
2413
2777
  searchId: zod.z.number().nullable()
2414
2778
  })
2415
2779
  });
2416
-
2417
- // src/namespaces/bug-reports.ts
2780
+ var TEN_MIN_MS = 10 * 60 * 1e3;
2781
+ var autoIdempotencyKey = (description, contextSeed) => {
2782
+ const bucket = Math.floor(Date.now() / TEN_MIN_MS);
2783
+ const seed = `${description}|${contextSeed ?? ""}|${bucket}`;
2784
+ return `auto-${crypto$1.createHash("sha256").update(seed).digest("hex").slice(0, 16)}`;
2785
+ };
2418
2786
  var BugReports = class {
2419
2787
  constructor(client) {
2420
2788
  this.client = client;
@@ -2422,16 +2790,26 @@ var BugReports = class {
2422
2790
  // POST /v1/bug-reports. Wallet-attributed server-side; the SDK client's
2423
2791
  // active credential drives attribution (account-mode → EIP-191 from the
2424
2792
  // wallet, session-mode → Bearer + server resolves the user's wallet).
2425
- create = (input, opts = {}) => request(
2426
- this.client,
2427
- {
2428
- method: "POST",
2429
- path: "/v1/bug-reports",
2430
- body: input,
2431
- signal: opts.signal
2432
- },
2433
- createBugReportResponseSchema
2434
- );
2793
+ // When `idempotencyKey` is omitted, one is auto-derived from the description
2794
+ // and (optional) contextSeed, bucketed to 10-minute windows so accidental
2795
+ // retries within the window dedup naturally.
2796
+ create = (input, opts = {}) => {
2797
+ const { contextSeed, ...rest } = input;
2798
+ const withKey = {
2799
+ ...rest,
2800
+ idempotencyKey: input.idempotencyKey ?? autoIdempotencyKey(input.description, contextSeed)
2801
+ };
2802
+ return request(
2803
+ this.client,
2804
+ {
2805
+ method: "POST",
2806
+ path: "/v1/bug-reports",
2807
+ body: withKey,
2808
+ signal: opts.signal
2809
+ },
2810
+ createBugReportResponseSchema
2811
+ );
2812
+ };
2435
2813
  };
2436
2814
  var ratingSchema = zod.z.object({
2437
2815
  score: zod.z.string(),
@@ -2491,6 +2869,9 @@ var capabilityResponseSchema = zod.z.object({
2491
2869
  "unknown_unparsed",
2492
2870
  "unprobed"
2493
2871
  ]).optional(),
2872
+ // ZERO-147 — provenance of displayCostAmount (settled | probe | registry |
2873
+ // unknown). `settled` means the shown price is reconciled from real charges.
2874
+ priceSource: zod.z.string().nullable().optional(),
2494
2875
  requiresHandshake: zod.z.boolean().optional(),
2495
2876
  reviewCount: zod.z.number(),
2496
2877
  rating: ratingSchema,
@@ -2755,50 +3136,39 @@ var Runs = class {
2755
3136
  batchReviewResponseSchema
2756
3137
  );
2757
3138
  };
2758
- var USDC_BASE2 = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
2759
- var USDC_TEMPO2 = "0x20c000000000000000000000b9537d11c60e8b50";
2760
- var TEMPO_CHAIN_ID2 = 4217;
2761
- var baseChain = chains.base;
2762
- var tempoChain2 = {
2763
- id: TEMPO_CHAIN_ID2,
2764
- name: "Tempo",
2765
- nativeCurrency: { name: "USD", symbol: "USD", decimals: 18 },
2766
- rpcUrls: {
2767
- default: { http: ["https://rpc.tempo.xyz"] }
2768
- }
2769
- };
2770
- var ERC20_BALANCE_ABI2 = [
2771
- {
2772
- inputs: [{ name: "account", type: "address" }],
2773
- name: "balanceOf",
2774
- outputs: [{ name: "", type: "uint256" }],
2775
- stateMutability: "view",
2776
- type: "function"
2777
- }
2778
- ];
2779
- var USDC_DECIMALS = 6;
2780
-
2781
- // src/namespaces/wallet.ts
2782
3139
  var fundingUrlResponseSchema = zod.z.object({ url: zod.z.string() });
2783
3140
  var userWalletListSchema = zod.z.array(userWalletDtoSchema);
2784
- var migrateAuthorizationResponseSchema = zod.z.object({
2785
- transactionHash: zod.z.string()
2786
- });
2787
3141
  var errorMessage = (reason) => reason instanceof Error ? reason.message : String(reason);
2788
3142
  var Wallet = class {
2789
3143
  constructor(client) {
2790
3144
  this.client = client;
2791
3145
  }
2792
3146
  clients = {};
2793
- // The configured wallet address, or null if the client wasn't constructed
2794
- // with an account. Stable read — does not hit the network.
2795
- get address() {
3147
+ // The configured account's address, or null when the client runs in
3148
+ // session/no-credential mode. Local read — never hits the network.
3149
+ get configuredAddress() {
2796
3150
  const credentials = this.client.getCredentials();
2797
3151
  if (credentials.kind !== "account") return null;
2798
3152
  return credentials.account.address;
2799
3153
  }
3154
+ // The wallet address this client acts as. Account mode resolves locally
3155
+ // (no network). Session mode resolves the user's managed (Privy-embedded)
3156
+ // wallet, provisioning one on first call if the user has none yet. Throws
3157
+ // on network/auth failure — callers that want a null-fallback should wrap
3158
+ // in try/catch (the CLI does this in `resolveManagedWalletAddress`).
3159
+ address = async (opts = {}) => {
3160
+ const configured = this.configuredAddress;
3161
+ if (configured) return configured;
3162
+ const wallets = await this.list(opts);
3163
+ const primary = wallets.find(
3164
+ (w) => w.source === "privy_embedded" && w.isPrimary
3165
+ );
3166
+ if (primary) return primary.walletAddress;
3167
+ const provisioned = await this.provision(opts);
3168
+ return provisioned.walletAddress;
3169
+ };
2800
3170
  balance = async (opts = {}) => {
2801
- const target = opts.address ?? this.address;
3171
+ const target = opts.address ?? this.configuredAddress;
2802
3172
  if (!target) {
2803
3173
  throw new ZeroWalletError(
2804
3174
  "balance() requires either an `address` option or a client constructed with an account"
@@ -2858,21 +3228,6 @@ var Wallet = class {
2858
3228
  },
2859
3229
  userWalletDtoSchema
2860
3230
  );
2861
- // Relays a BYO-wallet-signed EIP-3009 ReceiveWithAuthorization, sweeping
2862
- // USDC from the BYO wallet to the user's Zero wallet on Base via the
2863
- // gas-paying relayer. The SDK does not author the authorization (chain
2864
- // nonce + EIP-712 domain coupling stays caller-side); it only forwards
2865
- // the signed payload. Session-only.
2866
- migrateAuthorization = (authorization, opts = {}) => request(
2867
- this.client,
2868
- {
2869
- method: "POST",
2870
- path: "/v1/users/me/wallets/migrate",
2871
- body: { authorization },
2872
- signal: opts.signal
2873
- },
2874
- migrateAuthorizationResponseSchema
2875
- );
2876
3231
  // Routes by identity: account mode signs EIP-191 against /v1/wallet/fund-url,
2877
3232
  // session mode hits /v1/users/me/fund-url (Bearer-authed, wallet resolved
2878
3233
  // server-side). Both honor `provider` (coinbase | stripe).
@@ -2908,7 +3263,7 @@ var Wallet = class {
2908
3263
  if (!this.clients.tempo) {
2909
3264
  this.clients.tempo = viem.createPublicClient({
2910
3265
  // biome-ignore lint/suspicious/noExplicitAny: tempo is a custom chain object that viem's stricter Chain type rejects shape-wise but accepts at runtime
2911
- chain: tempoChain2,
3266
+ chain: tempoChain,
2912
3267
  transport: viem.http()
2913
3268
  });
2914
3269
  }
@@ -2924,10 +3279,10 @@ var Wallet = class {
2924
3279
  */
2925
3280
  readChainBalance = async (chain, address) => {
2926
3281
  const publicClient = this.getPublicClient(chain);
2927
- const tokenAddress = chain === "base" ? USDC_BASE2 : USDC_TEMPO2;
3282
+ const tokenAddress = chain === "base" ? USDC_BASE : USDC_TEMPO;
2928
3283
  const balance = await publicClient.readContract({
2929
3284
  address: tokenAddress,
2930
- abi: ERC20_BALANCE_ABI2,
3285
+ abi: ERC20_BALANCE_ABI,
2931
3286
  functionName: "balanceOf",
2932
3287
  args: [address]
2933
3288
  });
@@ -2965,6 +3320,10 @@ var searchResultSchema = zod.z.object({
2965
3320
  url: zod.z.string(),
2966
3321
  urlTemplate: zod.z.string().nullable().optional(),
2967
3322
  cost: zod.z.object({ amount: zod.z.string(), asset: zod.z.string() }),
3323
+ // ZERO-199 — the server-resolved price. Prefer `pricing.summary` over
3324
+ // deriving a label from `cost.amount` (which flattens usage-priced caps).
3325
+ // Optional: absent on older API deploys.
3326
+ pricing: zod.z.object({ kind: zod.z.string(), summary: zod.z.string() }).optional(),
2968
3327
  // Payment protocol (x402 | mpp) for this result. The server emits it; the SDK
2969
3328
  // previously stripped it, leaving an agent unable to tell which handshake to
2970
3329
  // engage from a search row. Optional/nullable so older deploys still parse
@@ -3358,6 +3717,26 @@ var ZeroClient = class _ZeroClient {
3358
3717
  // path is flat on the client, same rationale as `search` above.
3359
3718
  // Orchestration lives in fetch.ts so this class stays readable.
3360
3719
  fetch = (url, opts = {}) => clientFetch(this, url, opts);
3720
+ // Poll the API server's /health endpoint until it responds OK. Useful for
3721
+ // warming up a cold container before spawning a subprocess that needs the
3722
+ // API ready. Resolves when healthy, resolves (silently) when maxAttempts
3723
+ // is exhausted — never throws, so callers proceed regardless of outcome.
3724
+ ping = async (opts = {}) => {
3725
+ const { maxAttempts = 20, timeoutMs = 2e3, retryDelayMs = 500 } = opts;
3726
+ const healthUrl = `${this.baseUrl}/health`;
3727
+ for (let i = 0; i < maxAttempts; i++) {
3728
+ try {
3729
+ const res = await this.fetchImpl(healthUrl, {
3730
+ signal: AbortSignal.timeout(timeoutMs)
3731
+ });
3732
+ if (res.ok) return;
3733
+ } catch {
3734
+ }
3735
+ if (i < maxAttempts - 1) {
3736
+ await new Promise((r) => setTimeout(r, retryDelayMs));
3737
+ }
3738
+ }
3739
+ };
3361
3740
  // No-op today. Reserved for an explicit drain/cancel handle once
3362
3741
  // long-running consumers need one — do NOT rely on this to abort
3363
3742
  // in-flight requests or flush recording. Consumers needing
@@ -3367,6 +3746,7 @@ var ZeroClient = class _ZeroClient {
3367
3746
  };
3368
3747
 
3369
3748
  exports.Auth = Auth;
3749
+ exports.AuthAgent = AuthAgent;
3370
3750
  exports.AuthDevice = AuthDevice;
3371
3751
  exports.BUG_REPORT_CATEGORIES = BUG_REPORT_CATEGORIES;
3372
3752
  exports.BugReports = BugReports;
@@ -3379,9 +3759,13 @@ exports.FETCH_WARNINGS = FETCH_WARNINGS;
3379
3759
  exports.Payments = Payments;
3380
3760
  exports.Runs = Runs;
3381
3761
  exports.SDK_VERSION = SDK_VERSION;
3382
- exports.TEMPO_CHAIN_ID = TEMPO_CHAIN_ID;
3762
+ exports.TEMPO_CHAIN_ID = TEMPO_CHAIN_ID2;
3383
3763
  exports.TEMPO_TESTNET_CHAIN_ID = TEMPO_TESTNET_CHAIN_ID;
3764
+ exports.USDC_BASE = USDC_BASE;
3765
+ exports.USDC_DECIMALS = USDC_DECIMALS;
3766
+ exports.USDC_TEMPO = USDC_TEMPO;
3384
3767
  exports.Wallet = Wallet;
3768
+ exports.ZeroAgentAuthError = ZeroAgentAuthError;
3385
3769
  exports.ZeroApiError = ZeroApiError;
3386
3770
  exports.ZeroAuthError = ZeroAuthError;
3387
3771
  exports.ZeroClient = ZeroClient;
@@ -3401,5 +3785,5 @@ exports.normalizeTransportEnvelopeRequest = normalizeTransportEnvelopeRequest;
3401
3785
  exports.paymentHasAnchor = paymentHasAnchor;
3402
3786
  exports.tempoChainLabelFromId = tempoChainLabelFromId;
3403
3787
  exports.unwrapTransportEnvelope = unwrapTransportEnvelope;
3404
- //# sourceMappingURL=chunk-O7QJMY3Y.cjs.map
3405
- //# sourceMappingURL=chunk-O7QJMY3Y.cjs.map
3788
+ //# sourceMappingURL=chunk-IFVGW4ZN.cjs.map
3789
+ //# sourceMappingURL=chunk-IFVGW4ZN.cjs.map