@capxul/mcp 2.8.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 +1550 -1004
  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.8.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",
@@ -479,6 +480,7 @@ const EXPECTED_OPERATION_OUTCOMES = /* @__PURE__ */ new Set([
479
480
  "INVALID_INPUT",
480
481
  "NOT_AUTHENTICATED",
481
482
  "SMART_ACCOUNT_MISSING",
483
+ "ACCOUNT_CLAIMED_BY_OTHER_SIGNER",
482
484
  "CANCELLED",
483
485
  "SIGNER_REJECTED",
484
486
  "VERIFICATION_REQUIRED",
@@ -537,6 +539,46 @@ function compactErrorOptions(options) {
537
539
  if (options.chain !== void 0) result.chain = options.chain;
538
540
  return result;
539
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
+ }
540
582
  const Errors = {
541
583
  notAuthenticated: (message, opts) => new CapxulError("NOT_AUTHENTICATED", message ?? "Not authenticated", opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : void 0),
542
584
  emailDeliveryFailed: (detail) => new CapxulError("EMAIL_DELIVERY_FAILED", "Failed to send email", { details: { detail } }),
@@ -635,10 +677,14 @@ const Errors = {
635
677
  }
636
678
  }),
637
679
  rateLimited: (details) => new CapxulError("RATE_LIMITED", "Rate limit exceeded", details === void 0 ? void 0 : { details: { ...details } }),
638
- networkError: (operation, cause) => new CapxulError("NETWORK_ERROR", `Network error during ${operation}`, {
639
- cause,
640
- details: { operation }
641
- }),
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
+ },
642
688
  unknown: (cause) => new CapxulError("UNKNOWN", "Unknown error", { cause }),
643
689
  otpExpired: (details) => new CapxulError("OTP_EXPIRED", "Verification code has expired. Request a new one.", details === void 0 ? void 0 : { details: { ...details } }),
644
690
  signerRejected: (details) => new CapxulError("SIGNER_REJECTED", "Signer rejected the request.", {
@@ -648,6 +694,11 @@ const Errors = {
648
694
  reason: details.reason
649
695
  }
650
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
+ } }),
651
702
  cancelled: (details) => new CapxulError("CANCELLED", "Operation was cancelled.", details === void 0 ? void 0 : { details: { ...details } }),
652
703
  /**
653
704
  * Method called from a flow state where its precondition fails (TA16). The
@@ -5859,6 +5910,7 @@ const DEFINITIVE_PROVIDER_MODES = /* @__PURE__ */ new Set([
5859
5910
  "auth-origin-mismatch",
5860
5911
  "app-env-allowlist",
5861
5912
  "no-secure-context",
5913
+ "signer-not-ready",
5862
5914
  "revert",
5863
5915
  "insufficient-balance",
5864
5916
  "insufficient-allowance",
@@ -6213,6 +6265,44 @@ Object.freeze({
6213
6265
  needsAction: false
6214
6266
  });
6215
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
6216
6306
  //#region ../../packages/sdk/src/surface/_shared/provisioning-telemetry.ts
6217
6307
  async function emitProvisioningTelemetry(telemetry, smartAccount) {
6218
6308
  if (telemetry === void 0) return;
@@ -6271,9 +6361,29 @@ function* causeChain(cause) {
6271
6361
  current = current.cause;
6272
6362
  }
6273
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
+ }
6274
6383
  /** Fold a signer throw into the public error contract. */
6275
6384
  function signerFailure(source, operation, cause) {
6276
6385
  let failureMode;
6386
+ const providerErrorCode = source === "openfort-embedded" ? openfortSignerNotReadyCode(cause) : void 0;
6277
6387
  for (const link of causeChain(cause)) {
6278
6388
  if (link instanceof CapxulError && link.code === "SIGNER_REJECTED") return link;
6279
6389
  failureMode = getFailureMode(link) ?? failureMode;
@@ -6282,46 +6392,15 @@ function signerFailure(source, operation, cause) {
6282
6392
  source,
6283
6393
  cause
6284
6394
  });
6285
- }
6286
- return Errors.providerError("signer", operation, cause, failureMode === void 0 ? void 0 : { failure_mode: failureMode });
6287
- }
6288
- //#endregion
6289
- //#region ../../packages/sdk/src/internal/invocation-observation.ts
6290
- const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
6291
- const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
6292
- /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
6293
- function attachInvocationObservation(target, source) {
6294
- const snapshot = Object.freeze(source.context === void 0 ? { active: source.active } : {
6295
- active: source.active,
6296
- context: Object.freeze({ ...source.context })
6297
- });
6298
- Object.defineProperty(target, INVOCATION_OBSERVATION, {
6299
- configurable: false,
6300
- enumerable: false,
6301
- value: snapshot,
6302
- writable: false
6303
- });
6304
- return target;
6305
- }
6306
- /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
6307
- function readInvocationObservation(source) {
6308
- if (typeof source !== "object" || source === null) return void 0;
6309
- return source[INVOCATION_OBSERVATION];
6310
- }
6311
- /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
6312
- function copyInvocationObservation(source, target) {
6313
- const snapshot = readInvocationObservation(source);
6314
- return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot);
6315
- }
6316
- /** @internal Carry the public call-start delivery decision with its failure envelope. */
6317
- function markFailureInvocationSnapshot(failure, snapshot) {
6318
- Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
6319
- configurable: false,
6320
- enumerable: false,
6321
- value: Object.freeze(snapshot),
6322
- 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
+ } }
6323
6403
  });
6324
- return failure;
6325
6404
  }
6326
6405
  //#endregion
6327
6406
  //#region ../../packages/sdk/src/domain/machine/telemetry.ts
@@ -6785,21 +6864,27 @@ async function runIdentityFacade(verb, controls, run, runPromise = Effect.runPro
6785
6864
  async function runPortEffect(effect, controls, operation = "port", runPromise = Effect.runPromise) {
6786
6865
  const deadlineDelay = controls?.deadlineMs === void 0 ? void 0 : Math.max(0, controls.deadlineMs - Date.now());
6787
6866
  const timeoutMs = controls?.timeoutMs === void 0 ? deadlineDelay : deadlineDelay === void 0 ? controls.timeoutMs : Math.min(controls.timeoutMs, deadlineDelay);
6788
- const observed = (timeoutMs === void 0 ? effect : effect.pipe(Effect.timeoutOrElse({
6867
+ return runCapxulEffect((timeoutMs === void 0 ? effect : effect.pipe(Effect.timeoutOrElse({
6789
6868
  duration: `${timeoutMs} millis`,
6790
6869
  orElse: () => Effect.fail({ publicError: Errors.providerTimeout("sdk", operation, timeoutMs) })
6791
- }))).pipe(Effect.tap(() => Effect.annotateCurrentSpan({ outcome: "succeeded" })), Effect.tapError((failure) => {
6792
- 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;
6793
6878
  return Effect.annotateCurrentSpan({
6794
- outcome: portFailureOutcome(failure.publicError.code),
6795
- failure_code: failure.publicError.code,
6879
+ outcome: portFailureOutcome(error.code),
6880
+ failure_code: error.code,
6796
6881
  ...typeof mode === "string" ? { mode } : {}
6797
6882
  });
6798
6883
  }), Effect.tapDefect(() => Effect.annotateCurrentSpan({
6799
6884
  outcome: "failed",
6800
6885
  failure_code: "UNKNOWN"
6801
- })), Effect.withSpan(`identity.port.${operation}`));
6802
- 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);
6803
6888
  }
6804
6889
  /** Map machine-internal failure state onto the public SDK error vocabulary. */
6805
6890
  function publicIdentityFailure(failure) {
@@ -8550,7 +8635,7 @@ function makeAccountMethods(deps) {
8550
8635
  value: provisioningPhase(deps.actor.snapshot())
8551
8636
  };
8552
8637
  };
8553
- const resolveLifecycle = async () => {
8638
+ const resolveLifecycle = async (controls) => {
8554
8639
  const phase = provisioningPhase(deps.actor.snapshot());
8555
8640
  const status = await getStatus();
8556
8641
  if (!status.ok) return accountFailureResult(status.error);
@@ -8558,7 +8643,7 @@ function makeAccountMethods(deps) {
8558
8643
  if (status.value.status !== "notAuthenticated" && (phase.status === "ready" || isRequirementMet(status.value, requirement))) {
8559
8644
  const accountReadPort = deps.accountReadPort;
8560
8645
  if (accountReadPort === void 0) return accountFailureResult(Errors.invalidInput("account", "accountReadPort is required to resolve ready lifecycle"));
8561
- 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);
8562
8647
  if (!account.ok) return accountFailureResult(account.error);
8563
8648
  accountId = String(account.value.id);
8564
8649
  }
@@ -8572,8 +8657,9 @@ function makeAccountMethods(deps) {
8572
8657
  })
8573
8658
  };
8574
8659
  };
8575
- const getLifecycle = () => resolveLifecycle();
8660
+ const getLifecycle = () => resolveLifecycle(deps.invocationControls?.());
8576
8661
  const retrySetup = async () => {
8662
+ const controls = deps.invocationControls?.();
8577
8663
  const resetSession = deps.signer?.resetSession;
8578
8664
  if (typeof resetSession === "function") try {
8579
8665
  resetSession.call(deps.signer);
@@ -8582,7 +8668,7 @@ function makeAccountMethods(deps) {
8582
8668
  }
8583
8669
  const retried = await drive({ _tag: "RetryAccount" });
8584
8670
  if (!retried.ok) return accountFailureResult(retried.error);
8585
- return resolveLifecycle();
8671
+ return resolveLifecycle(controls);
8586
8672
  };
8587
8673
  return {
8588
8674
  methods: {
@@ -8642,14 +8728,14 @@ const moneyExecutionContract = {
8642
8728
  };
8643
8729
  //#endregion
8644
8730
  //#region ../../packages/sdk/package.json
8645
- var version = "2.8.0";
8731
+ var version = "2.8.2";
8646
8732
  //#endregion
8647
- //#region ../../packages/sdk/src/telemetry/capture-exception.ts
8648
- /** 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. */
8649
8735
  const EXCEPTION_MESSAGE = "Capxul SDK operation failed";
8736
+ const SDK_VERSION$1 = version;
8650
8737
  //#endregion
8651
8738
  //#region ../../packages/sdk/src/observation.ts
8652
- const SDK_VERSION$1 = version;
8653
8739
  /** @internal Observe public result methods at the assembled Core SDK boundary. */
8654
8740
  function observeSdkClient(client, adapter, snapshot) {
8655
8741
  if (adapter === void 0) return client;
@@ -8893,18 +8979,45 @@ function errorKind$1(cause) {
8893
8979
  * Shared by the failure boundary and the `bootstrap_failed` product event.
8894
8980
  */
8895
8981
  function failureDetail(cause) {
8896
- if (!isCapxulError(cause)) return void 0;
8897
- const details = cause.details;
8982
+ const error = observationError(cause);
8983
+ if (error === void 0) return void 0;
8984
+ const details = error.details;
8898
8985
  const source = typeof details === "object" && details !== null ? details : {};
8899
8986
  return sanitizeFailureDetail({
8900
8987
  provider: source.provider,
8901
8988
  provider_operation: source.operation,
8902
- 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,
8903
8993
  reason: source.reason,
8904
8994
  http_status: source.httpStatus,
8905
- ...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)
8906
9006
  });
8907
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
+ }
8908
9021
  /** The chain-cause half of {@link sanitizeFailureDetail}: same bounds, same masking. */
8909
9022
  function sanitizeChainDetail(source, detail) {
8910
9023
  for (const key of [
@@ -8916,6 +9029,7 @@ function sanitizeChainDetail(source, detail) {
8916
9029
  const value = source[key];
8917
9030
  if (typeof value === "string" && ENUMERATED_DETAIL_RE.test(value)) detail[key] = value;
8918
9031
  }
9032
+ sanitizeProviderErrorDetail(source, detail);
8919
9033
  const status = source.http_status;
8920
9034
  if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599) detail.http_status = status;
8921
9035
  for (const key of [
@@ -8944,15 +9058,51 @@ function sanitizeChainDetail(source, detail) {
8944
9058
  const providerMessage = evidenceText(source.chain_provider_message);
8945
9059
  if (providerMessage !== void 0) detail.chain_provider_message = providerMessage;
8946
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
+ }
8947
9095
  function sanitizeFailureDetail(input) {
8948
9096
  if (typeof input !== "object" || input === null) return void 0;
8949
9097
  const source = input;
8950
9098
  const detail = {};
9099
+ sanitizeConnectionDetail(source, detail);
8951
9100
  sanitizeChainDetail(source, detail);
8952
9101
  return Object.keys(detail).length === 0 ? void 0 : detail;
8953
9102
  }
8954
9103
  /** Enumerated codes only (`convex`, `no-secure-context`, `bootstrap-encode`); free text fails. */
8955
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;
8956
9106
  /** A four-byte revert selector, or the bare `0x` of an empty revert. */
8957
9107
  const REVERT_SELECTOR_RE = /^0x(?:[0-9a-fA-F]{8})?$/u;
8958
9108
  function normalizeOperation$1(value) {
@@ -11157,11 +11307,13 @@ async function safeText$1(res) {
11157
11307
  }
11158
11308
  var HttpBootstrapAdapter = class {
11159
11309
  bootstrapBaseUrl;
11310
+ bootstrapHost;
11160
11311
  fetchImpl;
11161
11312
  observation;
11162
11313
  retry;
11163
11314
  constructor(deps) {
11164
11315
  this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\/$/, "");
11316
+ this.bootstrapHost = hostOf(this.bootstrapBaseUrl);
11165
11317
  this.observation = deps.observation;
11166
11318
  this.retry = deps.retry ?? DEFAULT_RETRY;
11167
11319
  this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));
@@ -11187,7 +11339,11 @@ var HttpBootstrapAdapter = class {
11187
11339
  body: JSON.stringify({ publishableKey: input.publishableKey })
11188
11340
  });
11189
11341
  },
11190
- 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
+ }))
11191
11347
  }).pipe(Effect.flatMap((res) => this.mapResponse(res)));
11192
11348
  }
11193
11349
  mapResponse(res) {
@@ -11243,6 +11399,13 @@ var HttpBootstrapAdapter = class {
11243
11399
  function HttpBootstrapLayer(deps) {
11244
11400
  return Layer.succeed(BootstrapPortTag, new HttpBootstrapAdapter(deps));
11245
11401
  }
11402
+ function hostOf(url) {
11403
+ try {
11404
+ return new URL(url).hostname;
11405
+ } catch {
11406
+ return;
11407
+ }
11408
+ }
11246
11409
  function normalizeRuntimeUrl(field, raw) {
11247
11410
  let parsed;
11248
11411
  try {
@@ -14209,26 +14372,207 @@ var ConvexClient = class {
14209
14372
  //#endregion
14210
14373
  //#region ../../packages/sdk/src/ports/convex-call.ts
14211
14374
  var ConvexCallError = class extends Data.TaggedError("ConvexCallError") {};
14212
- function convexCallErrorFromCapxul(operation, error) {
14375
+ function convexCallErrorFromCapxul(operation, error, transport) {
14213
14376
  return new ConvexCallError({
14214
14377
  operation,
14215
14378
  publicCode: error.code,
14216
14379
  publicError: error,
14217
14380
  cause: error,
14218
- ...error.details === void 0 ? {} : { details: error.details }
14381
+ ...error.details === void 0 ? {} : { details: error.details },
14382
+ ...transport === void 0 ? {} : { transport }
14219
14383
  });
14220
14384
  }
14221
14385
  var ConvexCallPortTag = class extends Context.Service()("@capxul/sdk/ports/ConvexCallPort") {};
14222
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
14223
14564
  //#region ../../packages/sdk/src/adapters/convex-call/ConvexCallAdapter.ts
14224
14565
  /** Exact floor-first allowlist; every additional handler must migrate its validator first. */
14225
14566
  const OBSERVED_CONVEX_ACTIONS = /* @__PURE__ */ new Set([
14567
+ "account/actions:readBalance",
14568
+ "holdings/actions:current",
14226
14569
  "smartAccount/actions:claim",
14227
14570
  "org/actions:prepareFounderAccount",
14228
14571
  "org/actions:prepareBootstrap",
14229
14572
  "org/actions:submitBootstrap",
14230
14573
  "org/actions:resumeBootstrapSubmission",
14231
- "org/actions:confirmBootstrap"
14574
+ "org/actions:confirmBootstrap",
14575
+ "org/actions:readTreasury"
14232
14576
  ]);
14233
14577
  const OBSERVED_CONVEX_QUERIES = /* @__PURE__ */ new Set([
14234
14578
  "identity/queries:loadByAuthUserId",
@@ -14249,8 +14593,11 @@ var ConvexCallAdapter = class {
14249
14593
  #tokenProvider;
14250
14594
  #applicationId;
14251
14595
  #observation;
14596
+ #connectionMonitor;
14252
14597
  constructor(deps) {
14253
- 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 });
14254
14601
  this.#tokenProvider = deps.tokenProvider;
14255
14602
  this.#applicationId = deps.applicationId;
14256
14603
  this.#observation = deps.observation;
@@ -14259,6 +14606,9 @@ var ConvexCallAdapter = class {
14259
14606
  refreshAuth() {
14260
14607
  if (this.#tokenProvider) this.#client.setAuth(this.#tokenProvider);
14261
14608
  }
14609
+ observeConnection(observer) {
14610
+ return this.#connectionMonitor.observe(this.#client, observer);
14611
+ }
14262
14612
  query(fn, args) {
14263
14613
  const path = getFunctionName(fn);
14264
14614
  return Effect.serviceOption(Tracer.ParentSpan).pipe(Effect.flatMap((parent) => {
@@ -14283,10 +14633,14 @@ var ConvexCallAdapter = class {
14283
14633
  const path = getFunctionName(fn);
14284
14634
  return Effect.serviceOption(Tracer.ParentSpan).pipe(Effect.flatMap((parent) => {
14285
14635
  const traceparent = parent._tag === "Some" ? formatTraceparent(parent.value) : void 0;
14636
+ const connectionAtStart = connectionState(this.#client);
14286
14637
  return Effect.tryPromise({
14287
14638
  try: () => this.#client.action(fn, this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args, traceparent)),
14288
- catch: (cause) => mapToConvexCallError(path, cause)
14289
- });
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)));
14290
14644
  }));
14291
14645
  }
14292
14646
  #observedArgs(allowlist, path, args, traceparent) {
@@ -14340,24 +14694,52 @@ var ConvexCallAdapter = class {
14340
14694
  })));
14341
14695
  }
14342
14696
  async close() {
14697
+ this.#connectionMonitor.close();
14343
14698
  await this.#client.close();
14344
14699
  }
14345
14700
  };
14346
14701
  function ConvexCallLayer(deps) {
14347
14702
  return Layer.effect(ConvexCallPortTag, Effect.acquireRelease(Effect.sync(() => new ConvexCallAdapter(deps)), (adapter) => Effect.promise(() => adapter.close()).pipe(Effect.orDie)));
14348
14703
  }
14349
- function mapToCapxulError(operation, err) {
14704
+ function mapToCapxulError(operation, err, transport) {
14350
14705
  const decoded = decodeConvexError(err);
14351
14706
  if (decoded !== null) return decoded;
14352
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
+ }
14353
14717
  if (err instanceof Error) {
14354
- if (isTransportError(err)) return Errors.networkError(operation, err);
14718
+ if (isTransportError(err)) return Errors.networkError(operation, err, { provider: "convex" });
14355
14719
  return Errors.providerError("convex", operation, err);
14356
14720
  }
14357
14721
  return Errors.providerError("convex", operation, new Error(String(err)));
14358
14722
  }
14359
- function mapToConvexCallError(operation, err) {
14360
- 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));
14361
14743
  }
14362
14744
  const TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
14363
14745
  "EAI_AGAIN",
@@ -14476,723 +14858,148 @@ function wireChainId(chainId) {
14476
14858
  return chainId;
14477
14859
  }
14478
14860
  //#endregion
14479
- //#region ../../packages/sdk/src/ports/account-read.ts
14480
- var AccountReadError = class extends Data.TaggedError("AccountReadError") {};
14481
- function accountReadErrorFromCapxul(operation, error, cause = error) {
14482
- return new AccountReadError({
14483
- operation,
14484
- publicCode: error.code,
14485
- publicError: error,
14486
- cause,
14487
- ...error.details === void 0 ? {} : { details: error.details }
14488
- });
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;
14489
14865
  }
14490
- var AccountReadPortTag = class extends Context.Service()("@capxul/sdk/ports/AccountReadPort") {};
14491
14866
  //#endregion
14492
- //#region ../../packages/sdk/src/adapters/account-read/ConvexAccountAdapter.ts
14493
- const DEFAULT_FUNCTIONS$3 = {
14494
- readBalance: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].readBalance),
14495
- faucetMint: makeFunctionReference(CAPXUL_FUNCTIONS["account/actions"].faucetMint)
14496
- };
14497
- var ConvexAccountAdapter = class {
14498
- #convex;
14499
- #fns;
14500
- constructor(deps) {
14501
- this.#convex = deps.convex;
14502
- this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$3;
14503
- }
14504
- readBalance(input) {
14505
- 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))));
14506
- }
14507
- fundFromFaucet(input) {
14508
- const operation = "fundFromFaucet";
14509
- return Effect.suspend(() => {
14510
- const rawAmount = toWei(input.amount);
14511
- return this.#convex.action(this.#fns.faucetMint, {
14512
- chainId: wireChainId(input.chainId),
14513
- rawAmount
14514
- });
14515
- }).pipe(Effect.mapError((error) => accountReadErrorFromCapxul(operation, error.publicError, error)), Effect.map((wire) => ({ txHash: wire.txHash })), Effect.catchDefect((cause) => Effect.fail(accountReadErrorFromUnknown(operation, cause))));
14516
- }
14517
- };
14518
- function ConvexAccountLayer() {
14519
- return Layer.effect(AccountReadPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexAccountAdapter({ convex })));
14520
- }
14521
- function brandAccountEffect(operation, wire) {
14522
- return Effect.try({
14523
- try: () => brandAccount(wire),
14524
- 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
+ }));
14525
14905
  });
14526
14906
  }
14527
- function brandAccount(wire) {
14528
- const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
14529
- const available = fromWei(wire.rawAvailableBalance ?? wire.rawBalance, wire.decimals, wire.currency);
14530
- return {
14531
- id: toAccountId(wire.accountId),
14532
- balance,
14533
- available
14534
- };
14535
- }
14536
- function accountReadErrorFromUnknown(operation, cause) {
14537
- if (cause instanceof CapxulError) return accountReadErrorFromCapxul(operation, cause);
14538
- return accountReadErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14539
- }
14540
- //#endregion
14541
- //#region ../../packages/sdk/src/ports/smart-account.ts
14542
- var SmartAccountError = class extends Data.TaggedError("SmartAccountError") {};
14543
- function smartAccountErrorFromCapxul(operation, error, cause = error) {
14544
- return new SmartAccountError({
14545
- operation,
14546
- publicCode: error.code,
14547
- publicError: error,
14548
- cause,
14549
- ...error.details === void 0 ? {} : { details: error.details }
14550
- });
14907
+ function omitTransportKind(transport) {
14908
+ const { kind: _kind, ...connection } = transport;
14909
+ return connection;
14551
14910
  }
14552
- var SmartAccountPortTag = class extends Context.Service()("@capxul/sdk/ports/SmartAccountPort") {};
14553
14911
  //#endregion
14554
- //#region ../../packages/sdk/src/adapters/smart-account/ConvexSmartAccountAdapter.ts
14555
- const DEFAULT_FUNCTIONS$2 = {
14556
- loadByAuthUserId: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadByAuthUserId),
14557
- loadBySmartAccountAddress: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/queries"].loadBySmartAccountAddress),
14558
- provision: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/mutations"].provision),
14559
- confirmDeployment: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].confirmDeployment),
14560
- claim: makeFunctionReference(CAPXUL_FUNCTIONS["smartAccount/actions"].claim)
14561
- };
14562
- var ConvexSmartAccountAdapter = class {
14563
- #convex;
14564
- #fns;
14565
- constructor(deps) {
14566
- this.#convex = deps.convex;
14567
- this.#fns = deps.functions ?? DEFAULT_FUNCTIONS$2;
14568
- }
14569
- loadByAuthUserId(authUserId) {
14570
- 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))));
14571
- }
14572
- loadBySmartAccountAddress(address) {
14573
- 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))));
14574
- }
14575
- provision(input) {
14576
- 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({
14577
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14578
- catch: (cause) => smartAccountErrorFromUnknown("provision", cause)
14579
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("provision", cause))));
14580
- }
14581
- confirmDeployment(input) {
14582
- const evidence = {
14583
- chainId: wireChainId(input.evidence.chainId),
14584
- signerAddress: input.evidence.signerAddress,
14585
- safeAddress: input.evidence.safeAddress,
14586
- ...input.evidence.userOpHash === void 0 ? {} : { userOpHash: input.evidence.userOpHash },
14587
- ...input.evidence.txHash === void 0 ? {} : { txHash: input.evidence.txHash },
14588
- ...input.evidence.blockNumber === void 0 ? {} : { blockNumber: input.evidence.blockNumber }
14589
- };
14590
- return this.#convex.action(this.#fns.confirmDeployment, {
14591
- chainId: wireChainId(input.chainId),
14592
- safeAddress: input.safeAddress,
14593
- evidence
14594
- }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("confirmDeployment", error.publicError, error)), Effect.flatMap((row) => Effect.try({
14595
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14596
- catch: (cause) => smartAccountErrorFromUnknown("confirmDeployment", cause)
14597
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("confirmDeployment", cause))));
14598
- }
14599
- claim(input) {
14600
- return this.#convex.action(this.#fns.claim, copyInvocationObservation(input, {
14601
- chainId: wireChainId(input.chainId),
14602
- signerAddress: input.signerAddress
14603
- })).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("claim", error.publicError, error)), Effect.flatMap((row) => Effect.try({
14604
- try: () => brandProvisionedSmartAccount(input.authUserId, row),
14605
- catch: (cause) => smartAccountErrorFromUnknown("claim", cause)
14606
- })), Effect.catchDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("claim", cause))));
14607
- }
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
14608
14969
  };
14609
- function ConvexSmartAccountLayer() {
14610
- return Layer.effect(SmartAccountPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexSmartAccountAdapter({ convex })));
14611
- }
14612
- function brandSmartAccountEffect(operation, wire) {
14613
- return Effect.try({
14614
- try: () => wire === null ? null : brandNonNullSmartAccount(wire),
14615
- catch: (cause) => smartAccountErrorFromUnknown(operation, cause)
14616
- });
14617
- }
14618
- function brandNonNullSmartAccount(wire) {
14619
- return {
14620
- authUserId: toAuthUserId(wire.authUserId),
14621
- signerAddress: wire.signerAddress === null ? null : toAddress(wire.signerAddress),
14622
- smartAccountAddress: toAddress(wire.smartAccountAddress),
14623
- chainId: toChainId(wire.chainId),
14624
- deployedAt: wire.deployedAt === null ? null : toEpochMs(wire.deployedAt),
14625
- claimedAt: wire.claimedAt === null ? null : toEpochMs(wire.claimedAt),
14626
- createdAt: toEpochMs(wire.createdAt)
14627
- };
14628
- }
14629
- function brandProvisionedSmartAccount(requestedAuthUserId, wire) {
14630
- if (wire.authUserId !== String(requestedAuthUserId)) throw Errors.notAuthenticated();
14631
- return brandNonNullSmartAccount(wire);
14632
- }
14633
- function smartAccountErrorFromUnknown(operation, cause) {
14634
- if (cause instanceof CapxulError) return smartAccountErrorFromCapxul(operation, cause);
14635
- return smartAccountErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14636
- }
14637
- //#endregion
14638
- //#region ../../packages/sdk/src/ports/org.ts
14639
- var OrgError = class extends Data.TaggedError("OrgError") {};
14640
- function orgErrorFromCapxul(operation, error, cause = error) {
14641
- return new OrgError({
14642
- operation,
14643
- publicCode: error.code,
14644
- publicError: error,
14645
- cause,
14646
- ...error.details === void 0 ? {} : { details: error.details }
14647
- });
14648
- }
14649
- var OrgPortTag = class extends Context.Service()("@capxul/sdk/ports/OrgPort") {};
14650
- //#endregion
14651
- //#region ../../packages/sdk/src/adapters/org/parse.ts
14652
14970
  /**
14653
- * Map a `WireOrg` + its (separately read) treasury `Account` into the branded
14654
- * `OrgView`. The viewer role is projected by the authenticated backend read;
14655
- * it must never be inferred from Organization ownership. Brands at the read
14656
- * 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.
14657
14975
  */
14658
- function brandOrgView(wire, treasury, viewerRole) {
14659
- return {
14660
- id: toOrgId(wire.orgId),
14661
- name: wire.name,
14662
- handle: wire.slug,
14663
- safeAddress: toAddress(wire.safeAddress.toLowerCase()),
14664
- role: viewerRole,
14665
- treasury,
14666
- bio: wire.bio ?? null,
14667
- size: wire.size ?? null,
14668
- logoUrl: wire.logoUrl ?? null
14669
- };
14670
- }
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
+ };
14671
14990
  /**
14672
- * Build the Org treasury `Account` from the raw on-chain `balanceOf` integer
14673
- * (the D3 RPC read). `available === balance` for a treasury with no envelope
14674
- * 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.
14675
14995
  */
14676
- function brandOrgTreasury(input) {
14677
- return {
14678
- id: toAccountId(`account_${orgIdBody(input.orgId)}`),
14679
- balance: input.money,
14680
- available: input.money
14681
- };
14682
- }
14683
- function brandOrgRole(wire) {
14684
- return {
14685
- orgId: toOrgId(wire.orgId),
14686
- label: wire.label,
14687
- roleKey: toRoleKey(wire.roleKey),
14688
- definition: parseRoleDefinition(wire.definitionJson)
14689
- };
14690
- }
14691
- function brandOrgMember(wire) {
14996
+ function stampTelemetryEnvelope(event, defaults) {
14692
14997
  return {
14693
- orgId: toOrgId(wire.orgId),
14694
- email: toEmail(wire.email),
14695
- name: wire.name,
14696
- personalSafeAddress: wire.personalSafeAddress === null ? null : toAddress(wire.personalSafeAddress),
14697
- role: wire.role,
14698
- roleKey: wire.roleKey === null ? null : toRoleKey(wire.roleKey),
14699
- status: wire.status,
14700
- grantTxHash: wire.grantTxHash,
14701
- revokeTxHash: wire.revokeTxHash
14702
- };
14703
- }
14704
- function parseRoleDefinition(json) {
14705
- let raw;
14706
- try {
14707
- const parsed = JSON.parse(json);
14708
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("expected object");
14709
- raw = parsed;
14710
- } catch (err) {
14711
- throw new Error(`Invalid role definition: malformed JSON - ${err instanceof Error ? err.message : String(err)}`, { cause: err });
14712
- }
14713
- if (typeof raw.label !== "string" || raw.label.trim().length === 0) throw new Error("Invalid role definition: missing label");
14714
- return {
14715
- label: raw.label,
14716
- ...raw.spend === void 0 ? {} : { spend: {
14717
- ...raw.spend.perTx === void 0 ? {} : { perTx: parseRoleMoney(raw.spend.perTx, "perTx") },
14718
- ...raw.spend.perDay === void 0 ? {} : { perDay: parseRoleMoney(raw.spend.perDay, "perDay") },
14719
- ...raw.spend.toRecipients === void 0 ? {} : { toRecipients: parseRoleRecipients(raw.spend.toRecipients) }
14720
- } },
14721
- ...typeof raw.canSpend === "boolean" ? { canSpend: raw.canSpend } : {},
14722
- ...typeof raw.canManageMembers === "boolean" ? { canManageMembers: raw.canManageMembers } : {},
14723
- ...typeof raw.canManageRoles === "boolean" ? { canManageRoles: raw.canManageRoles } : {}
14724
- };
14725
- }
14726
- function parseRoleMoney(raw, field) {
14727
- if (typeof raw.currency !== "string" || typeof raw.value !== "string" || !/^\d+$/.test(raw.value) || raw.decimals !== 6) throw new Error(`Invalid role money: ${field}`);
14728
- return {
14729
- currency: toCurrencyCode(raw.currency),
14730
- value: raw.value,
14731
- decimals: raw.decimals
14732
- };
14733
- }
14734
- function parseRoleRecipients(raw) {
14735
- if (raw === "anyone") return "anyone";
14736
- if (!Array.isArray(raw)) throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
14737
- return raw.map((recipient) => {
14738
- if (typeof recipient !== "string") throw new Error("Invalid role definition: toRecipients must be \"anyone\" or an array");
14739
- return toAddress(recipient);
14740
- });
14741
- }
14742
- /** Strip the `org_` prefix + non-alphanumerics so the body re-seeds `account_`. */
14743
- function orgIdBody(orgId) {
14744
- const underscore = orgId.indexOf("_");
14745
- const cleaned = (underscore < 0 ? orgId : orgId.slice(underscore + 1)).replace(/[^0-9A-Za-z]/g, "");
14746
- return cleaned.length > 0 ? cleaned : "0";
14747
- }
14748
- //#endregion
14749
- //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationAdapter.ts
14750
- const DEFAULT_FUNCTIONS$1 = {
14751
- listAll: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listAll),
14752
- listRoles: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listRolesByOrgId),
14753
- listMembers: makeFunctionReference(CAPXUL_FUNCTIONS["org/queries"].listMembersByOrgId),
14754
- readTreasury: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].readTreasury),
14755
- inviteMember: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].inviteMember),
14756
- resendInvite: makeFunctionReference(CAPXUL_FUNCTIONS["org/mutations"].resendInviteToken),
14757
- detectInvitations: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].detectAndAcceptPendingInvitations)
14758
- };
14759
- /**
14760
- * Standard production Organization read adapter. It intentionally has no
14761
- * deployer/RPC/test configuration: authenticated Convex actions own live chain
14762
- * reads, while the lifecycle adapter owns the single sponsored bootstrap.
14763
- */
14764
- var ConvexOrganizationAdapter = class {
14765
- #convex;
14766
- #fns;
14767
- constructor(input) {
14768
- this.#convex = input.convex;
14769
- this.#fns = input.functions ?? DEFAULT_FUNCTIONS$1;
14770
- }
14771
- createOrg(_input) {
14772
- return Effect.fail(orgErrorFromCapxul("createOrg", Errors.notImplemented("organizationSetup", "use onboarding.completeOrganization")));
14773
- }
14774
- listOrgs(_input) {
14775
- 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) => {
14776
- const viewerRole = wire.viewerRole.trim();
14777
- if (viewerRole.length === 0) throw Errors.wrongState({
14778
- method: "listOrgs",
14779
- currentState: "viewerRoleMissing",
14780
- validStates: ["activeViewerRole"]
14781
- });
14782
- return brandOrgView(wire, treasury, viewerRole);
14783
- })))), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("listOrgs", cause))));
14784
- }
14785
- readTreasury(input) {
14786
- return this.#readTreasuryWire(String(input.orgId)).pipe(Effect.catchDefect((cause) => Effect.fail(toOrgError$1("readTreasury", cause))));
14787
- }
14788
- listRoles(input) {
14789
- 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))));
14790
- }
14791
- listMembers(input) {
14792
- 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))));
14793
- }
14794
- pendingMembers(input) {
14795
- return this.listMembers(input).pipe(Effect.map((members) => members.filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant")));
14796
- }
14797
- inviteMember(input) {
14798
- return this.#convex.action(this.#fns.inviteMember, {
14799
- orgId: input.orgId,
14800
- email: input.input.email,
14801
- role: input.input.role
14802
- }).pipe(Effect.mapError((error) => orgErrorFromCapxul("inviteMember", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("inviteMember", cause))));
14803
- }
14804
- resendInviteToken(input) {
14805
- return this.#convex.mutation(this.#fns.resendInvite, {
14806
- orgId: input.orgId,
14807
- email: input.email
14808
- }).pipe(Effect.mapError((error) => orgErrorFromCapxul("resendInviteToken", error.publicError, error)), Effect.map(brandOrgMember), Effect.catchDefect((cause) => Effect.fail(toOrgError$1("resendInviteToken", cause))));
14809
- }
14810
- detectAndAcceptPendingInvitations(_input) {
14811
- 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))));
14812
- }
14813
- #readTreasuryWire(orgId) {
14814
- return this.#convex.action(this.#fns.readTreasury, { orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("readTreasury", error.publicError, error)), Effect.map((wire) => {
14815
- if (wire.orgId !== orgId) throw Errors.invalidInput("orgId", "Organization treasury scope does not match");
14816
- const balance = fromWei(wire.rawBalance, wire.decimals, wire.currency);
14817
- const available = fromWei(wire.rawAvailableBalance, wire.decimals, wire.currency);
14818
- return {
14819
- ...brandOrgTreasury({
14820
- orgId: wire.orgId,
14821
- money: balance
14822
- }),
14823
- available
14824
- };
14825
- }));
14826
- }
14827
- };
14828
- function toOrgError$1(operation, cause) {
14829
- if (cause instanceof CapxulError) return orgErrorFromCapxul(operation, cause);
14830
- return orgErrorFromCapxul(operation, Errors.providerError("convex", operation, cause), cause);
14831
- }
14832
- function partialOrgTruth(operation, currentState) {
14833
- return orgErrorFromCapxul(operation, Errors.wrongState({
14834
- method: operation,
14835
- currentState,
14836
- validStates: ["completeProductionOrganizationTruth"]
14837
- }));
14838
- }
14839
- //#endregion
14840
- //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationSetupAdapter.ts
14841
- const DEFAULT_FUNCTIONS = {
14842
- startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].startOrResume),
14843
- prepareFounderAccount: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareFounderAccount),
14844
- prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareBootstrap),
14845
- submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].submitBootstrap),
14846
- resumeBootstrapSubmission: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].resumeBootstrapSubmission),
14847
- confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].confirmBootstrap),
14848
- recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].recordFailure),
14849
- load: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].load),
14850
- retry: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].retry)
14851
- };
14852
- /** Durable Organization setup capability composed by the standard client. */
14853
- var ConvexOrganizationSetupAdapter = class {
14854
- #convex;
14855
- #signer;
14856
- #chainId;
14857
- #fns;
14858
- constructor(input) {
14859
- this.#convex = input.convex;
14860
- this.#signer = input.signer;
14861
- this.#chainId = input.chainId;
14862
- this.#fns = input.functions ?? DEFAULT_FUNCTIONS;
14863
- }
14864
- async startOrResume(input) {
14865
- const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, copyInvocationObservation(input, {
14866
- ...input,
14867
- chainId: this.#chainId
14868
- })));
14869
- if (!result.ok) return result;
14870
- const lifecycle = parseLifecycle("startOrResume", result.value.lifecycle);
14871
- if (!lifecycle.ok) return lifecycle;
14872
- const orgId = parseOrgId("startOrResume", result.value.orgId);
14873
- if (!orgId.ok) return orgId;
14874
- if (String(orgId.value) !== String(lifecycle.value.orgId)) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle scope does not match"));
14875
- return {
14876
- ok: true,
14877
- value: {
14878
- orgId: orgId.value,
14879
- lifecycle: lifecycle.value
14880
- }
14881
- };
14882
- }
14883
- prepareFounderAccount(input) {
14884
- return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, copyInvocationObservation(input, {
14885
- orgId: input.orgId,
14886
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14887
- })));
14888
- }
14889
- async authorizeAndSubmitBootstrap(input) {
14890
- const cancelled = cancellation(input.signal);
14891
- if (cancelled !== void 0) return cancelled;
14892
- const signerAddress = await signerResult(this.#signer.source, "getAddress", () => this.#signer.getAddress());
14893
- if (!signerAddress.ok) return signerAddress;
14894
- const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, copyInvocationObservation(input, {
14895
- orgId: input.orgId,
14896
- signerAddress: signerAddress.value,
14897
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14898
- })));
14899
- if (!prepared.ok) return prepared;
14900
- const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);
14901
- if (!authority.ok) return authority;
14902
- const cancelledAfterPrepare = cancellation(input.signal);
14903
- if (cancelledAfterPrepare !== void 0) return cancelledAfterPrepare;
14904
- const signature = await signerResult(this.#signer.source, "signUserOpHash", () => this.#signer.signUserOpHash(prepared.value.digest));
14905
- if (!signature.ok) return signature;
14906
- const cancelledAfterSign = cancellation(input.signal);
14907
- if (cancelledAfterSign !== void 0) return cancelledAfterSign;
14908
- const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, copyInvocationObservation(input, {
14909
- orgId: input.orgId,
14910
- signerAddress: signerAddress.value,
14911
- signature: signature.value,
14912
- userOp: prepared.value.userOp,
14913
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14914
- })));
14915
- if (!submitted.ok) return submitted;
14916
- return parseLifecycle("submitBootstrap", submitted.value);
14917
- }
14918
- resumeSubmittedBootstrap(input) {
14919
- return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, copyInvocationObservation(input, {
14920
- orgId: input.orgId,
14921
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14922
- })));
14923
- }
14924
- confirmSubmittedBootstrap(input) {
14925
- return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, copyInvocationObservation(input, {
14926
- orgId: input.orgId,
14927
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext },
14928
- ...input.retryDelayMs === void 0 ? {} : { retryDelayMs: input.retryDelayMs }
14929
- })));
14930
- }
14931
- async recordFailure(input) {
14932
- const errorProvider = input.error.details?.provider;
14933
- const errorOperation = input.error.details?.operation;
14934
- const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, copyInvocationObservation(input, {
14935
- orgId: input.orgId,
14936
- errorCode: input.error.code,
14937
- ...typeof errorProvider === "string" && typeof errorOperation === "string" ? {
14938
- errorProvider,
14939
- errorOperation
14940
- } : {},
14941
- retryable: input.retryable,
14942
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14943
- })));
14944
- return result.ok ? parseLifecycle("recordFailure", result.value) : result;
14945
- }
14946
- async loadLifecycle(input) {
14947
- const result = await runCall("loadLifecycle", this.#convex.query(this.#fns.load, input));
14948
- if (!result.ok) return result;
14949
- if (result.value === null) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle was not found"));
14950
- return parseLifecycle("loadLifecycle", result.value);
14951
- }
14952
- async retry(input) {
14953
- const cancelled = cancellation(input.signal);
14954
- if (cancelled !== void 0) return cancelled;
14955
- const current = await this.loadLifecycle({
14956
- orgId: input.orgId,
14957
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14958
- });
14959
- if (!current.ok) return current;
14960
- if (current.value.status === "failed" && current.value.retryable && (current.value.at === "awaitingFounderAuthorization" || current.value.at === "submittingBootstrap")) {
14961
- const reset = resetSignerSession(this.#signer);
14962
- if (!reset.ok) return reset;
14963
- }
14964
- const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, copyInvocationObservation(input, {
14965
- orgId: input.orgId,
14966
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
14967
- })));
14968
- if (!result.ok) return result;
14969
- return parseLifecycle("retry", result.value);
14970
- }
14971
- async #lifecycleAction(operation, input, call) {
14972
- const cancelled = cancellation(input.signal);
14973
- if (cancelled !== void 0) return cancelled;
14974
- const result = await runCall(operation, call());
14975
- if (!result.ok) return result;
14976
- const cancelledAfter = cancellation(input.signal);
14977
- if (cancelledAfter !== void 0) return cancelledAfter;
14978
- return parseLifecycle(operation, result.value);
14979
- }
14980
- };
14981
- function resetSignerSession(signer) {
14982
- const resetSession = signer.resetSession;
14983
- if (typeof resetSession !== "function") return {
14984
- ok: true,
14985
- value: void 0
14986
- };
14987
- try {
14988
- resetSession.call(signer);
14989
- return {
14990
- ok: true,
14991
- value: void 0
14992
- };
14993
- } catch (cause) {
14994
- return fail$1(signerFailure(signer.source, "resetSession", cause));
14995
- }
14996
- }
14997
- async function runCall(operation, effect) {
14998
- try {
14999
- const result = await Effect.runPromise(Effect.result(effect));
15000
- return Result.isSuccess(result) ? {
15001
- ok: true,
15002
- value: result.success
15003
- } : fail$1(publicError(operation, result.failure));
15004
- } catch (cause) {
15005
- return fail$1(publicError(operation, cause));
15006
- }
15007
- }
15008
- function publicError(operation, cause) {
15009
- if (cause instanceof CapxulError) return cause;
15010
- if (typeof cause === "object" && cause !== null) {
15011
- const carried = cause.publicError;
15012
- if (carried instanceof CapxulError) return carried;
15013
- }
15014
- return Errors.providerError("convex-organization", operation, cause);
15015
- }
15016
- async function signerResult(source, operation, run) {
15017
- try {
15018
- return {
15019
- ok: true,
15020
- value: await run()
15021
- };
15022
- } catch (cause) {
15023
- return fail$1(signerFailure(source, operation, cause));
15024
- }
15025
- }
15026
- function validatePreparedAuthorities(prepared, signerAddress) {
15027
- const signer = signerAddress.toLowerCase();
15028
- const preparedSigner = prepared.signerAddress.toLowerCase();
15029
- const founder = prepared.founderPersonalAccount.toLowerCase();
15030
- const organization = prepared.organizationAccountAddress.toLowerCase();
15031
- const sender = prepared.userOp.sender.toLowerCase();
15032
- if (preparedSigner !== signer) return fail$1(Errors.invalidInput("signerAddress", "Prepared signer does not match configured signer"));
15033
- if (founder === signer || organization === signer || organization === founder) return fail$1(Errors.invalidInput("organizationAuthority", "Signer EOA, founder Account, and Organization Account must be distinct"));
15034
- if (sender !== founder) return fail$1(Errors.invalidInput("userOp.sender", "Bootstrap sender must be the founder Account"));
15035
- 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"));
15036
- return {
15037
- ok: true,
15038
- value: void 0
15039
- };
15040
- }
15041
- function parseLifecycle(operation, wire) {
15042
- const orgId = parseOrgId(operation, wire.orgId);
15043
- if (!orgId.ok) return orgId;
15044
- if (wire.status === "loading") return {
15045
- ok: true,
15046
- value: {
15047
- status: "loading",
15048
- orgId: orgId.value
15049
- }
15050
- };
15051
- if (wire.status === "ready") return {
15052
- ok: true,
15053
- value: {
15054
- status: "ready",
15055
- orgId: orgId.value,
15056
- canTransact: true
15057
- }
15058
- };
15059
- if (wire.status === "failed") {
15060
- if (!isSetupStep(wire.at)) return fail$1(Errors.invalidInput("lifecycle.at", "Unknown setup step"));
15061
- return {
15062
- ok: true,
15063
- value: {
15064
- status: "failed",
15065
- orgId: orgId.value,
15066
- at: wire.at,
15067
- error: new CapxulError(wire.error.code, wire.error.message),
15068
- retryable: wire.retryable
15069
- }
15070
- };
15071
- }
15072
- if (!isSetupStep(wire.step)) return fail$1(Errors.invalidInput("lifecycle.step", `Unknown setup step from ${operation}`));
15073
- return {
15074
- ok: true,
15075
- value: {
15076
- status: "settingUp",
15077
- orgId: orgId.value,
15078
- step: wire.step
15079
- }
15080
- };
15081
- }
15082
- function parseOrgId(operation, value) {
15083
- try {
15084
- return {
15085
- ok: true,
15086
- value: toOrgId(value)
15087
- };
15088
- } catch (cause) {
15089
- return fail$1(Errors.providerError("convex-organization", operation, cause));
15090
- }
15091
- }
15092
- function isSetupStep(value) {
15093
- return value === "preparingFounderAccount" || value === "awaitingFounderAuthorization" || value === "submittingBootstrap" || value === "confirmingBootstrap";
15094
- }
15095
- function cancellation(signal) {
15096
- return signal?.aborted ? fail$1(Errors.cancelled({ operation: "organization.setup" })) : void 0;
15097
- }
15098
- function fail$1(error) {
15099
- return {
15100
- ok: false,
15101
- error
15102
- };
15103
- }
15104
- //#endregion
15105
- //#region ../../packages/observability/src/index.ts
15106
- const PII = Schema.String.pipe(Schema.brand("PII"));
15107
- const OptionalString = Schema.optional(Schema.String);
15108
- const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
15109
- decode: SchemaGetter.transform((value) => value.toLowerCase()),
15110
- encode: SchemaGetter.transform((value) => value)
15111
- }), Schema.refine((value) => EVM_ADDRESS_RE$1.test(value), { message: "must be 0x + 40 hex chars" }));
15112
- const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
15113
- const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15114
- const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
15115
- const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15116
- const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
15117
- const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
15118
- const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE$1.test(value), { message: "must be 0x + 64 hex chars" }));
15119
- const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
15120
- const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
15121
- const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
15122
- const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
15123
- const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
15124
- const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
15125
- const OptionalAccountId = Schema.optional(AccountIdSchema);
15126
- const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
15127
- const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
15128
- const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
15129
- const OptionalAddress = Schema.optional(AddressSchema);
15130
- const OptionalAppId = Schema.optional(AppIdSchema);
15131
- const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
15132
- const OptionalChainId = Schema.optional(ChainIdSchema);
15133
- const OptionalDurationMs = Schema.optional(DurationMsSchema);
15134
- const OptionalEpochMs = Schema.optional(EpochMsSchema);
15135
- const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
15136
- const OptionalTxHash = Schema.optional(TxHashSchema);
15137
- /**
15138
- * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
15139
- * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
15140
- * decode instead of silently shipping an unattributable event. Call sites do
15141
- * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
15142
- * which is the only place that knows where the process runs.
15143
- */
15144
- const TelemetryEnvelopeProps = {
15145
- capxul_env: Schema.Literals([
15146
- "development",
15147
- "staging",
15148
- "production",
15149
- "unknown",
15150
- "local"
15151
- ]),
15152
- producer: Schema.Literals([
15153
- "server",
15154
- "browser",
15155
- "sdk",
15156
- "mcp",
15157
- "e2e"
15158
- ]),
15159
- journey_id: OptionalString,
15160
- correlation_id: OptionalString,
15161
- sdk_version: OptionalString
15162
- };
15163
- /**
15164
- * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
15165
- * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
15166
- * failure came from the chain path. Spread into every failure event and posted
15167
- * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
15168
- */
15169
- const FailureModeSchema = Schema.Literals(FAILURE_MODES$1);
15170
- const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
15171
- const ChainCauseTelemetryProps = {
15172
- failure_mode: Schema.optional(FailureModeSchema),
15173
- chain_upstream: Schema.optional(ChainUpstreamSchema),
15174
- chain_method: OptionalString,
15175
- chain_retryable: Schema.optional(Schema.Boolean),
15176
- chain_http_status: Schema.optional(Schema.Number),
15177
- chain_rpc_code: Schema.optional(Schema.Number),
15178
- chain_revert_name: OptionalString,
15179
- chain_revert_selector: OptionalString,
15180
- chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
15181
- chain_provider_message: OptionalString
15182
- };
15183
- /**
15184
- * Stamp the required envelope onto an event at its emit boundary. Call-site
15185
- * props win on conflict: a relay that already knows the true producer (the
15186
- * browser-failure relay stamps `browser` while running on the server) must not
15187
- * be overwritten by the transport's own default.
15188
- */
15189
- function stampTelemetryEnvelope(event, defaults) {
15190
- return {
15191
- name: event.name,
15192
- props: {
15193
- ...defaults,
15194
- ...event.props
15195
- }
14998
+ name: event.name,
14999
+ props: {
15000
+ ...defaults,
15001
+ ...event.props
15002
+ }
15196
15003
  };
15197
15004
  }
15198
15005
  const AuthOtpRequestedProps = Schema.Struct({
@@ -15252,7 +15059,10 @@ const BootstrapFailedProps = Schema.Struct({
15252
15059
  applicationId: OptionalAppId,
15253
15060
  durationMs: OptionalDurationMs,
15254
15061
  origin: OptionalString,
15255
- reason: OptionalString
15062
+ provider: OptionalString,
15063
+ provider_operation: OptionalString,
15064
+ reason: OptionalString,
15065
+ target_host: OptionalString
15256
15066
  });
15257
15067
  const AccountBalanceReadProps = Schema.Struct({
15258
15068
  ...TelemetryEnvelopeProps,
@@ -15317,6 +15127,9 @@ const OperationRetriedProps = Schema.Struct({
15317
15127
  ...TelemetryEnvelopeProps,
15318
15128
  operation: Schema.String,
15319
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),
15320
15133
  attempt: Schema.Number,
15321
15134
  delay_ms: DurationMsSchema
15322
15135
  });
@@ -15493,7 +15306,9 @@ const PaymentVerificationRetryProps = Schema.Struct({
15493
15306
  command_id: Schema.String,
15494
15307
  attempt: Schema.Number,
15495
15308
  reason_code: Schema.String,
15496
- chain_id: Schema.Number
15309
+ chain_id: Schema.Number,
15310
+ delay_ms: DurationMsSchema,
15311
+ outcome: Schema.Literals(["scheduled", "unresolved"])
15497
15312
  });
15498
15313
  const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
15499
15314
  const DepositSettledProps = Schema.Struct({
@@ -15727,190 +15542,824 @@ const TELEMETRY_EVENT_SCHEMAS = {
15727
15542
  props: MovementScanIncidentProps
15728
15543
  })
15729
15544
  };
15730
- function redactTelemetryProps(name, props, options = {}) {
15731
- if (props === void 0) return void 0;
15732
- const clone = cloneProps$1(props);
15733
- if (options.rawMode === true) return clone;
15734
- for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
15735
- 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);
15736
16090
  }
15737
- const PII_PROP_KEYS_BY_EVENT = {
15738
- auth_otp_requested: ["email"],
15739
- auth_otp_delivered: ["email"],
15740
- auth_otp_expired: ["email"],
15741
- 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)
15742
16110
  };
15743
- function redactProperty(props, key) {
15744
- const value = props[key];
15745
- 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
+ }
15746
16255
  }
15747
- function cloneProps$1(props) {
15748
- const cloned = {};
15749
- for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue$1(value);
15750
- 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
+ }
15751
16266
  }
15752
- function cloneTelemetryValue$1(value) {
15753
- if (Array.isArray(value)) return value.map(cloneTelemetryValue$1);
15754
- if (value === null || typeof value !== "object") return value;
15755
- if (Object.getPrototypeOf(value) !== Object.prototype) return value;
15756
- const cloned = {};
15757
- for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue$1(nested);
15758
- 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);
15759
16274
  }
15760
- const SHA256_INITIAL_HASH = [
15761
- 1779033703,
15762
- 3144134277,
15763
- 1013904242,
15764
- 2773480762,
15765
- 1359893119,
15766
- 2600822924,
15767
- 528734635,
15768
- 1541459225
15769
- ];
15770
- const SHA256_K = [
15771
- 1116352408,
15772
- 1899447441,
15773
- 3049323471,
15774
- 3921009573,
15775
- 961987163,
15776
- 1508970993,
15777
- 2453635748,
15778
- 2870763221,
15779
- 3624381080,
15780
- 310598401,
15781
- 607225278,
15782
- 1426881987,
15783
- 1925078388,
15784
- 2162078206,
15785
- 2614888103,
15786
- 3248222580,
15787
- 3835390401,
15788
- 4022224774,
15789
- 264347078,
15790
- 604807628,
15791
- 770255983,
15792
- 1249150122,
15793
- 1555081692,
15794
- 1996064986,
15795
- 2554220882,
15796
- 2821834349,
15797
- 2952996808,
15798
- 3210313671,
15799
- 3336571891,
15800
- 3584528711,
15801
- 113926993,
15802
- 338241895,
15803
- 666307205,
15804
- 773529912,
15805
- 1294757372,
15806
- 1396182291,
15807
- 1695183700,
15808
- 1986661051,
15809
- 2177026350,
15810
- 2456956037,
15811
- 2730485921,
15812
- 2820302411,
15813
- 3259730800,
15814
- 3345764771,
15815
- 3516065817,
15816
- 3600352804,
15817
- 4094571909,
15818
- 275423344,
15819
- 430227734,
15820
- 506948616,
15821
- 659060556,
15822
- 883997877,
15823
- 958139571,
15824
- 1322822218,
15825
- 1537002063,
15826
- 1747873779,
15827
- 1955562222,
15828
- 2024104815,
15829
- 2227730452,
15830
- 2361852424,
15831
- 2428436474,
15832
- 2756734187,
15833
- 3204031479,
15834
- 3329325298
15835
- ];
15836
- function sha256Hex(input) {
15837
- const padded = padSha256Message(new TextEncoder().encode(input));
15838
- const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
15839
- const words = /* @__PURE__ */ new Uint32Array(64);
15840
- let h0 = SHA256_INITIAL_HASH[0];
15841
- let h1 = SHA256_INITIAL_HASH[1];
15842
- let h2 = SHA256_INITIAL_HASH[2];
15843
- let h3 = SHA256_INITIAL_HASH[3];
15844
- let h4 = SHA256_INITIAL_HASH[4];
15845
- let h5 = SHA256_INITIAL_HASH[5];
15846
- let h6 = SHA256_INITIAL_HASH[6];
15847
- let h7 = SHA256_INITIAL_HASH[7];
15848
- for (let offset = 0; offset < padded.byteLength; offset += 64) {
15849
- for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
15850
- for (let i = 16; i < 64; i++) {
15851
- const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
15852
- const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
15853
- 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
15854
16308
  }
15855
- let a = h0;
15856
- let b = h1;
15857
- let c = h2;
15858
- let d = h3;
15859
- let e = h4;
15860
- let f = h5;
15861
- let g = h6;
15862
- let h = h7;
15863
- for (let i = 0; i < 64; i++) {
15864
- const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
15865
- const ch = e & f ^ ~e & g;
15866
- const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
15867
- const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
15868
- h = g;
15869
- g = f;
15870
- f = e;
15871
- e = d + temp1 >>> 0;
15872
- d = c;
15873
- c = b;
15874
- b = a;
15875
- 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
15876
16316
  }
15877
- h0 = h0 + a >>> 0;
15878
- h1 = h1 + b >>> 0;
15879
- h2 = h2 + c >>> 0;
15880
- h3 = h3 + d >>> 0;
15881
- h4 = h4 + e >>> 0;
15882
- h5 = h5 + f >>> 0;
15883
- h6 = h6 + g >>> 0;
15884
- 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
+ };
15885
16330
  }
15886
- return [
15887
- h0,
15888
- h1,
15889
- h2,
15890
- h3,
15891
- h4,
15892
- h5,
15893
- h6,
15894
- h7
15895
- ].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
+ };
15896
16340
  }
15897
- function padSha256Message(bytes) {
15898
- const bitLength = bytes.byteLength * 8;
15899
- const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
15900
- const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
15901
- output.set(bytes);
15902
- output[bytes.byteLength] = 128;
15903
- const view = new DataView(output.buffer);
15904
- view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
15905
- view.setUint32(output.byteLength - 4, bitLength >>> 0);
15906
- 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
+ }
15907
16350
  }
15908
- function rotr(value, bits) {
15909
- 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
+ };
15910
16362
  }
15911
- //#endregion
15912
- //#region ../../packages/sdk/src/ports/telemetry.ts
15913
- var TelemetryPortTag = class extends Context.Service()("@capxul/sdk/ports/TelemetryPort") {};
15914
16363
  //#endregion
15915
16364
  //#region ../../packages/sdk/src/adapters/telemetry/PostHogTelemetryAdapter.ts
15916
16365
  var PostHogTelemetryAdapter = class {
@@ -39032,8 +39481,59 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
39032
39481
  embeddedWallet: openfort.embeddedWallet,
39033
39482
  ensureWalletReady: ensureOpenfortWalletReady
39034
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
+ };
39035
39534
  return {
39036
39535
  ...signer,
39536
+ signUserOpHash,
39037
39537
  statusStore,
39038
39538
  ensureWalletReady: ensureOpenfortWalletReady,
39039
39539
  getAddress: async () => {
@@ -39049,12 +39549,7 @@ function createOpenfortBrowserSignerFromBootstrap(bootstrap, options = {}) {
39049
39549
  throw openfortProviderError("getAddress", cause);
39050
39550
  }
39051
39551
  },
39052
- resetSession: () => {
39053
- walletReadyPromise = null;
39054
- clearStaleOpenfortBrowserStorage(bootstrap.openfortPublishableKey);
39055
- signer.resetAddressCache();
39056
- setStatus("unknown");
39057
- }
39552
+ resetSession: resetReadiness
39058
39553
  };
39059
39554
  }
39060
39555
  function normalizeBetterAuthBaseUrl(raw) {
@@ -39980,7 +40475,7 @@ function accountsDepsLayer(deps) {
39980
40475
  }
39981
40476
  const readAccountProgram = Effect.gen(function* () {
39982
40477
  const deps = yield* AccountsDepsTag;
39983
- 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));
39984
40479
  });
39985
40480
  function fundFromFaucetProgram(amount) {
39986
40481
  return Effect.gen(function* () {
@@ -40010,7 +40505,11 @@ function makeAccountsMethods(deps) {
40010
40505
  ok: false,
40011
40506
  error: Errors.cancelled({ operation: "accounts.read" })
40012
40507
  };
40013
- 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);
40014
40513
  },
40015
40514
  async fund(amount, options) {
40016
40515
  if (options?.signal?.aborted) return {
@@ -40775,7 +41274,7 @@ function emitCreationFunnelTail(telemetry, org, chainId) {
40775
41274
  function readTreasuryProgram(orgId) {
40776
41275
  return Effect.gen(function* () {
40777
41276
  const deps = yield* OrgDepsTag;
40778
- 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));
40779
41278
  return zeroTreasury(orgId);
40780
41279
  });
40781
41280
  }
@@ -40859,7 +41358,7 @@ function detectAndAcceptPendingInvitationsProgram() {
40859
41358
  function listOrgsProgram() {
40860
41359
  return Effect.gen(function* () {
40861
41360
  const deps = yield* OrgDepsTag;
40862
- 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));
40863
41362
  return [];
40864
41363
  });
40865
41364
  }
@@ -40947,11 +41446,28 @@ function isRetryableOrganizationSetupFailure(error) {
40947
41446
  * state. The closed-over `orgId` is its only entity reference.
40948
41447
  */
40949
41448
  function makeOrgMethods(deps) {
40950
- const layer = orgDepsLayer({
41449
+ const orgDeps = {
40951
41450
  ...deps.orgPort === void 0 ? {} : { orgPort: deps.orgPort },
40952
41451
  ...deps.chainId === void 0 ? {} : { chainId: deps.chainId },
40953
41452
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
40954
- });
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
+ };
40955
41471
  return {
40956
41472
  createOrg(input, options) {
40957
41473
  if (options?.signal?.aborted) return Promise.resolve({
@@ -40960,13 +41476,7 @@ function makeOrgMethods(deps) {
40960
41476
  });
40961
41477
  return toCapxulResult(createOrgProgram(input), layer);
40962
41478
  },
40963
- orgs: Object.assign((options) => {
40964
- if (options?.signal?.aborted) return Promise.resolve({
40965
- ok: false,
40966
- error: Errors.cancelled({ operation: "org.orgs" })
40967
- });
40968
- return toCapxulResult(listOrgsProgram(), layer);
40969
- }, { detectAndAcceptPendingInvitations(options) {
41479
+ orgs: Object.assign((options) => listOrganizations(deps.invocationControls?.(options) ?? options), { detectAndAcceptPendingInvitations(options) {
40970
41480
  if (options?.signal?.aborted) return Promise.resolve({
40971
41481
  ok: false,
40972
41482
  error: Errors.cancelled({ operation: "orgs.detectAndAcceptPendingInvitations" })
@@ -41038,19 +41548,20 @@ function makeOrgMethods(deps) {
41038
41548
  ok: false,
41039
41549
  error: Errors.cancelled({ operation: "org.treasury" })
41040
41550
  });
41041
- return toCapxulResult(readTreasuryProgram(orgId), layer);
41551
+ return treasury(orgId, deps.invocationControls?.(options) ?? options);
41042
41552
  },
41043
41553
  account: { async get(options) {
41044
41554
  if (options?.signal?.aborted) return {
41045
41555
  ok: false,
41046
41556
  error: Errors.cancelled({ operation: "org.account.get" })
41047
41557
  };
41048
- const treasury = await toCapxulResult(readTreasuryProgram(orgId), layer);
41049
- if (!treasury.ok) return {
41558
+ const controls = deps.invocationControls?.(options) ?? options;
41559
+ const treasuryResult = await treasury(orgId, controls);
41560
+ if (!treasuryResult.ok) return {
41050
41561
  ok: false,
41051
- error: treasury.error
41562
+ error: treasuryResult.error
41052
41563
  };
41053
- const orgList = await toCapxulResult(listOrgsProgram(), layer);
41564
+ const orgList = await listOrganizations(controls);
41054
41565
  if (!orgList.ok) return {
41055
41566
  ok: false,
41056
41567
  error: orgList.error
@@ -41059,10 +41570,10 @@ function makeOrgMethods(deps) {
41059
41570
  return {
41060
41571
  ok: true,
41061
41572
  value: {
41062
- id: treasury.value.id,
41573
+ id: treasuryResult.value.id,
41063
41574
  address: org?.safeAddress ?? null,
41064
- balance: treasury.value.balance,
41065
- available: treasury.value.available
41575
+ balance: treasuryResult.value.balance,
41576
+ available: treasuryResult.value.available
41066
41577
  }
41067
41578
  };
41068
41579
  } },
@@ -41214,13 +41725,16 @@ function compareDecimal(first, second) {
41214
41725
  //#region ../../packages/sdk/src/surface/holdings.ts
41215
41726
  function makeHoldingsMethods(deps) {
41216
41727
  const functions = deps.functions ?? holdingsContract;
41217
- const read = (operation, actor, signal, pick) => runIfActive(signal, operation, () => deps.convexCall.action(functions.current, actor?.kind === "organization" ? { actor: {
41218
- kind: "organization",
41219
- orgId: actor.organizationId
41220
- } } : {}).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
+ };
41221
41735
  return {
41222
- current: (input, options) => read("holdings.current", input?.actor, options?.signal, (snapshot) => snapshot),
41223
- 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))
41224
41738
  };
41225
41739
  }
41226
41740
  //#endregion
@@ -41339,13 +41853,6 @@ function detectAuthCacheAdapter() {
41339
41853
  return new InMemoryAuthCacheAdapter();
41340
41854
  }
41341
41855
  //#endregion
41342
- //#region ../../packages/sdk/src/telemetry/from-posthog.ts
41343
- const PRODUCT_INVOCATION = Symbol("capxul.product-telemetry-invocation");
41344
- /** @internal Bind paired emit/identify/reset work to one call-start snapshot. */
41345
- function bindProductTelemetryInvocation(telemetry, source) {
41346
- return telemetry[PRODUCT_INVOCATION]?.(source) ?? telemetry;
41347
- }
41348
- //#endregion
41349
41856
  //#region ../../packages/sdk/src/telemetry/identity-product.ts
41350
41857
  const NONE = null;
41351
41858
  const IDENTITY_EVENT_TAG_SET = new Set(IDENTITY_EVENT_TAGS);
@@ -41558,6 +42065,8 @@ function assembleCapxulClient(input) {
41558
42065
  accountReadPort: input.ports.accountRead,
41559
42066
  profileMethods: financialOps.me,
41560
42067
  convexCall: input.ports.convexCall,
42068
+ runPromise: effectRunner.runPromise,
42069
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
41561
42070
  ...input.signer === void 0 ? {} : { signer: input.signer }
41562
42071
  });
41563
42072
  kickProvisioning = accountBundle.kickProvisioning;
@@ -41595,16 +42104,25 @@ function assembleCapxulClient(input) {
41595
42104
  });
41596
42105
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
41597
42106
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
41598
- 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
+ });
41599
42113
  const accounts = makeAccountsMethods({
41600
42114
  accountReadPort: input.ports.accountRead,
41601
42115
  chainId: input.bootstrap.chainId,
41602
- telemetry: input.ports.telemetry
42116
+ telemetry: input.ports.telemetry,
42117
+ runPromise: effectRunner.runPromise,
42118
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls)
41603
42119
  });
41604
42120
  const orgMethods = makeOrgMethods({
41605
42121
  actor,
41606
42122
  chainId: input.bootstrap.chainId,
41607
42123
  telemetry: input.ports.telemetry,
42124
+ runPromise: effectRunner.runPromise,
42125
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
41608
42126
  requestKeyScope: `${input.bootstrap.convexUrl}:${String(input.bootstrap.chainId)}`,
41609
42127
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
41610
42128
  convexCall: input.ports.convexCall,
@@ -41741,11 +42259,7 @@ function transitionError(record) {
41741
42259
  }
41742
42260
  function withHostObservation(actor, snapshot) {
41743
42261
  if (snapshot === void 0) return actor;
41744
- const controls = (input) => {
41745
- const captured = snapshot();
41746
- const copied = { ...input };
41747
- return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
41748
- };
42262
+ const controls = (input) => withHostObservationControls(snapshot, input);
41749
42263
  return {
41750
42264
  ...actor,
41751
42265
  ask: (event, input) => actor.ask(event, controls(input)),
@@ -41753,6 +42267,11 @@ function withHostObservation(actor, snapshot) {
41753
42267
  restoreAuthSession: (session, input) => actor.restoreAuthSession(session, controls(input))
41754
42268
  };
41755
42269
  }
42270
+ function withHostObservationControls(snapshot, input) {
42271
+ const copied = { ...input };
42272
+ const captured = snapshot?.();
42273
+ return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
42274
+ }
41756
42275
  //#endregion
41757
42276
  //#region ../../packages/sdk/src/host-observability.ts
41758
42277
  const HOST_INVOCATION = Symbol("capxul.host-observability-invocation");
@@ -41837,7 +42356,10 @@ function makeProductionAdapterLayerEntries(input) {
41837
42356
  },
41838
42357
  {
41839
42358
  name: "org",
41840
- 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
+ }))))
41841
42363
  }
41842
42364
  ];
41843
42365
  }
@@ -41846,10 +42368,13 @@ function mergeProductionAdapterLayers(entries) {
41846
42368
  for (const entry of entries) byName.set(entry.name, entry.layer);
41847
42369
  const authClientLayer = byName.get("authClient");
41848
42370
  const convexCallLayer = byName.get("convexCall");
42371
+ const telemetryLayer = byName.get("telemetry");
41849
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);
41850
42374
  return entries.map((entry) => {
41851
42375
  const layer = byName.get(entry.name) ?? entry.layer;
41852
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));
41853
42378
  if (isConvexDependentLayer(entry.name)) return convexCallReadyLayer === void 0 ? layer : layer.pipe(Layer.provide(convexCallReadyLayer));
41854
42379
  return layer;
41855
42380
  }).reduce((current, layer) => Layer.merge(current, layer), Layer.empty);
@@ -42010,13 +42535,22 @@ async function createProductionAdapters(input) {
42010
42535
  }));
42011
42536
  const applicationLayer = Layer.merge(portsLayer, optionalEngineeringTelemetryLayer(bootstrapResult.value.engineeringTelemetry, resolvedInput.value.runtime));
42012
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
+ });
42013
42547
  return {
42014
42548
  ok: true,
42015
42549
  value: {
42016
42550
  context,
42017
- ports: await Effect.runPromise(collectProductionFlowPorts.pipe(Effect.provide(context))),
42551
+ ports,
42018
42552
  bootstrap: bootstrapResult.value,
42019
- close: closeScope
42553
+ close
42020
42554
  }
42021
42555
  };
42022
42556
  } catch (cause) {
@@ -42027,6 +42561,18 @@ async function createProductionAdapters(input) {
42027
42561
  };
42028
42562
  }
42029
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
+ }
42030
42576
  function optionalEngineeringTelemetryLayer(policy, runtime) {
42031
42577
  if (policy === void 0) return Layer.empty;
42032
42578
  try {