@capxul/mcp 2.7.0 → 2.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.mjs +1646 -1009
  2. package/package.json +3 -3
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.7.0";
243
+ var version$2 = "2.8.2";
244
244
  //#endregion
245
245
  //#region ../../packages/errors/src/chain-cause.ts
246
246
  /**
@@ -255,6 +255,7 @@ const FAILURE_MODES$1 = [
255
255
  "stale-openfort-cache",
256
256
  "app-env-allowlist",
257
257
  "no-secure-context",
258
+ "signer-not-ready",
258
259
  "rate-limited",
259
260
  "timeout",
260
261
  "upstream-down",
@@ -364,6 +365,69 @@ function chainCauseProperties(chain) {
364
365
  };
365
366
  }
366
367
  /**
368
+ * Safe (safe-contracts v1.4.1) revert codes. The contracts revert with these
369
+ * short strings to save gas; the sentence lives in the Safe docs
370
+ * (`docs/error_codes.md`). Every Safe on the Capxul rail is this version.
371
+ */
372
+ const SAFE_REVERT_REASONS = {
373
+ GS000: "could not finish initialization",
374
+ GS001: "threshold needs to be defined",
375
+ GS010: "not enough gas to execute Safe transaction",
376
+ GS011: "could not pay gas costs with ether",
377
+ GS012: "could not pay gas costs with token",
378
+ GS013: "Safe transaction failed when gasPrice and safeTxGas were 0",
379
+ GS020: "signatures data too short",
380
+ GS021: "invalid contract signature location: inside static part",
381
+ GS022: "invalid contract signature location: length not present",
382
+ GS023: "invalid contract signature location: data not complete",
383
+ GS024: "invalid contract signature provided",
384
+ GS025: "hash has not been approved",
385
+ GS026: "invalid owner provided",
386
+ GS030: "only owners can approve a hash",
387
+ GS031: "method can only be called from this contract",
388
+ GS100: "modules have already been initialized",
389
+ GS101: "invalid module address provided",
390
+ GS102: "module has already been added",
391
+ GS103: "invalid prevModule, module pair provided",
392
+ GS104: "method can only be called from an enabled module",
393
+ GS105: "invalid starting point for fetching paginated modules",
394
+ GS106: "invalid page size for fetching paginated modules",
395
+ GS200: "owners have already been set up",
396
+ GS201: "threshold cannot exceed owner count",
397
+ GS202: "threshold needs to be greater than 0",
398
+ GS203: "invalid owner address provided",
399
+ GS204: "address is already an owner",
400
+ GS205: "invalid prevOwner, owner pair provided",
401
+ GS300: "guard does not implement IERC165",
402
+ GS400: "fallback handler cannot be set to self"
403
+ };
404
+ /**
405
+ * `Error(GS205: invalid prevOwner, owner pair provided)`, or the bare selector
406
+ * when the name is unknown. Safe codes travel only as the `message` of an
407
+ * `Error(string)` revert, so only that argument is expanded from
408
+ * {@link SAFE_REVERT_REASONS}; every other argument reads `name=value`, even
409
+ * when a custom error's field happens to hold a `GS` string.
410
+ */
411
+ function revertSummaryText(revert) {
412
+ if (revert.name === null) return revert.selector === "0x" ? "empty revert" : `unknown selector ${revert.selector}`;
413
+ const args = Object.entries(revert.args).map(([name, value]) => {
414
+ const reason = revert.name === "Error" && name === "message" ? SAFE_REVERT_REASONS[value] : void 0;
415
+ return reason === void 0 ? `${name}=${value}` : `${value}: ${reason}`;
416
+ }).join(", ");
417
+ return `${revert.name}(${args})`;
418
+ }
419
+ /**
420
+ * The cause in one line for an issue description: the decoded revert first,
421
+ * because the provider's own message masks the raw revert data (`reason:
422
+ * [REDACTED]`), then the provider's words. `undefined` when the cause carries
423
+ * neither, so the caller falls back to the error message.
424
+ */
425
+ function chainCauseSummary(chain) {
426
+ const revert = chain.revert === void 0 ? void 0 : revertSummaryText(chain.revert);
427
+ if (revert === void 0) return chain.providerMessage;
428
+ return chain.providerMessage === void 0 ? revert : `${revert}; ${chain.providerMessage}`;
429
+ }
430
+ /**
367
431
  * The error-tracking fingerprint for a failure: the code, the one-word cause,
368
432
  * and the operation. PostHog groups `$exception` rows by this value, so one
369
433
  * issue is one cause at one operation instead of every provider failure in
@@ -381,6 +445,7 @@ const CAPXUL_ERROR_CODES = [
381
445
  "SMART_ACCOUNT_MISSING",
382
446
  "PLAYER_NOT_FOUND",
383
447
  "ACCOUNT_NOT_FOUND",
448
+ "ACCOUNT_CLAIMED_BY_OTHER_SIGNER",
384
449
  "PROVIDER_ERROR",
385
450
  "CAPABILITY_UNAVAILABLE",
386
451
  "INVALID_INPUT",
@@ -415,6 +480,7 @@ const EXPECTED_OPERATION_OUTCOMES = /* @__PURE__ */ new Set([
415
480
  "INVALID_INPUT",
416
481
  "NOT_AUTHENTICATED",
417
482
  "SMART_ACCOUNT_MISSING",
483
+ "ACCOUNT_CLAIMED_BY_OTHER_SIGNER",
418
484
  "CANCELLED",
419
485
  "SIGNER_REJECTED",
420
486
  "VERIFICATION_REQUIRED",
@@ -473,6 +539,46 @@ function compactErrorOptions(options) {
473
539
  if (options.chain !== void 0) result.chain = options.chain;
474
540
  return result;
475
541
  }
542
+ const NETWORK_DETAIL_LABEL_RE = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u;
543
+ const NETWORK_TARGET_HOST_RE = /^[A-Za-z0-9.[\]:-]{1,253}$/u;
544
+ const DOCUMENT_VISIBILITY = /* @__PURE__ */ new Set(["hidden", "visible"]);
545
+ const BROWSER_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
546
+ "visibility-visible",
547
+ "visibility-hidden",
548
+ "pagehide",
549
+ "pageshow",
550
+ "online",
551
+ "offline"
552
+ ]);
553
+ function networkErrorDetails(operation, options) {
554
+ const details = { operation };
555
+ if (options === void 0) return details;
556
+ if (typeof options.provider === "string" && NETWORK_DETAIL_LABEL_RE.test(options.provider)) details.provider = options.provider;
557
+ if (typeof options.target_host === "string" && NETWORK_TARGET_HOST_RE.test(options.target_host)) details.target_host = options.target_host;
558
+ if (isFailureMode(options.failure_mode)) details.failure_mode = options.failure_mode;
559
+ if (options.reason === "connection-lost-in-flight") details.reason = options.reason;
560
+ if (typeof options.connection_id === "string" && NETWORK_DETAIL_LABEL_RE.test(options.connection_id)) details.connection_id = options.connection_id;
561
+ for (const key of [
562
+ "connection_count",
563
+ "connection_retries",
564
+ "close_code",
565
+ "ms_since_browser_event"
566
+ ]) {
567
+ const value = options[key];
568
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && (key !== "close_code" || value <= 4999)) details[key] = value;
569
+ }
570
+ for (const key of [
571
+ "close_was_clean",
572
+ "close_reason_present",
573
+ "navigator_online"
574
+ ]) {
575
+ const value = options[key];
576
+ if (typeof value === "boolean") details[key] = value;
577
+ }
578
+ if (DOCUMENT_VISIBILITY.has(options.document_visibility ?? "")) details.document_visibility = options.document_visibility;
579
+ if (BROWSER_LIFECYCLE_EVENTS.has(options.last_browser_event ?? "")) details.last_browser_event = options.last_browser_event;
580
+ return details;
581
+ }
476
582
  const Errors = {
477
583
  notAuthenticated: (message, opts) => new CapxulError("NOT_AUTHENTICATED", message ?? "Not authenticated", opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : void 0),
478
584
  emailDeliveryFailed: (detail) => new CapxulError("EMAIL_DELIVERY_FAILED", "Failed to send email", { details: { detail } }),
@@ -480,6 +586,14 @@ const Errors = {
480
586
  smartAccountMissing: (authUserId) => new CapxulError("SMART_ACCOUNT_MISSING", "Smart account not provisioned", { details: { authUserId } }),
481
587
  playerNotFound: (playerId) => new CapxulError("PLAYER_NOT_FOUND", playerId ? `Openfort player ${playerId} not found` : "Openfort player not found", playerId === void 0 ? void 0 : { details: { playerId } }),
482
588
  accountNotFound: (accountId) => new CapxulError("ACCOUNT_NOT_FOUND", accountId ? `Openfort account ${accountId} not found` : "Openfort account not found", accountId === void 0 ? void 0 : { details: { accountId } }),
589
+ /**
590
+ * The Safe at this email's address is deployed and its owner is neither the
591
+ * Capxul bootstrap owner nor the caller's signer. The claim
592
+ * `swapOwner(bootstrap → signer)` cannot succeed: only the on-chain owner
593
+ * can hand the account over. Read from `getOwners()` before any
594
+ * UserOperation is built (2026-09-02), so no simulation and no retry.
595
+ */
596
+ accountClaimedByOtherSigner: (details) => new CapxulError("ACCOUNT_CLAIMED_BY_OTHER_SIGNER", "This account is already owned by a different signer.", { details }),
483
597
  providerError: (provider, operation, cause, opts) => {
484
598
  const details = {
485
599
  ...opts?.details,
@@ -563,10 +677,14 @@ const Errors = {
563
677
  }
564
678
  }),
565
679
  rateLimited: (details) => new CapxulError("RATE_LIMITED", "Rate limit exceeded", details === void 0 ? void 0 : { details: { ...details } }),
566
- networkError: (operation, cause) => new CapxulError("NETWORK_ERROR", `Network error during ${operation}`, {
567
- cause,
568
- details: { operation }
569
- }),
680
+ networkError: (operation, cause, opts) => {
681
+ const mode = isFailureMode(opts?.failure_mode) ? opts.failure_mode : void 0;
682
+ return new CapxulError("NETWORK_ERROR", `Network error during ${operation}`, {
683
+ cause,
684
+ details: networkErrorDetails(operation, opts),
685
+ ...mode === void 0 ? {} : { mode }
686
+ });
687
+ },
570
688
  unknown: (cause) => new CapxulError("UNKNOWN", "Unknown error", { cause }),
571
689
  otpExpired: (details) => new CapxulError("OTP_EXPIRED", "Verification code has expired. Request a new one.", details === void 0 ? void 0 : { details: { ...details } }),
572
690
  signerRejected: (details) => new CapxulError("SIGNER_REJECTED", "Signer rejected the request.", {
@@ -576,6 +694,11 @@ const Errors = {
576
694
  reason: details.reason
577
695
  }
578
696
  }),
697
+ superseded: (details) => new CapxulError("SUPERSEDED", "Operation was superseded.", { details: {
698
+ operation: details.operation,
699
+ reason: details.reason,
700
+ ...details.executionId === void 0 ? {} : { executionId: details.executionId }
701
+ } }),
579
702
  cancelled: (details) => new CapxulError("CANCELLED", "Operation was cancelled.", details === void 0 ? void 0 : { details: { ...details } }),
580
703
  /**
581
704
  * Method called from a flow state where its precondition fails (TA16). The
@@ -5778,11 +5901,28 @@ var PendingAuthStore = class {
5778
5901
  //#region ../../packages/sdk/src/domain/identity/model.ts
5779
5902
  const WRONG = { refused: "WRONG_STATE" };
5780
5903
  /** org-lifecycle.ts:173-184, lifted verbatim. */
5904
+ /**
5905
+ * Causes that do not change on a retry: the same request reverts, is refused,
5906
+ * or fails the same pre-flight again. A retry re-enters the same lane and
5907
+ * fails the same way (the GS205 loop of 2026-09-02).
5908
+ */
5909
+ const DEFINITIVE_PROVIDER_MODES = /* @__PURE__ */ new Set([
5910
+ "auth-origin-mismatch",
5911
+ "app-env-allowlist",
5912
+ "no-secure-context",
5913
+ "signer-not-ready",
5914
+ "revert",
5915
+ "insufficient-balance",
5916
+ "insufficient-allowance",
5917
+ "rejected",
5918
+ "unauthorized"
5919
+ ]);
5781
5920
  const isRetryable = (failure) => {
5782
5921
  if (failure.code === "CANCELLED" || failure.code === "SIGNER_REJECTED") return true;
5783
5922
  if (failure.code === "PROVIDER_ERROR") {
5784
- const mode = failure.mode;
5785
- return mode !== "auth-origin-mismatch" && mode !== "app-env-allowlist" && mode !== "no-secure-context";
5923
+ const chainRetryable = failure.error?.chain?.retryable;
5924
+ if (chainRetryable !== void 0) return chainRetryable;
5925
+ return !DEFINITIVE_PROVIDER_MODES.has(failure.mode);
5786
5926
  }
5787
5927
  return failure.code === "NETWORK_ERROR" || failure.code === "UNKNOWN";
5788
5928
  };
@@ -6125,6 +6265,44 @@ Object.freeze({
6125
6265
  needsAction: false
6126
6266
  });
6127
6267
  //#endregion
6268
+ //#region ../../packages/sdk/src/internal/invocation-observation.ts
6269
+ const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
6270
+ const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
6271
+ /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
6272
+ function attachInvocationObservation(target, source) {
6273
+ const snapshot = Object.freeze(source.context === void 0 ? { active: source.active } : {
6274
+ active: source.active,
6275
+ context: Object.freeze({ ...source.context })
6276
+ });
6277
+ Object.defineProperty(target, INVOCATION_OBSERVATION, {
6278
+ configurable: false,
6279
+ enumerable: false,
6280
+ value: snapshot,
6281
+ writable: false
6282
+ });
6283
+ return target;
6284
+ }
6285
+ /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
6286
+ function readInvocationObservation(source) {
6287
+ if (typeof source !== "object" || source === null) return void 0;
6288
+ return source[INVOCATION_OBSERVATION];
6289
+ }
6290
+ /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
6291
+ function copyInvocationObservation(source, target) {
6292
+ const snapshot = readInvocationObservation(source);
6293
+ return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot);
6294
+ }
6295
+ /** @internal Carry the public call-start delivery decision with its failure envelope. */
6296
+ function markFailureInvocationSnapshot(failure, snapshot) {
6297
+ Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
6298
+ configurable: false,
6299
+ enumerable: false,
6300
+ value: Object.freeze(snapshot),
6301
+ writable: false
6302
+ });
6303
+ return failure;
6304
+ }
6305
+ //#endregion
6128
6306
  //#region ../../packages/sdk/src/surface/_shared/provisioning-telemetry.ts
6129
6307
  async function emitProvisioningTelemetry(telemetry, smartAccount) {
6130
6308
  if (telemetry === void 0) return;
@@ -6183,9 +6361,29 @@ function* causeChain(cause) {
6183
6361
  current = current.cause;
6184
6362
  }
6185
6363
  }
6364
+ const SIGNER_NOT_READY_CODES = /* @__PURE__ */ new Set(["MISSING_SIGNER", "NOT_CONFIGURED"]);
6365
+ function isOpenfortSignerNotReadyCode(value) {
6366
+ return typeof value === "string" && SIGNER_NOT_READY_CODES.has(value);
6367
+ }
6368
+ /** Return the exact Openfort code that requires an embedded-signer rebuild. */
6369
+ function openfortSignerNotReadyCode(cause) {
6370
+ for (const link of causeChain(cause)) {
6371
+ const error = link;
6372
+ for (const value of [
6373
+ error.error,
6374
+ error.code,
6375
+ error.details?.provider_error_code
6376
+ ]) if (isOpenfortSignerNotReadyCode(value)) return value;
6377
+ }
6378
+ }
6379
+ /** Openfort's typed signal that its embedded signer state must be rebuilt. */
6380
+ function isSignerNotReadySignal(cause) {
6381
+ return openfortSignerNotReadyCode(cause) !== void 0;
6382
+ }
6186
6383
  /** Fold a signer throw into the public error contract. */
6187
6384
  function signerFailure(source, operation, cause) {
6188
6385
  let failureMode;
6386
+ const providerErrorCode = source === "openfort-embedded" ? openfortSignerNotReadyCode(cause) : void 0;
6189
6387
  for (const link of causeChain(cause)) {
6190
6388
  if (link instanceof CapxulError && link.code === "SIGNER_REJECTED") return link;
6191
6389
  failureMode = getFailureMode(link) ?? failureMode;
@@ -6194,46 +6392,15 @@ function signerFailure(source, operation, cause) {
6194
6392
  source,
6195
6393
  cause
6196
6394
  });
6197
- }
6198
- return Errors.providerError("signer", operation, cause, failureMode === void 0 ? void 0 : { failure_mode: failureMode });
6199
- }
6200
- //#endregion
6201
- //#region ../../packages/sdk/src/internal/invocation-observation.ts
6202
- const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
6203
- const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
6204
- /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
6205
- function attachInvocationObservation(target, source) {
6206
- const snapshot = Object.freeze(source.context === void 0 ? { active: source.active } : {
6207
- active: source.active,
6208
- context: Object.freeze({ ...source.context })
6209
- });
6210
- Object.defineProperty(target, INVOCATION_OBSERVATION, {
6211
- configurable: false,
6212
- enumerable: false,
6213
- value: snapshot,
6214
- writable: false
6215
- });
6216
- return target;
6217
- }
6218
- /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
6219
- function readInvocationObservation(source) {
6220
- if (typeof source !== "object" || source === null) return void 0;
6221
- return source[INVOCATION_OBSERVATION];
6222
- }
6223
- /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
6224
- function copyInvocationObservation(source, target) {
6225
- const snapshot = readInvocationObservation(source);
6226
- return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot);
6227
- }
6228
- /** @internal Carry the public call-start delivery decision with its failure envelope. */
6229
- function markFailureInvocationSnapshot(failure, snapshot) {
6230
- Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
6231
- configurable: false,
6232
- enumerable: false,
6233
- value: Object.freeze(snapshot),
6234
- writable: false
6395
+ if (providerErrorCode !== void 0) failureMode = "signer-not-ready";
6396
+ }
6397
+ return Errors.providerError("signer", operation, cause, failureMode === void 0 && providerErrorCode === void 0 ? void 0 : {
6398
+ ...failureMode === void 0 ? {} : { failure_mode: failureMode },
6399
+ ...providerErrorCode === void 0 ? {} : { details: {
6400
+ provider_error_source: "openfort",
6401
+ provider_error_code: providerErrorCode
6402
+ } }
6235
6403
  });
6236
- return failure;
6237
6404
  }
6238
6405
  //#endregion
6239
6406
  //#region ../../packages/sdk/src/domain/machine/telemetry.ts
@@ -6697,21 +6864,27 @@ async function runIdentityFacade(verb, controls, run, runPromise = Effect.runPro
6697
6864
  async function runPortEffect(effect, controls, operation = "port", runPromise = Effect.runPromise) {
6698
6865
  const deadlineDelay = controls?.deadlineMs === void 0 ? void 0 : Math.max(0, controls.deadlineMs - Date.now());
6699
6866
  const timeoutMs = controls?.timeoutMs === void 0 ? deadlineDelay : deadlineDelay === void 0 ? controls.timeoutMs : Math.min(controls.timeoutMs, deadlineDelay);
6700
- const observed = (timeoutMs === void 0 ? effect : effect.pipe(Effect.timeoutOrElse({
6867
+ return runCapxulEffect((timeoutMs === void 0 ? effect : effect.pipe(Effect.timeoutOrElse({
6701
6868
  duration: `${timeoutMs} millis`,
6702
6869
  orElse: () => Effect.fail({ publicError: Errors.providerTimeout("sdk", operation, timeoutMs) })
6703
- }))).pipe(Effect.tap(() => Effect.annotateCurrentSpan({ outcome: "succeeded" })), Effect.tapError((failure) => {
6704
- const mode = failure.publicError.details?.failure_mode;
6870
+ }))).pipe(Effect.mapError((failure) => failure.publicError)), controls, operation, runPromise);
6871
+ }
6872
+ /** Observe a public Effect that already uses the canonical CapxulError channel. */
6873
+ async function runCapxulEffect(effect, controls, operation = "port", runPromise = Effect.runPromise) {
6874
+ const invocation = readInvocationObservation(controls);
6875
+ const correlationId = safeEngineeringIdentifier(controls?.correlation_id ?? invocation?.context?.correlationId);
6876
+ const observed = effect.pipe(Effect.tap(() => Effect.annotateCurrentSpan({ outcome: "succeeded" })), Effect.tapError((error) => {
6877
+ const mode = error.mode ?? error.details?.failure_mode;
6705
6878
  return Effect.annotateCurrentSpan({
6706
- outcome: portFailureOutcome(failure.publicError.code),
6707
- failure_code: failure.publicError.code,
6879
+ outcome: portFailureOutcome(error.code),
6880
+ failure_code: error.code,
6708
6881
  ...typeof mode === "string" ? { mode } : {}
6709
6882
  });
6710
6883
  }), Effect.tapDefect(() => Effect.annotateCurrentSpan({
6711
6884
  outcome: "failed",
6712
6885
  failure_code: "UNKNOWN"
6713
- })), Effect.withSpan(`identity.port.${operation}`));
6714
- return runIfActive(controls?.signal, operation, () => withInvocationParentSpan(observed, controls), runPromise);
6886
+ })), Effect.withSpan(`identity.port.${operation}`), Effect.annotateSpans(correlationId === void 0 ? {} : { correlation_id: correlationId }));
6887
+ return runIfActive(controls?.signal, operation, () => withInvocationParentSpan(observed, controls).pipe(Effect.mapError((publicError) => ({ publicError }))), runPromise);
6715
6888
  }
6716
6889
  /** Map machine-internal failure state onto the public SDK error vocabulary. */
6717
6890
  function publicIdentityFailure(failure) {
@@ -8462,7 +8635,7 @@ function makeAccountMethods(deps) {
8462
8635
  value: provisioningPhase(deps.actor.snapshot())
8463
8636
  };
8464
8637
  };
8465
- const resolveLifecycle = async () => {
8638
+ const resolveLifecycle = async (controls) => {
8466
8639
  const phase = provisioningPhase(deps.actor.snapshot());
8467
8640
  const status = await getStatus();
8468
8641
  if (!status.ok) return accountFailureResult(status.error);
@@ -8470,7 +8643,7 @@ function makeAccountMethods(deps) {
8470
8643
  if (status.value.status !== "notAuthenticated" && (phase.status === "ready" || isRequirementMet(status.value, requirement))) {
8471
8644
  const accountReadPort = deps.accountReadPort;
8472
8645
  if (accountReadPort === void 0) return accountFailureResult(Errors.invalidInput("account", "accountReadPort is required to resolve ready lifecycle"));
8473
- const account = await runPortEffect(accountReadPort.readBalance({ chainId: toChainId(deps.chainId) }));
8646
+ const account = await runPortEffect(accountReadPort.readBalance(copyInvocationObservation(controls, { chainId: toChainId(deps.chainId) })), controls, "accounts.read", deps.runPromise);
8474
8647
  if (!account.ok) return accountFailureResult(account.error);
8475
8648
  accountId = String(account.value.id);
8476
8649
  }
@@ -8484,8 +8657,9 @@ function makeAccountMethods(deps) {
8484
8657
  })
8485
8658
  };
8486
8659
  };
8487
- const getLifecycle = () => resolveLifecycle();
8660
+ const getLifecycle = () => resolveLifecycle(deps.invocationControls?.());
8488
8661
  const retrySetup = async () => {
8662
+ const controls = deps.invocationControls?.();
8489
8663
  const resetSession = deps.signer?.resetSession;
8490
8664
  if (typeof resetSession === "function") try {
8491
8665
  resetSession.call(deps.signer);
@@ -8494,7 +8668,7 @@ function makeAccountMethods(deps) {
8494
8668
  }
8495
8669
  const retried = await drive({ _tag: "RetryAccount" });
8496
8670
  if (!retried.ok) return accountFailureResult(retried.error);
8497
- return resolveLifecycle();
8671
+ return resolveLifecycle(controls);
8498
8672
  };
8499
8673
  return {
8500
8674
  methods: {
@@ -8554,14 +8728,14 @@ const moneyExecutionContract = {
8554
8728
  };
8555
8729
  //#endregion
8556
8730
  //#region ../../packages/sdk/package.json
8557
- var version = "2.7.0";
8731
+ var version = "2.8.2";
8558
8732
  //#endregion
8559
- //#region ../../packages/sdk/src/telemetry/capture-exception.ts
8560
- /** Fixed, leak-safe message — the raw error message may carry PII and never ships. */
8733
+ //#region ../../packages/sdk/src/telemetry/exception-projection.ts
8734
+ /** Fixed fallback for failures that have no safe message. */
8561
8735
  const EXCEPTION_MESSAGE = "Capxul SDK operation failed";
8736
+ const SDK_VERSION$1 = version;
8562
8737
  //#endregion
8563
8738
  //#region ../../packages/sdk/src/observation.ts
8564
- const SDK_VERSION$1 = version;
8565
8739
  /** @internal Observe public result methods at the assembled Core SDK boundary. */
8566
8740
  function observeSdkClient(client, adapter, snapshot) {
8567
8741
  if (adapter === void 0) return client;
@@ -8805,18 +8979,45 @@ function errorKind$1(cause) {
8805
8979
  * Shared by the failure boundary and the `bootstrap_failed` product event.
8806
8980
  */
8807
8981
  function failureDetail(cause) {
8808
- if (!isCapxulError(cause)) return void 0;
8809
- const details = cause.details;
8982
+ const error = observationError(cause);
8983
+ if (error === void 0) return void 0;
8984
+ const details = error.details;
8810
8985
  const source = typeof details === "object" && details !== null ? details : {};
8811
8986
  return sanitizeFailureDetail({
8812
8987
  provider: source.provider,
8813
8988
  provider_operation: source.operation,
8814
- failure_mode: cause.mode ?? source.failure_mode,
8989
+ provider_error_source: source.provider_error_source,
8990
+ provider_error_code: source.provider_error_code,
8991
+ target_host: source.target_host,
8992
+ failure_mode: error.mode ?? source.failure_mode,
8815
8993
  reason: source.reason,
8816
8994
  http_status: source.httpStatus,
8817
- ...cause.chain === void 0 ? {} : chainCauseProperties(cause.chain)
8995
+ connection_id: source.connection_id,
8996
+ connection_count: source.connection_count,
8997
+ connection_retries: source.connection_retries,
8998
+ close_code: source.close_code,
8999
+ close_was_clean: source.close_was_clean,
9000
+ close_reason_present: source.close_reason_present,
9001
+ document_visibility: source.document_visibility,
9002
+ navigator_online: source.navigator_online,
9003
+ last_browser_event: source.last_browser_event,
9004
+ ms_since_browser_event: source.ms_since_browser_event,
9005
+ ...error.chain === void 0 ? {} : chainCauseProperties(error.chain)
8818
9006
  });
8819
9007
  }
9008
+ const CAPXUL_ERROR_CODE_SET = new Set(CAPXUL_ERROR_CODES);
9009
+ function observationError(cause) {
9010
+ if (isCapxulError(cause)) return cause;
9011
+ if (typeof cause !== "object" || cause === null) return void 0;
9012
+ const candidate = cause;
9013
+ if (typeof candidate.code !== "string" || !CAPXUL_ERROR_CODE_SET.has(candidate.code) || typeof candidate.message !== "string") return;
9014
+ const chain = decodeChainCause(candidate.chain);
9015
+ return {
9016
+ ...candidate.details === void 0 ? {} : { details: candidate.details },
9017
+ ...candidate.mode === void 0 ? {} : { mode: candidate.mode },
9018
+ ...chain === null ? {} : { chain }
9019
+ };
9020
+ }
8820
9021
  /** The chain-cause half of {@link sanitizeFailureDetail}: same bounds, same masking. */
8821
9022
  function sanitizeChainDetail(source, detail) {
8822
9023
  for (const key of [
@@ -8828,17 +9029,19 @@ function sanitizeChainDetail(source, detail) {
8828
9029
  const value = source[key];
8829
9030
  if (typeof value === "string" && ENUMERATED_DETAIL_RE.test(value)) detail[key] = value;
8830
9031
  }
9032
+ sanitizeProviderErrorDetail(source, detail);
8831
9033
  const status = source.http_status;
8832
9034
  if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599) detail.http_status = status;
8833
9035
  for (const key of [
8834
9036
  "chain_upstream",
8835
9037
  "chain_method",
8836
- "chain_revert_name",
8837
- "chain_revert_selector"
9038
+ "chain_revert_name"
8838
9039
  ]) {
8839
9040
  const value = source[key];
8840
9041
  if (typeof value === "string" && ENUMERATED_DETAIL_RE.test(value)) detail[key] = value;
8841
9042
  }
9043
+ const selector = source.chain_revert_selector;
9044
+ if (typeof selector === "string" && REVERT_SELECTOR_RE.test(selector)) detail.chain_revert_selector = selector;
8842
9045
  if (typeof source.chain_retryable === "boolean") detail.chain_retryable = source.chain_retryable;
8843
9046
  const chainHttpStatus = source.chain_http_status;
8844
9047
  if (typeof chainHttpStatus === "number" && Number.isInteger(chainHttpStatus) && chainHttpStatus >= 100 && chainHttpStatus <= 599) detail.chain_http_status = chainHttpStatus;
@@ -8855,15 +9058,53 @@ function sanitizeChainDetail(source, detail) {
8855
9058
  const providerMessage = evidenceText(source.chain_provider_message);
8856
9059
  if (providerMessage !== void 0) detail.chain_provider_message = providerMessage;
8857
9060
  }
9061
+ function sanitizeProviderErrorDetail(source, detail) {
9062
+ if (source.provider_error_source !== "openfort") return;
9063
+ detail.provider_error_source = "openfort";
9064
+ if (isOpenfortSignerNotReadyCode(source.provider_error_code)) detail.provider_error_code = source.provider_error_code;
9065
+ }
9066
+ function sanitizeConnectionDetail(source, detail) {
9067
+ const targetHost = source.target_host;
9068
+ if (typeof targetHost === "string" && TARGET_HOST_RE.test(targetHost)) detail.target_host = targetHost;
9069
+ for (const key of [
9070
+ "connection_id",
9071
+ "document_visibility",
9072
+ "last_browser_event"
9073
+ ]) {
9074
+ const value = source[key];
9075
+ if (typeof value === "string" && ENUMERATED_DETAIL_RE.test(value)) detail[key] = value;
9076
+ }
9077
+ for (const key of [
9078
+ "connection_count",
9079
+ "connection_retries",
9080
+ "close_code",
9081
+ "ms_since_browser_event"
9082
+ ]) {
9083
+ const value = source[key];
9084
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && (key !== "close_code" || value <= 4999)) detail[key] = value;
9085
+ }
9086
+ for (const key of [
9087
+ "close_was_clean",
9088
+ "close_reason_present",
9089
+ "navigator_online"
9090
+ ]) {
9091
+ const value = source[key];
9092
+ if (typeof value === "boolean") detail[key] = value;
9093
+ }
9094
+ }
8858
9095
  function sanitizeFailureDetail(input) {
8859
9096
  if (typeof input !== "object" || input === null) return void 0;
8860
9097
  const source = input;
8861
9098
  const detail = {};
9099
+ sanitizeConnectionDetail(source, detail);
8862
9100
  sanitizeChainDetail(source, detail);
8863
9101
  return Object.keys(detail).length === 0 ? void 0 : detail;
8864
9102
  }
8865
9103
  /** Enumerated codes only (`convex`, `no-secure-context`, `bootstrap-encode`); free text fails. */
8866
9104
  const ENUMERATED_DETAIL_RE = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u;
9105
+ const TARGET_HOST_RE = /^[A-Za-z0-9.[\]:-]{1,253}$/u;
9106
+ /** A four-byte revert selector, or the bare `0x` of an empty revert. */
9107
+ const REVERT_SELECTOR_RE = /^0x(?:[0-9a-fA-F]{8})?$/u;
8867
9108
  function normalizeOperation$1(value) {
8868
9109
  return typeof value === "string" && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,255}$/u.test(value) ? value : "unknown";
8869
9110
  }
@@ -11066,11 +11307,13 @@ async function safeText$1(res) {
11066
11307
  }
11067
11308
  var HttpBootstrapAdapter = class {
11068
11309
  bootstrapBaseUrl;
11310
+ bootstrapHost;
11069
11311
  fetchImpl;
11070
11312
  observation;
11071
11313
  retry;
11072
11314
  constructor(deps) {
11073
11315
  this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\/$/, "");
11316
+ this.bootstrapHost = hostOf(this.bootstrapBaseUrl);
11074
11317
  this.observation = deps.observation;
11075
11318
  this.retry = deps.retry ?? DEFAULT_RETRY;
11076
11319
  this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));
@@ -11096,7 +11339,11 @@ var HttpBootstrapAdapter = class {
11096
11339
  body: JSON.stringify({ publishableKey: input.publishableKey })
11097
11340
  });
11098
11341
  },
11099
- catch: (cause) => bootstrapErrorFromCapxul("network", Errors.networkError("bootstrap", cause))
11342
+ catch: (cause) => bootstrapErrorFromCapxul("network", Errors.networkError("bootstrap", cause, {
11343
+ provider: "bootstrap",
11344
+ failure_mode: "upstream-down",
11345
+ ...this.bootstrapHost === void 0 ? {} : { target_host: this.bootstrapHost }
11346
+ }))
11100
11347
  }).pipe(Effect.flatMap((res) => this.mapResponse(res)));
11101
11348
  }
11102
11349
  mapResponse(res) {
@@ -11152,6 +11399,13 @@ var HttpBootstrapAdapter = class {
11152
11399
  function HttpBootstrapLayer(deps) {
11153
11400
  return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));
11154
11401
  }
11402
+ function hostOf(url) {
11403
+ try {
11404
+ return new URL(url).hostname;
11405
+ } catch {
11406
+ return;
11407
+ }
11408
+ }
11155
11409
  function normalizeRuntimeUrl(field, raw) {
11156
11410
  let parsed;
11157
11411
  try {
@@ -14118,26 +14372,207 @@ var ConvexClient = class {
14118
14372
  //#endregion
14119
14373
  //#region ../../packages/sdk/src/ports/convex-call.ts
14120
14374
  var ConvexCallError = class extends Data.TaggedError("ConvexCallError") {};
14121
- function convexCallErrorFromCapxul(operation, error) {
14375
+ function convexCallErrorFromCapxul(operation, error, transport) {
14122
14376
  return new ConvexCallError({
14123
14377
  operation,
14124
14378
  publicCode: error.code,
14125
14379
  publicError: error,
14126
14380
  cause: error,
14127
- ...error.details === void 0 ? {} : { details: error.details }
14381
+ ...error.details === void 0 ? {} : { details: error.details },
14382
+ ...transport === void 0 ? {} : { transport }
14128
14383
  });
14129
14384
  }
14130
14385
  var ConvexCallPortTag = class extends Context.Service()("@capxul/sdk/ports/ConvexCallPort") {};
14131
14386
  //#endregion
14387
+ //#region ../../packages/sdk/src/adapters/convex-call/convex-connection-monitor.ts
14388
+ var ConvexConnectionMonitor = class {
14389
+ #connectionId = makeConnectionId();
14390
+ #browser = new BrowserLifecycleMonitor();
14391
+ #lastClose;
14392
+ observedWebSocketConstructor() {
14393
+ const NativeWebSocket = globalThis.WebSocket;
14394
+ if (typeof globalThis.window === "undefined" || NativeWebSocket === void 0) return void 0;
14395
+ return new Proxy(NativeWebSocket, { construct: (Target, args) => {
14396
+ const socket = Reflect.construct(Target, args);
14397
+ socket.addEventListener("close", (event) => {
14398
+ this.#lastClose = this.#browser.socketClose(event);
14399
+ });
14400
+ return socket;
14401
+ } });
14402
+ }
14403
+ close() {
14404
+ this.#browser.close();
14405
+ }
14406
+ observe(client, observer) {
14407
+ const subscribe = client.subscribeToConnectionState?.bind(client);
14408
+ if (subscribe === void 0) return () => this.#browser.close();
14409
+ let previous;
14410
+ const unsubscribe = subscribe((next) => {
14411
+ const diagnostics = this.#diagnostics(previous, next);
14412
+ previous = next;
14413
+ for (const diagnostic of diagnostics) emitDiagnostic(observer, diagnostic);
14414
+ });
14415
+ if (previous === void 0) {
14416
+ const current = safeConnectionState(client);
14417
+ if (current !== void 0) {
14418
+ previous = current;
14419
+ for (const diagnostic of this.#diagnostics(void 0, current)) emitDiagnostic(observer, diagnostic);
14420
+ }
14421
+ }
14422
+ let closed = false;
14423
+ return () => {
14424
+ if (closed) return;
14425
+ closed = true;
14426
+ try {
14427
+ unsubscribe();
14428
+ } finally {
14429
+ this.#browser.close();
14430
+ }
14431
+ };
14432
+ }
14433
+ reconnectEvidence(start, end) {
14434
+ if (!connectionRestarted(start, end)) return void 0;
14435
+ return {
14436
+ kind: "connection-lost-in-flight",
14437
+ connection_id: this.#connectionId,
14438
+ start_connection_count: start.connectionCount,
14439
+ connection_count: end.connectionCount,
14440
+ ...end.connectionRetries === void 0 ? {} : { connection_retries: end.connectionRetries },
14441
+ ...closeFields(this.#lastClose)
14442
+ };
14443
+ }
14444
+ #diagnostics(previous, next) {
14445
+ const transitions = connectionTransitions(previous, next);
14446
+ if (transitions.length === 0) return [];
14447
+ const oldest = next.timeOfOldestInflightRequest;
14448
+ const oldestInflightMs = oldest instanceof Date && Number.isFinite(oldest.getTime()) ? Math.max(0, Date.now() - oldest.getTime()) : void 0;
14449
+ return transitions.map((transition) => ({
14450
+ connection_id: this.#connectionId,
14451
+ transition,
14452
+ previous_connected: previous?.isWebSocketConnected ?? false,
14453
+ connected: next.isWebSocketConnected,
14454
+ ...next.hasEverConnected === void 0 ? {} : { has_ever_connected: next.hasEverConnected },
14455
+ connection_count: next.connectionCount,
14456
+ ...next.connectionRetries === void 0 ? {} : { connection_retries: next.connectionRetries },
14457
+ ...next.hasInflightRequests === void 0 ? {} : { has_inflight_requests: next.hasInflightRequests },
14458
+ ...next.inflightActions === void 0 ? {} : { inflight_actions: next.inflightActions },
14459
+ ...next.inflightMutations === void 0 ? {} : { inflight_mutations: next.inflightMutations },
14460
+ ...oldestInflightMs === void 0 ? {} : { oldest_inflight_ms: oldestInflightMs },
14461
+ ...closeFields(this.#lastClose)
14462
+ }));
14463
+ }
14464
+ };
14465
+ function connectionRestarted(start, end) {
14466
+ if (start === void 0 || end === void 0) return false;
14467
+ const opensBeforeCancellation = start.isWebSocketConnected ? 1 : 2;
14468
+ return end.connectionCount >= start.connectionCount + opensBeforeCancellation;
14469
+ }
14470
+ function connectionTransitions(previous, next) {
14471
+ if (previous === void 0) {
14472
+ if (next.isWebSocketConnected) return (next.connectionRetries ?? 0) > 0 ? ["retrying", "connected"] : ["connected"];
14473
+ return (next.connectionRetries ?? 0) > 0 ? ["disconnected", "retrying"] : [];
14474
+ }
14475
+ const transitions = [];
14476
+ if (previous.isWebSocketConnected !== next.isWebSocketConnected) transitions.push(next.isWebSocketConnected ? "connected" : "disconnected");
14477
+ if ((next.connectionRetries ?? 0) > (previous.connectionRetries ?? 0)) transitions.push("retrying");
14478
+ return transitions;
14479
+ }
14480
+ function emitDiagnostic(observer, diagnostic) {
14481
+ try {
14482
+ observer(diagnostic);
14483
+ } catch {}
14484
+ }
14485
+ function safeConnectionState(client) {
14486
+ try {
14487
+ return client.connectionState?.();
14488
+ } catch {
14489
+ return;
14490
+ }
14491
+ }
14492
+ function closeFields(close) {
14493
+ if (close === void 0) return {};
14494
+ return {
14495
+ close_code: close.code,
14496
+ close_was_clean: close.wasClean,
14497
+ close_reason_present: close.reasonPresent,
14498
+ ...close.documentVisibility === void 0 ? {} : { document_visibility: close.documentVisibility },
14499
+ ...close.navigatorOnline === void 0 ? {} : { navigator_online: close.navigatorOnline },
14500
+ ...close.browserEvent === void 0 ? {} : { last_browser_event: close.browserEvent },
14501
+ ...close.msSinceBrowserEvent === void 0 ? {} : { ms_since_browser_event: close.msSinceBrowserEvent }
14502
+ };
14503
+ }
14504
+ var BrowserLifecycleMonitor = class {
14505
+ #listeners = [];
14506
+ #last = {};
14507
+ constructor() {
14508
+ const windowTarget = eventTarget(globalThis.window);
14509
+ const documentTarget = eventTarget(globalThis.document);
14510
+ if (windowTarget === void 0 || documentTarget === void 0) return;
14511
+ this.#listen(documentTarget, "visibilitychange", () => {
14512
+ this.#record(globalThis.document?.visibilityState === "hidden" ? "visibility-hidden" : "visibility-visible");
14513
+ });
14514
+ this.#listen(windowTarget, "pagehide", () => this.#record("pagehide"));
14515
+ this.#listen(windowTarget, "pageshow", () => this.#record("pageshow"));
14516
+ this.#listen(windowTarget, "online", () => this.#record("online"));
14517
+ this.#listen(windowTarget, "offline", () => this.#record("offline"));
14518
+ }
14519
+ socketClose(event) {
14520
+ const now = Date.now();
14521
+ return {
14522
+ code: event.code,
14523
+ wasClean: event.wasClean,
14524
+ reasonPresent: event.reason.length > 0,
14525
+ ...this.#last.event === void 0 ? {} : { browserEvent: this.#last.event },
14526
+ ...this.#last.at === void 0 ? {} : { msSinceBrowserEvent: Math.max(0, now - this.#last.at) },
14527
+ ...globalThis.document?.visibilityState === void 0 ? {} : { documentVisibility: globalThis.document.visibilityState },
14528
+ ...globalThis.navigator?.onLine === void 0 ? {} : { navigatorOnline: globalThis.navigator.onLine }
14529
+ };
14530
+ }
14531
+ close() {
14532
+ for (const [target, name, listener] of this.#listeners) target.removeEventListener(name, listener);
14533
+ this.#listeners.length = 0;
14534
+ }
14535
+ #listen(target, name, listener) {
14536
+ target.addEventListener(name, listener);
14537
+ this.#listeners.push([
14538
+ target,
14539
+ name,
14540
+ listener
14541
+ ]);
14542
+ }
14543
+ #record(event) {
14544
+ this.#last = {
14545
+ event,
14546
+ at: Date.now()
14547
+ };
14548
+ }
14549
+ };
14550
+ function eventTarget(value) {
14551
+ if (typeof value !== "object" || value === null || !("addEventListener" in value) || typeof value.addEventListener !== "function" || !("removeEventListener" in value) || typeof value.removeEventListener !== "function") return;
14552
+ return value;
14553
+ }
14554
+ let fallbackConnectionId = 0;
14555
+ function makeConnectionId() {
14556
+ try {
14557
+ return `convex_${globalThis.crypto.randomUUID()}`;
14558
+ } catch {
14559
+ fallbackConnectionId += 1;
14560
+ return `convex_${Date.now().toString(36)}_${fallbackConnectionId.toString(36)}`;
14561
+ }
14562
+ }
14563
+ //#endregion
14132
14564
  //#region ../../packages/sdk/src/adapters/convex-call/ConvexCallAdapter.ts
14133
14565
  /** Exact floor-first allowlist; every additional handler must migrate its validator first. */
14134
14566
  const OBSERVED_CONVEX_ACTIONS = /* @__PURE__ */ new Set([
14567
+ "account/actions:readBalance",
14568
+ "holdings/actions:current",
14135
14569
  "smartAccount/actions:claim",
14136
14570
  "org/actions:prepareFounderAccount",
14137
14571
  "org/actions:prepareBootstrap",
14138
14572
  "org/actions:submitBootstrap",
14139
14573
  "org/actions:resumeBootstrapSubmission",
14140
- "org/actions:confirmBootstrap"
14574
+ "org/actions:confirmBootstrap",
14575
+ "org/actions:readTreasury"
14141
14576
  ]);
14142
14577
  const OBSERVED_CONVEX_QUERIES = /* @__PURE__ */ new Set([
14143
14578
  "identity/queries:loadByAuthUserId",
@@ -14158,8 +14593,11 @@ var ConvexCallAdapter = class {
14158
14593
  #tokenProvider;
14159
14594
  #applicationId;
14160
14595
  #observation;
14596
+ #connectionMonitor;
14161
14597
  constructor(deps) {
14162
- this.#client = deps.client ?? new ConvexClient(deps.convexUrl);
14598
+ this.#connectionMonitor = new ConvexConnectionMonitor();
14599
+ const webSocketConstructor = this.#connectionMonitor.observedWebSocketConstructor();
14600
+ this.#client = deps.client ?? new ConvexClient(deps.convexUrl, webSocketConstructor === void 0 ? {} : { webSocketConstructor });
14163
14601
  this.#tokenProvider = deps.tokenProvider;
14164
14602
  this.#applicationId = deps.applicationId;
14165
14603
  this.#observation = deps.observation;
@@ -14168,6 +14606,9 @@ var ConvexCallAdapter = class {
14168
14606
  refreshAuth() {
14169
14607
  if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);
14170
14608
  }
14609
+ observeConnection(observer) {
14610
+ return this.#connectionMonitor.observe(this.#client, observer);
14611
+ }
14171
14612
  query(fn, args) {
14172
14613
  const path = getFunctionName(fn);
14173
14614
  return Effect.serviceOption(Tracer.ParentSpan).pipe(Effect.flatMap((parent) => {
@@ -14192,10 +14633,14 @@ var ConvexCallAdapter = class {
14192
14633
  const path = getFunctionName(fn);
14193
14634
  return Effect.serviceOption(Tracer.ParentSpan).pipe(Effect.flatMap((parent) => {
14194
14635
  const traceparent = parent._tag === "Some" ? formatTraceparent(parent.value) : void 0;
14636
+ const connectionAtStart = connectionState(this.#client);
14195
14637
  return Effect.tryPromise({
14196
14638
  try: () => this.#client.action(fn, this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args, traceparent)),
14197
- catch: (cause) => mapToConvexCallError(path, cause)
14198
- });
14639
+ catch: (cause) => {
14640
+ const transport = this.#connectionMonitor.reconnectEvidence(connectionAtStart, connectionState(this.#client));
14641
+ return mapToConvexCallError(path, cause, transport);
14642
+ }
14643
+ }).pipe(Effect.tapError((error) => logActionTransportFailure(path, error)));
14199
14644
  }));
14200
14645
  }
14201
14646
  #observedArgs(allowlist, path, args, traceparent) {
@@ -14249,24 +14694,52 @@ var ConvexCallAdapter = class {
14249
14694
  })));
14250
14695
  }
14251
14696
  async close() {
14697
+ this.#connectionMonitor.close();
14252
14698
  await this.#client.close();
14253
14699
  }
14254
14700
  };
14255
14701
  function ConvexCallLayer(deps) {
14256
14702
  return Layer.effect(ConvexCallPortTag, Effect.acquireRelease(Effect.sync(() => new ConvexCallAdapter(deps)), (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie)));
14257
14703
  }
14258
- function mapToCapxulError(operation, err) {
14704
+ function mapToCapxulError(operation, err, transport) {
14259
14705
  const decoded = decodeConvexError(err);
14260
14706
  if (decoded !== null) return decoded;
14261
14707
  if (err instanceof CapxulError) return err;
14708
+ if (transport !== void 0) {
14709
+ const { kind: _kind, start_connection_count: _start, ...connection } = transport;
14710
+ return Errors.networkError(operation, err, {
14711
+ provider: "convex",
14712
+ failure_mode: "upstream-down",
14713
+ reason: "connection-lost-in-flight",
14714
+ ...connection
14715
+ });
14716
+ }
14262
14717
  if (err instanceof Error) {
14263
- if (isTransportError(err)) return Errors.networkError(operation, err);
14718
+ if (isTransportError(err)) return Errors.networkError(operation, err, { provider: "convex" });
14264
14719
  return Errors.providerError("convex", operation, err);
14265
14720
  }
14266
14721
  return Errors.providerError("convex", operation, new Error(String(err)));
14267
14722
  }
14268
- function mapToConvexCallError(operation, err) {
14269
- return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err));
14723
+ function mapToConvexCallError(operation, err, transport) {
14724
+ return convexCallErrorFromCapxul(operation, mapToCapxulError(operation, err, transport), transport);
14725
+ }
14726
+ function connectionState(client) {
14727
+ try {
14728
+ const state = client.connectionState?.();
14729
+ return typeof state?.connectionCount === "number" ? state : void 0;
14730
+ } catch {
14731
+ return;
14732
+ }
14733
+ }
14734
+ function logActionTransportFailure(operation, error) {
14735
+ if (error.transport === void 0) return Effect.void;
14736
+ const { kind, ...connection } = error.transport;
14737
+ return Effect.logWarning("convex.action.connection_lost").pipe(Effect.annotateLogs({
14738
+ operation,
14739
+ failure_mode: "upstream-down",
14740
+ reason: kind,
14741
+ ...connection
14742
+ }), Effect.catchCause(() => Effect.void));
14270
14743
  }
14271
14744
  const TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
14272
14745
  "EAI_AGAIN",
@@ -14385,723 +14858,148 @@ function wireChainId(chainId) {
14385
14858
  return chainId;
14386
14859
  }
14387
14860
  //#endregion
14388
- //#region ../../packages/sdk/src/ports/account-read.ts
14389
- var AccountReadError = class extends Data.TaggedError("AccountReadError") {};
14390
- function accountReadErrorFromCapxul(operation, error, cause = error) {
14391
- return new AccountReadError({
14392
- operation,
14393
- publicCode: error.code,
14394
- publicError: error,
14395
- cause,
14396
- ...error.details === void 0 ? {} : { details: error.details }
14397
- });
14861
+ //#region ../../packages/sdk/src/telemetry/invocation.ts
14862
+ const PRODUCT_INVOCATION = Symbol("capxul.product-telemetry-invocation");
14863
+ function bindProductTelemetryInvocation(telemetry, source) {
14864
+ return telemetry[PRODUCT_INVOCATION]?.(source) ?? telemetry;
14398
14865
  }
14399
- var AccountReadPortTag = class extends Context.Service()("@capxul/sdk/ports/AccountReadPort") {};
14400
14866
  //#endregion
14401
- //#region ../../packages/sdk/src/adapters/account-read/ConvexAccountAdapter.ts
14402
- const DEFAULT_FUNCTIONS$3 = {
14403
- readBalance: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].readBalance),
14404
- faucetMint: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].faucetMint)
14405
- };
14406
- var ConvexAccountAdapter = class {
14407
- #convex;
14408
- #fns;
14409
- constructor(deps) {
14410
- this.#convex = deps.convex;
14411
- this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$3;
14412
- }
14413
- readBalance(input) {
14414
- return this.#convex.action(this.#fns.readBalance, { chainId: wireChainId(input.chainId) }).pipe(Effect.mapError((error) => accountReadErrorFromCapxul("readBalance", error.publicError, error)), Effect.flatMap((wire) => brandAccountEffect("readBalance", wire)), Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown("readBalance", cause))));
14415
- }
14416
- fundFromFaucet(input) {
14417
- const operation = "fundFromFaucet";
14418
- return Effect.suspend(() => {
14419
- const rawAmount = toWei(input.amount);
14420
- return this.#convex.action(this.#fns.faucetMint, {
14421
- chainId: wireChainId(input.chainId),
14422
- rawAmount
14423
- });
14424
- }).pipe(Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)), Effect.map((wire) => ({ txHash: wire.txHash })), Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))));
14425
- }
14426
- };
14427
- function ConvexAccountLayer() {
14428
- return Layer.effect(AccountReadPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })));
14429
- }
14430
- function brandAccountEffect(operation, wire) {
14431
- return Effect.try({
14432
- try: () => brandAccount(wire),
14433
- catch: (cause) => accountReadErrorFromUnknown(operation, cause)
14867
+ //#region ../../packages/sdk/src/adapters/convex-call/retry-idempotent-read.ts
14868
+ const MAX_RETRIES = 2;
14869
+ function isConnectionLoss(error) {
14870
+ return error.publicCode === "NETWORK_ERROR" && error.publicError.mode === "upstream-down" && error.publicError.details?.reason === "connection-lost-in-flight";
14871
+ }
14872
+ function retryIdempotentRead(effect, operation, telemetry, invocationSource) {
14873
+ return Effect.suspend(() => {
14874
+ let attempt = 0;
14875
+ const invocationTelemetry = telemetry === void 0 ? void 0 : bindProductTelemetryInvocation(telemetry, invocationSource);
14876
+ return effect.pipe(Effect.tapError((error) => {
14877
+ if (!isConnectionLoss(error) || attempt >= MAX_RETRIES) return Effect.void;
14878
+ attempt += 1;
14879
+ const eventFields = {
14880
+ operation,
14881
+ failure_mode: "upstream-down",
14882
+ reason: "connection-lost-in-flight",
14883
+ attempt,
14884
+ delay_ms: 0,
14885
+ ...error.transport === void 0 ? {} : {
14886
+ connection_id: error.transport.connection_id,
14887
+ connection_count: error.transport.connection_count
14888
+ }
14889
+ };
14890
+ const transport = error.transport;
14891
+ const connection = transport === void 0 ? void 0 : omitTransportKind(transport);
14892
+ const log = Effect.logInfo("capxul.operation.retried").pipe(Effect.annotateLogs(connection === void 0 ? eventFields : {
14893
+ ...eventFields,
14894
+ ...connection
14895
+ }), Effect.catchCause(() => Effect.void));
14896
+ if (invocationTelemetry === void 0) return log;
14897
+ return log.pipe(Effect.andThen(invocationTelemetry.emit({
14898
+ name: "operation_retried",
14899
+ props: eventFields
14900
+ })), Effect.catchCause(() => Effect.void));
14901
+ }), Effect.retry({
14902
+ times: MAX_RETRIES,
14903
+ while: isConnectionLoss
14904
+ }));
14434
14905
  });
14435
14906
  }
14436
- function brandAccount(wire) {
14437
- const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
14438
- const available = fromWei(wire.rawAvailableBalance ?? wire.rawBalance, wire.decimals, wire.currency);
14439
- return {
14440
- id: toAccountId(wire.accountId),
14441
- balance,
14442
- available
14443
- };
14444
- }
14445
- function accountReadErrorFromUnknown(operation, cause) {
14446
- if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);
14447
- return accountReadErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14448
- }
14449
- //#endregion
14450
- //#region ../../packages/sdk/src/ports/smart-account.ts
14451
- var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
14452
- function smartAccountErrorFromCapxul(operation, error, cause = error) {
14453
- return new SmartAccountError({
14454
- operation,
14455
- publicCode: error.code,
14456
- publicError: error,
14457
- cause,
14458
- ...error.details === void 0 ? {} : { details: error.details }
14459
- });
14907
+ function omitTransportKind(transport) {
14908
+ const { kind: _kind, ...connection } = transport;
14909
+ return connection;
14460
14910
  }
14461
- var SmartAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SmartAccountPort") {};
14462
14911
  //#endregion
14463
- //#region ../../packages/sdk/src/adapters/smart-account/ConvexSmartAccountAdapter.ts
14464
- const DEFAULT_FUNCTIONS$2 = {
14465
- loadByAuthUserId: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadByAuthUserId),
14466
- loadBySmartAccountAddress: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadBySmartAccountAddress),
14467
- provision: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/mutations"].provision),
14468
- confirmDeployment: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].confirmDeployment),
14469
- claim: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].claim)
14470
- };
14471
- var ConvexSmartAccountAdapter = class {
14472
- #convex;
14473
- #fns;
14474
- constructor(deps) {
14475
- this.#convex = deps.convex;
14476
- this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$2;
14477
- }
14478
- loadByAuthUserId(authUserId) {
14479
- return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("loadByAuthUserId", error.publicError, error)), Effect.flatMap((row) => brandSmartAccountEffect("loadByAuthUserId", row)), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("loadByAuthUserId", cause))));
14480
- }
14481
- loadBySmartAccountAddress(address) {
14482
- return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("loadBySmartAccountAddress", error.publicError, error)), Effect.flatMap((row) => brandSmartAccountEffect("loadBySmartAccountAddress", row)), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("loadBySmartAccountAddress", cause))));
14483
- }
14484
- provision(input) {
14485
- return this.#convex.mutation(this.#fns.provision, { chainId: wireChainId(input.chainId) }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("provision", error.publicError, error)), Effect.flatMap((row) => Effect.try({
14486
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14487
- catch: (cause) => smartAccountErrorFromUnknown("provision", cause)
14488
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("provision", cause))));
14489
- }
14490
- confirmDeployment(input) {
14491
- const evidence = {
14492
- chainId: wireChainId(input.evidence.chainId),
14493
- signerAddress: input.evidence.signerAddress,
14494
- safeAddress: input.evidence.safeAddress,
14495
- ...input.evidence.userOpHash === void 0 ? {} : { userOpHash: input.evidence.userOpHash },
14496
- ...input.evidence.txHash === void 0 ? {} : { txHash: input.evidence.txHash },
14497
- ...input.evidence.blockNumber === void 0 ? {} : { blockNumber: input.evidence.blockNumber }
14498
- };
14499
- return this.#convex.action(this.#fns.confirmDeployment, {
14500
- chainId: wireChainId(input.chainId),
14501
- safeAddress: input.safeAddress,
14502
- evidence
14503
- }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("confirmDeployment", error.publicError, error)), Effect.flatMap((row) => Effect.try({
14504
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14505
- catch: (cause) => smartAccountErrorFromUnknown("confirmDeployment", cause)
14506
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("confirmDeployment", cause))));
14507
- }
14508
- claim(input) {
14509
- return this.#convex.action(this.#fns.claim, copyInvocationObservation(input, {
14510
- chainId: wireChainId(input.chainId),
14511
- signerAddress: input.signerAddress
14512
- })).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("claim", error.publicError, error)), Effect.flatMap((row) => Effect.try({
14513
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14514
- catch: (cause) => smartAccountErrorFromUnknown("claim", cause)
14515
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("claim", cause))));
14516
- }
14912
+ //#region ../../packages/observability/src/index.ts
14913
+ const PII = Schema.String.pipe(Schema.brand("PII"));
14914
+ const OptionalString = Schema.optional(Schema.String);
14915
+ const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
14916
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
14917
+ encode: SchemaGetter.transform((value) => value)
14918
+ }), Schema.refine((value) => EVM_ADDRESS_RE$1.test(value), { message: "must be 0x + 40 hex chars" }));
14919
+ const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
14920
+ const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
14921
+ const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
14922
+ const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
14923
+ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
14924
+ const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
14925
+ const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE$1.test(value), { message: "must be 0x + 64 hex chars" }));
14926
+ const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
14927
+ const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
14928
+ const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
14929
+ const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
14930
+ const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
14931
+ const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
14932
+ const OptionalAccountId = Schema.optional(AccountIdSchema);
14933
+ const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
14934
+ const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
14935
+ const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
14936
+ const OptionalAddress = Schema.optional(AddressSchema);
14937
+ const OptionalAppId = Schema.optional(AppIdSchema);
14938
+ const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
14939
+ const OptionalChainId = Schema.optional(ChainIdSchema);
14940
+ const OptionalDurationMs = Schema.optional(DurationMsSchema);
14941
+ const OptionalEpochMs = Schema.optional(EpochMsSchema);
14942
+ const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
14943
+ const OptionalTxHash = Schema.optional(TxHashSchema);
14944
+ /**
14945
+ * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
14946
+ * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
14947
+ * decode instead of silently shipping an unattributable event. Call sites do
14948
+ * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
14949
+ * which is the only place that knows where the process runs.
14950
+ */
14951
+ const TelemetryEnvelopeProps = {
14952
+ capxul_env: Schema.Literals([
14953
+ "development",
14954
+ "staging",
14955
+ "production",
14956
+ "unknown",
14957
+ "local"
14958
+ ]),
14959
+ producer: Schema.Literals([
14960
+ "server",
14961
+ "browser",
14962
+ "sdk",
14963
+ "mcp",
14964
+ "e2e"
14965
+ ]),
14966
+ journey_id: OptionalString,
14967
+ correlation_id: OptionalString,
14968
+ sdk_version: OptionalString
14517
14969
  };
14518
- function ConvexSmartAccountLayer() {
14519
- return Layer.effect(SmartAccountPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })));
14520
- }
14521
- function brandSmartAccountEffect(operation, wire) {
14522
- return Effect.try({
14523
- try: () => wire === null ? null : brandNonNullSmartAccount(wire),
14524
- catch: (cause) => smartAccountErrorFromUnknown(operation, cause)
14525
- });
14526
- }
14527
- function brandNonNullSmartAccount(wire) {
14528
- return {
14529
- authUserId: toAuthUserId(wire.authUserId),
14530
- signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),
14531
- smartAccountAddress: toAddress(wire.smartAccountAddress),
14532
- chainId: toChainId(wire.chainId),
14533
- deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),
14534
- claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),
14535
- createdAt: toEpochMs(wire.createdAt)
14536
- };
14537
- }
14538
- function brandProvisionedSmartAccount(requestedAuthUserId, wire) {
14539
- if (wire.authUserId !== String(requestedAuthUserId)) throw Errors.notAuthenticated();
14540
- return brandNonNullSmartAccount(wire);
14541
- }
14542
- function smartAccountErrorFromUnknown(operation, cause) {
14543
- if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);
14544
- return smartAccountErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14545
- }
14546
- //#endregion
14547
- //#region ../../packages/sdk/src/ports/org.ts
14548
- var OrgError = class extends Data.TaggedError("OrgError") {};
14549
- function orgErrorFromCapxul(operation, error, cause = error) {
14550
- return new OrgError({
14551
- operation,
14552
- publicCode: error.code,
14553
- publicError: error,
14554
- cause,
14555
- ...error.details === void 0 ? {} : { details: error.details }
14556
- });
14557
- }
14558
- var OrgPortTag = class extends Context.Service()("@capxul/sdk/ports/OrgPort") {};
14559
- //#endregion
14560
- //#region ../../packages/sdk/src/adapters/org/parse.ts
14561
14970
  /**
14562
- * Map a `WireOrg` + its (separately read) treasury `Account` into the branded
14563
- * `OrgView`. The viewer role is projected by the authenticated backend read;
14564
- * it must never be inferred from Organization ownership. Brands at the read
14565
- * edge: `orgId`, `safeAddress`.
14971
+ * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
14972
+ * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
14973
+ * failure came from the chain path. Spread into every failure event and posted
14974
+ * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
14566
14975
  */
14567
- function brandOrgView(wire, treasury, viewerRole) {
14568
- return {
14569
- id: toOrgId(wire.orgId),
14570
- name: wire.name,
14571
- handle: wire.slug,
14572
- safeAddress: toAddress(wire.safeAddress.toLowerCase()),
14573
- role: viewerRole,
14574
- treasury,
14575
- bio: wire.bio ?? null,
14576
- size: wire.size ?? null,
14577
- logoUrl: wire.logoUrl ?? null
14578
- };
14579
- }
14976
+ const FailureModeSchema = Schema.Literals(FAILURE_MODES$1);
14977
+ const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
14978
+ const ChainCauseTelemetryProps = {
14979
+ failure_mode: Schema.optional(FailureModeSchema),
14980
+ chain_upstream: Schema.optional(ChainUpstreamSchema),
14981
+ chain_method: OptionalString,
14982
+ chain_retryable: Schema.optional(Schema.Boolean),
14983
+ chain_http_status: Schema.optional(Schema.Number),
14984
+ chain_rpc_code: Schema.optional(Schema.Number),
14985
+ chain_revert_name: OptionalString,
14986
+ chain_revert_selector: OptionalString,
14987
+ chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
14988
+ chain_provider_message: OptionalString
14989
+ };
14580
14990
  /**
14581
- * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer
14582
- * (the D3 RPC read). `available === balance` for a treasury with no envelope
14583
- * partition yet (a fresh Org reads back $0).
14991
+ * Stamp the required envelope onto an event at its emit boundary. Call-site
14992
+ * props win on conflict: a relay that already knows the true producer (the
14993
+ * browser-failure relay stamps `browser` while running on the server) must not
14994
+ * be overwritten by the transport's own default.
14584
14995
  */
14585
- function brandOrgTreasury(input) {
14586
- return {
14587
- id: toAccountId(`account_${orgIdBody(input.orgId)}`),
14588
- balance: input.money,
14589
- available: input.money
14590
- };
14591
- }
14592
- function brandOrgRole(wire) {
14996
+ function stampTelemetryEnvelope(event, defaults) {
14593
14997
  return {
14594
- orgId: toOrgId(wire.orgId),
14595
- label: wire.label,
14596
- roleKey: toRoleKey(wire.roleKey),
14597
- definition: parseRoleDefinition(wire.definitionJson)
14598
- };
14599
- }
14600
- function brandOrgMember(wire) {
14601
- return {
14602
- orgId: toOrgId(wire.orgId),
14603
- email: toEmail(wire.email),
14604
- name: wire.name,
14605
- personalSafeAddress: wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),
14606
- role: wire.role,
14607
- roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),
14608
- status: wire.status,
14609
- grantTxHash: wire.grantTxHash,
14610
- revokeTxHash: wire.revokeTxHash
14611
- };
14612
- }
14613
- function parseRoleDefinition(json) {
14614
- let raw;
14615
- try {
14616
- const parsed = JSON.parse(json);
14617
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("expected object");
14618
- raw = parsed;
14619
- } catch (err) {
14620
- throw new Error(`Invalid role definition: malformed JSON - ${err instanceof Error ? err.message : String(err)}`, { cause: err });
14621
- }
14622
- if (typeof raw.label !== "string" || raw.label.trim().length === 0) throw new Error("Invalid role definition: missing label");
14623
- return {
14624
- label: raw.label,
14625
- ...raw.spend === void 0 ? {} : { spend: {
14626
- ...raw.spend.perTx === void 0 ? {} : { perTx: parseRoleMoney(raw.spend.perTx, "perTx") },
14627
- ...raw.spend.perDay === void 0 ? {} : { perDay: parseRoleMoney(raw.spend.perDay, "perDay") },
14628
- ...raw.spend.toRecipients === void 0 ? {} : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }
14629
- } },
14630
- ...typeof raw.canSpend === "boolean" ? { canSpend: raw.canSpend } : {},
14631
- ...typeof raw.canManageMembers === "boolean" ? { canManageMembers: raw.canManageMembers } : {},
14632
- ...typeof raw.canManageRoles === "boolean" ? { canManageRoles: raw.canManageRoles } : {}
14633
- };
14634
- }
14635
- function parseRoleMoney(raw, field) {
14636
- if (typeof raw.currency !== "string" || typeof raw.value !== "string" || !/^\d+$/.test(raw.value) || raw.decimals !== 6) throw new Error(`Invalid role money: ${field}`);
14637
- return {
14638
- currency: toCurrencyCode(raw.currency),
14639
- value: raw.value,
14640
- decimals: raw.decimals
14641
- };
14642
- }
14643
- function parseRoleRecipients(raw) {
14644
- if (raw === "anyone") return "anyone";
14645
- if (!Array.isArray(raw)) throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
14646
- return raw.map((recipient) => {
14647
- if (typeof recipient !== "string") throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
14648
- return toAddress(recipient);
14649
- });
14650
- }
14651
- /** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */
14652
- function orgIdBody(orgId) {
14653
- const underscore = orgId.indexOf("_");
14654
- const cleaned = (underscore < 0 ? orgId : orgId.slice(underscore + 1)).replace(/[^0-9A-Za-z]/g, "");
14655
- return cleaned.length > 0 ? cleaned : "0";
14656
- }
14657
- //#endregion
14658
- //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationAdapter.ts
14659
- const DEFAULT_FUNCTIONS$1 = {
14660
- listAll: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listAll),
14661
- listRoles: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listRolesByOrgId),
14662
- listMembers: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listMembersByOrgId),
14663
- readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].readTreasury),
14664
- inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].inviteMember),
14665
- resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS["org/mutations"].resendInviteToken),
14666
- detectInvitations: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].detectAndAcceptPendingInvitations)
14667
- };
14668
- /**
14669
- * Standard production Organization read adapter. It intentionally has no
14670
- * deployer/RPC/test configuration: authenticated Convex actions own live chain
14671
- * reads, while the lifecycle adapter owns the single sponsored bootstrap.
14672
- */
14673
- var ConvexOrganizationAdapter = class {
14674
- #convex;
14675
- #fns;
14676
- constructor(input) {
14677
- this.#convex = input.convex;
14678
- this.#fns = input.functions ?? DEFAULT_FUNCTIONS$1;
14679
- }
14680
- createOrg(_input) {
14681
- return Effect.fail(orgErrorFromCapxul("createOrg", Errors.notImplemented("organizationSetup", "use onboarding.completeOrganization")));
14682
- }
14683
- listOrgs(_input) {
14684
- return this.#convex.query(this.#fns.listAll, {}).pipe(Effect.mapError((error) => orgErrorFromCapxul("listOrgs", error.publicError, error)), Effect.flatMap((wires) => Effect.forEach(wires, (wire) => this.#readTreasuryWire(wire.orgId).pipe(Effect.map((treasury) => {
14685
- const viewerRole = wire.viewerRole.trim();
14686
- if (viewerRole.length === 0) throw Errors.wrongState({
14687
- method: "listOrgs",
14688
- currentState: "viewerRoleMissing",
14689
- validStates: ["activeViewerRole"]
14690
- });
14691
- return brandOrgView(wire, treasury, viewerRole);
14692
- })))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listOrgs", cause))));
14693
- }
14694
- readTreasury(input) {
14695
- return this.#readTreasuryWire(String(input.orgId)).pipe(Effect.catchDefect((cause) => Effect.fail(toOrgError$1("readTreasury", cause))));
14696
- }
14697
- listRoles(input) {
14698
- return this.#convex.query(this.#fns.listRoles, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listRoles", error.publicError, error)), Effect.flatMap((rows) => rows.length === 0 ? Effect.fail(partialOrgTruth("listRoles", "activeRoleMissing")) : Effect.succeed(rows.map(brandOrgRole))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listRoles", cause))));
14699
- }
14700
- listMembers(input) {
14701
- return this.#convex.query(this.#fns.listMembers, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listMembers", error.publicError, error)), Effect.flatMap((rows) => rows.length === 0 ? Effect.fail(partialOrgTruth("listMembers", "activeMemberMissing")) : Effect.succeed(rows.map(brandOrgMember))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listMembers", cause))));
14702
- }
14703
- pendingMembers(input) {
14704
- return this.listMembers(input).pipe(Effect.map((members) => members.filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant")));
14705
- }
14706
- inviteMember(input) {
14707
- return this.#convex.action(this.#fns.inviteMember, {
14708
- orgId: input.orgId,
14709
- email: input.input.email,
14710
- role: input.input.role
14711
- }).pipe(Effect.mapError((error) => orgErrorFromCapxul("inviteMember", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("inviteMember", cause))));
14712
- }
14713
- resendInviteToken(input) {
14714
- return this.#convex.mutation(this.#fns.resendInvite, {
14715
- orgId: input.orgId,
14716
- email: input.email
14717
- }).pipe(Effect.mapError((error) => orgErrorFromCapxul("resendInviteToken", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("resendInviteToken", cause))));
14718
- }
14719
- detectAndAcceptPendingInvitations(_input) {
14720
- return this.#convex.action(this.#fns.detectInvitations, {}).pipe(Effect.mapError((error) => orgErrorFromCapxul("detectAndAcceptPendingInvitations", error.publicError, error)), Effect.map((result) => ({ matched: result.matched.map(toOrgId) })), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("detectAndAcceptPendingInvitations", cause))));
14721
- }
14722
- #readTreasuryWire(orgId) {
14723
- return this.#convex.action(this.#fns.readTreasury, { orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("readTreasury", error.publicError, error)), Effect.map((wire) => {
14724
- if (wire.orgId !== orgId) throw Errors.invalidInput("orgId", "Organization treasury scope does not match");
14725
- const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
14726
- const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);
14727
- return {
14728
- ...brandOrgTreasury({
14729
- orgId: wire.orgId,
14730
- money: balance
14731
- }),
14732
- available
14733
- };
14734
- }));
14735
- }
14736
- };
14737
- function toOrgError$1(operation, cause) {
14738
- if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);
14739
- return orgErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14740
- }
14741
- function partialOrgTruth(operation, currentState) {
14742
- return orgErrorFromCapxul(operation, Errors.wrongState({
14743
- method: operation,
14744
- currentState,
14745
- validStates: ["completeProductionOrganizationTruth"]
14746
- }));
14747
- }
14748
- //#endregion
14749
- //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationSetupAdapter.ts
14750
- const DEFAULT_FUNCTIONS = {
14751
- startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].startOrResume),
14752
- prepareFounderAccount: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareFounderAccount),
14753
- prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareBootstrap),
14754
- submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].submitBootstrap),
14755
- resumeBootstrapSubmission: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].resumeBootstrapSubmission),
14756
- confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].confirmBootstrap),
14757
- recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].recordFailure),
14758
- load: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].load),
14759
- retry: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].retry)
14760
- };
14761
- /** Durable Organization setup capability composed by the standard client. */
14762
- var ConvexOrganizationSetupAdapter = class {
14763
- #convex;
14764
- #signer;
14765
- #chainId;
14766
- #fns;
14767
- constructor(input) {
14768
- this.#convex = input.convex;
14769
- this.#signer = input.signer;
14770
- this.#chainId = input.chainId;
14771
- this.#fns = input.functions ?? DEFAULT_FUNCTIONS;
14772
- }
14773
- async startOrResume(input) {
14774
- const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, copyInvocationObservation(input, {
14775
- ...input,
14776
- chainId: this.#chainId
14777
- })));
14778
- if (!result.ok) return result;
14779
- const lifecycle = parseLifecycle("startOrResume", result.value.lifecycle);
14780
- if (!lifecycle.ok) return lifecycle;
14781
- const orgId = parseOrgId("startOrResume", result.value.orgId);
14782
- if (!orgId.ok) return orgId;
14783
- if (String(orgId.value) !== String(lifecycle.value.orgId)) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle scope does not match"));
14784
- return {
14785
- ok: true,
14786
- value: {
14787
- orgId: orgId.value,
14788
- lifecycle: lifecycle.value
14789
- }
14790
- };
14791
- }
14792
- prepareFounderAccount(input) {
14793
- return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, copyInvocationObservation(input, {
14794
- orgId: input.orgId,
14795
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14796
- })));
14797
- }
14798
- async authorizeAndSubmitBootstrap(input) {
14799
- const cancelled = cancellation(input.signal);
14800
- if (cancelled !== void 0) return cancelled;
14801
- const signerAddress = await signerResult(this.#signer.source, "getAddress", () => this.#signer.getAddress());
14802
- if (!signerAddress.ok) return signerAddress;
14803
- const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, copyInvocationObservation(input, {
14804
- orgId: input.orgId,
14805
- signerAddress: signerAddress.value,
14806
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14807
- })));
14808
- if (!prepared.ok) return prepared;
14809
- const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);
14810
- if (!authority.ok) return authority;
14811
- const cancelledAfterPrepare = cancellation(input.signal);
14812
- if (cancelledAfterPrepare !== void 0) return cancelledAfterPrepare;
14813
- const signature = await signerResult(this.#signer.source, "signUserOpHash", () => this.#signer.signUserOpHash(prepared.value.digest));
14814
- if (!signature.ok) return signature;
14815
- const cancelledAfterSign = cancellation(input.signal);
14816
- if (cancelledAfterSign !== void 0) return cancelledAfterSign;
14817
- const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, copyInvocationObservation(input, {
14818
- orgId: input.orgId,
14819
- signerAddress: signerAddress.value,
14820
- signature: signature.value,
14821
- userOp: prepared.value.userOp,
14822
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14823
- })));
14824
- if (!submitted.ok) return submitted;
14825
- return parseLifecycle("submitBootstrap", submitted.value);
14826
- }
14827
- resumeSubmittedBootstrap(input) {
14828
- return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, copyInvocationObservation(input, {
14829
- orgId: input.orgId,
14830
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14831
- })));
14832
- }
14833
- confirmSubmittedBootstrap(input) {
14834
- return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, copyInvocationObservation(input, {
14835
- orgId: input.orgId,
14836
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext },
14837
- ...input.retryDelayMs === void 0 ? {} : { retryDelayMs: input.retryDelayMs }
14838
- })));
14839
- }
14840
- async recordFailure(input) {
14841
- const errorProvider = input.error.details?.provider;
14842
- const errorOperation = input.error.details?.operation;
14843
- const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, copyInvocationObservation(input, {
14844
- orgId: input.orgId,
14845
- errorCode: input.error.code,
14846
- ...typeof errorProvider === "string" && typeof errorOperation === "string" ? {
14847
- errorProvider,
14848
- errorOperation
14849
- } : {},
14850
- retryable: input.retryable,
14851
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14852
- })));
14853
- return result.ok ? parseLifecycle("recordFailure", result.value) : result;
14854
- }
14855
- async loadLifecycle(input) {
14856
- const result = await runCall("loadLifecycle", this.#convex.query(this.#fns.load, input));
14857
- if (!result.ok) return result;
14858
- if (result.value === null) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle was not found"));
14859
- return parseLifecycle("loadLifecycle", result.value);
14860
- }
14861
- async retry(input) {
14862
- const cancelled = cancellation(input.signal);
14863
- if (cancelled !== void 0) return cancelled;
14864
- const current = await this.loadLifecycle({
14865
- orgId: input.orgId,
14866
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14867
- });
14868
- if (!current.ok) return current;
14869
- if (current.value.status === "failed" && current.value.retryable && (current.value.at === "awaitingFounderAuthorization" || current.value.at === "submittingBootstrap")) {
14870
- const reset = resetSignerSession(this.#signer);
14871
- if (!reset.ok) return reset;
14872
- }
14873
- const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, copyInvocationObservation(input, {
14874
- orgId: input.orgId,
14875
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14876
- })));
14877
- if (!result.ok) return result;
14878
- return parseLifecycle("retry", result.value);
14879
- }
14880
- async #lifecycleAction(operation, input, call) {
14881
- const cancelled = cancellation(input.signal);
14882
- if (cancelled !== void 0) return cancelled;
14883
- const result = await runCall(operation, call());
14884
- if (!result.ok) return result;
14885
- const cancelledAfter = cancellation(input.signal);
14886
- if (cancelledAfter !== void 0) return cancelledAfter;
14887
- return parseLifecycle(operation, result.value);
14888
- }
14889
- };
14890
- function resetSignerSession(signer) {
14891
- const resetSession = signer.resetSession;
14892
- if (typeof resetSession !== "function") return {
14893
- ok: true,
14894
- value: void 0
14895
- };
14896
- try {
14897
- resetSession.call(signer);
14898
- return {
14899
- ok: true,
14900
- value: void 0
14901
- };
14902
- } catch (cause) {
14903
- return fail$1(signerFailure(signer.source, "resetSession", cause));
14904
- }
14905
- }
14906
- async function runCall(operation, effect) {
14907
- try {
14908
- const result = await Effect.runPromise(Effect.result(effect));
14909
- return Result.isSuccess(result) ? {
14910
- ok: true,
14911
- value: result.success
14912
- } : fail$1(publicError(operation, result.failure));
14913
- } catch (cause) {
14914
- return fail$1(publicError(operation, cause));
14915
- }
14916
- }
14917
- function publicError(operation, cause) {
14918
- if (cause instanceof CapxulError) return cause;
14919
- if (typeof cause === "object" && cause !== null) {
14920
- const carried = cause.publicError;
14921
- if (carried instanceof CapxulError) return carried;
14922
- }
14923
- return Errors.providerError("convex-organization", operation, cause);
14924
- }
14925
- async function signerResult(source, operation, run) {
14926
- try {
14927
- return {
14928
- ok: true,
14929
- value: await run()
14930
- };
14931
- } catch (cause) {
14932
- return fail$1(signerFailure(source, operation, cause));
14933
- }
14934
- }
14935
- function validatePreparedAuthorities(prepared, signerAddress) {
14936
- const signer = signerAddress.toLowerCase();
14937
- const preparedSigner = prepared.signerAddress.toLowerCase();
14938
- const founder = prepared.founderPersonalAccount.toLowerCase();
14939
- const organization = prepared.organizationAccountAddress.toLowerCase();
14940
- const sender = prepared.userOp.sender.toLowerCase();
14941
- if (preparedSigner !== signer) return fail$1(Errors.invalidInput("signerAddress", "Prepared signer does not match configured signer"));
14942
- if (founder === signer || organization === signer || organization === founder) return fail$1(Errors.invalidInput("organizationAuthority", "Signer EOA, founder Account, and Organization Account must be distinct"));
14943
- if (sender !== founder) return fail$1(Errors.invalidInput("userOp.sender", "Bootstrap sender must be the founder Account"));
14944
- if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) return fail$1(Errors.invalidInput("digest", "Prepared bootstrap digest must be 32-byte hex"));
14945
- return {
14946
- ok: true,
14947
- value: void 0
14948
- };
14949
- }
14950
- function parseLifecycle(operation, wire) {
14951
- const orgId = parseOrgId(operation, wire.orgId);
14952
- if (!orgId.ok) return orgId;
14953
- if (wire.status === "loading") return {
14954
- ok: true,
14955
- value: {
14956
- status: "loading",
14957
- orgId: orgId.value
14958
- }
14959
- };
14960
- if (wire.status === "ready") return {
14961
- ok: true,
14962
- value: {
14963
- status: "ready",
14964
- orgId: orgId.value,
14965
- canTransact: true
14966
- }
14967
- };
14968
- if (wire.status === "failed") {
14969
- if (!isSetupStep(wire.at)) return fail$1(Errors.invalidInput("lifecycle.at", "Unknown setup step"));
14970
- return {
14971
- ok: true,
14972
- value: {
14973
- status: "failed",
14974
- orgId: orgId.value,
14975
- at: wire.at,
14976
- error: new CapxulError(wire.error.code, wire.error.message),
14977
- retryable: wire.retryable
14978
- }
14979
- };
14980
- }
14981
- if (!isSetupStep(wire.step)) return fail$1(Errors.invalidInput("lifecycle.step", `Unknown setup step from ${operation}`));
14982
- return {
14983
- ok: true,
14984
- value: {
14985
- status: "settingUp",
14986
- orgId: orgId.value,
14987
- step: wire.step
14988
- }
14989
- };
14990
- }
14991
- function parseOrgId(operation, value) {
14992
- try {
14993
- return {
14994
- ok: true,
14995
- value: toOrgId(value)
14996
- };
14997
- } catch (cause) {
14998
- return fail$1(Errors.providerError("convex-organization", operation, cause));
14999
- }
15000
- }
15001
- function isSetupStep(value) {
15002
- return value === "preparingFounderAccount" || value === "awaitingFounderAuthorization" || value === "submittingBootstrap" || value === "confirmingBootstrap";
15003
- }
15004
- function cancellation(signal) {
15005
- return signal?.aborted ? fail$1(Errors.cancelled({ operation: "organization.setup" })) : void 0;
15006
- }
15007
- function fail$1(error) {
15008
- return {
15009
- ok: false,
15010
- error
15011
- };
15012
- }
15013
- //#endregion
15014
- //#region ../../packages/observability/src/index.ts
15015
- const PII = Schema.String.pipe(Schema.brand("PII"));
15016
- const OptionalString = Schema.optional(Schema.String);
15017
- const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
15018
- decode: SchemaGetter.transform((value) => value.toLowerCase()),
15019
- encode: SchemaGetter.transform((value) => value)
15020
- }), Schema.refine((value) => EVM_ADDRESS_RE$1.test(value), { message: "must be 0x + 40 hex chars" }));
15021
- const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
15022
- const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15023
- const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
15024
- const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15025
- const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15026
- const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
15027
- const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE$1.test(value), { message: "must be 0x + 64 hex chars" }));
15028
- const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
15029
- const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
15030
- const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
15031
- const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
15032
- const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
15033
- const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
15034
- const OptionalAccountId = Schema.optional(AccountIdSchema);
15035
- const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
15036
- const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
15037
- const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
15038
- const OptionalAddress = Schema.optional(AddressSchema);
15039
- const OptionalAppId = Schema.optional(AppIdSchema);
15040
- const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
15041
- const OptionalChainId = Schema.optional(ChainIdSchema);
15042
- const OptionalDurationMs = Schema.optional(DurationMsSchema);
15043
- const OptionalEpochMs = Schema.optional(EpochMsSchema);
15044
- const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
15045
- const OptionalTxHash = Schema.optional(TxHashSchema);
15046
- /**
15047
- * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
15048
- * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
15049
- * decode instead of silently shipping an unattributable event. Call sites do
15050
- * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
15051
- * which is the only place that knows where the process runs.
15052
- */
15053
- const TelemetryEnvelopeProps = {
15054
- capxul_env: Schema.Literals([
15055
- "development",
15056
- "staging",
15057
- "production",
15058
- "unknown",
15059
- "local"
15060
- ]),
15061
- producer: Schema.Literals([
15062
- "server",
15063
- "browser",
15064
- "sdk",
15065
- "mcp",
15066
- "e2e"
15067
- ]),
15068
- journey_id: OptionalString,
15069
- correlation_id: OptionalString,
15070
- sdk_version: OptionalString
15071
- };
15072
- /**
15073
- * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
15074
- * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
15075
- * failure came from the chain path. Spread into every failure event and posted
15076
- * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
15077
- */
15078
- const FailureModeSchema = Schema.Literals(FAILURE_MODES$1);
15079
- const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
15080
- const ChainCauseTelemetryProps = {
15081
- failure_mode: Schema.optional(FailureModeSchema),
15082
- chain_upstream: Schema.optional(ChainUpstreamSchema),
15083
- chain_method: OptionalString,
15084
- chain_retryable: Schema.optional(Schema.Boolean),
15085
- chain_http_status: Schema.optional(Schema.Number),
15086
- chain_rpc_code: Schema.optional(Schema.Number),
15087
- chain_revert_name: OptionalString,
15088
- chain_revert_selector: OptionalString,
15089
- chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
15090
- chain_provider_message: OptionalString
15091
- };
15092
- /**
15093
- * Stamp the required envelope onto an event at its emit boundary. Call-site
15094
- * props win on conflict: a relay that already knows the true producer (the
15095
- * browser-failure relay stamps `browser` while running on the server) must not
15096
- * be overwritten by the transport's own default.
15097
- */
15098
- function stampTelemetryEnvelope(event, defaults) {
15099
- return {
15100
- name: event.name,
15101
- props: {
15102
- ...defaults,
15103
- ...event.props
15104
- }
14998
+ name: event.name,
14999
+ props: {
15000
+ ...defaults,
15001
+ ...event.props
15002
+ }
15105
15003
  };
15106
15004
  }
15107
15005
  const AuthOtpRequestedProps = Schema.Struct({
@@ -15161,7 +15059,10 @@ const BootstrapFailedProps = Schema.Struct({
15161
15059
  applicationId: OptionalAppId,
15162
15060
  durationMs: OptionalDurationMs,
15163
15061
  origin: OptionalString,
15164
- reason: OptionalString
15062
+ provider: OptionalString,
15063
+ provider_operation: OptionalString,
15064
+ reason: OptionalString,
15065
+ target_host: OptionalString
15165
15066
  });
15166
15067
  const AccountBalanceReadProps = Schema.Struct({
15167
15068
  ...TelemetryEnvelopeProps,
@@ -15226,6 +15127,9 @@ const OperationRetriedProps = Schema.Struct({
15226
15127
  ...TelemetryEnvelopeProps,
15227
15128
  operation: Schema.String,
15228
15129
  failure_mode: FailureModeSchema,
15130
+ reason: Schema.optional(Schema.Literal("connection-lost-in-flight")),
15131
+ connection_id: OptionalString,
15132
+ connection_count: Schema.optional(Schema.Number),
15229
15133
  attempt: Schema.Number,
15230
15134
  delay_ms: DurationMsSchema
15231
15135
  });
@@ -15402,7 +15306,9 @@ const PaymentVerificationRetryProps = Schema.Struct({
15402
15306
  command_id: Schema.String,
15403
15307
  attempt: Schema.Number,
15404
15308
  reason_code: Schema.String,
15405
- chain_id: Schema.Number
15309
+ chain_id: Schema.Number,
15310
+ delay_ms: DurationMsSchema,
15311
+ outcome: Schema.Literals(["scheduled", "unresolved"])
15406
15312
  });
15407
15313
  const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
15408
15314
  const DepositSettledProps = Schema.Struct({
@@ -15636,190 +15542,824 @@ const TELEMETRY_EVENT_SCHEMAS = {
15636
15542
  props: MovementScanIncidentProps
15637
15543
  })
15638
15544
  };
15639
- function redactTelemetryProps(name, props, options = {}) {
15640
- if (props === void 0) return void 0;
15641
- const clone = cloneProps$1(props);
15642
- if (options.rawMode === true) return clone;
15643
- for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
15644
- return clone;
15545
+ function redactTelemetryProps(name, props, options = {}) {
15546
+ if (props === void 0) return void 0;
15547
+ const clone = cloneProps$1(props);
15548
+ if (options.rawMode === true) return clone;
15549
+ for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
15550
+ return clone;
15551
+ }
15552
+ const PII_PROP_KEYS_BY_EVENT = {
15553
+ auth_otp_requested: ["email"],
15554
+ auth_otp_delivered: ["email"],
15555
+ auth_otp_expired: ["email"],
15556
+ auth_failed: ["email"]
15557
+ };
15558
+ function redactProperty(props, key) {
15559
+ const value = props[key];
15560
+ if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
15561
+ }
15562
+ function cloneProps$1(props) {
15563
+ const cloned = {};
15564
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue$1(value);
15565
+ return cloned;
15566
+ }
15567
+ function cloneTelemetryValue$1(value) {
15568
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue$1);
15569
+ if (value === null || typeof value !== "object") return value;
15570
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
15571
+ const cloned = {};
15572
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue$1(nested);
15573
+ return cloned;
15574
+ }
15575
+ const SHA256_INITIAL_HASH = [
15576
+ 1779033703,
15577
+ 3144134277,
15578
+ 1013904242,
15579
+ 2773480762,
15580
+ 1359893119,
15581
+ 2600822924,
15582
+ 528734635,
15583
+ 1541459225
15584
+ ];
15585
+ const SHA256_K = [
15586
+ 1116352408,
15587
+ 1899447441,
15588
+ 3049323471,
15589
+ 3921009573,
15590
+ 961987163,
15591
+ 1508970993,
15592
+ 2453635748,
15593
+ 2870763221,
15594
+ 3624381080,
15595
+ 310598401,
15596
+ 607225278,
15597
+ 1426881987,
15598
+ 1925078388,
15599
+ 2162078206,
15600
+ 2614888103,
15601
+ 3248222580,
15602
+ 3835390401,
15603
+ 4022224774,
15604
+ 264347078,
15605
+ 604807628,
15606
+ 770255983,
15607
+ 1249150122,
15608
+ 1555081692,
15609
+ 1996064986,
15610
+ 2554220882,
15611
+ 2821834349,
15612
+ 2952996808,
15613
+ 3210313671,
15614
+ 3336571891,
15615
+ 3584528711,
15616
+ 113926993,
15617
+ 338241895,
15618
+ 666307205,
15619
+ 773529912,
15620
+ 1294757372,
15621
+ 1396182291,
15622
+ 1695183700,
15623
+ 1986661051,
15624
+ 2177026350,
15625
+ 2456956037,
15626
+ 2730485921,
15627
+ 2820302411,
15628
+ 3259730800,
15629
+ 3345764771,
15630
+ 3516065817,
15631
+ 3600352804,
15632
+ 4094571909,
15633
+ 275423344,
15634
+ 430227734,
15635
+ 506948616,
15636
+ 659060556,
15637
+ 883997877,
15638
+ 958139571,
15639
+ 1322822218,
15640
+ 1537002063,
15641
+ 1747873779,
15642
+ 1955562222,
15643
+ 2024104815,
15644
+ 2227730452,
15645
+ 2361852424,
15646
+ 2428436474,
15647
+ 2756734187,
15648
+ 3204031479,
15649
+ 3329325298
15650
+ ];
15651
+ function sha256Hex(input) {
15652
+ const padded = padSha256Message(new TextEncoder().encode(input));
15653
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
15654
+ const words = /* @__PURE__ */ new Uint32Array(64);
15655
+ let h0 = SHA256_INITIAL_HASH[0];
15656
+ let h1 = SHA256_INITIAL_HASH[1];
15657
+ let h2 = SHA256_INITIAL_HASH[2];
15658
+ let h3 = SHA256_INITIAL_HASH[3];
15659
+ let h4 = SHA256_INITIAL_HASH[4];
15660
+ let h5 = SHA256_INITIAL_HASH[5];
15661
+ let h6 = SHA256_INITIAL_HASH[6];
15662
+ let h7 = SHA256_INITIAL_HASH[7];
15663
+ for (let offset = 0; offset < padded.byteLength; offset += 64) {
15664
+ for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
15665
+ for (let i = 16; i < 64; i++) {
15666
+ const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
15667
+ const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
15668
+ words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
15669
+ }
15670
+ let a = h0;
15671
+ let b = h1;
15672
+ let c = h2;
15673
+ let d = h3;
15674
+ let e = h4;
15675
+ let f = h5;
15676
+ let g = h6;
15677
+ let h = h7;
15678
+ for (let i = 0; i < 64; i++) {
15679
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
15680
+ const ch = e & f ^ ~e & g;
15681
+ const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
15682
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
15683
+ h = g;
15684
+ g = f;
15685
+ f = e;
15686
+ e = d + temp1 >>> 0;
15687
+ d = c;
15688
+ c = b;
15689
+ b = a;
15690
+ a = temp1 + temp2 >>> 0;
15691
+ }
15692
+ h0 = h0 + a >>> 0;
15693
+ h1 = h1 + b >>> 0;
15694
+ h2 = h2 + c >>> 0;
15695
+ h3 = h3 + d >>> 0;
15696
+ h4 = h4 + e >>> 0;
15697
+ h5 = h5 + f >>> 0;
15698
+ h6 = h6 + g >>> 0;
15699
+ h7 = h7 + h >>> 0;
15700
+ }
15701
+ return [
15702
+ h0,
15703
+ h1,
15704
+ h2,
15705
+ h3,
15706
+ h4,
15707
+ h5,
15708
+ h6,
15709
+ h7
15710
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
15711
+ }
15712
+ function padSha256Message(bytes) {
15713
+ const bitLength = bytes.byteLength * 8;
15714
+ const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
15715
+ const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
15716
+ output.set(bytes);
15717
+ output[bytes.byteLength] = 128;
15718
+ const view = new DataView(output.buffer);
15719
+ view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
15720
+ view.setUint32(output.byteLength - 4, bitLength >>> 0);
15721
+ return output;
15722
+ }
15723
+ function rotr(value, bits) {
15724
+ return value >>> bits | value << 32 - bits;
15725
+ }
15726
+ //#endregion
15727
+ //#region ../../packages/sdk/src/ports/telemetry.ts
15728
+ var TelemetryPortTag = class extends Context.Service()("@capxul/sdk/ports/TelemetryPort") {};
15729
+ //#endregion
15730
+ //#region ../../packages/sdk/src/ports/account-read.ts
15731
+ var AccountReadError = class extends Data.TaggedError("AccountReadError") {};
15732
+ function accountReadErrorFromCapxul(operation, error, cause = error) {
15733
+ return new AccountReadError({
15734
+ operation,
15735
+ publicCode: error.code,
15736
+ publicError: error,
15737
+ cause,
15738
+ ...error.details === void 0 ? {} : { details: error.details }
15739
+ });
15740
+ }
15741
+ var AccountReadPortTag = class extends Context.Service()("@capxul/sdk/ports/AccountReadPort") {};
15742
+ //#endregion
15743
+ //#region ../../packages/sdk/src/adapters/account-read/ConvexAccountAdapter.ts
15744
+ const DEFAULT_FUNCTIONS$3 = {
15745
+ readBalance: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].readBalance),
15746
+ faucetMint: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].faucetMint)
15747
+ };
15748
+ var ConvexAccountAdapter = class {
15749
+ #convex;
15750
+ #fns;
15751
+ #telemetry;
15752
+ constructor(deps) {
15753
+ this.#convex = deps.convex;
15754
+ this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$3;
15755
+ this.#telemetry = deps.telemetry;
15756
+ }
15757
+ readBalance(input) {
15758
+ return retryIdempotentRead(this.#convex.action(this.#fns.readBalance, copyInvocationObservation(input, { chainId: wireChainId(input.chainId) })), "accounts.read", this.#telemetry, input).pipe(Effect.mapError((error) => accountReadErrorFromCapxul("readBalance", error.publicError, error)), Effect.flatMap((wire) => brandAccountEffect("readBalance", wire)), Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown("readBalance", cause))));
15759
+ }
15760
+ fundFromFaucet(input) {
15761
+ const operation = "fundFromFaucet";
15762
+ return Effect.suspend(() => {
15763
+ const rawAmount = toWei(input.amount);
15764
+ return this.#convex.action(this.#fns.faucetMint, {
15765
+ chainId: wireChainId(input.chainId),
15766
+ rawAmount
15767
+ });
15768
+ }).pipe(Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)), Effect.map((wire) => ({ txHash: wire.txHash })), Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))));
15769
+ }
15770
+ };
15771
+ function ConvexAccountLayer() {
15772
+ return Layer.effect(AccountReadPortTag, Effect.all([ConvexCallPortTag, TelemetryPortTag]).pipe(Effect.map(([convex, telemetry]) => new ConvexAccountAdapter({
15773
+ convex,
15774
+ telemetry
15775
+ }))));
15776
+ }
15777
+ function brandAccountEffect(operation, wire) {
15778
+ return Effect.try({
15779
+ try: () => brandAccount(wire),
15780
+ catch: (cause) => accountReadErrorFromUnknown(operation, cause)
15781
+ });
15782
+ }
15783
+ function brandAccount(wire) {
15784
+ const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
15785
+ const available = fromWei(wire.rawAvailableBalance ?? wire.rawBalance, wire.decimals, wire.currency);
15786
+ return {
15787
+ id: toAccountId(wire.accountId),
15788
+ balance,
15789
+ available
15790
+ };
15791
+ }
15792
+ function accountReadErrorFromUnknown(operation, cause) {
15793
+ if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);
15794
+ return accountReadErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
15795
+ }
15796
+ //#endregion
15797
+ //#region ../../packages/sdk/src/ports/smart-account.ts
15798
+ var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
15799
+ function smartAccountErrorFromCapxul(operation, error, cause = error) {
15800
+ return new SmartAccountError({
15801
+ operation,
15802
+ publicCode: error.code,
15803
+ publicError: error,
15804
+ cause,
15805
+ ...error.details === void 0 ? {} : { details: error.details }
15806
+ });
15807
+ }
15808
+ var SmartAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SmartAccountPort") {};
15809
+ //#endregion
15810
+ //#region ../../packages/sdk/src/adapters/smart-account/ConvexSmartAccountAdapter.ts
15811
+ const DEFAULT_FUNCTIONS$2 = {
15812
+ loadByAuthUserId: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadByAuthUserId),
15813
+ loadBySmartAccountAddress: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadBySmartAccountAddress),
15814
+ provision: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/mutations"].provision),
15815
+ confirmDeployment: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].confirmDeployment),
15816
+ claim: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].claim)
15817
+ };
15818
+ var ConvexSmartAccountAdapter = class {
15819
+ #convex;
15820
+ #fns;
15821
+ constructor(deps) {
15822
+ this.#convex = deps.convex;
15823
+ this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$2;
15824
+ }
15825
+ loadByAuthUserId(authUserId) {
15826
+ return this.#convex.query(this.#fns.loadByAuthUserId, { authUserId }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("loadByAuthUserId", error.publicError, error)), Effect.flatMap((row) => brandSmartAccountEffect("loadByAuthUserId", row)), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("loadByAuthUserId", cause))));
15827
+ }
15828
+ loadBySmartAccountAddress(address) {
15829
+ return this.#convex.query(this.#fns.loadBySmartAccountAddress, { address }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("loadBySmartAccountAddress", error.publicError, error)), Effect.flatMap((row) => brandSmartAccountEffect("loadBySmartAccountAddress", row)), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("loadBySmartAccountAddress", cause))));
15830
+ }
15831
+ provision(input) {
15832
+ return this.#convex.mutation(this.#fns.provision, { chainId: wireChainId(input.chainId) }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("provision", error.publicError, error)), Effect.flatMap((row) => Effect.try({
15833
+ try: () => brandProvisionedSmartAccount(input.authUserId, row),
15834
+ catch: (cause) => smartAccountErrorFromUnknown("provision", cause)
15835
+ })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("provision", cause))));
15836
+ }
15837
+ confirmDeployment(input) {
15838
+ const evidence = {
15839
+ chainId: wireChainId(input.evidence.chainId),
15840
+ signerAddress: input.evidence.signerAddress,
15841
+ safeAddress: input.evidence.safeAddress,
15842
+ ...input.evidence.userOpHash === void 0 ? {} : { userOpHash: input.evidence.userOpHash },
15843
+ ...input.evidence.txHash === void 0 ? {} : { txHash: input.evidence.txHash },
15844
+ ...input.evidence.blockNumber === void 0 ? {} : { blockNumber: input.evidence.blockNumber }
15845
+ };
15846
+ return this.#convex.action(this.#fns.confirmDeployment, {
15847
+ chainId: wireChainId(input.chainId),
15848
+ safeAddress: input.safeAddress,
15849
+ evidence
15850
+ }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("confirmDeployment", error.publicError, error)), Effect.flatMap((row) => Effect.try({
15851
+ try: () => brandProvisionedSmartAccount(input.authUserId, row),
15852
+ catch: (cause) => smartAccountErrorFromUnknown("confirmDeployment", cause)
15853
+ })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("confirmDeployment", cause))));
15854
+ }
15855
+ claim(input) {
15856
+ return this.#convex.action(this.#fns.claim, copyInvocationObservation(input, {
15857
+ chainId: wireChainId(input.chainId),
15858
+ signerAddress: input.signerAddress
15859
+ })).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("claim", error.publicError, error)), Effect.flatMap((row) => Effect.try({
15860
+ try: () => brandProvisionedSmartAccount(input.authUserId, row),
15861
+ catch: (cause) => smartAccountErrorFromUnknown("claim", cause)
15862
+ })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("claim", cause))));
15863
+ }
15864
+ };
15865
+ function ConvexSmartAccountLayer() {
15866
+ return Layer.effect(SmartAccountPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })));
15867
+ }
15868
+ function brandSmartAccountEffect(operation, wire) {
15869
+ return Effect.try({
15870
+ try: () => wire === null ? null : brandNonNullSmartAccount(wire),
15871
+ catch: (cause) => smartAccountErrorFromUnknown(operation, cause)
15872
+ });
15873
+ }
15874
+ function brandNonNullSmartAccount(wire) {
15875
+ return {
15876
+ authUserId: toAuthUserId(wire.authUserId),
15877
+ signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),
15878
+ smartAccountAddress: toAddress(wire.smartAccountAddress),
15879
+ chainId: toChainId(wire.chainId),
15880
+ deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),
15881
+ claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),
15882
+ createdAt: toEpochMs(wire.createdAt)
15883
+ };
15884
+ }
15885
+ function brandProvisionedSmartAccount(requestedAuthUserId, wire) {
15886
+ if (wire.authUserId !== String(requestedAuthUserId)) throw Errors.notAuthenticated();
15887
+ return brandNonNullSmartAccount(wire);
15888
+ }
15889
+ function smartAccountErrorFromUnknown(operation, cause) {
15890
+ if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);
15891
+ return smartAccountErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
15892
+ }
15893
+ //#endregion
15894
+ //#region ../../packages/sdk/src/ports/org.ts
15895
+ var OrgError = class extends Data.TaggedError("OrgError") {};
15896
+ function orgErrorFromCapxul(operation, error, cause = error) {
15897
+ return new OrgError({
15898
+ operation,
15899
+ publicCode: error.code,
15900
+ publicError: error,
15901
+ cause,
15902
+ ...error.details === void 0 ? {} : { details: error.details }
15903
+ });
15904
+ }
15905
+ var OrgPortTag = class extends Context.Service()("@capxul/sdk/ports/OrgPort") {};
15906
+ //#endregion
15907
+ //#region ../../packages/sdk/src/adapters/org/parse.ts
15908
+ /**
15909
+ * Map a `WireOrg` + its (separately read) treasury `Account` into the branded
15910
+ * `OrgView`. The viewer role is projected by the authenticated backend read;
15911
+ * it must never be inferred from Organization ownership. Brands at the read
15912
+ * edge: `orgId`, `safeAddress`.
15913
+ */
15914
+ function brandOrgView(wire, treasury, viewerRole) {
15915
+ return {
15916
+ id: toOrgId(wire.orgId),
15917
+ name: wire.name,
15918
+ handle: wire.slug,
15919
+ safeAddress: toAddress(wire.safeAddress.toLowerCase()),
15920
+ role: viewerRole,
15921
+ treasury,
15922
+ bio: wire.bio ?? null,
15923
+ size: wire.size ?? null,
15924
+ logoUrl: wire.logoUrl ?? null
15925
+ };
15926
+ }
15927
+ /**
15928
+ * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer
15929
+ * (the D3 RPC read). `available === balance` for a treasury with no envelope
15930
+ * partition yet (a fresh Org reads back $0).
15931
+ */
15932
+ function brandOrgTreasury(input) {
15933
+ return {
15934
+ id: toAccountId(`account_${orgIdBody(input.orgId)}`),
15935
+ balance: input.money,
15936
+ available: input.money
15937
+ };
15938
+ }
15939
+ function brandOrgRole(wire) {
15940
+ return {
15941
+ orgId: toOrgId(wire.orgId),
15942
+ label: wire.label,
15943
+ roleKey: toRoleKey(wire.roleKey),
15944
+ definition: parseRoleDefinition(wire.definitionJson)
15945
+ };
15946
+ }
15947
+ function brandOrgMember(wire) {
15948
+ return {
15949
+ orgId: toOrgId(wire.orgId),
15950
+ email: toEmail(wire.email),
15951
+ name: wire.name,
15952
+ personalSafeAddress: wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),
15953
+ role: wire.role,
15954
+ roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),
15955
+ status: wire.status,
15956
+ grantTxHash: wire.grantTxHash,
15957
+ revokeTxHash: wire.revokeTxHash
15958
+ };
15959
+ }
15960
+ function parseRoleDefinition(json) {
15961
+ let raw;
15962
+ try {
15963
+ const parsed = JSON.parse(json);
15964
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("expected object");
15965
+ raw = parsed;
15966
+ } catch (err) {
15967
+ throw new Error(`Invalid role definition: malformed JSON - ${err instanceof Error ? err.message : String(err)}`, { cause: err });
15968
+ }
15969
+ if (typeof raw.label !== "string" || raw.label.trim().length === 0) throw new Error("Invalid role definition: missing label");
15970
+ return {
15971
+ label: raw.label,
15972
+ ...raw.spend === void 0 ? {} : { spend: {
15973
+ ...raw.spend.perTx === void 0 ? {} : { perTx: parseRoleMoney(raw.spend.perTx, "perTx") },
15974
+ ...raw.spend.perDay === void 0 ? {} : { perDay: parseRoleMoney(raw.spend.perDay, "perDay") },
15975
+ ...raw.spend.toRecipients === void 0 ? {} : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }
15976
+ } },
15977
+ ...typeof raw.canSpend === "boolean" ? { canSpend: raw.canSpend } : {},
15978
+ ...typeof raw.canManageMembers === "boolean" ? { canManageMembers: raw.canManageMembers } : {},
15979
+ ...typeof raw.canManageRoles === "boolean" ? { canManageRoles: raw.canManageRoles } : {}
15980
+ };
15981
+ }
15982
+ function parseRoleMoney(raw, field) {
15983
+ if (typeof raw.currency !== "string" || typeof raw.value !== "string" || !/^\d+$/.test(raw.value) || raw.decimals !== 6) throw new Error(`Invalid role money: ${field}`);
15984
+ return {
15985
+ currency: toCurrencyCode(raw.currency),
15986
+ value: raw.value,
15987
+ decimals: raw.decimals
15988
+ };
15989
+ }
15990
+ function parseRoleRecipients(raw) {
15991
+ if (raw === "anyone") return "anyone";
15992
+ if (!Array.isArray(raw)) throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
15993
+ return raw.map((recipient) => {
15994
+ if (typeof recipient !== "string") throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
15995
+ return toAddress(recipient);
15996
+ });
15997
+ }
15998
+ /** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */
15999
+ function orgIdBody(orgId) {
16000
+ const underscore = orgId.indexOf("_");
16001
+ const cleaned = (underscore < 0 ? orgId : orgId.slice(underscore + 1)).replace(/[^0-9A-Za-z]/g, "");
16002
+ return cleaned.length > 0 ? cleaned : "0";
16003
+ }
16004
+ //#endregion
16005
+ //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationAdapter.ts
16006
+ const DEFAULT_FUNCTIONS$1 = {
16007
+ listAll: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listAll),
16008
+ listRoles: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listRolesByOrgId),
16009
+ listMembers: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listMembersByOrgId),
16010
+ readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].readTreasury),
16011
+ inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].inviteMember),
16012
+ resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS["org/mutations"].resendInviteToken),
16013
+ detectInvitations: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].detectAndAcceptPendingInvitations)
16014
+ };
16015
+ /**
16016
+ * Standard production Organization read adapter. It intentionally has no
16017
+ * deployer/RPC/test configuration: authenticated Convex actions own live chain
16018
+ * reads, while the lifecycle adapter owns the single sponsored bootstrap.
16019
+ */
16020
+ var ConvexOrganizationAdapter = class {
16021
+ #convex;
16022
+ #fns;
16023
+ #telemetry;
16024
+ constructor(input) {
16025
+ this.#convex = input.convex;
16026
+ this.#fns = input.functions ?? DEFAULT_FUNCTIONS$1;
16027
+ this.#telemetry = input.telemetry;
16028
+ }
16029
+ createOrg(_input) {
16030
+ return Effect.fail(orgErrorFromCapxul("createOrg", Errors.notImplemented("organizationSetup", "use onboarding.completeOrganization")));
16031
+ }
16032
+ listOrgs(input) {
16033
+ return this.#convex.query(this.#fns.listAll, copyInvocationObservation(input, {})).pipe(Effect.mapError((error) => orgErrorFromCapxul("listOrgs", error.publicError, error)), Effect.flatMap((wires) => Effect.forEach(wires, (wire) => this.#readTreasuryWire(copyInvocationObservation(input, { orgId: toOrgId(wire.orgId) })).pipe(Effect.map((treasury) => {
16034
+ const viewerRole = wire.viewerRole.trim();
16035
+ if (viewerRole.length === 0) throw Errors.wrongState({
16036
+ method: "listOrgs",
16037
+ currentState: "viewerRoleMissing",
16038
+ validStates: ["activeViewerRole"]
16039
+ });
16040
+ return brandOrgView(wire, treasury, viewerRole);
16041
+ })))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listOrgs", cause))));
16042
+ }
16043
+ readTreasury(input) {
16044
+ return this.#readTreasuryWire(input).pipe(Effect.catchDefect((cause) => Effect.fail(toOrgError$1("readTreasury", cause))));
16045
+ }
16046
+ listRoles(input) {
16047
+ return this.#convex.query(this.#fns.listRoles, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listRoles", error.publicError, error)), Effect.flatMap((rows) => rows.length === 0 ? Effect.fail(partialOrgTruth("listRoles", "activeRoleMissing")) : Effect.succeed(rows.map(brandOrgRole))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listRoles", cause))));
16048
+ }
16049
+ listMembers(input) {
16050
+ return this.#convex.query(this.#fns.listMembers, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listMembers", error.publicError, error)), Effect.flatMap((rows) => rows.length === 0 ? Effect.fail(partialOrgTruth("listMembers", "activeMemberMissing")) : Effect.succeed(rows.map(brandOrgMember))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listMembers", cause))));
16051
+ }
16052
+ pendingMembers(input) {
16053
+ return this.listMembers(input).pipe(Effect.map((members) => members.filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant")));
16054
+ }
16055
+ inviteMember(input) {
16056
+ return this.#convex.action(this.#fns.inviteMember, {
16057
+ orgId: input.orgId,
16058
+ email: input.input.email,
16059
+ role: input.input.role
16060
+ }).pipe(Effect.mapError((error) => orgErrorFromCapxul("inviteMember", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("inviteMember", cause))));
16061
+ }
16062
+ resendInviteToken(input) {
16063
+ return this.#convex.mutation(this.#fns.resendInvite, {
16064
+ orgId: input.orgId,
16065
+ email: input.email
16066
+ }).pipe(Effect.mapError((error) => orgErrorFromCapxul("resendInviteToken", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("resendInviteToken", cause))));
16067
+ }
16068
+ detectAndAcceptPendingInvitations(_input) {
16069
+ return this.#convex.action(this.#fns.detectInvitations, {}).pipe(Effect.mapError((error) => orgErrorFromCapxul("detectAndAcceptPendingInvitations", error.publicError, error)), Effect.map((result) => ({ matched: result.matched.map(toOrgId) })), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("detectAndAcceptPendingInvitations", cause))));
16070
+ }
16071
+ #readTreasuryWire(input) {
16072
+ const orgId = String(input.orgId);
16073
+ return retryIdempotentRead(this.#convex.action(this.#fns.readTreasury, copyInvocationObservation(input, { orgId })), "org.treasury", this.#telemetry, input).pipe(Effect.mapError((error) => orgErrorFromCapxul("readTreasury", error.publicError, error)), Effect.map((wire) => {
16074
+ if (wire.orgId !== orgId) throw Errors.invalidInput("orgId", "Organization treasury scope does not match");
16075
+ const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
16076
+ const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);
16077
+ return {
16078
+ ...brandOrgTreasury({
16079
+ orgId: wire.orgId,
16080
+ money: balance
16081
+ }),
16082
+ available
16083
+ };
16084
+ }));
16085
+ }
16086
+ };
16087
+ function toOrgError$1(operation, cause) {
16088
+ if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);
16089
+ return orgErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
15645
16090
  }
15646
- const PII_PROP_KEYS_BY_EVENT = {
15647
- auth_otp_requested: ["email"],
15648
- auth_otp_delivered: ["email"],
15649
- auth_otp_expired: ["email"],
15650
- auth_failed: ["email"]
16091
+ function partialOrgTruth(operation, currentState) {
16092
+ return orgErrorFromCapxul(operation, Errors.wrongState({
16093
+ method: operation,
16094
+ currentState,
16095
+ validStates: ["completeProductionOrganizationTruth"]
16096
+ }));
16097
+ }
16098
+ //#endregion
16099
+ //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationSetupAdapter.ts
16100
+ const DEFAULT_FUNCTIONS = {
16101
+ startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].startOrResume),
16102
+ prepareFounderAccount: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareFounderAccount),
16103
+ prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareBootstrap),
16104
+ submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].submitBootstrap),
16105
+ resumeBootstrapSubmission: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].resumeBootstrapSubmission),
16106
+ confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].confirmBootstrap),
16107
+ recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].recordFailure),
16108
+ load: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].load),
16109
+ retry: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].retry)
15651
16110
  };
15652
- function redactProperty(props, key) {
15653
- const value = props[key];
15654
- if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
16111
+ /** Durable Organization setup capability composed by the standard client. */
16112
+ var ConvexOrganizationSetupAdapter = class {
16113
+ #convex;
16114
+ #signer;
16115
+ #chainId;
16116
+ #fns;
16117
+ constructor(input) {
16118
+ this.#convex = input.convex;
16119
+ this.#signer = input.signer;
16120
+ this.#chainId = input.chainId;
16121
+ this.#fns = input.functions ?? DEFAULT_FUNCTIONS;
16122
+ }
16123
+ async startOrResume(input) {
16124
+ const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, copyInvocationObservation(input, {
16125
+ ...input,
16126
+ chainId: this.#chainId
16127
+ })));
16128
+ if (!result.ok) return result;
16129
+ const lifecycle = parseLifecycle("startOrResume", result.value.lifecycle);
16130
+ if (!lifecycle.ok) return lifecycle;
16131
+ const orgId = parseOrgId("startOrResume", result.value.orgId);
16132
+ if (!orgId.ok) return orgId;
16133
+ if (String(orgId.value) !== String(lifecycle.value.orgId)) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle scope does not match"));
16134
+ return {
16135
+ ok: true,
16136
+ value: {
16137
+ orgId: orgId.value,
16138
+ lifecycle: lifecycle.value
16139
+ }
16140
+ };
16141
+ }
16142
+ prepareFounderAccount(input) {
16143
+ return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, copyInvocationObservation(input, {
16144
+ orgId: input.orgId,
16145
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16146
+ })));
16147
+ }
16148
+ async authorizeAndSubmitBootstrap(input) {
16149
+ const cancelled = cancellation(input.signal);
16150
+ if (cancelled !== void 0) return cancelled;
16151
+ const signerAddress = await signerResult(this.#signer.source, "getAddress", () => this.#signer.getAddress());
16152
+ if (!signerAddress.ok) return signerAddress;
16153
+ const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, copyInvocationObservation(input, {
16154
+ orgId: input.orgId,
16155
+ signerAddress: signerAddress.value,
16156
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16157
+ })));
16158
+ if (!prepared.ok) return prepared;
16159
+ const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);
16160
+ if (!authority.ok) return authority;
16161
+ const cancelledAfterPrepare = cancellation(input.signal);
16162
+ if (cancelledAfterPrepare !== void 0) return cancelledAfterPrepare;
16163
+ const signature = await signerResult(this.#signer.source, "signUserOpHash", () => this.#signer.signUserOpHash(prepared.value.digest));
16164
+ if (!signature.ok) return signature;
16165
+ const cancelledAfterSign = cancellation(input.signal);
16166
+ if (cancelledAfterSign !== void 0) return cancelledAfterSign;
16167
+ const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, copyInvocationObservation(input, {
16168
+ orgId: input.orgId,
16169
+ signerAddress: signerAddress.value,
16170
+ signature: signature.value,
16171
+ userOp: prepared.value.userOp,
16172
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16173
+ })));
16174
+ if (!submitted.ok) return submitted;
16175
+ return parseLifecycle("submitBootstrap", submitted.value);
16176
+ }
16177
+ resumeSubmittedBootstrap(input) {
16178
+ return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, copyInvocationObservation(input, {
16179
+ orgId: input.orgId,
16180
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16181
+ })));
16182
+ }
16183
+ confirmSubmittedBootstrap(input) {
16184
+ return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, copyInvocationObservation(input, {
16185
+ orgId: input.orgId,
16186
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext },
16187
+ ...input.retryDelayMs === void 0 ? {} : { retryDelayMs: input.retryDelayMs }
16188
+ })));
16189
+ }
16190
+ async recordFailure(input) {
16191
+ const errorProvider = input.error.details?.provider;
16192
+ const errorOperation = input.error.details?.operation;
16193
+ const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, copyInvocationObservation(input, {
16194
+ orgId: input.orgId,
16195
+ errorCode: input.error.code,
16196
+ ...typeof errorProvider === "string" && typeof errorOperation === "string" ? {
16197
+ errorProvider,
16198
+ errorOperation
16199
+ } : {},
16200
+ retryable: input.retryable,
16201
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16202
+ })));
16203
+ return result.ok ? parseLifecycle("recordFailure", result.value) : result;
16204
+ }
16205
+ async loadLifecycle(input) {
16206
+ const result = await runCall("loadLifecycle", this.#convex.query(this.#fns.load, input));
16207
+ if (!result.ok) return result;
16208
+ if (result.value === null) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle was not found"));
16209
+ return parseLifecycle("loadLifecycle", result.value);
16210
+ }
16211
+ async retry(input) {
16212
+ const cancelled = cancellation(input.signal);
16213
+ if (cancelled !== void 0) return cancelled;
16214
+ const current = await this.loadLifecycle({
16215
+ orgId: input.orgId,
16216
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16217
+ });
16218
+ if (!current.ok) return current;
16219
+ if (current.value.status === "failed" && current.value.retryable && (current.value.at === "awaitingFounderAuthorization" || current.value.at === "submittingBootstrap")) {
16220
+ const reset = resetSignerSession(this.#signer);
16221
+ if (!reset.ok) return reset;
16222
+ }
16223
+ const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, copyInvocationObservation(input, {
16224
+ orgId: input.orgId,
16225
+ ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
16226
+ })));
16227
+ if (!result.ok) return result;
16228
+ return parseLifecycle("retry", result.value);
16229
+ }
16230
+ async #lifecycleAction(operation, input, call) {
16231
+ const cancelled = cancellation(input.signal);
16232
+ if (cancelled !== void 0) return cancelled;
16233
+ const result = await runCall(operation, call());
16234
+ if (!result.ok) return result;
16235
+ const cancelledAfter = cancellation(input.signal);
16236
+ if (cancelledAfter !== void 0) return cancelledAfter;
16237
+ return parseLifecycle(operation, result.value);
16238
+ }
16239
+ };
16240
+ function resetSignerSession(signer) {
16241
+ const resetSession = signer.resetSession;
16242
+ if (typeof resetSession !== "function") return {
16243
+ ok: true,
16244
+ value: void 0
16245
+ };
16246
+ try {
16247
+ resetSession.call(signer);
16248
+ return {
16249
+ ok: true,
16250
+ value: void 0
16251
+ };
16252
+ } catch (cause) {
16253
+ return fail$1(signerFailure(signer.source, "resetSession", cause));
16254
+ }
15655
16255
  }
15656
- function cloneProps$1(props) {
15657
- const cloned = {};
15658
- for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue$1(value);
15659
- return cloned;
16256
+ async function runCall(operation, effect) {
16257
+ try {
16258
+ const result = await Effect.runPromise(Effect.result(effect));
16259
+ return Result.isSuccess(result) ? {
16260
+ ok: true,
16261
+ value: result.success
16262
+ } : fail$1(publicError(operation, result.failure));
16263
+ } catch (cause) {
16264
+ return fail$1(publicError(operation, cause));
16265
+ }
15660
16266
  }
15661
- function cloneTelemetryValue$1(value) {
15662
- if (Array.isArray(value)) return value.map(cloneTelemetryValue$1);
15663
- if (value === null || typeof value !== "object") return value;
15664
- if (Object.getPrototypeOf(value) !== Object.prototype) return value;
15665
- const cloned = {};
15666
- for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue$1(nested);
15667
- return cloned;
16267
+ function publicError(operation, cause) {
16268
+ if (cause instanceof CapxulError) return cause;
16269
+ if (typeof cause === "object" && cause !== null) {
16270
+ const carried = cause.publicError;
16271
+ if (carried instanceof CapxulError) return carried;
16272
+ }
16273
+ return Errors.providerError("convex-organization", operation, cause);
15668
16274
  }
15669
- const SHA256_INITIAL_HASH = [
15670
- 1779033703,
15671
- 3144134277,
15672
- 1013904242,
15673
- 2773480762,
15674
- 1359893119,
15675
- 2600822924,
15676
- 528734635,
15677
- 1541459225
15678
- ];
15679
- const SHA256_K = [
15680
- 1116352408,
15681
- 1899447441,
15682
- 3049323471,
15683
- 3921009573,
15684
- 961987163,
15685
- 1508970993,
15686
- 2453635748,
15687
- 2870763221,
15688
- 3624381080,
15689
- 310598401,
15690
- 607225278,
15691
- 1426881987,
15692
- 1925078388,
15693
- 2162078206,
15694
- 2614888103,
15695
- 3248222580,
15696
- 3835390401,
15697
- 4022224774,
15698
- 264347078,
15699
- 604807628,
15700
- 770255983,
15701
- 1249150122,
15702
- 1555081692,
15703
- 1996064986,
15704
- 2554220882,
15705
- 2821834349,
15706
- 2952996808,
15707
- 3210313671,
15708
- 3336571891,
15709
- 3584528711,
15710
- 113926993,
15711
- 338241895,
15712
- 666307205,
15713
- 773529912,
15714
- 1294757372,
15715
- 1396182291,
15716
- 1695183700,
15717
- 1986661051,
15718
- 2177026350,
15719
- 2456956037,
15720
- 2730485921,
15721
- 2820302411,
15722
- 3259730800,
15723
- 3345764771,
15724
- 3516065817,
15725
- 3600352804,
15726
- 4094571909,
15727
- 275423344,
15728
- 430227734,
15729
- 506948616,
15730
- 659060556,
15731
- 883997877,
15732
- 958139571,
15733
- 1322822218,
15734
- 1537002063,
15735
- 1747873779,
15736
- 1955562222,
15737
- 2024104815,
15738
- 2227730452,
15739
- 2361852424,
15740
- 2428436474,
15741
- 2756734187,
15742
- 3204031479,
15743
- 3329325298
15744
- ];
15745
- function sha256Hex(input) {
15746
- const padded = padSha256Message(new TextEncoder().encode(input));
15747
- const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
15748
- const words = /* @__PURE__ */ new Uint32Array(64);
15749
- let h0 = SHA256_INITIAL_HASH[0];
15750
- let h1 = SHA256_INITIAL_HASH[1];
15751
- let h2 = SHA256_INITIAL_HASH[2];
15752
- let h3 = SHA256_INITIAL_HASH[3];
15753
- let h4 = SHA256_INITIAL_HASH[4];
15754
- let h5 = SHA256_INITIAL_HASH[5];
15755
- let h6 = SHA256_INITIAL_HASH[6];
15756
- let h7 = SHA256_INITIAL_HASH[7];
15757
- for (let offset = 0; offset < padded.byteLength; offset += 64) {
15758
- for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
15759
- for (let i = 16; i < 64; i++) {
15760
- const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
15761
- const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
15762
- words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
16275
+ async function signerResult(source, operation, run) {
16276
+ try {
16277
+ return {
16278
+ ok: true,
16279
+ value: await run()
16280
+ };
16281
+ } catch (cause) {
16282
+ return fail$1(signerFailure(source, operation, cause));
16283
+ }
16284
+ }
16285
+ function validatePreparedAuthorities(prepared, signerAddress) {
16286
+ const signer = signerAddress.toLowerCase();
16287
+ const preparedSigner = prepared.signerAddress.toLowerCase();
16288
+ const founder = prepared.founderPersonalAccount.toLowerCase();
16289
+ const organization = prepared.organizationAccountAddress.toLowerCase();
16290
+ const sender = prepared.userOp.sender.toLowerCase();
16291
+ if (preparedSigner !== signer) return fail$1(Errors.invalidInput("signerAddress", "Prepared signer does not match configured signer"));
16292
+ if (founder === signer || organization === signer || organization === founder) return fail$1(Errors.invalidInput("organizationAuthority", "Signer EOA, founder Account, and Organization Account must be distinct"));
16293
+ if (sender !== founder) return fail$1(Errors.invalidInput("userOp.sender", "Bootstrap sender must be the founder Account"));
16294
+ if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) return fail$1(Errors.invalidInput("digest", "Prepared bootstrap digest must be 32-byte hex"));
16295
+ return {
16296
+ ok: true,
16297
+ value: void 0
16298
+ };
16299
+ }
16300
+ function parseLifecycle(operation, wire) {
16301
+ const orgId = parseOrgId(operation, wire.orgId);
16302
+ if (!orgId.ok) return orgId;
16303
+ if (wire.status === "loading") return {
16304
+ ok: true,
16305
+ value: {
16306
+ status: "loading",
16307
+ orgId: orgId.value
15763
16308
  }
15764
- let a = h0;
15765
- let b = h1;
15766
- let c = h2;
15767
- let d = h3;
15768
- let e = h4;
15769
- let f = h5;
15770
- let g = h6;
15771
- let h = h7;
15772
- for (let i = 0; i < 64; i++) {
15773
- const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
15774
- const ch = e & f ^ ~e & g;
15775
- const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
15776
- const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
15777
- h = g;
15778
- g = f;
15779
- f = e;
15780
- e = d + temp1 >>> 0;
15781
- d = c;
15782
- c = b;
15783
- b = a;
15784
- a = temp1 + temp2 >>> 0;
16309
+ };
16310
+ if (wire.status === "ready") return {
16311
+ ok: true,
16312
+ value: {
16313
+ status: "ready",
16314
+ orgId: orgId.value,
16315
+ canTransact: true
15785
16316
  }
15786
- h0 = h0 + a >>> 0;
15787
- h1 = h1 + b >>> 0;
15788
- h2 = h2 + c >>> 0;
15789
- h3 = h3 + d >>> 0;
15790
- h4 = h4 + e >>> 0;
15791
- h5 = h5 + f >>> 0;
15792
- h6 = h6 + g >>> 0;
15793
- h7 = h7 + h >>> 0;
16317
+ };
16318
+ if (wire.status === "failed") {
16319
+ if (!isSetupStep(wire.at)) return fail$1(Errors.invalidInput("lifecycle.at", "Unknown setup step"));
16320
+ return {
16321
+ ok: true,
16322
+ value: {
16323
+ status: "failed",
16324
+ orgId: orgId.value,
16325
+ at: wire.at,
16326
+ error: new CapxulError(wire.error.code, wire.error.message),
16327
+ retryable: wire.retryable
16328
+ }
16329
+ };
15794
16330
  }
15795
- return [
15796
- h0,
15797
- h1,
15798
- h2,
15799
- h3,
15800
- h4,
15801
- h5,
15802
- h6,
15803
- h7
15804
- ].map((word) => word.toString(16).padStart(8, "0")).join("");
16331
+ if (!isSetupStep(wire.step)) return fail$1(Errors.invalidInput("lifecycle.step", `Unknown setup step from ${operation}`));
16332
+ return {
16333
+ ok: true,
16334
+ value: {
16335
+ status: "settingUp",
16336
+ orgId: orgId.value,
16337
+ step: wire.step
16338
+ }
16339
+ };
15805
16340
  }
15806
- function padSha256Message(bytes) {
15807
- const bitLength = bytes.byteLength * 8;
15808
- const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
15809
- const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
15810
- output.set(bytes);
15811
- output[bytes.byteLength] = 128;
15812
- const view = new DataView(output.buffer);
15813
- view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
15814
- view.setUint32(output.byteLength - 4, bitLength >>> 0);
15815
- return output;
16341
+ function parseOrgId(operation, value) {
16342
+ try {
16343
+ return {
16344
+ ok: true,
16345
+ value: toOrgId(value)
16346
+ };
16347
+ } catch (cause) {
16348
+ return fail$1(Errors.providerError("convex-organization", operation, cause));
16349
+ }
15816
16350
  }
15817
- function rotr(value, bits) {
15818
- return value >>> bits | value << 32 - bits;
16351
+ function isSetupStep(value) {
16352
+ return value === "preparingFounderAccount" || value === "awaitingFounderAuthorization" || value === "submittingBootstrap" || value === "confirmingBootstrap";
16353
+ }
16354
+ function cancellation(signal) {
16355
+ return signal?.aborted ? fail$1(Errors.cancelled({ operation: "organization.setup" })) : void 0;
16356
+ }
16357
+ function fail$1(error) {
16358
+ return {
16359
+ ok: false,
16360
+ error
16361
+ };
15819
16362
  }
15820
- //#endregion
15821
- //#region ../../packages/sdk/src/ports/telemetry.ts
15822
- var TelemetryPortTag = class extends Context.Service()("@capxul/sdk/ports/TelemetryPort") {};
15823
16363
  //#endregion
15824
16364
  //#region ../../packages/sdk/src/adapters/telemetry/PostHogTelemetryAdapter.ts
15825
16365
  var PostHogTelemetryAdapter = class {
@@ -38941,8 +39481,59 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
38941
39481
  embeddedWallet: openfort.embeddedWallet,
38942
39482
  ensureWalletReady: ensureOpenfortWalletReady
38943
39483
  });
39484
+ const resetReadiness = () => {
39485
+ walletReadyPromise = null;
39486
+ clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
39487
+ signer.resetAddressCache();
39488
+ setStatus("unknown");
39489
+ };
39490
+ const signUserOpHash = async (hash) => {
39491
+ try {
39492
+ return await signer.signUserOpHash(hash);
39493
+ } catch (cause) {
39494
+ const providerErrorCode = openfortSignerNotReadyCode(cause);
39495
+ if (providerErrorCode === void 0) throw cause;
39496
+ diagnostic?.trace("openfort.signerRecovery", {
39497
+ outcome: "started",
39498
+ attempt: 1,
39499
+ failure_mode: "signer-not-ready"
39500
+ });
39501
+ resetReadiness();
39502
+ try {
39503
+ await ensureOpenfortWalletReady();
39504
+ const signature = await signer.signUserOpHash(hash);
39505
+ diagnostic?.trace("openfort.signerRecovery", {
39506
+ outcome: "succeeded",
39507
+ attempt: 1,
39508
+ failure_mode: "signer-not-ready"
39509
+ });
39510
+ return signature;
39511
+ } catch (retryCause) {
39512
+ const retryFailure = signerFailure("openfort-embedded", "signUserOpHash", retryCause);
39513
+ if (retryFailure.code === "SIGNER_REJECTED") throw retryFailure;
39514
+ if (isSignerNotReadySignal(retryCause)) {
39515
+ walletReadyPromise = null;
39516
+ signer.resetAddressCache();
39517
+ setStatus("unavailable");
39518
+ }
39519
+ diagnostic?.trace("openfort.signerRecovery", {
39520
+ outcome: "failed",
39521
+ attempt: 1,
39522
+ failure_mode: isSignerNotReadySignal(retryCause) ? "signer-not-ready" : "unknown"
39523
+ });
39524
+ throw Errors.providerError("openfort", "signerRecovery", retryCause, {
39525
+ failure_mode: "signer-not-ready",
39526
+ details: {
39527
+ provider_error_source: "openfort",
39528
+ provider_error_code: providerErrorCode
39529
+ }
39530
+ });
39531
+ }
39532
+ }
39533
+ };
38944
39534
  return {
38945
39535
  ...signer,
39536
+ signUserOpHash,
38946
39537
  statusStore,
38947
39538
  ensureWalletReady: ensureOpenfortWalletReady,
38948
39539
  getAddress: async () => {
@@ -38958,12 +39549,7 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
38958
39549
  throw openfortProviderError("getAddress", cause);
38959
39550
  }
38960
39551
  },
38961
- resetSession: () => {
38962
- walletReadyPromise = null;
38963
- clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
38964
- signer.resetAddressCache();
38965
- setStatus("unknown");
38966
- }
39552
+ resetSession: resetReadiness
38967
39553
  };
38968
39554
  }
38969
39555
  function normalizeBetterAuthBaseUrl(raw) {
@@ -39889,7 +40475,7 @@ function accountsDepsLayer(deps) {
39889
40475
  }
39890
40476
  const readAccountProgram = Effect.gen(function* () {
39891
40477
  const deps = yield* AccountsDepsTag;
39892
- return yield* deps.accountReadPort.readBalance({ chainId: deps.chainId }).pipe(Effect.tapError((error) => Effect.promise(() => emitAccountBalanceFailed(deps.telemetry, error.publicError))), Effect.mapError((error) => error.publicError));
40478
+ return yield* deps.accountReadPort.readBalance(copyInvocationObservation(deps.invocationSource, { chainId: deps.chainId })).pipe(Effect.tapError((error) => Effect.promise(() => emitAccountBalanceFailed(deps.telemetry, error.publicError))), Effect.mapError((error) => error.publicError));
39893
40479
  });
39894
40480
  function fundFromFaucetProgram(amount) {
39895
40481
  return Effect.gen(function* () {
@@ -39919,7 +40505,11 @@ function makeAccountsMethods(deps) {
39919
40505
  ok: false,
39920
40506
  error: Errors.cancelled({ operation: "accounts.read" })
39921
40507
  };
39922
- return toCapxulResult(readAccountProgram, accountsDepsLayer(deps));
40508
+ const controls = deps.invocationControls?.(options) ?? options;
40509
+ return runCapxulEffect(readAccountProgram.pipe(Effect.provide(accountsDepsLayer({
40510
+ ...deps,
40511
+ ...controls === void 0 ? {} : { invocationSource: controls }
40512
+ }))), controls, "accounts.read", deps.runPromise);
39923
40513
  },
39924
40514
  async fund(amount, options) {
39925
40515
  if (options?.signal?.aborted) return {
@@ -40684,7 +41274,7 @@ function emitCreationFunnelTail(telemetry, org, chainId) {
40684
41274
  function readTreasuryProgram(orgId) {
40685
41275
  return Effect.gen(function* () {
40686
41276
  const deps = yield* OrgDepsTag;
40687
- if (deps.orgPort !== void 0) return yield* deps.orgPort.readTreasury({ orgId }).pipe(Effect.mapError((error) => error.publicError));
41277
+ if (deps.orgPort !== void 0) return yield* deps.orgPort.readTreasury(copyInvocationObservation(deps.invocationSource, { orgId })).pipe(Effect.mapError((error) => error.publicError));
40688
41278
  return zeroTreasury(orgId);
40689
41279
  });
40690
41280
  }
@@ -40768,7 +41358,7 @@ function detectAndAcceptPendingInvitationsProgram() {
40768
41358
  function listOrgsProgram() {
40769
41359
  return Effect.gen(function* () {
40770
41360
  const deps = yield* OrgDepsTag;
40771
- if (deps.orgPort !== void 0) return yield* deps.orgPort.listOrgs({}).pipe(Effect.mapError((error) => error.publicError));
41361
+ if (deps.orgPort !== void 0) return yield* deps.orgPort.listOrgs(copyInvocationObservation(deps.invocationSource, {})).pipe(Effect.mapError((error) => error.publicError));
40772
41362
  return [];
40773
41363
  });
40774
41364
  }
@@ -40856,11 +41446,28 @@ function isRetryableOrganizationSetupFailure(error) {
40856
41446
  * state. The closed-over `orgId` is its only entity reference.
40857
41447
  */
40858
41448
  function makeOrgMethods(deps) {
40859
- const layer = orgDepsLayer({
41449
+ const orgDeps = {
40860
41450
  ...deps.orgPort === void 0 ? {} : { orgPort: deps.orgPort },
40861
41451
  ...deps.chainId === void 0 ? {} : { chainId: deps.chainId },
40862
41452
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
40863
- });
41453
+ };
41454
+ const layer = orgDepsLayer(orgDeps);
41455
+ const treasury = (orgId, controls) => {
41456
+ return runCapxulEffect(readTreasuryProgram(orgId).pipe(Effect.provide(orgDepsLayer({
41457
+ ...orgDeps,
41458
+ ...controls === void 0 ? {} : { invocationSource: controls }
41459
+ }))), controls, "org.treasury", deps.runPromise);
41460
+ };
41461
+ const listOrganizations = (controls) => {
41462
+ if (controls?.signal?.aborted) return Promise.resolve({
41463
+ ok: false,
41464
+ error: Errors.cancelled({ operation: "org.orgs" })
41465
+ });
41466
+ return runCapxulEffect(listOrgsProgram().pipe(Effect.provide(orgDepsLayer({
41467
+ ...orgDeps,
41468
+ ...controls === void 0 ? {} : { invocationSource: controls }
41469
+ }))), controls, "org.orgs", deps.runPromise);
41470
+ };
40864
41471
  return {
40865
41472
  createOrg(input, options) {
40866
41473
  if (options?.signal?.aborted) return Promise.resolve({
@@ -40869,13 +41476,7 @@ function makeOrgMethods(deps) {
40869
41476
  });
40870
41477
  return toCapxulResult(createOrgProgram(input), layer);
40871
41478
  },
40872
- orgs: Object.assign((options) => {
40873
- if (options?.signal?.aborted) return Promise.resolve({
40874
- ok: false,
40875
- error: Errors.cancelled({ operation: "org.orgs" })
40876
- });
40877
- return toCapxulResult(listOrgsProgram(), layer);
40878
- }, { detectAndAcceptPendingInvitations(options) {
41479
+ orgs: Object.assign((options) => listOrganizations(deps.invocationControls?.(options) ?? options), { detectAndAcceptPendingInvitations(options) {
40879
41480
  if (options?.signal?.aborted) return Promise.resolve({
40880
41481
  ok: false,
40881
41482
  error: Errors.cancelled({ operation: "orgs.detectAndAcceptPendingInvitations" })
@@ -40947,19 +41548,20 @@ function makeOrgMethods(deps) {
40947
41548
  ok: false,
40948
41549
  error: Errors.cancelled({ operation: "org.treasury" })
40949
41550
  });
40950
- return toCapxulResult(readTreasuryProgram(orgId), layer);
41551
+ return treasury(orgId, deps.invocationControls?.(options) ?? options);
40951
41552
  },
40952
41553
  account: { async get(options) {
40953
41554
  if (options?.signal?.aborted) return {
40954
41555
  ok: false,
40955
41556
  error: Errors.cancelled({ operation: "org.account.get" })
40956
41557
  };
40957
- const treasury = await toCapxulResult(readTreasuryProgram(orgId), layer);
40958
- if (!treasury.ok) return {
41558
+ const controls = deps.invocationControls?.(options) ?? options;
41559
+ const treasuryResult = await treasury(orgId, controls);
41560
+ if (!treasuryResult.ok) return {
40959
41561
  ok: false,
40960
- error: treasury.error
41562
+ error: treasuryResult.error
40961
41563
  };
40962
- const orgList = await toCapxulResult(listOrgsProgram(), layer);
41564
+ const orgList = await listOrganizations(controls);
40963
41565
  if (!orgList.ok) return {
40964
41566
  ok: false,
40965
41567
  error: orgList.error
@@ -40968,10 +41570,10 @@ function makeOrgMethods(deps) {
40968
41570
  return {
40969
41571
  ok: true,
40970
41572
  value: {
40971
- id: treasury.value.id,
41573
+ id: treasuryResult.value.id,
40972
41574
  address: org?.safeAddress ?? null,
40973
- balance: treasury.value.balance,
40974
- available: treasury.value.available
41575
+ balance: treasuryResult.value.balance,
41576
+ available: treasuryResult.value.available
40975
41577
  }
40976
41578
  };
40977
41579
  } },
@@ -41123,13 +41725,16 @@ function compareDecimal(first, second) {
41123
41725
  //#region ../../packages/sdk/src/surface/holdings.ts
41124
41726
  function makeHoldingsMethods(deps) {
41125
41727
  const functions = deps.functions ?? holdingsContract;
41126
- const read = (operation, actor, signal, pick) => runIfActive(signal, operation, () => deps.convexCall.action(functions.current, actor?.kind === "organization" ? { actor: {
41127
- kind: "organization",
41128
- orgId: actor.organizationId
41129
- } } : {}).pipe(Effect.map(pick)));
41728
+ const read = (operation, actor, options, pick) => {
41729
+ const controls = deps.invocationControls?.(options) ?? options;
41730
+ return runCapxulEffect(retryIdempotentRead(deps.convexCall.action(functions.current, copyInvocationObservation(controls, actor?.kind === "organization" ? { actor: {
41731
+ kind: "organization",
41732
+ orgId: actor.organizationId
41733
+ } } : {})), operation, deps.telemetry, controls).pipe(Effect.map(pick), Effect.mapError((error) => error.publicError)), controls, operation, deps.runPromise);
41734
+ };
41130
41735
  return {
41131
- current: (input, options) => read("holdings.current", input?.actor, options?.signal, (snapshot) => snapshot),
41132
- primary: (input, options) => read("holdings.primary", input?.actor, options?.signal, (snapshot) => primaryHolding(snapshot.rows))
41736
+ current: (input, options) => read("holdings.current", input?.actor, options, (snapshot) => snapshot),
41737
+ primary: (input, options) => read("holdings.primary", input?.actor, options, (snapshot) => primaryHolding(snapshot.rows))
41133
41738
  };
41134
41739
  }
41135
41740
  //#endregion
@@ -41248,13 +41853,6 @@ function detectAuthCacheAdapter() {
41248
41853
  return new InMemoryAuthCacheAdapter();
41249
41854
  }
41250
41855
  //#endregion
41251
- //#region ../../packages/sdk/src/telemetry/from-posthog.ts
41252
- const PRODUCT_INVOCATION = Symbol("capxul.product-telemetry-invocation");
41253
- /** @internal Bind paired emit/identify/reset work to one call-start snapshot. */
41254
- function bindProductTelemetryInvocation(telemetry, source) {
41255
- return telemetry[PRODUCT_INVOCATION]?.(source) ?? telemetry;
41256
- }
41257
- //#endregion
41258
41856
  //#region ../../packages/sdk/src/telemetry/identity-product.ts
41259
41857
  const NONE = null;
41260
41858
  const IDENTITY_EVENT_TAG_SET = new Set(IDENTITY_EVENT_TAGS);
@@ -41467,6 +42065,8 @@ function assembleCapxulClient(input) {
41467
42065
  accountReadPort: input.ports.accountRead,
41468
42066
  profileMethods: financialOps.me,
41469
42067
  convexCall: input.ports.convexCall,
42068
+ runPromise: effectRunner.runPromise,
42069
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
41470
42070
  ...input.signer === void 0 ? {} : { signer: input.signer }
41471
42071
  });
41472
42072
  kickProvisioning = accountBundle.kickProvisioning;
@@ -41504,16 +42104,25 @@ function assembleCapxulClient(input) {
41504
42104
  });
41505
42105
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
41506
42106
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
41507
- const holdings = makeHoldingsMethods({ convexCall: input.ports.convexCall });
42107
+ const holdings = makeHoldingsMethods({
42108
+ convexCall: input.ports.convexCall,
42109
+ telemetry: input.ports.telemetry,
42110
+ runPromise: effectRunner.runPromise,
42111
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls)
42112
+ });
41508
42113
  const accounts = makeAccountsMethods({
41509
42114
  accountReadPort: input.ports.accountRead,
41510
42115
  chainId: input.bootstrap.chainId,
41511
- telemetry: input.ports.telemetry
42116
+ telemetry: input.ports.telemetry,
42117
+ runPromise: effectRunner.runPromise,
42118
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls)
41512
42119
  });
41513
42120
  const orgMethods = makeOrgMethods({
41514
42121
  actor,
41515
42122
  chainId: input.bootstrap.chainId,
41516
42123
  telemetry: input.ports.telemetry,
42124
+ runPromise: effectRunner.runPromise,
42125
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
41517
42126
  requestKeyScope: `${input.bootstrap.convexUrl}:${String(input.bootstrap.chainId)}`,
41518
42127
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
41519
42128
  convexCall: input.ports.convexCall,
@@ -41650,11 +42259,7 @@ function transitionError(record) {
41650
42259
  }
41651
42260
  function withHostObservation(actor, snapshot) {
41652
42261
  if (snapshot === void 0) return actor;
41653
- const controls = (input) => {
41654
- const captured = snapshot();
41655
- const copied = { ...input };
41656
- return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
41657
- };
42262
+ const controls = (input) => withHostObservationControls(snapshot, input);
41658
42263
  return {
41659
42264
  ...actor,
41660
42265
  ask: (event, input) => actor.ask(event, controls(input)),
@@ -41662,6 +42267,11 @@ function withHostObservation(actor, snapshot) {
41662
42267
  restoreAuthSession: (session, input) => actor.restoreAuthSession(session, controls(input))
41663
42268
  };
41664
42269
  }
42270
+ function withHostObservationControls(snapshot, input) {
42271
+ const copied = { ...input };
42272
+ const captured = snapshot?.();
42273
+ return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
42274
+ }
41665
42275
  //#endregion
41666
42276
  //#region ../../packages/sdk/src/host-observability.ts
41667
42277
  const HOST_INVOCATION = Symbol("capxul.host-observability-invocation");
@@ -41746,7 +42356,10 @@ function makeProductionAdapterLayerEntries(input) {
41746
42356
  },
41747
42357
  {
41748
42358
  name: "org",
41749
- layer: Layer.effect(OrgPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexOrganizationAdapter({ convex })))
42359
+ layer: Layer.effect(OrgPortTag, Effect.all([ConvexCallPortTag, TelemetryPortTag]).pipe(Effect.map(([convex, telemetry]) => new ConvexOrganizationAdapter({
42360
+ convex,
42361
+ telemetry
42362
+ }))))
41750
42363
  }
41751
42364
  ];
41752
42365
  }
@@ -41755,10 +42368,13 @@ function mergeProductionAdapterLayers(entries) {
41755
42368
  for (const entry of entries) byName.set(entry.name, entry.layer);
41756
42369
  const authClientLayer = byName.get("authClient");
41757
42370
  const convexCallLayer = byName.get("convexCall");
42371
+ const telemetryLayer = byName.get("telemetry");
41758
42372
  const convexCallReadyLayer = convexCallLayer === void 0 || authClientLayer === void 0 ? convexCallLayer : convexCallLayer.pipe(Layer.provide(authClientLayer));
42373
+ const observedConvexCallLayer = convexCallReadyLayer === void 0 ? telemetryLayer : telemetryLayer === void 0 ? convexCallReadyLayer : Layer.merge(convexCallReadyLayer, telemetryLayer);
41759
42374
  return entries.map((entry) => {
41760
42375
  const layer = byName.get(entry.name) ?? entry.layer;
41761
42376
  if (entry.name === "convexCall") return convexCallReadyLayer ?? layer;
42377
+ if (entry.name === "accountRead" || entry.name === "org") return observedConvexCallLayer === void 0 ? layer : layer.pipe(Layer.provide(observedConvexCallLayer));
41762
42378
  if (isConvexDependentLayer(entry.name)) return convexCallReadyLayer === void 0 ? layer : layer.pipe(Layer.provide(convexCallReadyLayer));
41763
42379
  return layer;
41764
42380
  }).reduce((current, layer) => Layer.merge(current, layer), Layer.empty);
@@ -41919,13 +42535,22 @@ async function createProductionAdapters(input) {
41919
42535
  }));
41920
42536
  const applicationLayer = Layer.merge(portsLayer, optionalEngineeringTelemetryLayer(bootstrapResult.value.engineeringTelemetry, resolvedInput.value.runtime));
41921
42537
  const context = await Effect.runPromise(Layer.buildWithScope(applicationLayer, scope));
42538
+ const ports = await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context)));
42539
+ const stopConnectionObservation = observeProductionConvexConnection(ports.convexCall, context);
42540
+ const close = idempotentClose(async () => {
42541
+ try {
42542
+ stopConnectionObservation();
42543
+ } finally {
42544
+ await closeScope();
42545
+ }
42546
+ });
41922
42547
  return {
41923
42548
  ok: true,
41924
42549
  value: {
41925
42550
  context,
41926
- ports: await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context))),
42551
+ ports,
41927
42552
  bootstrap: bootstrapResult.value,
41928
- close: closeScope
42553
+ close
41929
42554
  }
41930
42555
  };
41931
42556
  } catch (cause) {
@@ -41936,6 +42561,18 @@ async function createProductionAdapters(input) {
41936
42561
  };
41937
42562
  }
41938
42563
  }
42564
+ function observeProductionConvexConnection(convexCall, context) {
42565
+ if (!("observeConnection" in convexCall) || typeof convexCall.observeConnection !== "function") return () => {};
42566
+ const runPromise = Effect.runPromiseWith(context);
42567
+ try {
42568
+ return convexCall.observeConnection((diagnostic) => {
42569
+ const message = diagnostic.transition === "connected" ? Effect.logInfo("convex.connection.changed") : Effect.logWarning("convex.connection.changed");
42570
+ runPromise(message.pipe(Effect.annotateLogs(diagnostic), Effect.catchCause(() => Effect.void))).catch(() => void 0);
42571
+ });
42572
+ } catch {
42573
+ return () => {};
42574
+ }
42575
+ }
41939
42576
  function optionalEngineeringTelemetryLayer(policy, runtime) {
41940
42577
  if (policy === void 0) return Layer.empty;
41941
42578
  try {
@@ -44852,7 +45489,7 @@ async function postServerException(error, errorKind, operation, properties, cont
44852
45489
  $exception_level: "error",
44853
45490
  $exception_fingerprint: failureFingerprint(errorKind, mode, operation),
44854
45491
  $issue_name: issueName(errorKind, mode, chain, operation),
44855
- $issue_description: safeText(chain?.providerMessage ?? message),
45492
+ $issue_description: safeText((chain === void 0 ? void 0 : chainCauseSummary(chain)) ?? message),
44856
45493
  $exception_list: [{
44857
45494
  type: errorKind,
44858
45495
  value: message,