@capxul/sdk 2.5.0 → 2.5.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.
@@ -96,10 +96,12 @@ const Errors = {
96
96
  accountNotFound: (accountId) => new CapxulError("ACCOUNT_NOT_FOUND", accountId ? `Openfort account ${accountId} not found` : "Openfort account not found", accountId === void 0 ? void 0 : { details: { accountId } }),
97
97
  providerError: (provider, operation, cause, opts) => {
98
98
  const details = {
99
+ ...opts?.details,
99
100
  provider,
100
101
  operation
101
102
  };
102
103
  if (opts?.failure_mode) details.failure_mode = opts.failure_mode;
104
+ if (opts?.httpStatus !== void 0) details.httpStatus = opts.httpStatus;
103
105
  return new CapxulError("PROVIDER_ERROR", `Provider error: ${provider} ${operation}`, {
104
106
  cause,
105
107
  details
@@ -1,4 +1,4 @@
1
- import { A as toPartyId, B as Errors, M as toPayrollRunId, P as toRoleKey, R as CapxulError, S as toCurrencyCode, V as isCapxulError, b as toChainId, c as BYTES32_RE, d as WEI_RE, f as ZERO_BYTES32, h as toAddress, j as toPayrollGroupId, k as toOrgId, l as EVM_ADDRESS_RE$1, m as toAccountId, n as BrowserAuthCacheAdapter, s as APP_ID_RE, t as InMemoryAuthCacheAdapter, u as SUPPORTED_CURRENCY_CODES, v as toAuthUserId, w as toEmail, x as toCountryCode, y as toBudgetId, z as EXPECTED_OPERATION_OUTCOMES } from "./InMemoryAuthCacheAdapter-D5Cv0yz0.mjs";
1
+ import { A as toPartyId, B as Errors, M as toPayrollRunId, P as toRoleKey, R as CapxulError, S as toCurrencyCode, V as isCapxulError, b as toChainId, c as BYTES32_RE, d as WEI_RE, f as ZERO_BYTES32, h as toAddress, j as toPayrollGroupId, k as toOrgId, l as EVM_ADDRESS_RE$1, m as toAccountId, n as BrowserAuthCacheAdapter, s as APP_ID_RE, t as InMemoryAuthCacheAdapter, u as SUPPORTED_CURRENCY_CODES, v as toAuthUserId, w as toEmail, x as toCountryCode, y as toBudgetId, z as EXPECTED_OPERATION_OUTCOMES } from "./InMemoryAuthCacheAdapter-uOcqpqu8.mjs";
2
2
  import { concat, encodeAbiParameters, encodeFunctionData, encodePacked, formatUnits, getContractAddress, keccak256, padHex, parseUnits, recoverAddress, stringToHex, toBytes, toEventSelector, toFunctionSelector, toFunctionSignature } from "viem";
3
3
  import { Context, Data, Deferred, Effect, Exit, Fiber, Layer, Queue, Ref, Result, Schema, SchemaGetter, Scope } from "effect";
4
4
  import { makeFunctionReference } from "convex/server";
@@ -2902,6 +2902,9 @@ const SENSITIVE_MATERIAL_PATTERNS = [
2902
2902
  /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/u,
2903
2903
  /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu
2904
2904
  ];
2905
+ const RAW_PRIVATE_KEY_MASK = /(^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?=$|[^a-fA-F0-9])/gu;
2906
+ const KNOWN_CREDENTIAL_MASK = /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/giu;
2907
+ const LABELLED_SECRET_MASK = /\b(api[ _-]?key|access[ _-]?token|token|secret|password|passphrase|private[ _-]?key|authorization|cookie|signature|request[ _-]?body|credential|otp|one[ _-]?time[ _-]?(?:password|code)|verification[ _-]?code)\b\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu;
2905
2908
  /**
2906
2909
  * Reject: does the value carry any known secret material? Best effort — callers
2907
2910
  * drop the whole value on a match; a false negative is a leak, a false positive
@@ -2910,6 +2913,14 @@ const SENSITIVE_MATERIAL_PATTERNS = [
2910
2913
  function containsSensitiveMaterial(value) {
2911
2914
  return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));
2912
2915
  }
2916
+ /**
2917
+ * Mask: return the value with every known secret rewritten to `[REDACTED]`,
2918
+ * preserving surrounding text. Used where a value must still be shown (log
2919
+ * lines, issue bodies) but must not carry live credentials.
2920
+ */
2921
+ function redactSecrets(value) {
2922
+ return value.replace(/\bBearer\s+[^\s,;]+/giu, "Bearer [REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, "[REDACTED]").replace(/\b0x[a-fA-F0-9]{40,}\b/gu, "[REDACTED]").replace(RAW_PRIVATE_KEY_MASK, "$1[REDACTED]").replace(KNOWN_CREDENTIAL_MASK, "[REDACTED]").replace(LABELLED_SECRET_MASK, (_match, label) => `${label}=[REDACTED]`);
2923
+ }
2913
2924
  //#endregion
2914
2925
  //#region ../wire/src/observation-context.ts
2915
2926
  /** Single bounded HTTP carrier used before a Convex action envelope exists. */
@@ -3243,8 +3254,8 @@ var ActorFailure = class extends Error {
3243
3254
  event;
3244
3255
  details;
3245
3256
  _tag = "ActorFailure";
3246
- constructor(reason, machine, state, event, details) {
3247
- super(`${machine}:${state}:${event} ${reason}`);
3257
+ constructor(reason, machine, state, event, details, cause) {
3258
+ super(`${machine}:${state}:${event} ${reason}`, cause === void 0 ? void 0 : { cause });
3248
3259
  this.reason = reason;
3249
3260
  this.machine = machine;
3250
3261
  this.state = state;
@@ -3319,8 +3330,8 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
3319
3330
  defect(cause);
3320
3331
  }
3321
3332
  };
3322
- const makeFailure = (state, event, reason, details) => new ActorFailure(reason, spec.machine, spec.label(state), event._tag, details);
3323
- const nonApplied = (state, event, reason, outcome, env) => {
3333
+ const makeFailure = (state, event, reason, details, cause) => new ActorFailure(reason, spec.machine, spec.label(state), event._tag, details, cause);
3334
+ const nonApplied = (state, event, reason, outcome, env, failure) => {
3324
3335
  const slot = env.origin?.slot ?? spec.slot(event);
3325
3336
  return copyInvocationObservation(env.invocation, {
3326
3337
  machine: spec.machine,
@@ -3331,7 +3342,8 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
3331
3342
  outcome,
3332
3343
  duration_ms: duration(env.startedAt),
3333
3344
  ...withCarriage(env.invocation),
3334
- ...outcome === "refused" ? { refusal_code: reason } : { error_code: reason }
3345
+ ...outcome === "refused" ? { refusal_code: reason } : { error_code: reason },
3346
+ ...failure === void 0 ? {} : { failure }
3335
3347
  });
3336
3348
  };
3337
3349
  const applied = (from, to, event, slot, epoch, env) => copyInvocationObservation(env.invocation, {
@@ -3384,12 +3396,13 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
3384
3396
  slots.delete(env.origin.slot);
3385
3397
  defect(exit.defect);
3386
3398
  const event = { _tag: env.origin.event };
3387
- const failedState = yield* recoverFailure(state, env.origin, {
3399
+ const died = {
3388
3400
  code: "WORK_DIED",
3389
- message: "Identity work died"
3390
- });
3391
- yield* emit(nonApplied(failedState, event, "WORK_DIED", "failed", env));
3392
- yield* failReply(held.reply, makeFailure(failedState, event, "WORK_DIED"));
3401
+ message: exit.defect instanceof Error ? exit.defect.message : "Identity work died"
3402
+ };
3403
+ const failedState = yield* recoverFailure(state, env.origin, died);
3404
+ yield* emit(nonApplied(failedState, event, "WORK_DIED", "failed", env, died));
3405
+ yield* failReply(held.reply, makeFailure(failedState, event, "WORK_DIED", void 0, died));
3393
3406
  return;
3394
3407
  }
3395
3408
  if (exit.failure !== void 0) {
@@ -3397,9 +3410,9 @@ const boot = (spec, options = {}) => Effect.gen(function* () {
3397
3410
  const outcome = exit.failure.code === "CANCELLED" ? "cancelled" : "failed";
3398
3411
  const event = { _tag: env.origin.event };
3399
3412
  const failedState = exit.failure === timeoutFailure || exit.failure === cancelledFailure ? yield* recoverFailure(state, env.origin, exit.failure) : state;
3400
- yield* emit(nonApplied(failedState, event, exit.failure.code, outcome, env));
3413
+ yield* emit(nonApplied(failedState, event, exit.failure.code, outcome, env, exit.failure));
3401
3414
  const details = exit.failure === timeoutFailure ? { reason: "timeout" } : void 0;
3402
- yield* failReply(held.reply, makeFailure(failedState, event, exit.failure.code, details));
3415
+ yield* failReply(held.reply, makeFailure(failedState, event, exit.failure.code, details, exit.failure.error ?? exit.failure));
3403
3416
  return;
3404
3417
  }
3405
3418
  yield* finish(env.origin, state);
@@ -5528,7 +5541,7 @@ function mapOk(result, f) {
5528
5541
  }
5529
5542
  //#endregion
5530
5543
  //#region package.json
5531
- var version = "2.5.0";
5544
+ var version = "2.5.2";
5532
5545
  //#endregion
5533
5546
  //#region src/ports/auth-client.ts
5534
5547
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -8824,23 +8837,50 @@ function observeSdkClient(client, adapter, snapshot) {
8824
8837
  }
8825
8838
  }
8826
8839
  /** @internal Reports a factory-level typed failure without changing its identity. */
8827
- function observeFailedResult(result, adapter, operation) {
8828
- if (adapter !== void 0 && isFailedResult(result)) report(adapter, "operation", operation, result.error, resolveAdapterSnapshot(adapter));
8840
+ function observeFailedResult(result, adapter, operation, origin) {
8841
+ if (adapter !== void 0 && isFailedResult(result)) report(adapter, "operation", operation, result.error, resolveAdapterSnapshot(adapter), origin);
8829
8842
  return result;
8830
8843
  }
8831
- function report(adapter, kind, operation, cause, invocation) {
8844
+ /**
8845
+ * One failure, one event. The identity machine reports a failed transition
8846
+ * first; when the same `CapxulError` then surfaces as a public method result
8847
+ * (directly or down its `cause` chain), the boundary drops that second report.
8848
+ * Only machine-reported errors are remembered, so a caller that reuses one
8849
+ * error object across unrelated public methods still sees every report.
8850
+ */
8851
+ const machineReportedCauses = /* @__PURE__ */ new WeakSet();
8852
+ function reportedByMachine(cause) {
8853
+ let link = cause;
8854
+ for (let depth = 0; depth < 8 && typeof link === "object" && link !== null; depth++) {
8855
+ if (machineReportedCauses.has(link)) return true;
8856
+ link = link.cause;
8857
+ }
8858
+ return false;
8859
+ }
8860
+ function report(adapter, kind, operation, cause, invocation, origin) {
8861
+ if (origin === "machine") {
8862
+ let link = cause;
8863
+ for (let depth = 0; depth < 8 && typeof link === "object" && link !== null; depth++) {
8864
+ machineReportedCauses.add(link);
8865
+ link = link.cause;
8866
+ }
8867
+ } else if (reportedByMachine(cause)) return;
8832
8868
  const operationName = normalizeOperation(operation);
8833
8869
  const kindName = normalizeErrorKind(errorKind(cause));
8834
8870
  const context = sanitizeObservationContext({
8835
8871
  ...invocation.context,
8836
8872
  ...isCapxulError(cause) && cause.correlationId !== void 0 ? { correlationId: cause.correlationId } : {}
8837
8873
  });
8874
+ const detail = failureDetail(cause);
8875
+ const evidence = failureEvidence(cause);
8838
8876
  const failure = markFailureInvocationSnapshot({
8839
- exception: syntheticException(operationName, kindName),
8877
+ exception: syntheticException(operationName, kindName, evidence.message, evidence.stack),
8840
8878
  sdkVersion: SDK_VERSION,
8841
8879
  operation: operationName,
8842
8880
  errorKind: kindName,
8843
- ...context === void 0 ? {} : { context }
8881
+ ...context === void 0 ? {} : { context },
8882
+ ...detail === void 0 ? {} : { detail },
8883
+ ...evidence
8844
8884
  }, {
8845
8885
  active: invocation.active,
8846
8886
  ...context === void 0 ? {} : { context }
@@ -8903,19 +8943,24 @@ function postHogProperties(failure, context) {
8903
8943
  operation: failure.operation,
8904
8944
  error_kind: failure.errorKind,
8905
8945
  handled: true,
8946
+ ...failure.detail,
8947
+ ...failure.message === void 0 ? {} : { error_message: failure.message },
8948
+ ...failure.details === void 0 ? {} : { error_details: failure.details },
8949
+ ...failure.causeChain === void 0 ? {} : { error_cause: failure.causeChain.join(" <- ") },
8906
8950
  ...observationContextProps(merged)
8907
8951
  };
8908
8952
  }
8909
8953
  function postHogExceptionProperties(failure, properties) {
8910
8954
  const filename = `capxul-sdk-observation://boundary/${failure.operation}`;
8955
+ const message = failure.message ?? "Capxul SDK operation failed";
8911
8956
  return {
8912
8957
  ...properties,
8913
8958
  $exception_type: failure.errorKind,
8914
- $exception_message: EXCEPTION_MESSAGE,
8959
+ $exception_message: message,
8915
8960
  $exception_level: "error",
8916
8961
  $exception_list: [{
8917
8962
  type: failure.errorKind,
8918
- value: EXCEPTION_MESSAGE,
8963
+ value: message,
8919
8964
  mechanism: {
8920
8965
  type: "capxul_sdk_boundary",
8921
8966
  handled: true,
@@ -8931,10 +8976,77 @@ function postHogExceptionProperties(failure, properties) {
8931
8976
  colno: 1,
8932
8977
  in_app: true
8933
8978
  }]
8934
- }
8979
+ },
8980
+ ...failure.stack === void 0 ? {} : { stack: failure.stack }
8935
8981
  }]
8936
8982
  };
8937
8983
  }
8984
+ const MAX_EVIDENCE_TEXT = 4e3;
8985
+ const MAX_CAUSE_DEPTH = 8;
8986
+ function evidenceText(value) {
8987
+ if (typeof value !== "string" || value.length === 0) return void 0;
8988
+ return redactSecrets(value).slice(0, MAX_EVIDENCE_TEXT);
8989
+ }
8990
+ /** A field whose NAME says credential is masked whatever its value looks like. */
8991
+ const CREDENTIAL_FIELD_NAME = /(?:otp|pass(?:word|wd|phrase)?|token|secret|credential|api[_-]?key|private[_-]?key|authorization|cookie|session)/iu;
8992
+ /** Copy a details object into a JSON-safe shape with every string masked. */
8993
+ function evidenceValue(value, depth = 0) {
8994
+ if (typeof value === "string") return evidenceText(value);
8995
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
8996
+ if (typeof value === "bigint") return value.toString();
8997
+ if (value instanceof Error) return evidenceText(value.message);
8998
+ if (depth >= 4 || typeof value !== "object") return void 0;
8999
+ if (Array.isArray(value)) return value.slice(0, 50).map((item) => evidenceValue(item, depth + 1));
9000
+ const copy = {};
9001
+ for (const [key, nested] of Object.entries(value)) {
9002
+ if (CREDENTIAL_FIELD_NAME.test(key)) {
9003
+ copy[key] = "[REDACTED]";
9004
+ continue;
9005
+ }
9006
+ const safe = evidenceValue(nested, depth + 1);
9007
+ if (safe !== void 0) copy[key] = safe;
9008
+ }
9009
+ return copy;
9010
+ }
9011
+ /**
9012
+ * @internal The evidence in PostHog property shape, for product events that
9013
+ * name a failure (`bootstrap_failed`). Same keys as the `$exception` event.
9014
+ */
9015
+ function failureEvidenceProps(cause) {
9016
+ const evidence = failureEvidence(cause);
9017
+ return {
9018
+ ...evidence.message === void 0 ? {} : { error_message: evidence.message },
9019
+ ...evidence.details === void 0 ? {} : { error_details: evidence.details },
9020
+ ...evidence.causeChain === void 0 ? {} : { error_cause: evidence.causeChain.join(" <- ") }
9021
+ };
9022
+ }
9023
+ /** The real failure, masked for secrets only. Never throws. */
9024
+ function failureEvidence(cause) {
9025
+ try {
9026
+ const message = cause instanceof Error ? evidenceText(cause.message) : evidenceText(cause);
9027
+ const stack = cause instanceof Error ? evidenceText(cause.stack) : void 0;
9028
+ const details = isCapxulError(cause) && typeof cause.details === "object" && cause.details !== null ? evidenceValue(cause.details) : void 0;
9029
+ const causeChain = [];
9030
+ let previous = message;
9031
+ let link = cause instanceof Error ? cause.cause : void 0;
9032
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && link !== void 0 && link !== null; depth++) {
9033
+ const text = link instanceof Error ? evidenceText(link.message) : evidenceText(link);
9034
+ if (text !== void 0 && text !== previous) {
9035
+ causeChain.push(text);
9036
+ previous = text;
9037
+ }
9038
+ link = link instanceof Error ? link.cause : void 0;
9039
+ }
9040
+ return {
9041
+ ...message === void 0 ? {} : { message },
9042
+ ...details === void 0 || Object.keys(details).length === 0 ? {} : { details },
9043
+ ...causeChain.length === 0 ? {} : { causeChain },
9044
+ ...stack === void 0 ? {} : { stack }
9045
+ };
9046
+ } catch {
9047
+ return {};
9048
+ }
9049
+ }
8938
9050
  function errorKind(cause) {
8939
9051
  try {
8940
9052
  if (isCapxulError(cause)) return normalizeErrorKind(cause.code);
@@ -8948,14 +9060,61 @@ function sanitizeFailureObservation(failure) {
8948
9060
  const operation = normalizeOperation(failure.operation);
8949
9061
  const kind = normalizeErrorKind(failure.errorKind);
8950
9062
  const context = sanitizeObservationContext(failure.context);
9063
+ const detail = sanitizeFailureDetail(failure.detail);
9064
+ const message = evidenceText(failure.message);
9065
+ const stack = evidenceText(failure.stack);
9066
+ const details = typeof failure.details === "object" && failure.details !== null ? evidenceValue(failure.details) : void 0;
9067
+ const causeChain = Array.isArray(failure.causeChain) ? failure.causeChain.map(evidenceText).filter((text) => text !== void 0) : void 0;
8951
9068
  return {
8952
- exception: syntheticException(operation, kind),
9069
+ exception: syntheticException(operation, kind, message, stack),
8953
9070
  sdkVersion: normalizeSdkVersion(failure.sdkVersion),
8954
9071
  operation,
8955
9072
  errorKind: kind,
8956
- ...context === void 0 ? {} : { context }
9073
+ ...context === void 0 ? {} : { context },
9074
+ ...detail === void 0 ? {} : { detail },
9075
+ ...message === void 0 ? {} : { message },
9076
+ ...details === void 0 || Object.keys(details).length === 0 ? {} : { details },
9077
+ ...causeChain === void 0 || causeChain.length === 0 ? {} : { causeChain },
9078
+ ...stack === void 0 ? {} : { stack }
8957
9079
  };
8958
9080
  }
9081
+ /**
9082
+ * @internal Lift the enumerated discriminators off a `CapxulError` so a
9083
+ * boundary event says WHICH provider failed and HOW, not just `PROVIDER_ERROR`.
9084
+ * Shared by the failure boundary and the `bootstrap_failed` product event.
9085
+ */
9086
+ function failureDetail(cause) {
9087
+ if (!isCapxulError(cause)) return void 0;
9088
+ const details = cause.details;
9089
+ if (typeof details !== "object" || details === null) return void 0;
9090
+ const source = details;
9091
+ return sanitizeFailureDetail({
9092
+ provider: source.provider,
9093
+ provider_operation: source.operation,
9094
+ failure_mode: source.failure_mode,
9095
+ reason: source.reason,
9096
+ http_status: source.httpStatus
9097
+ });
9098
+ }
9099
+ function sanitizeFailureDetail(input) {
9100
+ if (typeof input !== "object" || input === null) return void 0;
9101
+ const source = input;
9102
+ const detail = {};
9103
+ for (const key of [
9104
+ "provider",
9105
+ "provider_operation",
9106
+ "failure_mode",
9107
+ "reason"
9108
+ ]) {
9109
+ const value = source[key];
9110
+ if (typeof value === "string" && ENUMERATED_DETAIL_RE.test(value)) detail[key] = value;
9111
+ }
9112
+ const status = source.http_status;
9113
+ if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599) detail.http_status = status;
9114
+ return Object.keys(detail).length === 0 ? void 0 : detail;
9115
+ }
9116
+ /** Enumerated codes only (`convex`, `no-secure-context`, `bootstrap-encode`); free text fails. */
9117
+ const ENUMERATED_DETAIL_RE = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u;
8959
9118
  function normalizeSdkVersion(value) {
8960
9119
  return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/u.test(value) ? value : "unknown";
8961
9120
  }
@@ -8965,10 +9124,10 @@ function normalizeOperation(value) {
8965
9124
  function normalizeErrorKind(value) {
8966
9125
  return typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(value) ? value : "Error";
8967
9126
  }
8968
- function syntheticException(operation, kind) {
8969
- const error = /* @__PURE__ */ new Error(EXCEPTION_MESSAGE);
9127
+ function syntheticException(operation, kind, message = EXCEPTION_MESSAGE, stack) {
9128
+ const error = new Error(message);
8970
9129
  error.name = kind;
8971
- error.stack = `${kind}: ${error.message}\n at CapxulSdkBoundary.${operation} (capxul-sdk-observation://boundary/${operation}:1:1)`;
9130
+ error.stack = `${kind}: ${error.message}\n at CapxulSdkBoundary.${operation} (capxul-sdk-observation://boundary/${operation}:1:1)` + (stack === void 0 ? "" : `\nCaused by: ${stack}`);
8972
9131
  return error;
8973
9132
  }
8974
9133
  function isPromiseLike(value) {
@@ -9173,10 +9332,19 @@ function assembleCapxulClient(input) {
9173
9332
  const unsubscribeProductTelemetry = actor.subscribeTransitions((record) => {
9174
9333
  effectRunner.runPromise(executeIdentityProductObservation(input.ports.telemetry, record, actor.snapshot())).catch(() => {});
9175
9334
  });
9335
+ const failureObservation = observation.failureObservation;
9336
+ const unsubscribeFailureObservation = failureObservation === void 0 ? () => {} : actor.subscribeTransitions((record) => {
9337
+ if (record.outcome !== "failed") return;
9338
+ observeFailedResult({
9339
+ ok: false,
9340
+ error: transitionError(record)
9341
+ }, failureObservation, `identity.${record.event}`, "machine");
9342
+ });
9176
9343
  let stopPromise = null;
9177
9344
  const stopActor = () => {
9178
9345
  if (stopPromise === null) {
9179
9346
  unsubscribeProductTelemetry();
9347
+ unsubscribeFailureObservation();
9180
9348
  stopPromise = effectRunner.runPromise(Scope.close(scope, Exit.void));
9181
9349
  }
9182
9350
  return stopPromise;
@@ -9361,6 +9529,30 @@ function assembleCapxulClient(input) {
9361
9529
  }
9362
9530
  }, observation.failureObservation, observation.hostObservationSnapshot);
9363
9531
  }
9532
+ function transitionError(record) {
9533
+ const failure = record.failure;
9534
+ if (failure?.error !== void 0) {
9535
+ const error = failure.error;
9536
+ if (record.correlation_id === void 0 || error.correlationId !== void 0) return error;
9537
+ return new CapxulError(error.code, error.message, {
9538
+ cause: error,
9539
+ correlationId: record.correlation_id,
9540
+ ...error.details === void 0 ? {} : { details: error.details },
9541
+ ...error.layer === void 0 ? {} : { layer: error.layer }
9542
+ });
9543
+ }
9544
+ return new CapxulError(record.error_code, failure?.message ?? "Identity work failed", {
9545
+ ...failure === void 0 ? {} : { cause: failure },
9546
+ details: {
9547
+ machine: record.machine,
9548
+ state: record.state,
9549
+ event: record.event,
9550
+ slot: record.slot,
9551
+ ...failure?.mode === void 0 ? {} : { failure_mode: failure.mode }
9552
+ },
9553
+ ...record.correlation_id === void 0 ? {} : { correlationId: record.correlation_id }
9554
+ });
9555
+ }
9364
9556
  function withHostObservation(actor, snapshot) {
9365
9557
  if (snapshot === void 0) return actor;
9366
9558
  const controls = (input) => {
@@ -9376,4 +9568,4 @@ function withHostObservation(actor, snapshot) {
9376
9568
  };
9377
9569
  }
9378
9570
  //#endregion
9379
- export { isClaimed as $, fingerprintPaymentIntent as A, OBSERVATION_CONTEXT_HEADER as B, ClockPortTag as C, AuthClientError as D, authClientPortFromPromiseAdapter as E, copyInvocationObservation as F, CAPXUL_FUNCTIONS as G, sanitizeObservationContext as H, readInvocationObservation as I, CAPXUL_PAYMENTS_V2_ADDRESS as J, BootstrapEnvelope as K, causeChain as L, fromWei as M, isSettingUpLifecycle as N, AuthClientPortTag as O, formatTraceparent as P, destination as Q, injectedWalletSigner as R, ClockError as S, bootstrapErrorFromCapxul as T, PAYMENT_DIRECTIONS as U, encodeObservationContextHeader as V, PAYMENT_STATUSES as W, BASE_SEPOLIA_CHAIN_ID as X, normalizeBindingEmail as Y, deriveCapxulSafeAddress as Z, wireChainId as _, observeFailedResult as a, ConvexCallPortTag as b, captureExceptionSync as c, TelemetryPortTag as d, isRestoring as et, redactTelemetryEvent as f, accountReadErrorFromCapxul as g, AccountReadPortTag as h, observationContextProps as i, toWei as j, version as k, detectAuthCacheAdapter as l, smartAccountErrorFromCapxul as m, postHogProductTelemetry as n, postHogFailureObservation as o, SmartAccountPortTag as p, EngineeringTelemetryBootstrapPolicy as q, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as r, captureException as s, assembleCapxulClient as t, PostHogTelemetryLayer as u, IdentityPortTag as v, BootstrapPortTag as w, convexCallErrorFromCapxul as x, identityErrorFromCapxul as y, signerFailure as z };
9571
+ export { deriveCapxulSafeAddress as $, AuthClientPortTag as A, injectedWalletSigner as B, convexCallErrorFromCapxul as C, bootstrapErrorFromCapxul as D, BootstrapPortTag as E, isSettingUpLifecycle as F, PAYMENT_DIRECTIONS as G, OBSERVATION_CONTEXT_HEADER as H, formatTraceparent as I, BootstrapEnvelope as J, PAYMENT_STATUSES as K, copyInvocationObservation as L, fingerprintPaymentIntent as M, toWei as N, authClientPortFromPromiseAdapter as O, fromWei as P, BASE_SEPOLIA_CHAIN_ID as Q, readInvocationObservation as R, ConvexCallPortTag as S, ClockPortTag as T, encodeObservationContextHeader as U, signerFailure as V, sanitizeObservationContext as W, CAPXUL_PAYMENTS_V2_ADDRESS as X, EngineeringTelemetryBootstrapPolicy as Y, normalizeBindingEmail as Z, AccountReadPortTag as _, failureEvidenceProps as a, IdentityPortTag as b, postHogFailureObservation as c, detectAuthCacheAdapter as d, destination as et, PostHogTelemetryLayer as f, smartAccountErrorFromCapxul as g, SmartAccountPortTag as h, failureDetail as i, version as j, AuthClientError as k, captureException as l, redactTelemetryEvent as m, postHogProductTelemetry as n, isRestoring as nt, observationContextProps as o, TelemetryPortTag as p, CAPXUL_FUNCTIONS as q, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as r, observeFailedResult as s, assembleCapxulClient as t, isClaimed as tt, captureExceptionSync as u, accountReadErrorFromCapxul as v, ClockError as w, identityErrorFromCapxul as x, wireChainId as y, causeChain as z };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as OrgId, C as Address, N as CountryCode, O as AuthSession, S as AccountId, U as PayrollGroupId, V as PartyId, W as PayrollRunId, Y as RoleKey, a as SignerStatusStore, at as CapxulErrorDetails, c as AccountProviderSource, ct as FailureMode, d as eip1193AccountProvider, et as toAddress, f as localPrivateKeyAccountProvider, g as SmartAccount, h as Session, i as SignerStatus, it as CapxulErrorCode, j as BudgetId, k as AuthUserId, l as AccountRequirement, lt as isCapxulError, m as Profile, n as CapxulSigner, nt as CAPXUL_ERROR_CODES, o as injectedWalletSigner, ot as Errors, p as CapxulResult, r as Eip1193RequestProvider, rt as CapxulError, s as AccountProvider, t as CapxulDigestSigner, tt as toCountryCode, u as Eip1193Provider, x as Account, z as Money } from "./signer-CRzTIrau.mjs";
2
- import { $ as PermissionChangeInput, $n as Readiness, $t as MovementActivityEvidence, A as OrgView, An as IdentityMethods, At as ActivityKind, B as PayrollGroupMember, Bn as PAYMENT_DIRECTIONS, Bt as DepositInstructions, C as DetectPendingOrgInvitationsResult, Cn as ResolvedTarget, Ct as InboxItem, D as OrgMethods, Dn as AccountLifecycle, Dt as ActivityDetail, E as MemberView, En as fingerprintPaymentIntent, Et as ActivityAnnotationInput, F as RoleSpendCap, Fn as ActorRef, Ft as ActivityReference, G as PayrollRunItemInput, Gt as DestinationPayload, H as PayrollMethods, Hn as PaymentStatus$1, Ht as DestinationAddInput, I as RoleView, In as CurrentHoldings, It as ActivitySummary, J as OrganizationPaymentBatchInput, Jn as CAPXUL_PAYMENTS_V2_ADDRESS, Jt as DestinationsMethods, K as PayrollRunStatus, Kt as DestinationRail, L as AuthorizeRunInput, Ln as Permission, Lt as ActivitySummaryParams, M as OrganizationAuditLogItem, Mn as AuthMethods, Mt as ActivityMethods, N as ResendInviteTokenInput, Nn as OrgLifecycle, Nt as ActivityPage, O as OrgScopedMethods, On as AccountSetupStep, Ot as ActivityFilter, P as RoleDefinition, Pn as OrgSetupStep, Pt as ActivityRange, Q as PermissionAssignInput, Qn as OrgLane, Qt as MeProfile, R as PayrollGroup, Rn as SubmittedPermissionExecution, Rt as ActivitySummaryTotal, S as CreateOrgInput, Sn as Ref, St as InboxApproveInput, T as MemberStatus, Tn as TargetsMethods, Tt as ActivityAnnotation, U as PayrollOptions, Un as RequestStatus, Ut as DestinationKind, V as PayrollGroupsMethods, Vn as PAYMENT_STATUSES, Vt as Destination, W as PayrollRun, Wt as DestinationListInput, X as OrganizationPaymentItemInput, Xn as IdentityEvent, Xt as HandlesMethods, Y as OrganizationPaymentInput, Yn as Destination$1, Yt as FinancialOpsMethods, Z as OrganizationPaymentsMethods, Zn as IdentityState, Zt as MeMethods, _ as SystemMethods, _n as PaymentType, _t as ActorRequestsMethods, a as SdkFailureObservation, an as PayeesMethods, ar as InvocationControls, at as PermissionReadResult, b as CurrentUserContext, bn as RecipientResolution, bt as AddressBookLabelInput, c as PostHogObservabilityOptions, cn as PaymentDirection, ct as OrgMeMethod, d as CreateCapxulClientInput, dn as PaymentDocumentRender, dt as AccountMethods, en as OfframpMethods, er as StateLabel, et as PermissionCreateInput, f as IdentityProfileDetails, fn as PaymentDocumentVerification, ft as ActorProfile, g as Holding, gn as PaymentTiming, gt as ActorRequestIssueInput, h as HoldingsMethods, hn as PaymentStatus, ht as ActorRequest, i as ObservationDelivery, in as Payee, ir as IdentityTransition, it as PermissionRevokeInput, j as OrganizationAccount, jn as SmartAccountMethods, jt as ActivityListParams, k as OrgTemplate, kn as isSettingUpLifecycle, kt as ActivityItem, l as postHogObservability, ln as PaymentDocumentKind, lt as OrgMeOptions, m as IdentityRuntimeSendResult, mn as PaymentMoney, mt as ActorRelationshipMethods, n as ObservationAdapter, nn as OfframpQuoteInput, nr as isClaimed, nt as PermissionOptions, o as HostObservability, on as Payment, ot as Budget, p as IdentityRuntime, pn as PaymentDocumentsMethods, pt as ActorProfileMethods, q as PayrollRuns, qn as TelemetryPort, qt as DestinationRemoveInput, r as ObservationContext, rn as OfframpStatus, rr as isRestoring, rt as PermissionReplaceInput, s as PostHogObservabilityClient, sn as PaymentActivityEvidence, st as OrgMe, t as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, tn as OfframpQuote, tr as destination, tt as PermissionMethods, u as CapxulClient, un as PaymentDocumentRef, ut as AccountsMethods, v as SystemHealth, vn as PaymentsMethods, vt as AddressBookAddInput, w as InviteMemberInput, wn as TargetReference, wt as InboxMethods, x as CurrentUserMethods, xn as RecipientResolutionKind, xt as AddressBookMethods, y as MediaMethods, yn as PaymentsPayInput, yt as AddressBookEntry, z as PayrollGroupInput, zn as InboxStatus, zt as ActorReference } from "./observation-CyNjyQxv.mjs";
1
+ import { B as OrgId, C as Address, N as CountryCode, O as AuthSession, S as AccountId, U as PayrollGroupId, V as PartyId, W as PayrollRunId, Y as RoleKey, a as SignerStatusStore, at as CapxulErrorDetails, c as AccountProviderSource, ct as FailureMode, d as eip1193AccountProvider, et as toAddress, f as localPrivateKeyAccountProvider, g as SmartAccount, h as Session, i as SignerStatus, it as CapxulErrorCode, j as BudgetId, k as AuthUserId, l as AccountRequirement, lt as isCapxulError, m as Profile, n as CapxulSigner, nt as CAPXUL_ERROR_CODES, o as injectedWalletSigner, ot as Errors, p as CapxulResult, r as Eip1193RequestProvider, rt as CapxulError, s as AccountProvider, t as CapxulDigestSigner, tt as toCountryCode, u as Eip1193Provider, x as Account, z as Money } from "./signer-BSEG9xgN.mjs";
2
+ import { $ as PermissionChangeInput, $n as Readiness, $t as MovementActivityEvidence, A as OrgView, An as IdentityMethods, At as ActivityKind, B as PayrollGroupMember, Bn as PAYMENT_DIRECTIONS, Bt as DepositInstructions, C as DetectPendingOrgInvitationsResult, Cn as ResolvedTarget, Ct as InboxItem, D as OrgMethods, Dn as AccountLifecycle, Dt as ActivityDetail, E as MemberView, En as fingerprintPaymentIntent, Et as ActivityAnnotationInput, F as RoleSpendCap, Fn as ActorRef, Ft as ActivityReference, G as PayrollRunItemInput, Gt as DestinationPayload, H as PayrollMethods, Hn as PaymentStatus$1, Ht as DestinationAddInput, I as RoleView, In as CurrentHoldings, It as ActivitySummary, J as OrganizationPaymentBatchInput, Jn as CAPXUL_PAYMENTS_V2_ADDRESS, Jt as DestinationsMethods, K as PayrollRunStatus, Kt as DestinationRail, L as AuthorizeRunInput, Ln as Permission, Lt as ActivitySummaryParams, M as OrganizationAuditLogItem, Mn as AuthMethods, Mt as ActivityMethods, N as ResendInviteTokenInput, Nn as OrgLifecycle, Nt as ActivityPage, O as OrgScopedMethods, On as AccountSetupStep, Ot as ActivityFilter, P as RoleDefinition, Pn as OrgSetupStep, Pt as ActivityRange, Q as PermissionAssignInput, Qn as OrgLane, Qt as MeProfile, R as PayrollGroup, Rn as SubmittedPermissionExecution, Rt as ActivitySummaryTotal, S as CreateOrgInput, Sn as Ref, St as InboxApproveInput, T as MemberStatus, Tn as TargetsMethods, Tt as ActivityAnnotation, U as PayrollOptions, Un as RequestStatus, Ut as DestinationKind, V as PayrollGroupsMethods, Vn as PAYMENT_STATUSES, Vt as Destination, W as PayrollRun, Wt as DestinationListInput, X as OrganizationPaymentItemInput, Xn as IdentityEvent, Xt as HandlesMethods, Y as OrganizationPaymentInput, Yn as Destination$1, Yt as FinancialOpsMethods, Z as OrganizationPaymentsMethods, Zn as IdentityState, Zt as MeMethods, _ as SystemMethods, _n as PaymentType, _t as ActorRequestsMethods, a as SdkFailureObservation, an as PayeesMethods, ar as InvocationControls, at as PermissionReadResult, b as CurrentUserContext, bn as RecipientResolution, bt as AddressBookLabelInput, c as PostHogObservabilityOptions, cn as PaymentDirection, ct as OrgMeMethod, d as CreateCapxulClientInput, dn as PaymentDocumentRender, dt as AccountMethods, en as OfframpMethods, er as StateLabel, et as PermissionCreateInput, f as IdentityProfileDetails, fn as PaymentDocumentVerification, ft as ActorProfile, g as Holding, gn as PaymentTiming, gt as ActorRequestIssueInput, h as HoldingsMethods, hn as PaymentStatus, ht as ActorRequest, i as ObservationDelivery, in as Payee, ir as IdentityTransition, it as PermissionRevokeInput, j as OrganizationAccount, jn as SmartAccountMethods, jt as ActivityListParams, k as OrgTemplate, kn as isSettingUpLifecycle, kt as ActivityItem, l as postHogObservability, ln as PaymentDocumentKind, lt as OrgMeOptions, m as IdentityRuntimeSendResult, mn as PaymentMoney, mt as ActorRelationshipMethods, n as ObservationAdapter, nn as OfframpQuoteInput, nr as isClaimed, nt as PermissionOptions, o as HostObservability, on as Payment, ot as Budget, p as IdentityRuntime, pn as PaymentDocumentsMethods, pt as ActorProfileMethods, q as PayrollRuns, qn as TelemetryPort, qt as DestinationRemoveInput, r as ObservationContext, rn as OfframpStatus, rr as isRestoring, rt as PermissionReplaceInput, s as PostHogObservabilityClient, sn as PaymentActivityEvidence, st as OrgMe, t as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, tn as OfframpQuote, tr as destination, tt as PermissionMethods, u as CapxulClient, un as PaymentDocumentRef, ut as AccountsMethods, v as SystemHealth, vn as PaymentsMethods, vt as AddressBookAddInput, w as InviteMemberInput, wn as TargetReference, wt as InboxMethods, x as CurrentUserMethods, xn as RecipientResolutionKind, xt as AddressBookMethods, y as MediaMethods, yn as PaymentsPayInput, yt as AddressBookEntry, z as PayrollGroupInput, zn as InboxStatus, zt as ActorReference } from "./observation-BQ2VKWH5.mjs";
3
3
  import { Hex } from "viem";
4
4
  import { Context, Effect, Layer } from "effect";
5
5
  import { FunctionReference } from "convex/server";
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { $ as isClaimed, A as fingerprintPaymentIntent, B as OBSERVATION_CONTEXT_HEADER, C as ClockPortTag, D as AuthClientError, E as authClientPortFromPromiseAdapter, F as copyInvocationObservation, G as CAPXUL_FUNCTIONS, H as sanitizeObservationContext, I as readInvocationObservation, J as CAPXUL_PAYMENTS_V2_ADDRESS, K as BootstrapEnvelope, L as causeChain, M as fromWei, N as isSettingUpLifecycle, O as AuthClientPortTag, P as formatTraceparent, Q as destination, R as injectedWalletSigner, S as ClockError, T as bootstrapErrorFromCapxul, U as PAYMENT_DIRECTIONS, V as encodeObservationContextHeader, W as PAYMENT_STATUSES, X as BASE_SEPOLIA_CHAIN_ID, Y as normalizeBindingEmail, _ as wireChainId, a as observeFailedResult, b as ConvexCallPortTag, c as captureExceptionSync, d as TelemetryPortTag, et as isRestoring, g as accountReadErrorFromCapxul, h as AccountReadPortTag, i as observationContextProps, j as toWei, k as version, l as detectAuthCacheAdapter, m as smartAccountErrorFromCapxul, n as postHogProductTelemetry, o as postHogFailureObservation, p as SmartAccountPortTag, q as EngineeringTelemetryBootstrapPolicy, r as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, s as captureException, t as assembleCapxulClient, u as PostHogTelemetryLayer, v as IdentityPortTag, w as BootstrapPortTag, x as convexCallErrorFromCapxul, y as identityErrorFromCapxul, z as signerFailure } from "./create-capxul-client-Btl4qyNC.mjs";
2
- import { B as Errors, C as toDurationMs, D as toJwtToken, E as toEpochSeconds, F as toSessionToken, I as decodeConvexError, L as CAPXUL_ERROR_CODES, N as toPublishableKey, O as toKycTier, P as toRoleKey, R as CapxulError, S as toCurrencyCode, T as toEpochMs, V as isCapxulError, b as toChainId, g as toAllowedOrigin, h as toAddress, k as toOrgId, m as toAccountId, o as AuthCachePortTag, p as currencySymbolFor, v as toAuthUserId, w as toEmail, x as toCountryCode } from "./InMemoryAuthCacheAdapter-D5Cv0yz0.mjs";
1
+ import { A as AuthClientPortTag, B as injectedWalletSigner, C as convexCallErrorFromCapxul, D as bootstrapErrorFromCapxul, E as BootstrapPortTag, F as isSettingUpLifecycle, G as PAYMENT_DIRECTIONS, H as OBSERVATION_CONTEXT_HEADER, I as formatTraceparent, J as BootstrapEnvelope, K as PAYMENT_STATUSES, L as copyInvocationObservation, M as fingerprintPaymentIntent, N as toWei, O as authClientPortFromPromiseAdapter, P as fromWei, Q as BASE_SEPOLIA_CHAIN_ID, R as readInvocationObservation, S as ConvexCallPortTag, T as ClockPortTag, U as encodeObservationContextHeader, V as signerFailure, W as sanitizeObservationContext, X as CAPXUL_PAYMENTS_V2_ADDRESS, Y as EngineeringTelemetryBootstrapPolicy, Z as normalizeBindingEmail, _ as AccountReadPortTag, a as failureEvidenceProps, b as IdentityPortTag, c as postHogFailureObservation, d as detectAuthCacheAdapter, et as destination, f as PostHogTelemetryLayer, g as smartAccountErrorFromCapxul, h as SmartAccountPortTag, i as failureDetail, j as version, k as AuthClientError, l as captureException, n as postHogProductTelemetry, nt as isRestoring, o as observationContextProps, p as TelemetryPortTag, q as CAPXUL_FUNCTIONS, r as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, s as observeFailedResult, t as assembleCapxulClient, tt as isClaimed, u as captureExceptionSync, v as accountReadErrorFromCapxul, w as ClockError, x as identityErrorFromCapxul, y as wireChainId, z as causeChain } from "./create-capxul-client-BDksczn-.mjs";
2
+ import { B as Errors, C as toDurationMs, D as toJwtToken, E as toEpochSeconds, F as toSessionToken, I as decodeConvexError, L as CAPXUL_ERROR_CODES, N as toPublishableKey, O as toKycTier, P as toRoleKey, R as CapxulError, S as toCurrencyCode, T as toEpochMs, V as isCapxulError, b as toChainId, g as toAllowedOrigin, h as toAddress, k as toOrgId, m as toAccountId, o as AuthCachePortTag, p as currencySymbolFor, v as toAuthUserId, w as toEmail, x as toCountryCode } from "./InMemoryAuthCacheAdapter-uOcqpqu8.mjs";
3
3
  import { keccak256, recoverAddress, stringToHex } from "viem";
4
- import { Cause, Context, Data, Effect, Exit, Layer, Result, SchemaIssue, SchemaParser, Scope, Tracer } from "effect";
4
+ import { Cause, Context, Data, Duration, Effect, Exit, Layer, Result, Schedule, SchemaIssue, SchemaParser, Scope, Tracer } from "effect";
5
5
  import { getFunctionName, makeFunctionReference } from "convex/server";
6
6
  import { privateKeyToAccount } from "viem/accounts";
7
7
  import { FetchHttpClient, Headers, HttpClient } from "effect/unstable/http";
@@ -1266,6 +1266,33 @@ function BetterAuthNodeLayer(deps) {
1266
1266
  }
1267
1267
  //#endregion
1268
1268
  //#region src/adapters/bootstrap/HttpBootstrapAdapter.ts
1269
+ const DEFAULT_RETRY = {
1270
+ attempts: 2,
1271
+ baseDelayMs: 400
1272
+ };
1273
+ /** Request-side statuses a proxy or backend returns while momentarily unable to serve. */
1274
+ const TRANSIENT_HTTP_STATUSES = new Set([
1275
+ 408,
1276
+ 425,
1277
+ 429
1278
+ ]);
1279
+ /** Every 5xx is a server-side condition worth one more try; the client sent nothing wrong. */
1280
+ function isTransientHttpStatus(status) {
1281
+ return status >= 500 || TRANSIENT_HTTP_STATUSES.has(status);
1282
+ }
1283
+ /**
1284
+ * A transient HTTP status is worth one more try. The bootstrap call crosses
1285
+ * the host's own proxy before it reaches Convex, and every observed failure
1286
+ * of that hop cleared on a retry seconds later. A network rejection (offline,
1287
+ * DNS, CORS) is not retried: it does not clear in a second, and the caller
1288
+ * surfaces it as `NETWORK_ERROR` at once. Auth and input rejections are
1289
+ * deterministic and never retried.
1290
+ */
1291
+ function isTransientBootstrapFailure(error) {
1292
+ if (error.kind !== "provider") return false;
1293
+ const status = error.details?.httpStatus;
1294
+ return typeof status === "number" && isTransientHttpStatus(status);
1295
+ }
1269
1296
  async function safeText(res) {
1270
1297
  try {
1271
1298
  return await res.text();
@@ -1277,12 +1304,21 @@ var HttpBootstrapAdapter = class {
1277
1304
  bootstrapBaseUrl;
1278
1305
  fetchImpl;
1279
1306
  observation;
1307
+ retry;
1280
1308
  constructor(deps) {
1281
1309
  this.bootstrapBaseUrl = deps.bootstrapBaseUrl.replace(/\/$/, "");
1282
1310
  this.observation = deps.observation;
1311
+ this.retry = deps.retry ?? DEFAULT_RETRY;
1283
1312
  this.fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));
1284
1313
  }
1285
1314
  resolve(input) {
1315
+ return this.attempt(input).pipe(Effect.retry({
1316
+ times: this.retry.attempts,
1317
+ while: isTransientBootstrapFailure,
1318
+ schedule: Schedule.exponential(Duration.millis(this.retry.baseDelayMs))
1319
+ }));
1320
+ }
1321
+ attempt(input) {
1286
1322
  return Effect.tryPromise({
1287
1323
  try: () => {
1288
1324
  const headers = {
@@ -1335,7 +1371,17 @@ var HttpBootstrapAdapter = class {
1335
1371
  return Effect.promise(() => safeText(res)).pipe(Effect.flatMap((body) => {
1336
1372
  if (res.status === 401 || body.startsWith("NOT_AUTHENTICATED")) return Effect.fail(bootstrapErrorFromCapxul("notAuthenticated", Errors.notAuthenticated()));
1337
1373
  if (res.status === 400 || body.startsWith("INVALID_INPUT")) return Effect.fail(bootstrapErrorFromCapxul("invalidInput", Errors.invalidInput("publishableKey", "rejected by bootstrap")));
1338
- return Effect.fail(bootstrapErrorFromCapxul("provider", Errors.providerError("convex", "bootstrap", /* @__PURE__ */ new Error(`HTTP ${res.status}`))));
1374
+ const responseBody = body.slice(0, 300);
1375
+ const edgeError = res.headers?.get?.("x-vercel-error") ?? void 0;
1376
+ const edgeRequestId = res.headers?.get?.("x-vercel-id") ?? void 0;
1377
+ return Effect.fail(bootstrapErrorFromCapxul("provider", Errors.providerError("convex", "bootstrap", /* @__PURE__ */ new Error(`HTTP ${res.status}${edgeError === void 0 ? "" : ` ${edgeError}`}`), {
1378
+ httpStatus: res.status,
1379
+ details: {
1380
+ ...responseBody.length === 0 ? {} : { responseBody },
1381
+ ...edgeError === void 0 ? {} : { edgeError },
1382
+ ...edgeRequestId === void 0 ? {} : { edgeRequestId }
1383
+ }
1384
+ })));
1339
1385
  }));
1340
1386
  }
1341
1387
  };
@@ -2794,7 +2840,9 @@ async function createProductionAdapters(input) {
2794
2840
  name: "bootstrap_failed",
2795
2841
  props: {
2796
2842
  ...bootstrapTelemetryEnvelope(input, resolvedInput.value),
2797
- reason: bootstrapResult.error.code
2843
+ reason: bootstrapResult.error.code,
2844
+ ...failureDetail(bootstrapResult.error),
2845
+ ...failureEvidenceProps(bootstrapResult.error)
2798
2846
  }
2799
2847
  });
2800
2848
  await closeScope().catch(() => void 0);
@@ -1,4 +1,4 @@
1
- import { O as AuthSession, _ as AuthCacheError, b as CachedJwt, n as CapxulSigner, v as AuthCachePort, y as AuthCachePortTag } from "../signer-CRzTIrau.mjs";
1
+ import { O as AuthSession, _ as AuthCacheError, b as CachedJwt, n as CapxulSigner, v as AuthCachePort, y as AuthCachePortTag } from "../signer-BSEG9xgN.mjs";
2
2
  import { Hex } from "viem";
3
3
  import { Effect, FileSystem, Layer, Path } from "effect";
4
4
 
@@ -1,4 +1,4 @@
1
- import { a as AuthCacheError, h as toAddress, i as parseCachedJwt, n as BrowserAuthCacheAdapter, o as AuthCachePortTag, r as parseAuthSession, t as InMemoryAuthCacheAdapter } from "../InMemoryAuthCacheAdapter-D5Cv0yz0.mjs";
1
+ import { a as AuthCacheError, h as toAddress, i as parseCachedJwt, n as BrowserAuthCacheAdapter, o as AuthCachePortTag, r as parseAuthSession, t as InMemoryAuthCacheAdapter } from "../InMemoryAuthCacheAdapter-uOcqpqu8.mjs";
2
2
  import { Effect, FileSystem, Layer, Path } from "effect";
3
3
  import { privateKeyToAccount } from "viem/accounts";
4
4
  import * as os from "node:os";
@@ -1,4 +1,4 @@
1
- import { $ as WeiAmount, A as BlockNumber, B as OrgId, C as Address$1, D as AppId, E as AnonymousDistinctId, F as DocumentHash, G as PermissionAssignmentId, H as PaymentCommandId, I as DurationMs, J as PublishableKey, K as PermissionId, L as Email, M as ChainId, N as CountryCode, O as AuthSession, P as CurrencyCode, Q as TxHash, R as EpochMs, T as AllowedOrigin, U as PayrollGroupId, V as PartyId, W as PayrollRunId, X as SessionToken, Y as RoleKey, Z as SmartAccount, a as SignerStatusStore, at as CapxulErrorDetails, b as CachedJwt, c as AccountProviderSource, ct as FailureMode, g as SmartAccount$1, h as Session$1, it as CapxulErrorCode, j as BudgetId, k as AuthUserId, l as AccountRequirement, m as Profile$1, n as CapxulSigner, p as CapxulResult, q as Profile, rt as CapxulError, st as Failure, v as AuthCachePort, w as AllowanceKey, x as Account$1, z as Money } from "./signer-CRzTIrau.mjs";
1
+ import { $ as WeiAmount, A as BlockNumber, B as OrgId, C as Address$1, D as AppId, E as AnonymousDistinctId, F as DocumentHash, G as PermissionAssignmentId, H as PaymentCommandId, I as DurationMs, J as PublishableKey, K as PermissionId, L as Email, M as ChainId, N as CountryCode, O as AuthSession, P as CurrencyCode, Q as TxHash, R as EpochMs, T as AllowedOrigin, U as PayrollGroupId, V as PartyId, W as PayrollRunId, X as SessionToken, Y as RoleKey, Z as SmartAccount, a as SignerStatusStore, at as CapxulErrorDetails, b as CachedJwt, c as AccountProviderSource, ct as FailureMode, g as SmartAccount$1, h as Session$1, it as CapxulErrorCode, j as BudgetId, k as AuthUserId, l as AccountRequirement, m as Profile$1, n as CapxulSigner, p as CapxulResult, q as Profile, rt as CapxulError, st as Failure, v as AuthCachePort, w as AllowanceKey, x as Account$1, z as Money } from "./signer-BSEG9xgN.mjs";
2
2
  import { Address, Hex } from "viem";
3
3
  import { Context, Effect, Layer, Schema, Scope, Tracer } from "effect";
4
4
  import { FunctionReference } from "convex/server";
@@ -38,7 +38,8 @@ type IdentityTransition = (RecordBase & {
38
38
  readonly outcome: "failed" | "cancelled";
39
39
  readonly state: string;
40
40
  readonly error_code: CapxulErrorCode;
41
- readonly refusal_code?: never;
41
+ readonly refusal_code?: never; /** The typed failure behind `error_code`, with its `CapxulError` when the port gave one. */
42
+ readonly failure?: Failure;
42
43
  });
43
44
  declare class ActorFailure<Reason extends CapxulErrorCode> extends Error {
44
45
  readonly reason: Reason;
@@ -47,7 +48,7 @@ declare class ActorFailure<Reason extends CapxulErrorCode> extends Error {
47
48
  readonly event: string;
48
49
  readonly details?: Readonly<Record<string, unknown>> | undefined;
49
50
  readonly _tag = "ActorFailure";
50
- constructor(reason: Reason, machine: string, state: string, event: string, details?: Readonly<Record<string, unknown>> | undefined);
51
+ constructor(reason: Reason, machine: string, state: string, event: string, details?: Readonly<Record<string, unknown>> | undefined, cause?: unknown);
51
52
  }
52
53
  interface Actor<S, Pub, Reason extends CapxulErrorCode> {
53
54
  readonly ask: (event: Pub, controls?: InvocationControls) => Effect.Effect<S, ActorFailure<Reason | CapxulErrorCode>>;
@@ -2701,9 +2702,11 @@ declare function postHogObservability(client: PostHogObservabilityClient | null
2701
2702
  /** Host-owned correlation fields that are safe to attach to an SDK failure. */
2702
2703
  interface ObservationContext extends Omit<WireObservationContext, "applicationId"> {}
2703
2704
  /**
2704
- * The small, SDK-owned failure envelope delivered to observation adapters.
2705
- * Method arguments, response bodies, wallet payloads, and arbitrary error
2706
- * details are deliberately absent.
2705
+ * The SDK-owned failure envelope delivered to observation adapters. It carries
2706
+ * the real error message, the `CapxulError.details` object, the cause chain,
2707
+ * and the stack. Secret material (keys, tokens, bearer headers) is masked;
2708
+ * nothing else is withheld. Ruling 2026-09-01: an operator reading an issue
2709
+ * needs the actual failure, not a placeholder.
2707
2710
  */
2708
2711
  interface SdkFailureObservation {
2709
2712
  readonly exception: Error;
@@ -2712,6 +2715,30 @@ interface SdkFailureObservation {
2712
2715
  readonly errorKind: string;
2713
2716
  /** Invocation snapshot; failure correlation wins over later host state. */
2714
2717
  readonly context?: ObservationContext;
2718
+ /** Enumerated discriminators from `CapxulError.details`, in property shape. */
2719
+ readonly detail?: SdkFailureDetail;
2720
+ /** The error's own message, secrets masked. */
2721
+ readonly message?: string;
2722
+ /** The full `CapxulError.details` object, secrets masked, JSON-safe. */
2723
+ readonly details?: Readonly<Record<string, unknown>>;
2724
+ /** Messages down the `cause` chain, outermost first, secrets masked. */
2725
+ readonly causeChain?: readonly string[];
2726
+ /** The original stack when the error had one, secrets masked. */
2727
+ readonly stack?: string;
2728
+ }
2729
+ /**
2730
+ * The PII-safe subset of `CapxulError.details`, already in PostHog property
2731
+ * shape. `provider` + `provider_operation` name the failing dependency
2732
+ * (`convex bootstrap`, `openfort configure`), `failure_mode` / `reason` are
2733
+ * enumerated codes, `http_status` is the upstream status. Anything else on
2734
+ * `details` (ids, field names, free text) is dropped at the boundary.
2735
+ */
2736
+ interface SdkFailureDetail {
2737
+ readonly provider?: string;
2738
+ readonly provider_operation?: string;
2739
+ readonly failure_mode?: string;
2740
+ readonly reason?: string;
2741
+ readonly http_status?: number;
2715
2742
  }
2716
2743
  type ObservationDelivery = void | PromiseLike<void>;
2717
2744
  /**
@@ -66,6 +66,8 @@ declare const Errors: {
66
66
  readonly accountNotFound: (accountId?: string) => CapxulError;
67
67
  readonly providerError: (provider: string, operation: string, cause: unknown, opts?: {
68
68
  readonly failure_mode?: FailureMode;
69
+ readonly httpStatus?: number; /** Extra evidence for the operator (response body, edge error code). */
70
+ readonly details?: Readonly<Record<string, unknown>>;
69
71
  }) => CapxulError;
70
72
  readonly capabilityUnavailable: (provider: string, operation: string) => CapxulError;
71
73
  readonly invalidInput: (field: string, reason: string) => CapxulError;
@@ -1,4 +1,4 @@
1
- import { Gn as TelemetryGroupInput, Kn as TelemetryIdentifyInput, Wn as TelemetryEvent, ir as IdentityTransition, n as ObservationAdapter, u as CapxulClient } from "../observation-CyNjyQxv.mjs";
1
+ import { Gn as TelemetryGroupInput, Kn as TelemetryIdentifyInput, Wn as TelemetryEvent, ir as IdentityTransition, n as ObservationAdapter, u as CapxulClient } from "../observation-BQ2VKWH5.mjs";
2
2
  import { Effect, Layer } from "effect";
3
3
 
4
4
  //#region src/testing/telemetry/RecordingTelemetryAdapter.d.ts
@@ -1,5 +1,5 @@
1
- import { E as authClientPortFromPromiseAdapter, M as fromWei, T as bootstrapErrorFromCapxul, Z as deriveCapxulSafeAddress, _ as wireChainId, f as redactTelemetryEvent, g as accountReadErrorFromCapxul, j as toWei, m as smartAccountErrorFromCapxul, t as assembleCapxulClient, x as convexCallErrorFromCapxul, y as identityErrorFromCapxul } from "../create-capxul-client-Btl4qyNC.mjs";
2
- import { B as Errors, C as toDurationMs, D as toJwtToken, E as toEpochSeconds, F as toSessionToken, N as toPublishableKey, O as toKycTier, R as CapxulError, T as toEpochMs, _ as toAppId, b as toChainId, g as toAllowedOrigin, h as toAddress, m as toAccountId, t as InMemoryAuthCacheAdapter, v as toAuthUserId, w as toEmail, x as toCountryCode } from "../InMemoryAuthCacheAdapter-D5Cv0yz0.mjs";
1
+ import { $ as deriveCapxulSafeAddress, C as convexCallErrorFromCapxul, D as bootstrapErrorFromCapxul, N as toWei, O as authClientPortFromPromiseAdapter, P as fromWei, g as smartAccountErrorFromCapxul, m as redactTelemetryEvent, t as assembleCapxulClient, v as accountReadErrorFromCapxul, x as identityErrorFromCapxul, y as wireChainId } from "../create-capxul-client-BDksczn-.mjs";
2
+ import { B as Errors, C as toDurationMs, D as toJwtToken, E as toEpochSeconds, F as toSessionToken, N as toPublishableKey, O as toKycTier, R as CapxulError, T as toEpochMs, _ as toAppId, b as toChainId, g as toAllowedOrigin, h as toAddress, m as toAccountId, t as InMemoryAuthCacheAdapter, v as toAuthUserId, w as toEmail, x as toCountryCode } from "../InMemoryAuthCacheAdapter-uOcqpqu8.mjs";
3
3
  import { keccak256 } from "viem";
4
4
  import { Effect, Result, Semaphore } from "effect";
5
5
  import { getFunctionName } from "convex/server";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/sdk",
3
- "version": "2.5.0",
3
+ "version": "2.5.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Xelmar-tech/infrastructure.git",
@@ -46,12 +46,12 @@
46
46
  "typescript": "npm:@typescript/typescript6@6.0.2",
47
47
  "vite-plus": "0.1.23",
48
48
  "vitest": "npm:@voidzero-dev/vite-plus-test@0.1.23",
49
- "@capxul/types": "0.2.0",
49
+ "@capxul/config": "0.2.1",
50
+ "@capxul/errors": "0.0.2",
50
51
  "@capxul/typescript-config": "0.0.0",
51
- "@capxul/config": "0.2.0",
52
- "@capxul/observability": "2.5.0",
53
- "@capxul/wire": "0.5.0",
54
- "@capxul/errors": "0.0.1"
52
+ "@capxul/observability": "2.5.2",
53
+ "@capxul/wire": "0.5.1",
54
+ "@capxul/types": "0.2.1"
55
55
  },
56
56
  "_permissionlessPinReason": "permissionless.toSafeSmartAccount is pinned to 0.3.4 for live Safe deployment E2E. Counterfactual address fixtures captured 2026-05-17 in packages/backend/convex/_shared/__tests__/counterfactual.test.ts and packages/config/tests/safe.test.ts must be re-verified before upgrading.",
57
57
  "scripts": {