@capxul/mcp 2.2.0 → 2.3.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.
Files changed (2) hide show
  1. package/dist/main.mjs +286 -301
  2. package/package.json +5 -5
package/dist/main.mjs CHANGED
@@ -240,7 +240,7 @@ function normalizeEmail(email) {
240
240
  }
241
241
  //#endregion
242
242
  //#region package.json
243
- var version$2 = "2.2.0";
243
+ var version$2 = "2.3.0";
244
244
  //#endregion
245
245
  //#region ../../packages/errors/src/errors.ts
246
246
  const CAPXUL_ERROR_CODES = [
@@ -1726,48 +1726,7 @@ function deriveCapxulOrgAddress(input) {
1726
1726
  bytecodeHash: keccak256(concat([SAFE_PROXY_CREATION_CODE, encodeAbiParameters([{ type: "uint256" }], [BigInt(SAFE_L2_SINGLETON)])]))
1727
1727
  }).toLowerCase();
1728
1728
  }
1729
- //#endregion
1730
- //#region ../../packages/config/src/role-dsl.ts
1731
- const USD_DECIMALS = 6;
1732
- const USD_SCALE = 10n ** BigInt(USD_DECIMALS);
1733
- const USD_DISPLAY_RE = /^\d+(?:\.\d{1,6})?$/;
1734
- const USD_BASE_UNIT_RE = /^\d+$/;
1735
- const EXEC_TRANSACTION_WITH_ROLE = "zodiac.roles.execTransactionWithRole";
1736
- const ASSIGN_ROLES = "zodiac.roles.assignRoles";
1737
- const SCOPE_TARGET = "zodiac.roles.scopeTarget";
1738
- const OWNER_ROLE_LABEL = "Owner";
1739
- const FOUNDER_BUDGET_ROLE_LABEL = "Founder Budget";
1740
- const FOUNDER_BUDGET_LIMIT = {
1741
- currency: "USD",
1742
- value: "1000000000000",
1743
- decimals: 6
1744
- };
1745
- function usd(value) {
1746
- return {
1747
- currency: "USD",
1748
- value: usdDisplayToBaseUnits(value),
1749
- decimals: USD_DECIMALS
1750
- };
1751
- }
1752
- function usdDisplayToBaseUnits(value) {
1753
- if (value.trim() !== value || !USD_DISPLAY_RE.test(value)) throw Errors.invalidInput("role.spend", "USD caps must be unsigned decimal strings with at most 6 fractional digits");
1754
- const parts = value.split(".");
1755
- const whole = parts[0] ?? "0";
1756
- const fraction = parts[1] ?? "";
1757
- return (BigInt(whole) * USD_SCALE + BigInt(fraction.padEnd(USD_DECIMALS, "0"))).toString();
1758
- }
1759
- function normalizeOrgRoleMoney(money, field) {
1760
- if (money.currency !== "USD" || money.decimals !== USD_DECIMALS || !USD_BASE_UNIT_RE.test(money.value)) throw Errors.invalidInput(field, `must be USD base units with ${USD_DECIMALS} decimals`);
1761
- return money;
1762
- }
1763
- function normalizeOrgRoleSpendCap(spend) {
1764
- if (spend === void 0) return void 0;
1765
- return {
1766
- ...spend.perTx === void 0 ? {} : { perTx: normalizeOrgRoleMoney(spend.perTx, "roles.spend.perTx") },
1767
- ...spend.perDay === void 0 ? {} : { perDay: normalizeOrgRoleMoney(spend.perDay, "roles.spend.perDay") },
1768
- ...spend.toRecipients === void 0 ? {} : { toRecipients: spend.toRecipients }
1769
- };
1770
- }
1729
+ 10n ** BigInt(6);
1771
1730
  function normalizeOrgRoleLabel(label) {
1772
1731
  const normalized = label.trim().replace(/\s+/g, " ");
1773
1732
  if (normalized.length === 0) throw Errors.invalidInput("role.label", "must be a non-empty role label");
@@ -1776,84 +1735,6 @@ function normalizeOrgRoleLabel(label) {
1776
1735
  function orgRoleKeyForLabel(label) {
1777
1736
  return keccak256(toBytes(normalizeOrgRoleLabel(label).toLowerCase()));
1778
1737
  }
1779
- function soloOrgRoleTemplate() {
1780
- return [{
1781
- label: "Owner",
1782
- canManageMembers: true,
1783
- canManageRoles: true
1784
- }, {
1785
- label: FOUNDER_BUDGET_ROLE_LABEL,
1786
- spend: {
1787
- perTx: FOUNDER_BUDGET_LIMIT,
1788
- perDay: FOUNDER_BUDGET_LIMIT,
1789
- toRecipients: "anyone"
1790
- }
1791
- }];
1792
- }
1793
- function startupOrgRoleTemplate() {
1794
- return [
1795
- ...soloOrgRoleTemplate(),
1796
- {
1797
- label: "Finance Manager",
1798
- spend: {
1799
- perTx: usd("25000"),
1800
- perDay: usd("100000"),
1801
- toRecipients: "anyone"
1802
- }
1803
- },
1804
- {
1805
- label: "Team Lead",
1806
- spend: {
1807
- perTx: usd("5000"),
1808
- perDay: usd("15000"),
1809
- toRecipients: "anyone"
1810
- }
1811
- }
1812
- ];
1813
- }
1814
- function orgRoleTemplateDefinitions(template, customRoles = []) {
1815
- switch (template) {
1816
- case "Solo": return soloOrgRoleTemplate();
1817
- case "Startup": return startupOrgRoleTemplate();
1818
- case "Custom": return customRoles.length === 0 ? soloOrgRoleTemplate() : customRoles;
1819
- default: return template;
1820
- }
1821
- }
1822
- function compileOrgRoleDefinitions(definitions) {
1823
- if (definitions.length === 0) throw Errors.invalidInput("roles", "must include at least one role");
1824
- const seen = /* @__PURE__ */ new Set();
1825
- const roles = definitions.map((definition) => {
1826
- const label = normalizeOrgRoleLabel(definition.label);
1827
- const roleKey = orgRoleKeyForLabel(label);
1828
- if (seen.has(roleKey)) throw Errors.invalidInput("roles", `duplicate role label: ${label}`);
1829
- seen.add(roleKey);
1830
- const spend = normalizeOrgRoleSpendCap(definition.spend);
1831
- const permissions = [];
1832
- if (spend !== void 0 || label === OWNER_ROLE_LABEL) permissions.push(EXEC_TRANSACTION_WITH_ROLE);
1833
- if (definition.canManageMembers === true) permissions.push(ASSIGN_ROLES);
1834
- if (definition.canManageRoles === true) permissions.push(SCOPE_TARGET);
1835
- return {
1836
- label,
1837
- roleKey,
1838
- definition: {
1839
- ...definition,
1840
- label,
1841
- ...spend === void 0 ? {} : { spend }
1842
- },
1843
- permissions,
1844
- allowance: spend ?? null
1845
- };
1846
- });
1847
- const manager = roles.find((role) => role.definition.canManageMembers === true);
1848
- if (manager === void 0) throw Errors.invalidInput("roles.canManageMembers", "at least one role must compile to the on-chain member-management permission");
1849
- return {
1850
- roles,
1851
- memberManagementRole: {
1852
- roleKey: manager.roleKey,
1853
- permission: ASSIGN_ROLES
1854
- }
1855
- };
1856
- }
1857
1738
  padHex(stringToHex("FM_DAILY"), {
1858
1739
  size: 32,
1859
1740
  dir: "right"
@@ -2357,6 +2238,7 @@ const ROLE_VIEW = {
2357
2238
  "restricted",
2358
2239
  "unset"
2359
2240
  ]),
2241
+ canSpend: z.boolean(),
2360
2242
  canManageMembers: z.boolean(),
2361
2243
  canManageRoles: z.boolean()
2362
2244
  };
@@ -2364,16 +2246,15 @@ function registerOrgTools(server, deps) {
2364
2246
  if (deps.paymentsEnabled !== true) return;
2365
2247
  server.registerTool("org.create", {
2366
2248
  title: "Create org",
2367
- description: "Create an organization and its on-chain Org Safe. name is the display name; handle is a globally-unique handle (^[a-z0-9-]{3,32}$); template selects the bootstrap shape (\"Solo\" | \"Startup\", default \"Startup\"); country is optional. Returns the org {orgId, name, handle, role} — never a Safe address. Consent scope: org:write (#522).",
2249
+ description: "Create an organization and its on-chain Org Safe. name is the display name; handle is a globally-unique handle (^[a-z0-9-]{3,32}$); country is optional. Returns the org {orgId, name, handle, role} — never a Safe address. Consent scope: org:write (#522).",
2368
2250
  inputSchema: {
2369
2251
  sessionToken: z.string(),
2370
2252
  name: z.string(),
2371
2253
  handle: z.string(),
2372
- template: z.enum(["Solo", "Startup"]).optional(),
2373
2254
  country: z.string().optional()
2374
2255
  },
2375
2256
  outputSchema: ORG_VIEW
2376
- }, ({ sessionToken, name, handle, template, country }) => guarded(async () => {
2257
+ }, ({ sessionToken, name, handle, country }) => guarded(async () => {
2377
2258
  const entry = requireSession(deps, sessionToken);
2378
2259
  if (entry === void 0) return errorResult(unknownSessionError$1());
2379
2260
  const createOrg = entry.handle.createOrg;
@@ -2381,7 +2262,6 @@ function registerOrgTools(server, deps) {
2381
2262
  const result = await createOrg({
2382
2263
  name,
2383
2264
  handle,
2384
- ...template === void 0 ? {} : { template },
2385
2265
  ...country === void 0 ? {} : { country }
2386
2266
  });
2387
2267
  return result.ok ? okResult({ ...result.value }) : errorResult(result.error);
@@ -2417,7 +2297,7 @@ function registerOrgTools(server, deps) {
2417
2297
  }, "org.members", deps.onToolCall));
2418
2298
  server.registerTool("org.roles", {
2419
2299
  title: "List org roles",
2420
- description: "List an org's roles with their spend caps and management permissions. Returns leak-safe roles {orgId, label, roleKey, perTxCap, perDayCap, recipientScope, canManageMembers, canManageRoles} — the raw allowed-recipient address list is reduced to a recipientScope label. Consent scope: org:read (#522).",
2300
+ description: "List the roles a member can be invited into, with their spend caps and management permissions. Returns leak-safe roles {orgId, label, roleKey, perTxCap, perDayCap, recipientScope, canSpend, canManageMembers, canManageRoles} — the raw allowed-recipient address list is reduced to a recipientScope label, and canSpend true with null caps means unlimited spend authority. Consent scope: org:read (#522).",
2421
2301
  inputSchema: {
2422
2302
  sessionToken: z.string(),
2423
2303
  orgId: z.string()
@@ -2515,6 +2395,9 @@ function toPartyId(raw) {
2515
2395
  if (typeof raw !== "string" || !PARTY_ID_RE$1.test(raw)) throw Errors.invalidInput("partyId", invalidValueReason("must be party_ plus an alphanumeric id", raw));
2516
2396
  return raw;
2517
2397
  }
2398
+ function toBudgetId(raw) {
2399
+ return toNonEmptyStringBrand(raw, "budgetId");
2400
+ }
2518
2401
  function toOrgId(raw) {
2519
2402
  return toNonEmptyStringBrand(raw, "orgId");
2520
2403
  }
@@ -2812,7 +2695,8 @@ const CAPXUL_FUNCTIONS = {
2812
2695
  listMembersByOrgId: "org/queries:listMembersByOrgId",
2813
2696
  listMine: "org/queries:listMine",
2814
2697
  listRolesByOrgId: "org/queries:listRolesByOrgId",
2815
- loadByOrgId: "org/queries:loadByOrgId"
2698
+ loadByOrgId: "org/queries:loadByOrgId",
2699
+ me: "org/queries:me"
2816
2700
  },
2817
2701
  "smartAccount/actions": {
2818
2702
  claim: "smartAccount/actions:claim",
@@ -5724,6 +5608,8 @@ const isRetryable = (failure) => {
5724
5608
  return failure.code === "NETWORK_ERROR" || failure.code === "UNKNOWN";
5725
5609
  };
5726
5610
  const SIGNED_OUT = { phase: "signed_out" };
5611
+ /** Where every client starts. `SessionRestored` / `SessionAbsent` settle it. */
5612
+ const RESTORING = { phase: "restoring" };
5727
5613
  const label = (state) => {
5728
5614
  if (state.phase !== "authenticated") return state.phase;
5729
5615
  if (state.account.at !== "claimed") return `authenticated:${state.account.at}`;
@@ -5738,6 +5624,8 @@ const EVENT_TAGS = [
5738
5624
  "RestoreSession",
5739
5625
  "ResumeOtpEntry",
5740
5626
  "Reset",
5627
+ "SessionRestored",
5628
+ "SessionAbsent",
5741
5629
  "EnsureAccount",
5742
5630
  "ClaimAccount",
5743
5631
  "RetryAccount",
@@ -5772,6 +5660,13 @@ const SESSION_EVENTS = [
5772
5660
  "Reset"
5773
5661
  ];
5774
5662
  const TRANSITION_TABLE = {
5663
+ restoring: [
5664
+ "SessionRestored",
5665
+ "SessionAbsent",
5666
+ "ReadSession",
5667
+ "RequestOtp",
5668
+ "Reset"
5669
+ ],
5775
5670
  signed_out: [
5776
5671
  "RequestOtp",
5777
5672
  "ReadSession",
@@ -5963,6 +5858,8 @@ const transition = (state, event, config = DEFAULT_CONFIG) => {
5963
5858
  requestedAt: state.resume.requestedAt
5964
5859
  } };
5965
5860
  case "Reset": return { next: SIGNED_OUT };
5861
+ case "SessionRestored": return { next: authenticated(event.session, event.profileComplete, { at: "unknown" }) };
5862
+ case "SessionAbsent": return { next: SIGNED_OUT };
5966
5863
  case "EnsureAccount":
5967
5864
  if (config.requirement === "none") return WRONG;
5968
5865
  return state.phase === "authenticated" ? { next: withAccount(state, {
@@ -6076,21 +5973,39 @@ function getFailureMode(error) {
6076
5973
  }
6077
5974
  //#endregion
6078
5975
  //#region ../../packages/sdk/src/signer.ts
6079
- /** Fold a signer throw into the public error contract. */
6080
- function signerFailure(source, operation, cause) {
5976
+ /**
5977
+ * The readiness store a signer reports when it runs no readiness cycle. It
5978
+ * fails CLOSED: a node key signer or an injected wallet never claims `ready`,
5979
+ * so a gate that reads this never opens on a guess.
5980
+ */
5981
+ const UNOBSERVABLE_SIGNER_STATUS = {
5982
+ status: () => "unknown",
5983
+ subscribe: () => () => void 0
5984
+ };
5985
+ /**
5986
+ * Walk an error and its `cause` links once each. A self-referential chain
5987
+ * terminates. Both signer predicates read the chain, so they read it here.
5988
+ */
5989
+ function* causeChain(cause) {
6081
5990
  const seen = /* @__PURE__ */ new Set();
6082
- let failureMode;
6083
5991
  let current = cause;
6084
5992
  while (typeof current === "object" && current !== null && !seen.has(current)) {
6085
5993
  seen.add(current);
6086
- if (current instanceof CapxulError && current.code === "SIGNER_REJECTED") return current;
6087
- failureMode = getFailureMode(current) ?? failureMode;
6088
- const error = current;
5994
+ yield current;
5995
+ current = current.cause;
5996
+ }
5997
+ }
5998
+ /** Fold a signer throw into the public error contract. */
5999
+ function signerFailure(source, operation, cause) {
6000
+ let failureMode;
6001
+ for (const link of causeChain(cause)) {
6002
+ if (link instanceof CapxulError && link.code === "SIGNER_REJECTED") return link;
6003
+ failureMode = getFailureMode(link) ?? failureMode;
6004
+ const error = link;
6089
6005
  if (error.code === 4001 || error.error === "passkey_user_cancelled") return Errors.signerRejected({
6090
6006
  source,
6091
6007
  cause
6092
6008
  });
6093
- current = error.cause;
6094
6009
  }
6095
6010
  return Errors.providerError("signer", operation, cause, failureMode === void 0 ? void 0 : { failure_mode: failureMode });
6096
6011
  }
@@ -8938,7 +8853,7 @@ async function recoverRawDigestSigner(input) {
8938
8853
  }
8939
8854
  //#endregion
8940
8855
  //#region ../../packages/sdk/package.json
8941
- var version = "2.2.0";
8856
+ var version = "2.3.0";
8942
8857
  //#endregion
8943
8858
  //#region ../../packages/observability/src/engineering.ts
8944
8859
  const SAFE_TRACED_HEADER_NAMES = [
@@ -13394,6 +13309,7 @@ function parseRoleDefinition(json) {
13394
13309
  ...raw.spend.perDay === void 0 ? {} : { perDay: parseRoleMoney(raw.spend.perDay, "perDay") },
13395
13310
  ...raw.spend.toRecipients === void 0 ? {} : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }
13396
13311
  } },
13312
+ ...typeof raw.canSpend === "boolean" ? { canSpend: raw.canSpend } : {},
13397
13313
  ...typeof raw.canManageMembers === "boolean" ? { canManageMembers: raw.canManageMembers } : {},
13398
13314
  ...typeof raw.canManageRoles === "boolean" ? { canManageRoles: raw.canManageRoles } : {}
13399
13315
  };
@@ -37122,6 +37038,10 @@ var y = class y {
37122
37038
  function openfortProviderError(operation, cause) {
37123
37039
  return cause instanceof CapxulError ? cause : Errors.providerError("openfort", operation, cause, { failure_mode: "unknown" });
37124
37040
  }
37041
+ /** Build a named PROVIDER_ERROR. The assembled Core SDK boundary reports it. */
37042
+ function failOpenfort(operation, failure_mode, cause) {
37043
+ return Errors.providerError("openfort", operation, cause, { failure_mode });
37044
+ }
37125
37045
  /**
37126
37046
  * True when the browser cannot perform Web Crypto — sandboxed iframes, headless
37127
37047
  * agent browsers, or non-HTTPS origins. OpenFort's embedded-wallet `configure`
@@ -37158,22 +37078,77 @@ function clearStaleOpenfortBrowserStorage(publishableKey) {
37158
37078
  if (scope === void 0) return;
37159
37079
  for (const key of OPENFORT_BROWSER_STORAGE_KEYS) localStorage.removeItem(`${scope}.${key}`);
37160
37080
  }
37081
+ /**
37082
+ * The Openfort error code that names the stale-user class (#1435).
37083
+ * `getThirdPartyAuthToken` skips `authenticateThirdParty` while a `userId` sits
37084
+ * in scoped storage. A purged `userId` therefore pins every later call to a 401
37085
+ * that `extractApiError` reports as `USER_NOT_FOUND`.
37086
+ *
37087
+ * The set holds one member on purpose. Session-expiry codes (`SESSION_EXPIRED`,
37088
+ * `NOT_LOGGED_IN`, `INVALID_TOKEN`, `REFRESH_TOKEN_ERROR`) are a different
37089
+ * cause, and a bare 401 is a different cause again: `app-env-allowlist` is a
37090
+ * 401 by definition (`packages/errors/src/errors.ts:80-81`). Healing those and
37091
+ * tagging them `stale-openfort-cache` would delete the triage signal the tag
37092
+ * exists to carry.
37093
+ */
37094
+ const STALE_USER_ERROR_CODES = new Set(["USER_NOT_FOUND"]);
37095
+ /**
37096
+ * The one predicate that opens the heal. It reads the Openfort error code and
37097
+ * never the message text (ADR-0023 R4). It walks the cause chain the way
37098
+ * `isTransportError` walks it in the Convex transport adapter.
37099
+ *
37100
+ * Known ceiling (#1435): a 401 that carries no recognized code is NOT healed.
37101
+ * `extractApiError` keeps the status only on `AuthenticationError`, so such a
37102
+ * payload is reachable. Add the code a live payload shows; do not add a message
37103
+ * match, because that trades one bug class for an ADR-0023 R4 violation.
37104
+ */
37105
+ function isStaleUserSignal(cause) {
37106
+ for (const link of causeChain(cause)) {
37107
+ const error = link;
37108
+ if (typeof error.error === "string" && STALE_USER_ERROR_CODES.has(error.error) || typeof error.code === "string" && STALE_USER_ERROR_CODES.has(error.code)) return true;
37109
+ }
37110
+ return false;
37111
+ }
37161
37112
  function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37162
37113
  const diagnostic = options.diagnostic;
37163
37114
  const authBaseUrl = normalizeBetterAuthBaseUrl(bootstrap.authBaseUrl);
37115
+ let currentStatus = "unknown";
37116
+ const statusListeners = /* @__PURE__ */ new Set();
37117
+ function setStatus(next) {
37118
+ if (currentStatus === next) return;
37119
+ currentStatus = next;
37120
+ for (const listener of statusListeners) try {
37121
+ listener(next);
37122
+ } catch {
37123
+ statusListeners.delete(listener);
37124
+ diagnostic?.trace("openfort.signerStatusListener", {
37125
+ ok: false,
37126
+ failure_mode: "unknown"
37127
+ });
37128
+ }
37129
+ }
37130
+ const statusStore = {
37131
+ status: () => currentStatus,
37132
+ subscribe: (listener) => {
37133
+ statusListeners.add(listener);
37134
+ return () => {
37135
+ statusListeners.delete(listener);
37136
+ };
37137
+ }
37138
+ };
37164
37139
  /**
37165
37140
  * Closes the black hole: when the browser has no Web Crypto, OpenFort's
37166
37141
  * `configure` would resolve to no address and the failure would be reported
37167
- * as `unknown`. Detect it before any network/wallet work, tag it
37168
- * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`, breadcrumb
37169
- * it via DiagnosticPort. The assembled Core SDK boundary reports the error.
37142
+ * as `unknown`. Detect it before any network or wallet work. Tag it
37143
+ * `no-secure-context` on a PROVIDER_ERROR scoped to `configure`. Add a
37144
+ * DiagnosticPort breadcrumb. The assembled Core SDK boundary reports it.
37170
37145
  */
37171
37146
  function failNoSecureContext() {
37172
37147
  diagnostic?.trace("openfort.configure", {
37173
37148
  ok: false,
37174
37149
  failure_mode: "no-secure-context"
37175
37150
  });
37176
- throw Errors.providerError("openfort", "configure", /* @__PURE__ */ new Error("Web Crypto unavailable: browser is not a secure context"), { failure_mode: "no-secure-context" });
37151
+ throw failOpenfort("configure", "no-secure-context", /* @__PURE__ */ new Error("Web Crypto unavailable: browser is not a secure context"));
37177
37152
  }
37178
37153
  function betterAuthSessionUrl() {
37179
37154
  return `${authBaseUrl}/get-session`;
@@ -37224,6 +37199,39 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37224
37199
  getAccessToken: fetchBetterAuthAccessToken
37225
37200
  }
37226
37201
  });
37202
+ async function configureEmbeddedWallet(encryptionSession) {
37203
+ await openfort.embeddedWallet.configure({
37204
+ accountType: N$1.EOA,
37205
+ chainType: c$6.EVM,
37206
+ recoveryParams: {
37207
+ recoveryMethod: e$10.AUTOMATIC,
37208
+ encryptionSession
37209
+ }
37210
+ });
37211
+ }
37212
+ /**
37213
+ * ONE heal cycle on the stale-user rejection (#1435). Clear the scoped
37214
+ * storage that pins the dead `userId`, run the existing configure path — it
37215
+ * re-runs third-party auth against the live Better Auth session now that no
37216
+ * `userId` is cached — and retry the read once. Exactly one cycle: a second
37217
+ * rejection is terminal and carries `failure_mode: "stale-openfort-cache"`.
37218
+ * The caller stays in `recovering` throughout; only the outcome moves it.
37219
+ */
37220
+ async function healStaleOpenfortCache(encryptionSession) {
37221
+ try {
37222
+ clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
37223
+ diagnostic?.trace("openfort.storageCleared", { beforeConfigure: false });
37224
+ await configureEmbeddedWallet(encryptionSession);
37225
+ await openfort.embeddedWallet.get();
37226
+ } catch (cause) {
37227
+ diagnostic?.trace("openfort.staleCacheHeal", {
37228
+ ok: false,
37229
+ failure_mode: "stale-openfort-cache"
37230
+ });
37231
+ throw failOpenfort("get", "stale-openfort-cache", cause);
37232
+ }
37233
+ diagnostic?.trace("openfort.staleCacheHeal", { ok: true });
37234
+ }
37227
37235
  let walletReadyPromise = null;
37228
37236
  function startWalletReady() {
37229
37237
  return (async () => {
@@ -37288,14 +37296,7 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37288
37296
  clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
37289
37297
  diagnostic?.trace("openfort.storageCleared", { beforeConfigure: true });
37290
37298
  try {
37291
- await openfort.embeddedWallet.configure({
37292
- accountType: N$1.EOA,
37293
- chainType: c$6.EVM,
37294
- recoveryParams: {
37295
- recoveryMethod: e$10.AUTOMATIC,
37296
- encryptionSession: encryptionBody.sessionId
37297
- }
37298
- });
37299
+ await configureEmbeddedWallet(encryptionBody.sessionId);
37299
37300
  diagnostic?.trace("openfort.configure", { ok: true });
37300
37301
  } catch (cause) {
37301
37302
  diagnostic?.trace("openfort.configure", {
@@ -37309,20 +37310,36 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37309
37310
  await openfort.embeddedWallet.get();
37310
37311
  diagnostic?.trace("openfort.get", { ok: true });
37311
37312
  } catch (cause) {
37313
+ if (!isStaleUserSignal(cause)) {
37314
+ diagnostic?.trace("openfort.get", {
37315
+ ok: false,
37316
+ failure_mode: "unknown"
37317
+ });
37318
+ throw openfortProviderError("get", cause);
37319
+ }
37312
37320
  diagnostic?.trace("openfort.get", {
37313
37321
  ok: false,
37314
- failure_mode: "unknown"
37322
+ failure_mode: "stale-openfort-cache"
37315
37323
  });
37316
- throw openfortProviderError("get", cause);
37324
+ await healStaleOpenfortCache(encryptionBody.sessionId);
37317
37325
  }
37318
37326
  })();
37319
37327
  }
37320
37328
  async function ensureOpenfortWalletReady() {
37321
- walletReadyPromise ??= startWalletReady();
37329
+ let joined = walletReadyPromise;
37330
+ if (joined === null) {
37331
+ joined = startWalletReady();
37332
+ walletReadyPromise = joined;
37333
+ setStatus("recovering");
37334
+ }
37322
37335
  try {
37323
- await walletReadyPromise;
37336
+ await joined;
37337
+ if (walletReadyPromise === joined) setStatus("ready");
37324
37338
  } catch (cause) {
37325
- walletReadyPromise = null;
37339
+ if (walletReadyPromise === joined) {
37340
+ walletReadyPromise = null;
37341
+ setStatus("unavailable");
37342
+ }
37326
37343
  throw cause;
37327
37344
  }
37328
37345
  }
@@ -37332,6 +37349,7 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37332
37349
  });
37333
37350
  return {
37334
37351
  ...signer,
37352
+ statusStore,
37335
37353
  getAddress: async () => {
37336
37354
  try {
37337
37355
  const address = await signer.getAddress();
@@ -37349,6 +37367,7 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
37349
37367
  walletReadyPromise = null;
37350
37368
  clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
37351
37369
  signer.resetAddressCache();
37370
+ setStatus("unknown");
37352
37371
  }
37353
37372
  };
37354
37373
  }
@@ -37367,6 +37386,8 @@ const IDENTITY_SLOT = {
37367
37386
  const IDENTITY_SLOT_BY_EVENT = {
37368
37387
  ReadSession: IDENTITY_SLOT.session,
37369
37388
  RestoreSession: IDENTITY_SLOT.session,
37389
+ SessionRestored: IDENTITY_SLOT.session,
37390
+ SessionAbsent: IDENTITY_SLOT.session,
37370
37391
  SessionRead: IDENTITY_SLOT.session,
37371
37392
  SessionReadFailed: IDENTITY_SLOT.session,
37372
37393
  RequestOtp: IDENTITY_SLOT.auth,
@@ -37678,7 +37699,7 @@ const identitySpec = (input, sessionStore = { current: null }) => {
37678
37699
  };
37679
37700
  return {
37680
37701
  machine: "identity",
37681
- initial: SIGNED_OUT,
37702
+ initial: RESTORING,
37682
37703
  label,
37683
37704
  slot: identitySlot,
37684
37705
  transition: (state, event) => transition(state, event, config),
@@ -37814,7 +37835,7 @@ const bootIdentityFlow = (input, options = {}) => Effect.gen(function* () {
37814
37835
  sessionStore.current = null;
37815
37836
  }) : Effect.void)),
37816
37837
  restoreAuthSession: (session, controls) => actor.ask({
37817
- _tag: "RestoreSession",
37838
+ _tag: actor.snapshot().phase === "restoring" ? "SessionRestored" : "RestoreSession",
37818
37839
  session: modelSession(session),
37819
37840
  profileComplete: false
37820
37841
  }, controls).pipe(Effect.tap(() => Effect.sync(() => {
@@ -37852,13 +37873,13 @@ const ask = (actor, event, controls, wrongState) => actor.ask(event, controls).p
37852
37873
  */
37853
37874
  const getSessionProgramWithOptions = (options) => Effect.gen(function* () {
37854
37875
  const deps = yield* CapxulDepsTag;
37855
- const cached = yield* deps.authCache.getSession.pipe(Effect.mapError((e) => Errors.providerError("auth-cache", "getSession", e)));
37876
+ const cached = yield* deps.authCache.getSession.pipe(Effect.mapError((e) => Errors.providerError("auth-cache", "getSession", e)), Effect.catch((failure) => deps.actor.snapshot().phase === "restoring" ? Effect.succeed(null) : Effect.fail(failure)));
37856
37877
  const observed = deps.actor.snapshot();
37857
37878
  const actorState = observed.phase;
37858
37879
  if (observed.phase === "faulted") return yield* Effect.fail(publicIdentityFailure(observed.failure));
37859
37880
  if (cached === null && (actorState === "otp_pending" || actorState === "otp_sending" || actorState === "otp_verifying")) return null;
37860
- if (cached !== null && actorState !== "signed_out") return cached;
37861
- if (cached !== null && actorState === "signed_out") {
37881
+ if (cached !== null && !(actorState === "signed_out" || actorState === "restoring")) return cached;
37882
+ if (cached !== null) {
37862
37883
  yield* deps.actor.restoreAuthSession(cached, depsRequestOptions(deps, options)).pipe(Effect.mapError(actorError));
37863
37884
  return cached;
37864
37885
  }
@@ -37961,6 +37982,7 @@ const signInProgram = (input, options) => Effect.gen(function* () {
37961
37982
  }, depsRequestOptions(deps, options), {
37962
37983
  method: "signIn",
37963
37984
  validStates: [
37985
+ "restoring",
37964
37986
  "signed_out",
37965
37987
  "otp_pending",
37966
37988
  "faulted"
@@ -37984,7 +38006,7 @@ const signInProgram = (input, options) => Effect.gen(function* () {
37984
38006
  const signOutProgramWithOptions = (options) => Effect.gen(function* () {
37985
38007
  const deps = yield* CapxulDepsTag;
37986
38008
  let phase = deps.actor.snapshot().phase;
37987
- if (phase === "signed_out") {
38009
+ if (phase === "signed_out" || phase === "restoring") {
37988
38010
  const cached = yield* deps.authCache.getSession.pipe(Effect.mapError((e) => Errors.providerError("auth-cache", "getSession", e)));
37989
38011
  if (cached !== null) {
37990
38012
  yield* deps.actor.restoreAuthSession(cached, depsRequestOptions(deps, options)).pipe(Effect.mapError(actorError));
@@ -38360,6 +38382,32 @@ function makeSystemMethods(deps) {
38360
38382
  return { health: (nonce, options) => runIfActive(options?.signal, "system.health", () => deps.convexCall.query(healthQuery, { nonce })) };
38361
38383
  }
38362
38384
  //#endregion
38385
+ //#region ../../packages/sdk/src/contract/org.ts
38386
+ const orgReadContract = { me: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].me) };
38387
+ //#endregion
38388
+ //#region ../../packages/sdk/src/surface/org-me.ts
38389
+ function toBudget(wire) {
38390
+ return {
38391
+ id: toBudgetId(wire.id),
38392
+ label: wire.label,
38393
+ limit: wire.limitRaw === null ? null : fromWei(wire.limitRaw, wire.decimals, wire.currency)
38394
+ };
38395
+ }
38396
+ function toOrgMe(wire) {
38397
+ return {
38398
+ role: wire.role === null ? null : { label: wire.role.label },
38399
+ capabilities: {
38400
+ canManagePeople: wire.capabilities.canManagePeople,
38401
+ canSpend: wire.capabilities.canSpend
38402
+ },
38403
+ budgets: wire.budgets.map(toBudget),
38404
+ observedAt: wire.observedAt
38405
+ };
38406
+ }
38407
+ function makeOrgMeMethod(deps, orgId) {
38408
+ return (options) => runIfActive(options?.signal, "org.me", () => Effect.map(deps.convexCall.query(orgReadContract.me, { orgId }), toOrgMe));
38409
+ }
38410
+ //#endregion
38363
38411
  //#region ../../packages/sdk/src/contract/permission.ts
38364
38412
  const permissionContract = { read: makeFunctionReference(CAPXUL_FUNCTIONS["permission/queries"].read) };
38365
38413
  //#endregion
@@ -38717,38 +38765,6 @@ function hermeticOrgView(input) {
38717
38765
  logoUrl: null
38718
38766
  };
38719
38767
  }
38720
- function moneyFromConfig(input) {
38721
- return {
38722
- currency: toCurrencyCode(input.currency),
38723
- value: input.value,
38724
- decimals: input.decimals
38725
- };
38726
- }
38727
- function recipientsFromConfig(toRecipients) {
38728
- if (toRecipients === void 0 || toRecipients === "anyone") return toRecipients;
38729
- return toRecipients.map((recipient) => toAddress(recipient));
38730
- }
38731
- function roleDefinitionFromConfig(definition) {
38732
- const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);
38733
- return {
38734
- label: definition.label,
38735
- ...definition.spend === void 0 ? {} : { spend: {
38736
- ...definition.spend.perTx === void 0 ? {} : { perTx: moneyFromConfig(definition.spend.perTx) },
38737
- ...definition.spend.perDay === void 0 ? {} : { perDay: moneyFromConfig(definition.spend.perDay) },
38738
- ...toRecipients === void 0 ? {} : { toRecipients }
38739
- } },
38740
- ...definition.canManageMembers === void 0 ? {} : { canManageMembers: definition.canManageMembers },
38741
- ...definition.canManageRoles === void 0 ? {} : { canManageRoles: definition.canManageRoles }
38742
- };
38743
- }
38744
- function startupRoleViews(orgId) {
38745
- return compileOrgRoleDefinitions(orgRoleTemplateDefinitions("Startup")).roles.map((role) => ({
38746
- orgId,
38747
- label: role.label,
38748
- roleKey: toRoleKey(role.roleKey),
38749
- definition: roleDefinitionFromConfig(role.definition)
38750
- }));
38751
- }
38752
38768
  function hermeticMember(input) {
38753
38769
  return {
38754
38770
  orgId: input.orgId,
@@ -38850,7 +38866,7 @@ function listRolesProgram(orgId) {
38850
38866
  return Effect.gen(function* () {
38851
38867
  const deps = yield* OrgDepsTag;
38852
38868
  if (deps.orgPort !== void 0) return yield* deps.orgPort.listRoles({ orgId }).pipe(Effect.mapError((error) => error.publicError));
38853
- return startupRoleViews(orgId);
38869
+ return [];
38854
38870
  });
38855
38871
  }
38856
38872
  function listMembersProgram(orgId) {
@@ -39015,6 +39031,7 @@ function makeOrgMethods(deps) {
39015
39031
  },
39016
39032
  ...convexCall === void 0 ? {} : { convexCall }
39017
39033
  }),
39034
+ me: convexCall === void 0 ? orgMeUnavailable : makeOrgMeMethod({ convexCall }, String(orgId)),
39018
39035
  async getLifecycle(options) {
39019
39036
  if (options?.signal?.aborted) return {
39020
39037
  ok: false,
@@ -39162,6 +39179,10 @@ function makeNotImplementedOrganizationPaymentsMethods() {
39162
39179
  payBatch: organizationPaymentExecutionUnavailable
39163
39180
  };
39164
39181
  }
39182
+ const orgMeUnavailable = () => Promise.resolve({
39183
+ ok: false,
39184
+ error: Errors.notImplemented("org", "me")
39185
+ });
39165
39186
  const permissionExecutionUnavailable = () => Promise.resolve({
39166
39187
  ok: false,
39167
39188
  error: Errors.notImplemented("permissions", "executionComposition")
@@ -39493,6 +39514,8 @@ const APPLIED_ACTION_BY_EVENT = {
39493
39514
  RestoreSession: "none",
39494
39515
  ResumeOtpEntry: "none",
39495
39516
  Reset: "none",
39517
+ SessionRestored: "none",
39518
+ SessionAbsent: "none",
39496
39519
  EnsureAccount: "none",
39497
39520
  ClaimAccount: "none",
39498
39521
  RetryAccount: "none",
@@ -39788,6 +39811,7 @@ function assembleCapxulClient(input) {
39788
39811
  createOrg: orgMethods.createOrg,
39789
39812
  orgs: orgMethods.orgs,
39790
39813
  org: orgMethods.org,
39814
+ signer: input.signer?.statusStore ?? UNOBSERVABLE_SIGNER_STATUS,
39791
39815
  _internal: {
39792
39816
  identity: identityRuntime,
39793
39817
  bootstrap: input.bootstrap,
@@ -40364,7 +40388,7 @@ function idempotentClose(close) {
40364
40388
  /**
40365
40389
  * Test/e2e-only client factory for the live Org Safe deploy lane (#327).
40366
40390
  *
40367
- * Org deployment port factories and RPC/deployer/gas-policy config must not
40391
+ * Org deployment port factories and RPC/deployer/bundler config must not
40368
40392
  * appear on the public consumer or `@capxul/sdk/production` adapter input.
40369
40393
  * Live proofs import this module explicitly instead of threading deploy
40370
40394
  * plumbing through the product API.
@@ -42215,12 +42239,6 @@ const envFields = {
42215
42239
  "required": false,
42216
42240
  "example": "alchemy_test"
42217
42241
  },
42218
- ALCHEMY_GAS_POLICY_ID: {
42219
- "runtime": "server",
42220
- "kind": "nonempty",
42221
- "required": false,
42222
- "example": "policy_test"
42223
- },
42224
42242
  ALCHEMY_WEBHOOK_SIGNING_KEY: {
42225
42243
  "runtime": "server",
42226
42244
  "kind": "nonempty",
@@ -42239,6 +42257,12 @@ const envFields = {
42239
42257
  "required": true,
42240
42258
  "example": "https://sepolia.base.org"
42241
42259
  },
42260
+ BASE_SEPOLIA_BUNDLER_RPC_URL: {
42261
+ "runtime": "server",
42262
+ "kind": "url",
42263
+ "required": false,
42264
+ "example": "https://aa-gateway.example.test/token"
42265
+ },
42242
42266
  CONVEX_SITE_URL: {
42243
42267
  "runtime": "server",
42244
42268
  "kind": "url",
@@ -42333,16 +42357,15 @@ function makeBaseSepoliaPublicClient(rpcUrl) {
42333
42357
  * UserOperations on Base Sepolia. Identical shape across both adapters.
42334
42358
  */
42335
42359
  function makeSponsoredBundlerClient(input) {
42336
- const paymaster = createPaymasterClient({ transport: http(input.rpcUrl) });
42360
+ const paymaster = createPaymasterClient({ transport: http(input.bundlerRpcUrl) });
42337
42361
  return createBundlerClient({
42338
42362
  chain: baseSepolia,
42339
42363
  client: input.publicClient,
42340
- transport: http(input.rpcUrl),
42364
+ transport: http(input.bundlerRpcUrl),
42341
42365
  paymaster: {
42342
42366
  getPaymasterData: paymaster.getPaymasterData,
42343
42367
  getPaymasterStubData: paymaster.getPaymasterStubData
42344
- },
42345
- paymasterContext: { policyId: input.gasPolicyId }
42368
+ }
42346
42369
  });
42347
42370
  }
42348
42371
  /** Assert the RPC endpoint actually serves Base Sepolia (guards a wrong RPC URL). */
@@ -42442,14 +42465,14 @@ var LiveOrgDeploymentAdapter = class {
42442
42465
  #convex;
42443
42466
  #deployer;
42444
42467
  #rpcUrl;
42445
- #gasPolicyId;
42468
+ #bundlerRpcUrl;
42446
42469
  #receiptTimeoutMs;
42447
42470
  #sendOrgProxyDeployUserOperation;
42448
42471
  constructor(deps) {
42449
42472
  this.#convex = deps.convex;
42450
42473
  this.#deployer = privateKeyToAccount(deps.privateKey);
42451
42474
  this.#rpcUrl = deps.rpcUrl;
42452
- this.#gasPolicyId = deps.gasPolicyId;
42475
+ this.#bundlerRpcUrl = deps.bundlerRpcUrl;
42453
42476
  this.#receiptTimeoutMs = deps.receiptTimeoutMs ?? DEFAULT_RECEIPT_TIMEOUT_MS;
42454
42477
  this.#sendOrgProxyDeployUserOperation = deps.sendOrgProxyDeployUserOperation;
42455
42478
  }
@@ -42458,7 +42481,6 @@ var LiveOrgDeploymentAdapter = class {
42458
42481
  name: input.input.name,
42459
42482
  handle: input.input.handle,
42460
42483
  template: input.input.template,
42461
- ...input.input.roles === void 0 ? {} : { roles: input.input.roles },
42462
42484
  country: input.input.country ?? null
42463
42485
  }).pipe(Effect.mapError((error) => orgErrorFromCapxul("createOrg", error.publicError, error)), Effect.flatMap((wire) => Effect.tryPromise({
42464
42486
  try: () => this.#deployAndRead(wire),
@@ -42587,8 +42609,7 @@ var LiveOrgDeploymentAdapter = class {
42587
42609
  });
42588
42610
  const bundler = makeSponsoredBundlerClient({
42589
42611
  publicClient: input.publicClient,
42590
- rpcUrl: this.#rpcUrl,
42591
- gasPolicyId: this.#gasPolicyId
42612
+ bundlerRpcUrl: this.#bundlerRpcUrl
42592
42613
  });
42593
42614
  const userOpHash = await bundler.sendUserOperation({
42594
42615
  account: founderSafe,
@@ -42598,10 +42619,12 @@ var LiveOrgDeploymentAdapter = class {
42598
42619
  data: createProxyCall
42599
42620
  }]
42600
42621
  });
42601
- if (!(await bundler.waitForUserOperationReceipt({
42622
+ const receipt = await bundler.waitForUserOperationReceipt({
42602
42623
  hash: userOpHash,
42603
42624
  timeout: this.#receiptTimeoutMs
42604
- })).success) throw Errors.providerError("permissionless-org-deployment", "createProxyWithNonce", "Org Safe proxy creation UserOperation failed");
42625
+ });
42626
+ if (!receipt.success) throw Errors.providerError("permissionless-org-deployment", "createProxyWithNonce", "Org Safe proxy creation UserOperation failed");
42627
+ await input.publicClient.waitForTransactionReceipt({ hash: receipt.receipt.transactionHash });
42605
42628
  }
42606
42629
  async #readBalance(publicClient, wire) {
42607
42630
  const money = fromWei((await publicClient.readContract({
@@ -42657,12 +42680,18 @@ const BUNDLER_RPC_METHODS = new Set([
42657
42680
  "eth_getUserOperationReceipt",
42658
42681
  "eth_getUserOperationByHash",
42659
42682
  "pm_getPaymasterStubData",
42660
- "pm_getPaymasterData",
42661
- "alchemy_requestGasAndPaymasterAndData"
42683
+ "pm_getPaymasterData"
42662
42684
  ]);
42685
+ function providerFor(method) {
42686
+ return BUNDLER_RPC_METHODS.has(method) ? "account-abstraction" : "alchemy";
42687
+ }
42688
+ function accountAbstractionUrl(chainId) {
42689
+ if (chainId !== 84532) throw Errors.invalidInput("chainId", `owned account-abstraction rail supports Base Sepolia; got ${String(chainId)}`);
42690
+ return requireEnvOrThrow("BASE_SEPOLIA_BUNDLER_RPC_URL");
42691
+ }
42663
42692
  function rethrowProvider(method) {
42664
42693
  return (e) => {
42665
- throw Errors.providerError("alchemy", method, e);
42694
+ throw Errors.providerError(providerFor(method), method, e);
42666
42695
  };
42667
42696
  }
42668
42697
  function parseAlchemyQuantity(value, operation, field) {
@@ -42673,7 +42702,7 @@ function parseAlchemyQuantity(value, operation, field) {
42673
42702
  }
42674
42703
  }
42675
42704
  function providerValue(value, pattern, operation, field) {
42676
- if (typeof value !== "string" || !pattern.test(value)) throw Errors.providerError("alchemy", operation, `invalid ${field}`);
42705
+ if (typeof value !== "string" || !pattern.test(value)) throw Errors.providerError(providerFor(operation), operation, `invalid ${field}`);
42677
42706
  return value.toLowerCase();
42678
42707
  }
42679
42708
  function providerAddress(value, operation, field) {
@@ -42686,9 +42715,8 @@ function providerData(value, operation, field) {
42686
42715
  return providerValue(value, EVEN_DATA_HEX, operation, field);
42687
42716
  }
42688
42717
  /**
42689
- * Construct the Alchemy URL for a given chain. Single endpoint for both
42690
- * node (eth_*) and bundler (eth_getUserOperationReceipt) RPCs — Alchemy
42691
- * routes by method.
42718
+ * Construct the node RPC URL for a given chain. Account-abstraction methods
42719
+ * use the separate owned gateway URL.
42692
42720
  */
42693
42721
  function alchemyUrl(chainId) {
42694
42722
  switch (chainId) {
@@ -42711,14 +42739,14 @@ function isValidJsonRpcEnvelope(value) {
42711
42739
  function isValidJsonRpcError(value) {
42712
42740
  return isRecord(value) && typeof value.code === "number" && Number.isInteger(value.code) && typeof value.message === "string";
42713
42741
  }
42714
- var DefinitiveAlchemyJsonRpcRejection = class extends Error {
42742
+ var DefinitiveUserOperationRpcRejection = class extends Error {
42715
42743
  constructor() {
42716
- super("Alchemy returned an explicit JSON-RPC rejection");
42717
- this.name = "DefinitiveAlchemyJsonRpcRejection";
42744
+ super("The bundler returned an explicit JSON-RPC rejection");
42745
+ this.name = "DefinitiveUserOperationRpcRejection";
42718
42746
  }
42719
42747
  };
42720
42748
  async function alchemyRpc(chainId, method, params, timeoutMs, externalSignal) {
42721
- const bundlerUrl = chainId === 84532 && BUNDLER_RPC_METHODS.has(method) ? optionalEnv("BASE_SEPOLIA_BUNDLER_RPC_URL") : void 0;
42749
+ const bundlerUrl = BUNDLER_RPC_METHODS.has(method) ? accountAbstractionUrl(chainId) : void 0;
42722
42750
  const evidenceUrl = chainId === 84532 && EVIDENCE_RPC_METHODS.has(method) ? optionalEnv("BASE_SEPOLIA_EVIDENCE_RPC_URL") : void 0;
42723
42751
  const url = bundlerUrl?.replace(/\/+$/u, "") ?? evidenceUrl?.replace(/\/+$/u, "") ?? alchemyUrl(chainId);
42724
42752
  const timeoutSignal = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
@@ -42736,35 +42764,35 @@ async function alchemyRpc(chainId, method, params, timeoutMs, externalSignal) {
42736
42764
  }).catch(rethrowProvider(method));
42737
42765
  if (!res.ok) {
42738
42766
  const body = await res.text().catch(() => "<no body>");
42739
- throw Errors.providerError("alchemy", `${method} ${res.status}`, body);
42767
+ throw Errors.providerError(providerFor(method), `${method} ${res.status}`, body);
42740
42768
  }
42741
42769
  let json;
42742
42770
  try {
42743
42771
  json = await res.json();
42744
42772
  } catch (cause) {
42745
- throw Errors.providerError("alchemy", `${method} json`, cause);
42773
+ throw Errors.providerError(providerFor(method), `${method} json`, cause);
42746
42774
  }
42747
- if (!isValidJsonRpcEnvelope(json)) throw Errors.providerError("alchemy", method, "malformed JSON-RPC envelope");
42775
+ if (!isValidJsonRpcEnvelope(json)) throw Errors.providerError(providerFor(method), method, "malformed JSON-RPC envelope");
42748
42776
  if (json.error !== void 0) {
42749
- if (!isValidJsonRpcError(json.error)) throw Errors.providerError("alchemy", method, "malformed JSON-RPC error");
42750
- throw Errors.providerError("alchemy", method, method === "eth_sendUserOperation" ? new DefinitiveAlchemyJsonRpcRejection() : json.error.message);
42777
+ if (!isValidJsonRpcError(json.error)) throw Errors.providerError(providerFor(method), method, "malformed JSON-RPC error");
42778
+ throw Errors.providerError(providerFor(method), method, method === "eth_sendUserOperation" ? new DefinitiveUserOperationRpcRejection() : json.error.message);
42751
42779
  }
42752
- if (json.result === void 0) throw Errors.providerError("alchemy", method, "missing result");
42780
+ if (json.result === void 0) throw Errors.providerError(providerFor(method), method, "missing result");
42753
42781
  return json.result;
42754
42782
  }
42755
42783
  function parseReceiptLogs(raw) {
42756
42784
  if (raw === void 0 || raw === null) return [];
42757
- if (!Array.isArray(raw)) throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", "logs is not an array");
42785
+ if (!Array.isArray(raw)) throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", "logs is not an array");
42758
42786
  return raw.map((entry) => {
42759
- if (typeof entry !== "object" || entry === null || typeof entry.address !== "string" || !Array.isArray(entry.topics) || typeof entry.data !== "string") throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", `malformed receipt log: ${JSON.stringify(entry)}`);
42787
+ if (typeof entry !== "object" || entry === null || typeof entry.address !== "string" || !Array.isArray(entry.topics) || typeof entry.data !== "string") throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", `malformed receipt log: ${JSON.stringify(entry)}`);
42760
42788
  const log = entry;
42761
42789
  const operation = "eth_getUserOperationReceipt";
42762
- if (log.logIndex !== void 0 && typeof log.logIndex !== "string") throw Errors.providerError("alchemy", operation, "invalid logIndex");
42763
- if (log.blockNumber !== void 0 && typeof log.blockNumber !== "string") throw Errors.providerError("alchemy", operation, "invalid blockNumber");
42764
- if (log.blockHash !== void 0 && typeof log.blockHash !== "string") throw Errors.providerError("alchemy", operation, "invalid blockHash");
42765
- if (log.transactionHash !== void 0 && typeof log.transactionHash !== "string") throw Errors.providerError("alchemy", operation, "invalid transactionHash");
42766
- if (log.transactionIndex !== void 0 && typeof log.transactionIndex !== "string") throw Errors.providerError("alchemy", operation, "invalid transactionIndex");
42767
- if (log.removed !== void 0 && typeof log.removed !== "boolean") throw Errors.providerError("alchemy", operation, "invalid removed");
42790
+ if (log.logIndex !== void 0 && typeof log.logIndex !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid logIndex");
42791
+ if (log.blockNumber !== void 0 && typeof log.blockNumber !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid blockNumber");
42792
+ if (log.blockHash !== void 0 && typeof log.blockHash !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid blockHash");
42793
+ if (log.transactionHash !== void 0 && typeof log.transactionHash !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid transactionHash");
42794
+ if (log.transactionIndex !== void 0 && typeof log.transactionIndex !== "string") throw Errors.providerError(providerFor(operation), operation, "invalid transactionIndex");
42795
+ if (log.removed !== void 0 && typeof log.removed !== "boolean") throw Errors.providerError(providerFor(operation), operation, "invalid removed");
42768
42796
  return {
42769
42797
  address: providerAddress(log.address, operation, "log address"),
42770
42798
  topics: log.topics.map((topic, index) => providerBytes32(topic, operation, `topic ${String(index)}`)),
@@ -42781,7 +42809,7 @@ function parseReceiptLogs(raw) {
42781
42809
  async function fetchUserOperationReceipt(args) {
42782
42810
  const raw = await alchemyRpc(args.chainId, "eth_getUserOperationReceipt", [args.userOpHash]);
42783
42811
  if (raw === null) return null;
42784
- if (typeof raw !== "object" || typeof raw.userOpHash !== "string" || typeof raw.sender !== "string" || typeof raw.success !== "boolean" || typeof raw.receipt !== "object" || typeof raw.receipt.blockNumber !== "string" || typeof raw.receipt.blockHash !== "string" || typeof raw.receipt.transactionHash !== "string" || typeof raw.receipt.transactionIndex !== "string") throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", `unexpected shape: ${JSON.stringify(raw)}`);
42812
+ if (typeof raw !== "object" || typeof raw.userOpHash !== "string" || typeof raw.sender !== "string" || typeof raw.success !== "boolean" || typeof raw.receipt !== "object" || typeof raw.receipt.blockNumber !== "string" || typeof raw.receipt.blockHash !== "string" || typeof raw.receipt.transactionHash !== "string" || typeof raw.receipt.transactionIndex !== "string") throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", `unexpected shape: ${JSON.stringify(raw)}`);
42785
42813
  return {
42786
42814
  userOpHash: providerBytes32(raw.userOpHash, "eth_getUserOperationReceipt", "userOpHash"),
42787
42815
  sender: providerAddress(raw.sender, "eth_getUserOperationReceipt", "sender"),
@@ -42801,15 +42829,15 @@ async function fetchUserOperationReceipt(args) {
42801
42829
  * (would silently round under `parseInt` per `.claude/rules/numeric-parsing.md`).
42802
42830
  */
42803
42831
  function hexToSafeInteger(hex, op) {
42804
- if (typeof hex !== "string" || !QUANTITY_HEX.test(hex)) throw Errors.providerError("alchemy", op, `expected a canonical hex quantity, got ${String(hex)}`);
42832
+ if (typeof hex !== "string" || !QUANTITY_HEX.test(hex)) throw Errors.providerError(providerFor(op), op, `expected a canonical hex quantity, got ${String(hex)}`);
42805
42833
  let big;
42806
42834
  try {
42807
42835
  big = BigInt(hex);
42808
42836
  } catch (cause) {
42809
- throw Errors.providerError("alchemy", op, `invalid hex integer: ${hex} (${String(cause)})`);
42837
+ throw Errors.providerError(providerFor(op), op, `invalid hex integer: ${hex} (${String(cause)})`);
42810
42838
  }
42811
42839
  const n = Number(big);
42812
- if (!Number.isSafeInteger(n)) throw Errors.providerError("alchemy", op, `hex value ${hex} exceeds MAX_SAFE_INTEGER`);
42840
+ if (!Number.isSafeInteger(n)) throw Errors.providerError(providerFor(op), op, `hex value ${hex} exceeds MAX_SAFE_INTEGER`);
42813
42841
  return n;
42814
42842
  }
42815
42843
  /**
@@ -42907,13 +42935,13 @@ async function fetchUserOperationFees(args) {
42907
42935
  }
42908
42936
  async function estimateUserOperationGas(args) {
42909
42937
  const raw = await alchemyRpc(args.chainId, "eth_estimateUserOperationGas", [args.userOp, ENTRY_POINT_07_ADDRESS]);
42910
- if (typeof raw !== "object" || typeof raw.preVerificationGas !== "string" || typeof raw.verificationGasLimit !== "string" || typeof raw.callGasLimit !== "string") throw Errors.providerError("alchemy", "eth_estimateUserOperationGas", `unexpected shape: ${JSON.stringify(raw)}`);
42938
+ if (typeof raw !== "object" || typeof raw.preVerificationGas !== "string" || typeof raw.verificationGasLimit !== "string" || typeof raw.callGasLimit !== "string") throw Errors.providerError("account-abstraction", "eth_estimateUserOperationGas", `unexpected shape: ${JSON.stringify(raw)}`);
42911
42939
  return raw;
42912
42940
  }
42913
42941
  function optionalPaymasterHex(raw, method, field) {
42914
42942
  const value = raw[field];
42915
42943
  if (value === void 0) return void 0;
42916
- if (typeof value !== "string" || !isHex(value)) throw Errors.providerError("alchemy", method, `unexpected ${field}: expected hex string`);
42944
+ if (typeof value !== "string" || !isHex(value)) throw Errors.providerError("account-abstraction", method, `unexpected ${field}: expected hex string`);
42917
42945
  return value;
42918
42946
  }
42919
42947
  function definedPaymasterFields(result) {
@@ -42924,19 +42952,14 @@ function definedPaymasterFields(result) {
42924
42952
  ...result.paymasterPostOpGasLimit === void 0 ? {} : { paymasterPostOpGasLimit: result.paymasterPostOpGasLimit }
42925
42953
  };
42926
42954
  }
42927
- function requiredRpcHex(raw, method, field) {
42928
- const value = raw[field];
42929
- if (typeof value !== "string" || !isHex(value)) throw Errors.providerError("alchemy", method, `unexpected ${field}: expected hex string`);
42930
- return value;
42931
- }
42932
42955
  async function paymasterRpc(method, args) {
42933
42956
  const raw = await alchemyRpc(args.chainId, method, [
42934
42957
  args.userOp,
42935
42958
  ENTRY_POINT_07_ADDRESS,
42936
42959
  toHex(args.chainId),
42937
- { policyId: args.policyId }
42960
+ {}
42938
42961
  ]);
42939
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw Errors.providerError("alchemy", method, `unexpected shape: ${JSON.stringify(raw)}`);
42962
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw Errors.providerError("account-abstraction", method, `unexpected shape: ${JSON.stringify(raw)}`);
42940
42963
  const result = raw;
42941
42964
  const paymaster = optionalPaymasterHex(result, method, "paymaster");
42942
42965
  const paymasterData = optionalPaymasterHex(result, method, "paymasterData");
@@ -42957,40 +42980,8 @@ function getPaymasterStubData(args) {
42957
42980
  function getPaymasterData(args) {
42958
42981
  return paymasterRpc("pm_getPaymasterData", args);
42959
42982
  }
42960
- /** Alchemy-hosted gas estimation and BSO sponsorship in one request. */
42961
- async function requestGasAndPaymasterAndData(args) {
42962
- const { signature, ...userOperation } = args.userOp;
42963
- const method = "alchemy_requestGasAndPaymasterAndData";
42964
- const raw = await alchemyRpc(args.chainId, method, [{
42965
- policyId: args.policyId,
42966
- entryPoint: ENTRY_POINT_07_ADDRESS,
42967
- dummySignature: signature,
42968
- userOperation
42969
- }]);
42970
- if (!isRecord(raw)) throw Errors.providerError("alchemy", method, `unexpected shape: ${JSON.stringify(raw)}`);
42971
- const paymaster = optionalPaymasterHex(raw, method, "paymaster");
42972
- const paymasterData = optionalPaymasterHex(raw, method, "paymasterData");
42973
- if (paymaster === void 0 || paymasterData === void 0) throw Errors.providerError("alchemy", method, "missing paymaster sponsorship");
42974
- const paymasterVerificationGasLimit = optionalPaymasterHex(raw, method, "paymasterVerificationGasLimit");
42975
- const paymasterPostOpGasLimit = optionalPaymasterHex(raw, method, "paymasterPostOpGasLimit");
42976
- return {
42977
- paymaster,
42978
- paymasterData,
42979
- preVerificationGas: requiredRpcHex(raw, method, "preVerificationGas"),
42980
- verificationGasLimit: requiredRpcHex(raw, method, "verificationGasLimit"),
42981
- callGasLimit: requiredRpcHex(raw, method, "callGasLimit"),
42982
- maxFeePerGas: requiredRpcHex(raw, method, "maxFeePerGas"),
42983
- maxPriorityFeePerGas: requiredRpcHex(raw, method, "maxPriorityFeePerGas"),
42984
- ...paymasterVerificationGasLimit === void 0 ? {} : { paymasterVerificationGasLimit },
42985
- ...paymasterPostOpGasLimit === void 0 ? {} : { paymasterPostOpGasLimit }
42986
- };
42987
- }
42988
- /** Select the hosted BSO method or the devnet ERC-7677 flow. */
42983
+ /** Sponsor one Base Sepolia UserOperation through the owned ERC-7677 gateway. */
42989
42984
  async function sponsorUserOperation(args) {
42990
- if (args.chainId !== 84532 || optionalEnv("BASE_SEPOLIA_BUNDLER_RPC_URL") === void 0) return {
42991
- ...args.userOp,
42992
- ...await requestGasAndPaymasterAndData(args)
42993
- };
42994
42985
  let request = args.userOp;
42995
42986
  request = {
42996
42987
  ...request,
@@ -43020,7 +43011,7 @@ async function sponsorUserOperation(args) {
43020
43011
  userOp: request
43021
43012
  }))
43022
43013
  };
43023
- if (request.paymaster === void 0 || request.paymasterData === void 0) throw Errors.providerError("alchemy", "pm_getPaymasterData", "missing paymaster sponsorship");
43014
+ if (request.paymaster === void 0 || request.paymasterData === void 0) throw Errors.providerError("account-abstraction", "pm_getPaymasterData", "missing paymaster sponsorship");
43024
43015
  return {
43025
43016
  ...request,
43026
43017
  paymaster: request.paymaster,
@@ -43030,17 +43021,17 @@ async function sponsorUserOperation(args) {
43030
43021
  /** Submit the signed UserOperation through the bundler — returns the userOpHash. */
43031
43022
  async function sendUserOperation(args) {
43032
43023
  const hash = await alchemyRpc(args.chainId, "eth_sendUserOperation", [args.userOp, ENTRY_POINT_07_ADDRESS]);
43033
- if (typeof hash !== "string" || !TX_HASH_HEX.test(hash)) throw Errors.providerError("alchemy", "eth_sendUserOperation", `unexpected hash: ${String(hash)}; expected 0x-prefixed 32-byte hex`);
43024
+ if (typeof hash !== "string" || !TX_HASH_HEX.test(hash)) throw Errors.providerError("account-abstraction", "eth_sendUserOperation", `unexpected hash: ${String(hash)}; expected 0x-prefixed 32-byte hex`);
43034
43025
  return hash;
43035
43026
  }
43036
43027
  //#endregion
43037
43028
  //#region ../../packages/backend/convex/smartAccount/deploy.ts
43038
43029
  function rpcQuantityToBigInt(value, field) {
43039
- if (!/^0x[0-9a-fA-F]+$/.test(value)) throw Errors.providerError("alchemy", "buildDeploymentUserOp", `invalid ${field} hex: ${value}`);
43030
+ if (!/^0x[0-9a-fA-F]+$/.test(value)) throw Errors.providerError("account-abstraction", "buildDeploymentUserOp", `invalid ${field} hex: ${value}`);
43040
43031
  try {
43041
43032
  return BigInt(value);
43042
43033
  } catch (cause) {
43043
- throw Errors.providerError("alchemy", "buildDeploymentUserOp", `invalid ${field} hex: ${value} (${String(cause)})`);
43034
+ throw Errors.providerError("account-abstraction", "buildDeploymentUserOp", `invalid ${field} hex: ${value} (${String(cause)})`);
43044
43035
  }
43045
43036
  }
43046
43037
  /** Attach the packed owner signature to a wire UserOp for the bundler RPC. */
@@ -43070,7 +43061,7 @@ function toRpcUserOp(op, signature) {
43070
43061
  * which passes v1-pinned owner factory args).
43071
43062
  */
43072
43063
  async function buildSponsoredSafeUserOp(input) {
43073
- const { chainId, sender, factoryArgs, callData, policyId } = input;
43064
+ const { chainId, sender, factoryArgs, callData } = input;
43074
43065
  const nonce = await fetchEntryPointNonce({
43075
43066
  chainId,
43076
43067
  sender
@@ -43093,10 +43084,9 @@ async function buildSponsoredSafeUserOp(input) {
43093
43084
  };
43094
43085
  request = await sponsorUserOperation({
43095
43086
  chainId,
43096
- userOp: request,
43097
- policyId
43087
+ userOp: request
43098
43088
  });
43099
- if (request.paymaster === void 0 || request.paymasterData === void 0) throw Errors.providerError("alchemy", "sponsorUserOperation", "missing paymaster sponsorship");
43089
+ if (request.paymaster === void 0 || request.paymasterData === void 0) throw Errors.providerError("account-abstraction", "sponsorUserOperation", "missing paymaster sponsorship");
43100
43090
  const userOp = {
43101
43091
  sender,
43102
43092
  nonce: toHex(nonce),
@@ -43244,8 +43234,7 @@ function makeSettlementPort(route) {
43244
43234
  const built = await maybeMapRevert(() => buildUserOp({
43245
43235
  chainId,
43246
43236
  sender: safeAddress,
43247
- callData: input.callData,
43248
- policyId: input.policyId
43237
+ callData: input.callData
43249
43238
  }), input.method, mapReverts);
43250
43239
  const packedSignature = packSafe4337OwnerSignature({ signature: await input.signer.signUserOpHash(built.digest) });
43251
43240
  const userOpHash = await maybeMapRevert(() => submitUserOp({
@@ -43271,8 +43260,8 @@ function makeSettlementPort(route) {
43271
43260
  };
43272
43261
  }
43273
43262
  if (Date.now() > deadline) {
43274
- if (mapReverts) throw Errors.providerTimeout("alchemy", "eth_getUserOperationReceipt", waitReceiptMs);
43275
- throw Errors.providerError("alchemy", "eth_getUserOperationReceipt", "receipt timeout");
43263
+ if (mapReverts) throw Errors.providerTimeout("account-abstraction", "eth_getUserOperationReceipt", waitReceiptMs);
43264
+ throw Errors.providerError("account-abstraction", "eth_getUserOperationReceipt", "receipt timeout");
43276
43265
  }
43277
43266
  await sleep(pollIntervalMs);
43278
43267
  }
@@ -43325,7 +43314,6 @@ async function submitFromMemberSafe(input) {
43325
43314
  const submitted = await (input.deps.port ?? directBaseSettlementPort()).submitAndConfirm({
43326
43315
  signer: input.deps.signer,
43327
43316
  payerEmail: input.email,
43328
- policyId: input.deps.policyId,
43329
43317
  callData: input.callData,
43330
43318
  method: input.operation,
43331
43319
  mapReverts: true,
@@ -43372,6 +43360,7 @@ function toMcpRoleView(view) {
43372
43360
  perTxCap: toMcpMoney(spend?.perTx),
43373
43361
  perDayCap: toMcpMoney(spend?.perDay),
43374
43362
  recipientScope,
43363
+ canSpend: view.definition.canSpend === true || spend !== void 0,
43375
43364
  canManageMembers: view.definition.canManageMembers ?? false,
43376
43365
  canManageRoles: view.definition.canManageRoles ?? false
43377
43366
  };
@@ -43657,7 +43646,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
43657
43646
  const res = await client.createOrg({
43658
43647
  name: input.name,
43659
43648
  handle: input.handle,
43660
- template: input.template ?? "Startup",
43649
+ template: "Solo",
43661
43650
  ...input.country === void 0 ? {} : { country: input.country }
43662
43651
  });
43663
43652
  return res.ok ? {
@@ -43684,16 +43673,12 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
43684
43673
  };
43685
43674
  }
43686
43675
  function buildDevOrgPort(input) {
43687
- const gasPolicyId = requireDevEnv(input.env, "ALCHEMY_GAS_POLICY_ID");
43688
43676
  return new LiveOrgDeploymentAdapter({
43689
43677
  convex: input.convex,
43690
43678
  privateKey: requireDevEnv(input.env, "DEPLOYER_PRIVATE_KEY"),
43691
43679
  rpcUrl: requireDevEnv(input.env, "BASE_SEPOLIA_RPC_URL"),
43692
- gasPolicyId,
43693
- sendOrgProxyDeployUserOperation: makeDevSignerOrgProxyDeploySender({
43694
- signer: input.signer,
43695
- policyId: gasPolicyId
43696
- })
43680
+ bundlerRpcUrl: requireDevEnv(input.env, "BASE_SEPOLIA_BUNDLER_RPC_URL"),
43681
+ sendOrgProxyDeployUserOperation: makeDevSignerOrgProxyDeploySender({ signer: input.signer })
43697
43682
  });
43698
43683
  }
43699
43684
  function requireDevEnv(env, name) {
@@ -43703,7 +43688,7 @@ function requireDevEnv(env, name) {
43703
43688
  }
43704
43689
  /** True iff the on-chain org-deployment seam env is fully present. */
43705
43690
  function hasOrgDeploymentEnv(env) {
43706
- return (env.DEPLOYER_PRIVATE_KEY?.trim().length ?? 0) > 0 && (env.BASE_SEPOLIA_RPC_URL?.trim().length ?? 0) > 0 && (env.ALCHEMY_GAS_POLICY_ID?.trim().length ?? 0) > 0;
43691
+ return (env.DEPLOYER_PRIVATE_KEY?.trim().length ?? 0) > 0 && (env.BASE_SEPOLIA_RPC_URL?.trim().length ?? 0) > 0 && (env.BASE_SEPOLIA_BUNDLER_RPC_URL?.trim().length ?? 0) > 0;
43707
43692
  }
43708
43693
  function createDevSignerSessionStorage() {
43709
43694
  const values = /* @__PURE__ */ new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/mcp",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "private": false,
5
5
  "description": "Capxul MCP server for auth, Account readiness, identity, Organizations, relationships, requests, destinations, and testnet funding over Streamable HTTP.",
6
6
  "keywords": [
@@ -47,12 +47,12 @@
47
47
  "typescript": "npm:@typescript/typescript6@6.0.2",
48
48
  "vite": "npm:@voidzero-dev/vite-plus-core@0.1.23",
49
49
  "vite-plus": "0.1.23",
50
- "@capxul/backend": "0.2.2",
50
+ "@capxul/backend": "0.2.3",
51
51
  "@capxul/config": "0.2.0",
52
- "@capxul/sdk": "2.2.0",
53
- "@capxul/types": "0.1.0",
52
+ "@capxul/sdk": "2.3.0",
53
+ "@capxul/types": "0.2.0",
54
54
  "@capxul/typescript-config": "0.0.0",
55
- "@capxul/wire": "0.3.0"
55
+ "@capxul/wire": "0.4.0"
56
56
  },
57
57
  "scripts": {
58
58
  "dev": "vp exec tsx src/main.ts serve",