@capxul/sdk 4.20.0-beta.2 → 4.20.0-beta.3

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.
@@ -76,7 +76,12 @@ const CREDENTIAL_FIELDS = /* @__PURE__ */ new Set([
76
76
  "authcode",
77
77
  "authorizationcode",
78
78
  "oauthcode",
79
- "codeverifier"
79
+ "codeverifier",
80
+ "devicecode",
81
+ "usercode",
82
+ "continuitytoken",
83
+ "refreshattemptid",
84
+ "revocationtoken"
80
85
  ]);
81
86
  /** Match credential fields by meaning, without hiding token addresses or replay IDs. */
82
87
  function isCredentialField(name, context) {
@@ -908,6 +913,8 @@ const COUNTRY_CODE_RE = /^[A-Z]{2}$/;
908
913
  const ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;
909
914
  const PARTY_ID_RE = /^party_[0-9A-Za-z]+$/;
910
915
  const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
916
+ const CLIENT_REQUEST_ID_RE = /^creq_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
917
+ const CLIENT_GRANT_ID_RE = /^cgrant_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
911
918
  const TX_HASH_RE = /^0x[0-9a-f]{64}$/i;
912
919
  const WEI_RE = /^[0-9]+$/;
913
920
  Math.floor(Number.MAX_SAFE_INTEGER / 1e3);
@@ -2478,4 +2485,4 @@ function readExchange(body) {
2478
2485
  };
2479
2486
  }
2480
2487
  //#endregion
2481
- export { toRoleKey as $, currencySymbolFor as A, toCurrencyCode as B, ASSET_ID_RE as C, isCredentialField as Ct, WEI_RE as D, SUPPORTED_CURRENCY_CODES as E, toAssetId as F, toHandle as G, toEmail as H, toAuthUserId as I, toOrgId as J, toJwtToken as K, toBudgetId as L, toAddress as M, toAllowedOrigin as N, ZERO_BYTES32 as O, toAppId as P, toPublishableKey as Q, toChainId as R, APP_ID_RE as S, containsSensitiveMaterial as St, EVM_ADDRESS_RE as T, redactUrlSecrets as Tt, toEpochMs as U, toDurationMs as V, toEpochSeconds as W, toPayrollGroupId as X, toPartyId as Y, toPayrollRunId as Z, normalizeBindingEmail as _, decodeChainCause as _t, parseAuthSession as a, HANDLE_RE as at, configuredMoneyAssetById as b, isFailureMode as bt, AuthCachePortTag as c, CapxulError as ct, authClientPortFromPromiseAdapter as d, isCapxulError as dt, toSessionToken as et, AuthClientError as f, CHAIN_UPSTREAMS as ft, CAPXUL_PAYMENTS_V2_ADDRESS as g, chainEvidenceLabel as gt, orgRoleKeyForLabel as h, chainCauseProperties as ht, BrowserAuthCacheAdapter as i, validateHandle as it, toAccountId as j, assetIdFor as k, SystemClockLayer as l, EXPECTED_OPERATION_OUTCOMES as lt, ADMIN_ROLE_LABEL as m, boundedResponseHeaders as mt, readClockNow as n, toTxHash as nt, parseCachedJwt as o, decodeConvexError as ot, AuthClientPortTag as p, FAILURE_MODES as pt, toKycTier as q, InMemoryAuthCacheAdapter as r, toWeiAmount as rt, AuthCacheError as s, CAPXUL_ERROR_CODES as st, oauthBearerAuthClient as t, toTesterKind as tt, ClockPortTag as u, Errors as ut, BASE_SEPOLIA_CHAIN_ID as v, failureFingerprint as vt, BYTES32_RE as w, redactSecrets as wt, ACCOUNT_ID_RE as x, revertSummaryText as xt, deriveCapxulSafeAddress as y, isChainUpstream as yt, toCountryCode as z };
2488
+ export { toPartyId as $, SUPPORTED_CURRENCY_CODES as A, toAuthUserId as B, ASSET_ID_RE as C, isChainUpstream as Ct, COUNTRY_CODE_RE as D, isCredentialField as Dt, CLIENT_REQUEST_ID_RE as E, containsSensitiveMaterial as Et, toAccountId as F, toDurationMs as G, toChainId as H, toAddress as I, toEpochSeconds as J, toEmail as K, toAllowedOrigin as L, ZERO_BYTES32 as M, assetIdFor as N, EMAIL_RE as O, redactSecrets as Ot, currencySymbolFor as P, toOrgId as Q, toAppId as R, APP_ID_RE as S, failureFingerprint as St, CLIENT_GRANT_ID_RE as T, revertSummaryText as Tt, toCountryCode as U, toBudgetId as V, toCurrencyCode as W, toJwtToken as X, toHandle as Y, toKycTier as Z, normalizeBindingEmail as _, FAILURE_MODES as _t, parseAuthSession as a, toTesterKind as at, configuredMoneyAssetById as b, chainEvidenceLabel as bt, AuthCachePortTag as c, validateHandle as ct, authClientPortFromPromiseAdapter as d, CAPXUL_ERROR_CODES as dt, toPayrollGroupId as et, AuthClientError as f, CapxulError as ft, CAPXUL_PAYMENTS_V2_ADDRESS as g, CHAIN_UPSTREAMS as gt, orgRoleKeyForLabel as h, isCapxulError as ht, BrowserAuthCacheAdapter as i, toSessionToken as it, WEI_RE as j, EVM_ADDRESS_RE as k, redactUrlSecrets as kt, SystemClockLayer as l, HANDLE_RE as lt, ADMIN_ROLE_LABEL as m, Errors as mt, readClockNow as n, toPublishableKey as nt, parseCachedJwt as o, toTxHash as ot, AuthClientPortTag as p, EXPECTED_OPERATION_OUTCOMES as pt, toEpochMs as q, InMemoryAuthCacheAdapter as r, toRoleKey as rt, AuthCacheError as s, toWeiAmount as st, oauthBearerAuthClient as t, toPayrollRunId as tt, ClockPortTag as u, decodeConvexError as ut, BASE_SEPOLIA_CHAIN_ID as v, boundedResponseHeaders as vt, BYTES32_RE as w, isFailureMode as wt, ACCOUNT_ID_RE as x, decodeChainCause as xt, deriveCapxulSafeAddress as y, chainCauseProperties as yt, toAssetId as z };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { $ as PayrollGroupId, B as ChainId, Ct as ChainCause, D as Account, Dt as RevertSummary, E as CAPXUL_PAYMENTS_V2_ADDRESS, Et as FailureMode, F as AssetId, G as EVM_ADDRESS_RE, H as CurrencyCode, I as AuthSession, J as Handle, L as AuthUserId, O as AccountId, P as AssetAmount, St as CHAIN_UPSTREAMS, Tt as FAILURE_MODES, V as CountryCode, X as OrgId, Y as Money, Z as PartyId, _ as Session, _t as CapxulErrorCode, a as Eip1193RequestProvider, at as RoleKey, c as injectedWalletSigner, ct as TesterKind, d as AccountRequirement, dt as toAddress, et as PayrollRunId, f as Eip1193Provider, ft as toCountryCode, g as Profile, gt as CapxulError, h as CapxulResult, ht as CAPXUL_ERROR_CODES, i as CapxulSigner, k as Address, l as AccountProvider, m as localPrivateKeyAccountProvider, mt as toPartyId, o as SignerStatus, p as eip1193AccountProvider, pt as toHandle, r as CapxulDigestSigner, s as SignerStatusStore, u as AccountProviderSource, v as SmartAccount, vt as CapxulErrorDetails, wt as ChainUpstream, xt as isCapxulError, yt as Errors, z as BudgetId } from "./OAuthBearerAuthClient-C-ip-z8M.mjs";
2
- import { $ as OrganizationPaymentBatchInput, $n as RequestStatus, $t as Destination, A as OrgScopedMethods, An as Ref, At as AddressBookAddInput, B as AuthorizeRunOptions, Bn as SmartAccountMethods, Bt as ActivityFilter, C as CurrentUserMethods, Cn as PaymentMoney, Ct as AccountMethods, D as MemberStatus, Dn as PaymentsMethods, Dt as ActorRequest, E as InviteMemberInput, En as PaymentType, Et as ActorRelationshipMethods, F as ResendInviteTokenInput, Fn as AccountLifecycle, Ft as InboxItem, G as PayrollGroupsMethods, Gn as ActorRef, Gt as ActivityPage, H as PayrollGroup, Hn as OrgLifecycle, Ht as ActivityKind, I as RoleDefinition, In as AccountSetupStep, It as InboxMethods, J as PayrollRun, Jn as SubmittedPermissionExecution, Jt as ActivitySummary, K as PayrollMethods, Kn as CurrentHoldings, Kt as ActivityRange, L as RoleSpendCap, Ln as isSettingUpLifecycle, Lt as ActivityAnnotation, M as OrgView, Mn as TargetReference, Mt as AddressBookLabelInput, N as OrganizationAccount, Nn as TargetsMethods, Nt as AddressBookMethods, O as MemberView, On as PaymentsPayInput, Ot as ActorRequestIssueInput, P as OrganizationAuditLogItem, Pn as fingerprintPaymentIntent, Pt as InboxApproveInput, Q as PayrollTermsUnit, Qn as PaymentStatus$1, Qt as DepositInstructions, R as RoleView, Rn as CompleteProfileInput, Rt as ActivityAnnotationInput, S as CurrentUserContext, Sn as PaymentDocumentsMethods, St as ReadyAccountLifecycle, T as DetectPendingOrgInvitationsResult, Tn as PaymentTiming, Tt as ActorProfileMethods, U as PayrollGroupInput, Un as OrgSetupStep, Ut as ActivityListParams, V as PayrollEngagementTerms, Vn as AuthMethods, Vt as ActivityItem, W as PayrollGroupMember, Wn as PayoutAddress, Wt as ActivityMethods, X as PayrollRunStatus, Xn as PAYMENT_DIRECTIONS, Xt as ActivitySummaryTotal, Y as PayrollRunItemInput, Yn as InboxStatus, Yt as ActivitySummaryParams, Z as PayrollRuns, Zn as PAYMENT_STATUSES, Zt as ActorReference, _ as HoldingsMethods, _n as PaymentDirection, _t as OnboardingMethods, a as ObservationContext, an as DestinationRemoveInput, ar as IdentityEvent, at as PermissionCreateInput, b as SystemHealth, bn as PaymentDocumentRender, bt as PersonOnboarding, c as HostObservability, cn as MeMethods, cr as Readiness, ct as PermissionReplaceInput, d as postHogObservability, dn as OfframpMethods, dr as isClaimed, dt as Budget, en as DestinationAddInput, et as OrganizationPaymentInput, f as CapxulClient, fn as OfframpQuote, fr as isRestoring, ft as OrgMe, g as IdentityRuntimeSendResult, gn as PaymentActivityEvidence, gt as CompletedPersonProfile, h as IdentityRuntime, hn as Payment, ht as AccountsMethods, i as ObservationAdapter, in as DestinationRail, ir as Destination$1, it as PermissionChangeInput, j as OrgTemplate, jn as ResolvedTarget, jt as AddressBookEntry, k as OrgMethods, kn as RecipientResolution, kt as ActorRequestsMethods, l as PostHogObservabilityClient, ln as MeProfile, lr as StateLabel, lt as PermissionRevokeInput, m as IdentityProfileDetails, mn as OfframpStatus, mr as InvocationControls, mt as OrgMeOptions, nn as DestinationListInput, nt as OrganizationPaymentsMethods, o as ObservationDelivery, on as DestinationsMethods, or as IdentityState, ot as PermissionMethods, p as CreateCapxulClientInput, pn as OfframpQuoteInput, pr as IdentityTransition, pt as OrgMeMethod, q as PayrollOptions, qn as Permission, qt as ActivityReference, r as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, rn as DestinationPayload, rr as TelemetryPort, rt as PermissionAssignInput, s as SdkFailureObservation, sn as FinancialOpsMethods, sr as OrgLane, st as PermissionOptions, t as CapxulClientInput, tn as DestinationKind, tt as OrganizationPaymentItemInput, u as PostHogObservabilityOptions, un as MovementActivityEvidence, ur as destination, ut as PermissionReadResult, v as Holding, vn as PaymentDocumentKind, vt as OrganizationOnboarding, w as CreateOrgInput, wn as PaymentStatus, wt as ActorProfile, x as MediaMethods, xn as PaymentDocumentVerification, xt as PersonOnboardingInput, y as SystemMethods, yn as PaymentDocumentRef, yt as OrganizationOnboardingInput, z as AuthorizeRunInput, zn as IdentityMethods, zt as ActivityDetail } from "./production-Cn5awmW8.mjs";
2
+ import { $ as OrganizationPaymentBatchInput, $n as RequestStatus, $t as Destination, A as OrgScopedMethods, An as Ref, At as AddressBookAddInput, B as AuthorizeRunOptions, Bn as SmartAccountMethods, Bt as ActivityFilter, C as CurrentUserMethods, Cn as PaymentMoney, Ct as AccountMethods, D as MemberStatus, Dn as PaymentsMethods, Dt as ActorRequest, E as InviteMemberInput, En as PaymentType, Et as ActorRelationshipMethods, F as ResendInviteTokenInput, Fn as AccountLifecycle, Ft as InboxItem, G as PayrollGroupsMethods, Gn as ActorRef, Gt as ActivityPage, H as PayrollGroup, Hn as OrgLifecycle, Ht as ActivityKind, I as RoleDefinition, In as AccountSetupStep, It as InboxMethods, J as PayrollRun, Jn as SubmittedPermissionExecution, Jt as ActivitySummary, K as PayrollMethods, Kn as CurrentHoldings, Kt as ActivityRange, L as RoleSpendCap, Ln as isSettingUpLifecycle, Lt as ActivityAnnotation, M as OrgView, Mn as TargetReference, Mt as AddressBookLabelInput, N as OrganizationAccount, Nn as TargetsMethods, Nt as AddressBookMethods, O as MemberView, On as PaymentsPayInput, Ot as ActorRequestIssueInput, P as OrganizationAuditLogItem, Pn as fingerprintPaymentIntent, Pt as InboxApproveInput, Q as PayrollTermsUnit, Qn as PaymentStatus$1, Qt as DepositInstructions, R as RoleView, Rn as CompleteProfileInput, Rt as ActivityAnnotationInput, S as CurrentUserContext, Sn as PaymentDocumentsMethods, St as ReadyAccountLifecycle, T as DetectPendingOrgInvitationsResult, Tn as PaymentTiming, Tt as ActorProfileMethods, U as PayrollGroupInput, Un as OrgSetupStep, Ut as ActivityListParams, V as PayrollEngagementTerms, Vn as AuthMethods, Vt as ActivityItem, W as PayrollGroupMember, Wn as PayoutAddress, Wt as ActivityMethods, X as PayrollRunStatus, Xn as PAYMENT_DIRECTIONS, Xt as ActivitySummaryTotal, Y as PayrollRunItemInput, Yn as InboxStatus, Yt as ActivitySummaryParams, Z as PayrollRuns, Zn as PAYMENT_STATUSES, Zt as ActorReference, _ as HoldingsMethods, _n as PaymentDirection, _t as OnboardingMethods, a as ObservationContext, an as DestinationRemoveInput, ar as IdentityEvent, at as PermissionCreateInput, b as SystemHealth, bn as PaymentDocumentRender, bt as PersonOnboarding, c as HostObservability, cn as MeMethods, cr as Readiness, ct as PermissionReplaceInput, d as postHogObservability, dn as OfframpMethods, dr as isClaimed, dt as Budget, en as DestinationAddInput, et as OrganizationPaymentInput, f as CapxulClient, fn as OfframpQuote, fr as isRestoring, ft as OrgMe, g as IdentityRuntimeSendResult, gn as PaymentActivityEvidence, gt as CompletedPersonProfile, h as IdentityRuntime, hn as Payment, ht as AccountsMethods, i as ObservationAdapter, in as DestinationRail, ir as Destination$1, it as PermissionChangeInput, j as OrgTemplate, jn as ResolvedTarget, jt as AddressBookEntry, k as OrgMethods, kn as RecipientResolution, kt as ActorRequestsMethods, l as PostHogObservabilityClient, ln as MeProfile, lr as StateLabel, lt as PermissionRevokeInput, m as IdentityProfileDetails, mn as OfframpStatus, mr as InvocationControls, mt as OrgMeOptions, nn as DestinationListInput, nt as OrganizationPaymentsMethods, o as ObservationDelivery, on as DestinationsMethods, or as IdentityState, ot as PermissionMethods, p as CreateCapxulClientInput, pn as OfframpQuoteInput, pr as IdentityTransition, pt as OrgMeMethod, q as PayrollOptions, qn as Permission, qt as ActivityReference, r as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, rn as DestinationPayload, rr as TelemetryPort, rt as PermissionAssignInput, s as SdkFailureObservation, sn as FinancialOpsMethods, sr as OrgLane, st as PermissionOptions, t as CapxulClientInput, tn as DestinationKind, tt as OrganizationPaymentItemInput, u as PostHogObservabilityOptions, un as MovementActivityEvidence, ur as destination, ut as PermissionReadResult, v as Holding, vn as PaymentDocumentKind, vt as OrganizationOnboarding, w as CreateOrgInput, wn as PaymentStatus, wt as ActorProfile, x as MediaMethods, xn as PaymentDocumentVerification, xt as PersonOnboardingInput, y as SystemMethods, yn as PaymentDocumentRef, yt as OrganizationOnboardingInput, z as AuthorizeRunInput, zn as IdentityMethods, zt as ActivityDetail } from "./production-CJwxgI8u.mjs";
3
3
  import { Hex } from "viem";
4
4
  import { Effect, Layer } from "effect";
5
5
  //#region ../errors/src/index.d.ts
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { A as signerFailure, B as isRestoring, C as normalizeExceptionErrorKind, E as safeExceptionLabel, F as CAPXUL_OPERATIONS, I as isCapxulOperation, L as normalizeCapxulOperation, M as PAYMENT_DIRECTIONS, N as PAYMENT_STATUSES, O as isSettingUpLifecycle, R as destination, S as SDK_VERSION, T as projectSdkException, _ as fingerprintPaymentIntent, b as failureDetail, d as embeddedSigner, f as openfortEmbeddedSigner, g as devPrivateKeySigner, h as deriveDevPrivateKey, j as resolveFailureMode, k as injectedWalletSigner, m as openfortEmbeddedWalletPort, p as openfortEmbeddedSignerFromWallet, r as postHogObservability, t as createCapxulClient$1, w as normalizeExceptionOperation, x as EXCEPTION_MESSAGE, y as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, z as isClaimed } from "./production-BQVXgcbY.mjs";
2
- import { A as currencySymbolFor, B as toCurrencyCode, G as toHandle, M as toAddress, T as EVM_ADDRESS_RE, Y as toPartyId, at as HANDLE_RE, b as configuredMoneyAssetById, ct as CapxulError, dt as isCapxulError, ft as CHAIN_UPSTREAMS, g as CAPXUL_PAYMENTS_V2_ADDRESS, k as assetIdFor, pt as FAILURE_MODES, st as CAPXUL_ERROR_CODES, ut as Errors, z as toCountryCode } from "./OAuthBearerAuthClient-DDD0JlaI.mjs";
1
+ import { A as signerFailure, B as isRestoring, C as normalizeExceptionErrorKind, E as safeExceptionLabel, F as CAPXUL_OPERATIONS, I as isCapxulOperation, L as normalizeCapxulOperation, M as PAYMENT_DIRECTIONS, N as PAYMENT_STATUSES, O as isSettingUpLifecycle, R as destination, S as SDK_VERSION, T as projectSdkException, _ as fingerprintPaymentIntent, b as failureDetail, d as embeddedSigner, f as openfortEmbeddedSigner, g as devPrivateKeySigner, h as deriveDevPrivateKey, j as resolveFailureMode, k as injectedWalletSigner, m as openfortEmbeddedWalletPort, p as openfortEmbeddedSignerFromWallet, r as postHogObservability, t as createCapxulClient$1, w as normalizeExceptionOperation, x as EXCEPTION_MESSAGE, y as CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, z as isClaimed } from "./production-M4dWz5g4.mjs";
2
+ import { $ as toPartyId, I as toAddress, N as assetIdFor, P as currencySymbolFor, U as toCountryCode, W as toCurrencyCode, Y as toHandle, _t as FAILURE_MODES, b as configuredMoneyAssetById, dt as CAPXUL_ERROR_CODES, ft as CapxulError, g as CAPXUL_PAYMENTS_V2_ADDRESS, gt as CHAIN_UPSTREAMS, ht as isCapxulError, k as EVM_ADDRESS_RE, lt as HANDLE_RE, mt as Errors } from "./OAuthBearerAuthClient-DWkofxdZ.mjs";
3
3
  import { formatUnits } from "viem";
4
4
  import { Effect } from "effect";
5
5
  import { privateKeyToAccount } from "viem/accounts";
@@ -1,4 +1,4 @@
1
- import { M as toAddress, a as parseAuthSession, c as AuthCachePortTag, i as BrowserAuthCacheAdapter, o as parseCachedJwt, r as InMemoryAuthCacheAdapter, s as AuthCacheError, t as oauthBearerAuthClient } from "../OAuthBearerAuthClient-DDD0JlaI.mjs";
1
+ import { I as toAddress, a as parseAuthSession, c as AuthCachePortTag, i as BrowserAuthCacheAdapter, o as parseCachedJwt, r as InMemoryAuthCacheAdapter, s as AuthCacheError, t as oauthBearerAuthClient } from "../OAuthBearerAuthClient-DWkofxdZ.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,7 +1,9 @@
1
1
  import { $ as PayrollGroupId, A as AllowanceKey, B as ChainId, C as AuthCachePort, D as Account$1, Et as FailureMode, F as AssetId, H as CurrencyCode, I as AuthSession, K as Email, L as AuthUserId, M as AnonymousDistinctId, N as AppId, Q as PaymentCommandId, R as BlockNumber, U as DocumentHash, V as CountryCode, W as DurationMs, X as OrgId, Y as Money, Z as PartyId, _ as Session$1, _t as CapxulErrorCode, at as RoleKey, b as AuthClientPort, bt as Failure, ct as TesterKind, d as AccountRequirement, et as PayrollRunId, g as Profile$1, gt as CapxulError, h as CapxulResult, i as CapxulSigner, it as PublishableKey, j as AllowedOrigin, k as Address$1, lt as TxHash, nt as PermissionId, ot as SessionToken, q as EpochMs, rt as Profile, s as SignerStatusStore, st as SmartAccount, tt as PermissionAssignmentId, u as AccountProviderSource, ut as WeiAmount, v as SmartAccount$1, vt as CapxulErrorDetails, x as CanSendOtpStatus, y as ClockPort, z as BudgetId } from "./OAuthBearerAuthClient-C-ip-z8M.mjs";
2
2
  import { Hex } from "viem";
3
- import { Context, Effect, Layer, Schema, Scope, Tracer } from "effect";
3
+ import { Context, Duration, Effect, Layer, Logger, Metric, References, Schema, Scope, Tracer } from "effect";
4
4
  import { FunctionReference } from "convex/server";
5
+ import { HttpClient, HttpClientError } from "effect/unstable/http";
6
+ import { OtlpExporter, OtlpSerialization } from "effect/unstable/observability";
5
7
  //#region src/domain/machine/shell.d.ts
6
8
  declare const INVOCATION_PARENT_SPAN: unique symbol;
7
9
  interface InvocationControls {
@@ -284,7 +286,7 @@ interface TelemetryPort {
284
286
  }
285
287
  //#endregion
286
288
  //#region ../observability/src/index.d.ts
287
- declare const TELEMETRY_EVENT_NAMES: readonly ["auth_otp_requested", "auth_otp_delivered", "auth_otp_expired", "auth_verified", "auth_failed", "identity_refused", "auth_signed_out", "onboarding_intent_selected", "onboarding_profile_submitted", "onboarding_organization_submitted", "onboarding_dashboard_reached", "provisioning_safe_created", "provisioning_safe_confirmed", "bootstrap_resolved", "bootstrap_failed", "member_activation_started", "member_activation_ready", "member_activation_failed", "organization_creation_started", "organization_creation_ready", "organization_creation_failed", "chain_upstream_fallback", "bundler_error", "receipt_pending", "operation_retried", "account_balance_read", "account_balance_failed", "faucet_requested", "faucet_confirmed", "faucet_failed", "org_create_started", "org_safe_created", "org_safe_confirmed", "org_roles_seeded", "org_created", "org_create_failed", "org_invite_sent", "org_invite_accepted", "org_invite_expired", "payment_initiated", "payment_settled", "payment_failed", "payment_verification_retry", "payment_lifecycle_transition", "quick_pay_external_address_acknowledged", "deposit_initiated", "deposit_settled", "permission_mirror_verification", "movement_scan_window", "movement_scan_checkpoint", "movement_scan_incident", "indexer_drift_corrected", "activity_annotation_saved", "ui_activity_action_completed", "contact_relationship_changed", "ui_contact_action_completed", "access_recovery_completed", "ui_access_step_completed", "org_invite_progressed", "invoice_issued", "invoice_request_transitioned", "ui_invoice_step_completed", "ui_treasury_step_completed", "ui_receive_step_completed", "payroll_group_changed", "payroll_run_transitioned", "ui_payroll_action_completed", "cli_diagnostic_completed"];
289
+ declare const TELEMETRY_EVENT_NAMES: readonly ["auth_otp_requested", "auth_otp_delivered", "auth_otp_expired", "auth_verified", "auth_failed", "identity_refused", "auth_signed_out", "onboarding_intent_selected", "onboarding_profile_submitted", "onboarding_organization_submitted", "onboarding_dashboard_reached", "provisioning_safe_created", "provisioning_safe_confirmed", "bootstrap_resolved", "bootstrap_failed", "member_activation_started", "member_activation_ready", "member_activation_failed", "organization_creation_started", "organization_creation_ready", "organization_creation_failed", "chain_upstream_fallback", "bundler_error", "receipt_pending", "operation_retried", "account_balance_read", "account_balance_failed", "faucet_requested", "faucet_confirmed", "faucet_failed", "org_create_started", "org_safe_created", "org_safe_confirmed", "org_roles_seeded", "org_created", "org_create_failed", "org_invite_sent", "org_invite_accepted", "org_invite_expired", "payment_initiated", "payment_settled", "payment_failed", "payment_verification_retry", "payment_lifecycle_transition", "quick_pay_external_address_acknowledged", "deposit_initiated", "deposit_settled", "permission_mirror_verification", "movement_scan_window", "movement_scan_checkpoint", "movement_scan_incident", "indexer_drift_corrected", "activity_annotation_saved", "ui_activity_action_completed", "contact_relationship_changed", "ui_contact_action_completed", "access_recovery_completed", "ui_access_step_completed", "org_invite_progressed", "invoice_issued", "invoice_request_transitioned", "ui_invoice_step_completed", "ui_treasury_step_completed", "ui_receive_step_completed", "payroll_group_changed", "payroll_run_transitioned", "ui_payroll_action_completed", "cli_diagnostic_completed", "cli_first_used", "cli_command_started", "cli_command_completed"];
288
290
  type TelemetryEventName = (typeof TELEMETRY_EVENT_NAMES)[number];
289
291
  type TelemetryProps = Record<string, unknown>;
290
292
  type TelemetryEvent = {
@@ -2929,6 +2931,32 @@ interface CreateCapxulClientInput {
2929
2931
  };
2930
2932
  }
2931
2933
  //#endregion
2934
+ //#region ../observability/src/engineering-delivery.d.ts
2935
+ type MetricEntry = Metric.Metric.Metadata<unknown, unknown>;
2936
+ interface CliEngineeringStats {
2937
+ readonly records: number;
2938
+ readonly reservedRecordBytes: number;
2939
+ readonly peakRecords: number;
2940
+ readonly peakReservedRecordBytes: number;
2941
+ readonly activeRequests: number;
2942
+ readonly requestBytes: number;
2943
+ readonly peakRequests: number;
2944
+ readonly peakRequestBytes: number;
2945
+ /** Rejected records, fields, metric registrations and export attempts; not delivered-event count. */
2946
+ readonly dropped: number;
2947
+ readonly metricSeries: number;
2948
+ }
2949
+ /** Shared, closure-owned admission state; no queue or mutable counters are exposed. */
2950
+ declare function makeCliEngineeringBudget(): Readonly<{
2951
+ metricRegistry: Map<string, MetricEntry>;
2952
+ emptyMetricRegistry: () => Map<string, MetricEntry>;
2953
+ drop: () => void;
2954
+ admitRecord(terminal: boolean): (() => void) | undefined;
2955
+ admitRequest(bytes: number, terminal: boolean): (() => void) | undefined;
2956
+ snapshot(): CliEngineeringStats;
2957
+ }>;
2958
+ type CliEngineeringBudget = ReturnType<typeof makeCliEngineeringBudget>;
2959
+ //#endregion
2932
2960
  //#region src/host-observability.d.ts
2933
2961
  /** One host-owned observability module at the SDK consumer boundary. */
2934
2962
  interface HostObservability {
@@ -2949,6 +2977,8 @@ interface PostHogObservabilityOptions {
2949
2977
  readonly engineeringEnabled?: boolean | (() => boolean);
2950
2978
  /** Opt in to code/timing/correlation-only engineering exports. Omission preserves full safe diagnostics. */
2951
2979
  readonly engineeringPrivacy?: "minimal";
2980
+ /** Shared CLI-only admission and transport budget; omitted for other hosts. */
2981
+ readonly engineeringDeliveryBudget?: CliEngineeringBudget;
2952
2982
  /** Host environment stamped on every SDK-owned product event. */
2953
2983
  readonly capxulEnv?: CapxulEnv;
2954
2984
  /** Host-owned correlation context shared by product and failure delivery. */
@@ -1,9 +1,9 @@
1
- import { $ as toRoleKey, B as toCurrencyCode, C as ASSET_ID_RE, Ct as isCredentialField, D as WEI_RE, E as SUPPORTED_CURRENCY_CODES, F as toAssetId, G as toHandle, H as toEmail, I as toAuthUserId, J as toOrgId, K as toJwtToken, L as toBudgetId, M as toAddress, N as toAllowedOrigin, O as ZERO_BYTES32, Q as toPublishableKey, R as toChainId, S as APP_ID_RE, St as containsSensitiveMaterial, T as EVM_ADDRESS_RE$1, Tt as redactUrlSecrets, U as toEpochMs, V as toDurationMs, W as toEpochSeconds, X as toPayrollGroupId, Y as toPartyId, Z as toPayrollRunId, _ as normalizeBindingEmail, _t as decodeChainCause, b as configuredMoneyAssetById, bt as isFailureMode, c as AuthCachePortTag, ct as CapxulError, d as authClientPortFromPromiseAdapter, dt as isCapxulError, et as toSessionToken, f as AuthClientError, ft as CHAIN_UPSTREAMS, gt as chainEvidenceLabel, h as orgRoleKeyForLabel, ht as chainCauseProperties, i as BrowserAuthCacheAdapter, it as validateHandle, j as toAccountId, l as SystemClockLayer, lt as EXPECTED_OPERATION_OUTCOMES, m as ADMIN_ROLE_LABEL, mt as boundedResponseHeaders, nt as toTxHash, ot as decodeConvexError, p as AuthClientPortTag, pt as FAILURE_MODES$1, q as toKycTier, r as InMemoryAuthCacheAdapter, rt as toWeiAmount, st as CAPXUL_ERROR_CODES, tt as toTesterKind, u as ClockPortTag, ut as Errors, v as BASE_SEPOLIA_CHAIN_ID, vt as failureFingerprint, w as BYTES32_RE, wt as redactSecrets, x as ACCOUNT_ID_RE, xt as revertSummaryText, y as deriveCapxulSafeAddress, yt as isChainUpstream, z as toCountryCode } from "./OAuthBearerAuthClient-DDD0JlaI.mjs";
1
+ import { $ as toPartyId, A as SUPPORTED_CURRENCY_CODES, B as toAuthUserId, C as ASSET_ID_RE, Ct as isChainUpstream, D as COUNTRY_CODE_RE, Dt as isCredentialField, E as CLIENT_REQUEST_ID_RE, Et as containsSensitiveMaterial, F as toAccountId, G as toDurationMs, H as toChainId, I as toAddress, J as toEpochSeconds, K as toEmail, L as toAllowedOrigin, M as ZERO_BYTES32, O as EMAIL_RE$1, Ot as redactSecrets, Q as toOrgId, S as APP_ID_RE, St as failureFingerprint, T as CLIENT_GRANT_ID_RE, Tt as revertSummaryText, U as toCountryCode, V as toBudgetId, W as toCurrencyCode, X as toJwtToken, Y as toHandle, Z as toKycTier, _ as normalizeBindingEmail, _t as FAILURE_MODES$1, at as toTesterKind, b as configuredMoneyAssetById, bt as chainEvidenceLabel, c as AuthCachePortTag, ct as validateHandle, d as authClientPortFromPromiseAdapter, dt as CAPXUL_ERROR_CODES, et as toPayrollGroupId, f as AuthClientError, ft as CapxulError, gt as CHAIN_UPSTREAMS, h as orgRoleKeyForLabel, ht as isCapxulError, i as BrowserAuthCacheAdapter, it as toSessionToken, j as WEI_RE, k as EVM_ADDRESS_RE$1, kt as redactUrlSecrets, l as SystemClockLayer, lt as HANDLE_RE$1, m as ADMIN_ROLE_LABEL, mt as Errors, nt as toPublishableKey, ot as toTxHash, p as AuthClientPortTag, pt as EXPECTED_OPERATION_OUTCOMES, q as toEpochMs, r as InMemoryAuthCacheAdapter, rt as toRoleKey, st as toWeiAmount, tt as toPayrollRunId, u as ClockPortTag, ut as decodeConvexError, v as BASE_SEPOLIA_CHAIN_ID, vt as boundedResponseHeaders, w as BYTES32_RE, wt as isFailureMode, x as ACCOUNT_ID_RE, xt as decodeChainCause, y as deriveCapxulSafeAddress, yt as chainCauseProperties, z as toAssetId } from "./OAuthBearerAuthClient-DWkofxdZ.mjs";
2
2
  import { formatUnits, keccak256, parseUnits, recoverAddress, stringToHex, toBytes } from "viem";
3
- import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, FiberSet, Layer, Logger, Option, Queue, Ref, Result, Schedule, Schema, SchemaGetter, SchemaIssue, SchemaParser, Scope, Stream, Tracer } from "effect";
3
+ import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, FiberSet, Layer, Logger, Metric, Option, Queue, Ref, References, Result, Schedule, Schema, SchemaGetter, SchemaIssue, SchemaParser, Scope, Stream, Tracer } from "effect";
4
4
  import { getFunctionName, makeFunctionReference } from "convex/server";
5
5
  import { privateKeyToAccount } from "viem/accounts";
6
- import { FetchHttpClient, Headers, HttpBody, HttpClient, HttpClientResponse, HttpTraceContext } from "effect/unstable/http";
6
+ import { FetchHttpClient, Headers, HttpBody, HttpClient, HttpClientError, HttpClientResponse, HttpTraceContext } from "effect/unstable/http";
7
7
  import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
8
8
  import { ConvexClient } from "convex/browser";
9
9
  import { AccountTypeEnum, ChainTypeEnum, EmbeddedState, Openfort, RecoveryMethod, ThirdPartyOAuthProvider } from "@openfort/openfort-js";
@@ -1735,6 +1735,92 @@ const ContactActionProps = {
1735
1735
  party_id: OptionalString,
1736
1736
  reason_code: OptionalReasonCode
1737
1737
  };
1738
+ /** One completed online CLI diagnostic. No command input or provider text. */
1739
+ const CLI_COMMAND_NAMES = [
1740
+ "capxul",
1741
+ "doctor",
1742
+ "telemetry",
1743
+ "telemetry.status",
1744
+ "telemetry.enable",
1745
+ "telemetry.disable",
1746
+ "unknown"
1747
+ ];
1748
+ const CLI_CAPABILITIES = [
1749
+ "cli",
1750
+ "diagnostics",
1751
+ "collection"
1752
+ ];
1753
+ const CLI_INVOCATION_KINDS = [
1754
+ "command",
1755
+ "help",
1756
+ "version",
1757
+ "completion",
1758
+ "parse_refusal",
1759
+ "collection_control"
1760
+ ];
1761
+ const CliRelease = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u));
1762
+ const CliInvocationProps = {
1763
+ ...TelemetryEnvelopeProps,
1764
+ schema_version: Schema.Literal(1),
1765
+ command: Schema.Literals(CLI_COMMAND_NAMES),
1766
+ capability: Schema.Literals(CLI_CAPABILITIES),
1767
+ invocation_kind: Schema.Literals(CLI_INVOCATION_KINDS),
1768
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
1769
+ cli_identity_kind: Schema.optional(Schema.Literal("anonymous")),
1770
+ anonymous_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u))),
1771
+ occurred_at: Schema.Number,
1772
+ cli_version: CliRelease,
1773
+ sdk_version: CliRelease,
1774
+ release: CliRelease,
1775
+ platform: Schema.Literals([
1776
+ "darwin",
1777
+ "linux",
1778
+ "unknown"
1779
+ ]),
1780
+ architecture: Schema.Literals([
1781
+ "arm64",
1782
+ "x64",
1783
+ "unknown"
1784
+ ]),
1785
+ ci: Schema.Boolean,
1786
+ tty: Schema.Boolean,
1787
+ output_mode: Schema.Literals(["human", "json"])
1788
+ };
1789
+ Schema.Struct({
1790
+ name: Schema.Literal("cli_first_used"),
1791
+ props: Schema.Struct(CliInvocationProps)
1792
+ });
1793
+ Schema.Struct({
1794
+ name: Schema.Literal("cli_command_started"),
1795
+ props: Schema.Struct({
1796
+ ...CliInvocationProps,
1797
+ invocation_kind: Schema.Literals([
1798
+ "command",
1799
+ "help",
1800
+ "version"
1801
+ ])
1802
+ })
1803
+ });
1804
+ Schema.Struct({
1805
+ name: Schema.Literal("cli_command_completed"),
1806
+ props: Schema.Struct({
1807
+ ...CliInvocationProps,
1808
+ outcome: Schema.Literals([
1809
+ "succeeded",
1810
+ "refused",
1811
+ "failed",
1812
+ "cancelled"
1813
+ ]),
1814
+ duration_ms: Schema.Number,
1815
+ error_code: Schema.optional(Schema.Literals([
1816
+ ...CAPXUL_ERROR_CODES,
1817
+ "CLI_USAGE",
1818
+ "CLI_CONFIG",
1819
+ "CLI_STORAGE",
1820
+ "CLI_DEFECT"
1821
+ ]))
1822
+ })
1823
+ });
1738
1824
  Schema.Struct({
1739
1825
  name: Schema.Literal("cli_diagnostic_completed"),
1740
1826
  props: Schema.Struct({
@@ -2607,6 +2693,30 @@ const PAYMENT_DOCUMENT_KINDS = [
2607
2693
  "receipt",
2608
2694
  "withdrawal"
2609
2695
  ];
2696
+ /** Native browser projection, distinct from the issuer's persisted request state. */
2697
+ const CLIENT_AUTHORIZATION_PHASE = {
2698
+ OTP_REQUIRED: "otp_required",
2699
+ REVIEW: "review",
2700
+ PROCESSING: "processing",
2701
+ CONNECTED: "connected",
2702
+ REFUSED: "refused"
2703
+ };
2704
+ CLIENT_AUTHORIZATION_PHASE.OTP_REQUIRED, CLIENT_AUTHORIZATION_PHASE.REVIEW, CLIENT_AUTHORIZATION_PHASE.PROCESSING, CLIENT_AUTHORIZATION_PHASE.CONNECTED, CLIENT_AUTHORIZATION_PHASE.REFUSED;
2705
+ /** Closed native refusals; existing Capxul error codes retain their own meaning. */
2706
+ const CLIENT_AUTHORIZATION_REFUSALS = [
2707
+ "signup_required",
2708
+ "setup_required",
2709
+ "already_signed_up",
2710
+ "identity_mismatch",
2711
+ "invalid_request",
2712
+ "request_expired",
2713
+ "request_denied",
2714
+ "cancelled",
2715
+ "grant_revoked",
2716
+ "grant_expired",
2717
+ "refresh_reused",
2718
+ "revoke_unconfirmed"
2719
+ ];
2610
2720
  //#endregion
2611
2721
  //#region ../wire/src/financial-ops.ts
2612
2722
  const MINOR_UNIT_STRING_RE = /^[0-9]+$/;
@@ -4308,6 +4418,251 @@ function isSafeField(field, value) {
4308
4418
  return value.length > 0 && value.length <= rule.maxLength && value === value.trim() && !value.includes("://") && !containsSensitiveMaterial(value) && rule.pattern.test(value);
4309
4419
  }
4310
4420
  //#endregion
4421
+ //#region ../wire/src/client-authorization.ts
4422
+ const NATIVE_CLIENT_ID = "capxul-cli";
4423
+ const NATIVE_CLIENT_SCOPE = "account:read";
4424
+ const NATIVE_CLIENT_LIMITS = {
4425
+ accessMs: 36e5,
4426
+ renewalMs: 2592e6,
4427
+ absoluteMs: 7776e6,
4428
+ requestMs: 6e5,
4429
+ pollSeconds: 5,
4430
+ imageBytes: 5242880
4431
+ };
4432
+ const strict = { parseOptions: { onExcessProperty: "error" } };
4433
+ const text$2 = (max) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(max));
4434
+ const nonNegativeInt = Schema.Number.check(Schema.makeFilter((n) => Number.isSafeInteger(n) && n >= 0));
4435
+ const normalize = (f) => Schema.String.pipe(Schema.decodeTo(Schema.String, {
4436
+ decode: SchemaGetter.transform(f),
4437
+ encode: SchemaGetter.transform((s) => s)
4438
+ }));
4439
+ const ClientRequestIdSchema = Schema.String.pipe(Schema.refine((s) => CLIENT_REQUEST_ID_RE.test(s)));
4440
+ const ClientGrantIdSchema = Schema.String.pipe(Schema.refine((s) => CLIENT_GRANT_ID_RE.test(s)));
4441
+ const authUserId = Schema.String.pipe(Schema.refine((s) => s.length > 0));
4442
+ const keyId = Schema.String.pipe(Schema.refine((s) => s.length > 0));
4443
+ const email = normalize((s) => s.toLowerCase()).pipe(Schema.refine((s) => EMAIL_RE$1.test(s))).check(Schema.isMaxLength(254));
4444
+ const handle = Schema.String.pipe(Schema.refine((s) => HANDLE_RE$1.test(s)));
4445
+ const country = normalize((s) => s.toUpperCase()).pipe(Schema.refine((s) => COUNTRY_CODE_RE.test(s)));
4446
+ const credential = Schema.RedactedFromValue(Schema.String.check(Schema.isMinLength(32), Schema.isMaxLength(8192), Schema.isPattern(/^[A-Za-z0-9._~-]+$/u)), { label: "native authorization credential" });
4447
+ const otp = Schema.RedactedFromValue(Schema.String.check(Schema.isPattern(/^[0-9]{6}$/u)), { label: "OTP" });
4448
+ const scopes = Schema.Tuple([Schema.Literal(NATIVE_CLIENT_SCOPE)]);
4449
+ /** Exact HTTPS origin, no credentials/path/query and no retired cloud deployment. */
4450
+ const NativeHttpsOriginSchema = Schema.String.check(Schema.makeFilter((value) => {
4451
+ try {
4452
+ const url = new URL(value);
4453
+ const host = url.hostname.toLowerCase().replace(/\.$/u, "");
4454
+ return url.protocol === "https:" && value === url.origin && !url.username && !url.password && !url.search && !url.hash && host !== "convex.cloud" && !host.endsWith(".convex.cloud") && host !== "convex.site" && !host.endsWith(".convex.site");
4455
+ } catch {
4456
+ return false;
4457
+ }
4458
+ }, { message: "must be a canonical credential-free HTTPS origin outside retired Convex cloud hosts" }));
4459
+ const NativeClientConfigurationSchema = Schema.Struct({
4460
+ clientId: Schema.Literal(NATIVE_CLIENT_ID),
4461
+ applicationId: AppIdSchema,
4462
+ keyId,
4463
+ environment: Schema.Literals([
4464
+ "development",
4465
+ "staging",
4466
+ "production"
4467
+ ]),
4468
+ keyEnvironment: Schema.Literals(["test", "live"]),
4469
+ issuer: NativeHttpsOriginSchema,
4470
+ verificationOrigin: NativeHttpsOriginSchema
4471
+ }).annotate(strict).check(Schema.makeFilter((c) => c.keyEnvironment === (c.environment === "production" ? "live" : "test"), { message: "key environment must match the configured deployment" })).annotate(strict);
4472
+ const NativeSignupProfileSchema = Schema.Struct({
4473
+ displayName: normalize((s) => s.trim()).check(Schema.isMinLength(1), Schema.isMaxLength(200)),
4474
+ country,
4475
+ handle,
4476
+ payoutAddresses: Schema.optional(Schema.Array(Schema.Struct({
4477
+ chain: Schema.Literals([
4478
+ "evm",
4479
+ "solana",
4480
+ "starknet"
4481
+ ]),
4482
+ address: text$2(256)
4483
+ }).annotate(strict)).check(Schema.isMaxLength(10))),
4484
+ image: Schema.optional(Schema.Struct({
4485
+ mediaType: Schema.Literals([
4486
+ "image/jpeg",
4487
+ "image/png",
4488
+ "image/webp"
4489
+ ]),
4490
+ byteLength: Schema.Number.check(Schema.isInt(), Schema.isBetween({
4491
+ minimum: 1,
4492
+ maximum: NATIVE_CLIENT_LIMITS.imageBytes
4493
+ })),
4494
+ sha256: Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/u))
4495
+ }).annotate(strict))
4496
+ }).annotate(strict);
4497
+ const ClientAuthorizationIntentSchema = Schema.Union([Schema.Struct({ mode: Schema.Literal("login") }).annotate(strict), Schema.Struct({
4498
+ mode: Schema.Literal("signup"),
4499
+ profile: NativeSignupProfileSchema
4500
+ }).annotate(strict)]).annotate(strict);
4501
+ Schema.Struct({
4502
+ clientId: Schema.Literal(NATIVE_CLIENT_ID),
4503
+ email,
4504
+ intent: ClientAuthorizationIntentSchema,
4505
+ waitMs: Schema.Number.check(Schema.isInt(), Schema.isBetween({
4506
+ minimum: 1,
4507
+ maximum: NATIVE_CLIENT_LIMITS.requestMs
4508
+ })),
4509
+ continuityToken: Schema.optional(credential)
4510
+ }).annotate(strict);
4511
+ const request = {
4512
+ requestId: ClientRequestIdSchema,
4513
+ revision: nonNegativeInt,
4514
+ expiresAt: EpochMsSchema
4515
+ };
4516
+ const principal = {
4517
+ authUserId,
4518
+ email
4519
+ };
4520
+ const profileSummary = {
4521
+ displayName: text$2(200),
4522
+ handle,
4523
+ country
4524
+ };
4525
+ Schema.Union([
4526
+ Schema.Struct({
4527
+ ...request,
4528
+ phase: Schema.Literal(CLIENT_AUTHORIZATION_PHASE.OTP_REQUIRED),
4529
+ email,
4530
+ resendAt: EpochMsSchema
4531
+ }).annotate(strict),
4532
+ Schema.Struct({
4533
+ ...request,
4534
+ phase: Schema.Literal(CLIENT_AUTHORIZATION_PHASE.REVIEW),
4535
+ ...principal,
4536
+ clientLabel: Schema.Literal("Capxul CLI"),
4537
+ scopes,
4538
+ intent: ClientAuthorizationIntentSchema,
4539
+ setupState: Schema.Literals([
4540
+ "not_required",
4541
+ "new",
4542
+ "resumable"
4543
+ ])
4544
+ }).annotate(strict).check(Schema.makeFilter((v) => v.intent.mode === "login" === (v.setupState === "not_required"), { message: "login review cannot permit account setup" })),
4545
+ Schema.Struct({
4546
+ ...request,
4547
+ phase: Schema.Literal(CLIENT_AUTHORIZATION_PHASE.PROCESSING),
4548
+ ...principal,
4549
+ purpose: Schema.Literals(["login", "signup"]),
4550
+ step: Schema.Literals([
4551
+ "profile",
4552
+ "wallet",
4553
+ "account",
4554
+ "delivery"
4555
+ ])
4556
+ }).annotate(strict).check(Schema.makeFilter((v) => v.purpose === "signup" || v.step === "delivery", { message: "login may wait for delivery but cannot enter signup processing" })),
4557
+ Schema.Struct({
4558
+ ...request,
4559
+ phase: Schema.Literal(CLIENT_AUTHORIZATION_PHASE.CONNECTED),
4560
+ ...principal,
4561
+ ...profileSummary,
4562
+ accountId: AccountIdSchema,
4563
+ grantId: ClientGrantIdSchema
4564
+ }).annotate(strict),
4565
+ Schema.Struct({
4566
+ ...request,
4567
+ phase: Schema.Literal(CLIENT_AUTHORIZATION_PHASE.REFUSED),
4568
+ reason: Schema.Literals(CLIENT_AUTHORIZATION_REFUSALS),
4569
+ code: Schema.Literals(CAPXUL_ERROR_CODES),
4570
+ field: Schema.optional(Schema.Literals([
4571
+ "email",
4572
+ "displayName",
4573
+ "country",
4574
+ "handle",
4575
+ "image",
4576
+ "payoutAddresses"
4577
+ ])),
4578
+ retryable: Schema.Boolean
4579
+ }).annotate(strict)
4580
+ ]).annotate(strict);
4581
+ Schema.Struct({
4582
+ requestId: ClientRequestIdSchema,
4583
+ revision: nonNegativeInt
4584
+ }).annotate(strict);
4585
+ Schema.Struct({
4586
+ requestId: ClientRequestIdSchema,
4587
+ code: otp
4588
+ }).annotate(strict);
4589
+ Schema.Struct({
4590
+ client_id: Schema.Literal(NATIVE_CLIENT_ID),
4591
+ grant_type: Schema.Literal("refresh_token"),
4592
+ refresh_token: credential,
4593
+ refreshAttemptId: Schema.RedactedFromValue(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]{32,128}$/u)), { label: "refresh attempt" })
4594
+ }).annotate(strict);
4595
+ Schema.Struct({
4596
+ client_id: Schema.Literal(NATIVE_CLIENT_ID),
4597
+ applicationId: AppIdSchema,
4598
+ resource: text$2(2048),
4599
+ token_type: Schema.Literal("Bearer"),
4600
+ access_token: credential,
4601
+ refresh_token: credential,
4602
+ scope: Schema.Literal(NATIVE_CLIENT_SCOPE),
4603
+ expires_in: Schema.Number.check(Schema.isInt(), Schema.isBetween({
4604
+ minimum: 1,
4605
+ maximum: NATIVE_CLIENT_LIMITS.accessMs / 1e3
4606
+ })),
4607
+ grantId: ClientGrantIdSchema,
4608
+ ...principal,
4609
+ accountId: AccountIdSchema,
4610
+ issuedAt: EpochMsSchema,
4611
+ grantCreatedAt: EpochMsSchema,
4612
+ accessExpiresAt: EpochMsSchema,
4613
+ renewalExpiresAt: EpochMsSchema,
4614
+ absoluteExpiresAt: EpochMsSchema,
4615
+ revision: nonNegativeInt
4616
+ }).annotate(strict).check(Schema.makeFilter((t) => t.grantCreatedAt <= t.issuedAt && t.absoluteExpiresAt - t.grantCreatedAt === NATIVE_CLIENT_LIMITS.absoluteMs && t.renewalExpiresAt <= Math.min(t.issuedAt + NATIVE_CLIENT_LIMITS.renewalMs, t.absoluteExpiresAt) && t.accessExpiresAt <= Math.min(t.issuedAt + NATIVE_CLIENT_LIMITS.accessMs, t.renewalExpiresAt) && t.expires_in === Math.floor((t.accessExpiresAt - t.issuedAt) / 1e3), { message: "native credentials must obey the approved access, renewal and absolute deadlines" })).annotate(strict);
4617
+ /** One endpoint mapping; consumers cannot substitute callback or resource URLs. */
4618
+ function nativeClientEndpoints(config) {
4619
+ const resource = `${config.issuer}/api/auth/native`;
4620
+ return {
4621
+ resource,
4622
+ device_authorization_endpoint: `${resource}/device/code`,
4623
+ token_endpoint: `${resource}/token`,
4624
+ revocation_endpoint: `${resource}/revoke`,
4625
+ session_endpoint: `${resource}/session`,
4626
+ verification_uri: `${config.verificationOrigin}/connect`
4627
+ };
4628
+ }
4629
+ Schema.Struct({
4630
+ protocol: Schema.Literal("capxul.client-authorization"),
4631
+ version: Schema.Literal(1),
4632
+ configuration: NativeClientConfigurationSchema,
4633
+ scopes_supported: scopes,
4634
+ grant_types_supported: Schema.Tuple([Schema.Literal("urn:ietf:params:oauth:grant-type:device_code"), Schema.Literal("refresh_token")]),
4635
+ resource: text$2(2048),
4636
+ device_authorization_endpoint: text$2(2048),
4637
+ token_endpoint: text$2(2048),
4638
+ revocation_endpoint: text$2(2048),
4639
+ session_endpoint: text$2(2048),
4640
+ verification_uri: text$2(2048)
4641
+ }).annotate(strict).check(Schema.makeFilter((m) => {
4642
+ const expected = nativeClientEndpoints(m.configuration);
4643
+ return m.resource === expected.resource && m.device_authorization_endpoint === expected.device_authorization_endpoint && m.token_endpoint === expected.token_endpoint && m.revocation_endpoint === expected.revocation_endpoint && m.session_endpoint === expected.session_endpoint && m.verification_uri === expected.verification_uri;
4644
+ }, { message: "native endpoints must match their configured issuer and verification origin" })).annotate(strict);
4645
+ Schema.Struct({
4646
+ client_id: Schema.Literal(NATIVE_CLIENT_ID),
4647
+ grant_type: Schema.Literal("urn:ietf:params:oauth:grant-type:device_code"),
4648
+ device_code: credential
4649
+ }).annotate(strict);
4650
+ Schema.Struct({
4651
+ requestId: ClientRequestIdSchema,
4652
+ device_code: credential,
4653
+ user_code: Schema.RedactedFromValue(Schema.String.check(Schema.isPattern(/^[A-Z0-9]{4}-[A-Z0-9]{4}$/u)), { label: "device user code" }),
4654
+ continuityToken: credential,
4655
+ verification_uri: text$2(2048),
4656
+ expires_in: Schema.Number.check(Schema.isInt(), Schema.isBetween({
4657
+ minimum: 1,
4658
+ maximum: NATIVE_CLIENT_LIMITS.requestMs / 1e3
4659
+ })),
4660
+ interval: Schema.Number.check(Schema.isInt(), Schema.isBetween({
4661
+ minimum: NATIVE_CLIENT_LIMITS.pollSeconds,
4662
+ maximum: NATIVE_CLIENT_LIMITS.requestMs / 1e3
4663
+ }))
4664
+ }).annotate(strict);
4665
+ //#endregion
4311
4666
  //#region src/internal/invocation-observation.ts
4312
4667
  const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
4313
4668
  const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
@@ -6467,7 +6822,7 @@ function subscribeActivity(deps, actor, controls, onChange) {
6467
6822
  }
6468
6823
  //#endregion
6469
6824
  //#region package.json
6470
- var version = "4.20.0-beta.2";
6825
+ var version = "4.20.0-beta.3";
6471
6826
  //#endregion
6472
6827
  //#region src/telemetry/exception-projection.ts
6473
6828
  /** Fixed fallback for failures that have no safe message. */
@@ -8581,6 +8936,277 @@ async function recoverRawDigestSigner(input) {
8581
8936
  }
8582
8937
  }
8583
8938
  //#endregion
8939
+ //#region ../observability/src/engineering-delivery.ts
8940
+ /** Fixed admission limits for one CLI invocation and its SDK client. */
8941
+ const CLI_ENGINEERING_LIMITS = Object.freeze({
8942
+ records: 80,
8943
+ ordinaryRecords: 64,
8944
+ recordBytes: 16384,
8945
+ requests: 5,
8946
+ ordinaryRequests: 2,
8947
+ requestBytes: 1572864,
8948
+ metricSeries: 16,
8949
+ requestTimeoutMs: 1e3
8950
+ });
8951
+ const text$1 = (value) => typeof value === "string" ? value.slice(0, 128) : "capxul.engineering";
8952
+ const attributes = (input, limit = 32) => {
8953
+ const out = {};
8954
+ let count = 0;
8955
+ let bytes = 0;
8956
+ try {
8957
+ for (const key in input) {
8958
+ if (count++ >= limit) break;
8959
+ if (key.length > 64) continue;
8960
+ const value = Object.getOwnPropertyDescriptor(input, key)?.value;
8961
+ const scalar = typeof value === "string" ? value.slice(0, 128) : typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : void 0;
8962
+ if (scalar === void 0) continue;
8963
+ bytes += new TextEncoder().encode(JSON.stringify([key, scalar])).length;
8964
+ if (bytes > (limit >= 24 ? 2e3 : 300)) break;
8965
+ out[key] = scalar;
8966
+ }
8967
+ } catch {}
8968
+ return out;
8969
+ };
8970
+ const terminalName = (name) => name === "cli.command.completed" || CLI_COMMAND_NAMES.some((command) => name === `cli.command.${command}`);
8971
+ /** Native exporters retain their serialization and scheduling; this owns admission only. */
8972
+ function cliEngineeringDelivery(budget, ownsMetrics) {
8973
+ const closed = Deferred.makeUnsafe();
8974
+ let isClosed = false;
8975
+ let metricsRunning = false;
8976
+ const logs = [];
8977
+ const spans = /* @__PURE__ */ new Map();
8978
+ const terminalBodies = /* @__PURE__ */ new WeakSet();
8979
+ const bodyLeases = /* @__PURE__ */ new WeakMap();
8980
+ const pendingBodies = /* @__PURE__ */ new Set();
8981
+ const holdBody = (body, releases) => {
8982
+ if (releases.length === 0) return;
8983
+ const lease = {
8984
+ started: false,
8985
+ release: () => {
8986
+ if (!pendingBodies.delete(lease)) return;
8987
+ bodyLeases.delete(body);
8988
+ for (const release of releases) release();
8989
+ }
8990
+ };
8991
+ bodyLeases.set(body, lease);
8992
+ pendingBodies.add(lease);
8993
+ };
8994
+ const discardBody = (body) => bodyLeases.get(body)?.release();
8995
+ const drainLogs = () => {
8996
+ for (const release of logs.splice(0)) release();
8997
+ };
8998
+ const close = () => {
8999
+ isClosed = true;
9000
+ Deferred.doneUnsafe(closed, Effect.void);
9001
+ for (const lease of pendingBodies) if (!lease.started) lease.release();
9002
+ drainLogs();
9003
+ for (const release of spans.values()) release();
9004
+ spans.clear();
9005
+ if (ownsMetrics) budget.metricRegistry.clear();
9006
+ };
9007
+ return {
9008
+ close,
9009
+ discardBody,
9010
+ metrics(run) {
9011
+ return Effect.suspend(() => {
9012
+ if (isClosed || metricsRunning) return Effect.void;
9013
+ metricsRunning = true;
9014
+ return run.pipe(Effect.ensuring(Effect.sync(() => {
9015
+ metricsRunning = false;
9016
+ })));
9017
+ });
9018
+ },
9019
+ logger(delegate) {
9020
+ return Logger.make((options) => {
9021
+ if (isClosed) return;
9022
+ let release;
9023
+ try {
9024
+ const message = text$1(Array.isArray(options.message) ? Object.getOwnPropertyDescriptor(options.message, "0")?.value : options.message);
9025
+ release = budget.admitRecord(terminalName(message));
9026
+ if (release === void 0) return;
9027
+ const context = Context.add(options.fiber.context, References.CurrentLogAnnotations, attributes(options.fiber.getRef(References.CurrentLogAnnotations)));
9028
+ const fiber = Object.create(options.fiber);
9029
+ Object.defineProperty(fiber, "getRef", { value: (ref) => Context.get(context, ref) });
9030
+ logs.push(release);
9031
+ delegate.log({
9032
+ ...options,
9033
+ message,
9034
+ cause: Cause.empty,
9035
+ fiber
9036
+ });
9037
+ } catch {
9038
+ if (release !== void 0) {
9039
+ const index = logs.indexOf(release);
9040
+ if (index !== -1) logs.splice(index, 1);
9041
+ release();
9042
+ }
9043
+ budget.drop();
9044
+ }
9045
+ });
9046
+ },
9047
+ tracer(delegate) {
9048
+ return Tracer.make({
9049
+ span(options) {
9050
+ const name = text$1(options.name);
9051
+ const release = isClosed ? void 0 : budget.admitRecord(terminalName(name));
9052
+ const spanOptions = {
9053
+ ...options,
9054
+ name,
9055
+ annotations: Context.empty(),
9056
+ links: []
9057
+ };
9058
+ const span = release === void 0 ? new Tracer.NativeSpan({
9059
+ ...spanOptions,
9060
+ sampled: false
9061
+ }) : delegate.span(spanOptions);
9062
+ if (release !== void 0) spans.set(span.spanId, release);
9063
+ const wrapped = Object.create(span);
9064
+ let fields = 0, events = 0, links = 0, attributeBytes = 0;
9065
+ let ended = false;
9066
+ Object.defineProperties(wrapped, {
9067
+ attribute: { value: (key, value) => {
9068
+ if (fields >= 32 && !span.attributes.has(key)) {
9069
+ budget.drop();
9070
+ return;
9071
+ }
9072
+ const safe = attributes({ [key]: value }, 1);
9073
+ if (!Object.hasOwn(safe, key)) return;
9074
+ const previous = span.attributes.has(key) ? new TextEncoder().encode(JSON.stringify([key, span.attributes.get(key)])).length : 0;
9075
+ const next = new TextEncoder().encode(JSON.stringify([key, safe[key]])).length;
9076
+ if (attributeBytes - previous + next > 2e3) {
9077
+ budget.drop();
9078
+ return;
9079
+ }
9080
+ attributeBytes += next - previous;
9081
+ if (!span.attributes.has(key)) fields += 1;
9082
+ span.attribute(key, safe[key]);
9083
+ } },
9084
+ event: { value: (eventName, time, attrs) => {
9085
+ if (events++ >= 2) {
9086
+ budget.drop();
9087
+ return;
9088
+ }
9089
+ span.event(text$1(eventName), time, attributes(attrs ?? {}, 4));
9090
+ } },
9091
+ addLinks: { value: (items) => {
9092
+ for (const item of items.slice(0, Math.max(0, 2 - links))) {
9093
+ if (!/^[a-f0-9]{32}$/u.test(item.span.traceId) || !/^[a-f0-9]{16}$/u.test(item.span.spanId)) {
9094
+ budget.drop();
9095
+ continue;
9096
+ }
9097
+ span.addLinks([{
9098
+ span: Tracer.externalSpan({
9099
+ traceId: item.span.traceId,
9100
+ spanId: item.span.spanId,
9101
+ sampled: item.span.sampled
9102
+ }),
9103
+ attributes: attributes(item.attributes, 4)
9104
+ }]);
9105
+ links += 1;
9106
+ }
9107
+ } },
9108
+ end: { value: (time, exit) => {
9109
+ if (ended) return;
9110
+ ended = true;
9111
+ span.end(time, Exit.isFailure(exit) ? Exit.fail("CLI operation failed") : Exit.void);
9112
+ } }
9113
+ });
9114
+ wrapped.addLinks(options.links ?? []);
9115
+ return wrapped;
9116
+ },
9117
+ ...delegate.context === void 0 ? {} : { context: delegate.context.bind(delegate) }
9118
+ });
9119
+ },
9120
+ serialization(delegate) {
9121
+ return {
9122
+ logs(data) {
9123
+ const releases = logs.splice(0);
9124
+ try {
9125
+ const body = delegate.logs(data);
9126
+ if (data.resourceLogs.some((r) => r.scopeLogs.some((s) => s.logRecords?.some((l) => l.body?.stringValue === "cli.command.completed")))) terminalBodies.add(body);
9127
+ holdBody(body, releases);
9128
+ return body;
9129
+ } catch (error) {
9130
+ for (const release of releases) release();
9131
+ throw error;
9132
+ }
9133
+ },
9134
+ traces(data) {
9135
+ const releases = [];
9136
+ for (const resource of data.resourceSpans) for (const scope of resource.scopeSpans) for (const span of scope.spans) {
9137
+ const release = spans.get(span.spanId);
9138
+ if (release !== void 0) releases.push(release);
9139
+ spans.delete(span.spanId);
9140
+ }
9141
+ try {
9142
+ const body = delegate.traces(data);
9143
+ if (data.resourceSpans.some((r) => r.scopeSpans.some((s) => s.spans.some((span) => terminalName(span.name))))) terminalBodies.add(body);
9144
+ holdBody(body, releases);
9145
+ return body;
9146
+ } catch (error) {
9147
+ for (const release of releases) release();
9148
+ throw error;
9149
+ }
9150
+ },
9151
+ metrics(data) {
9152
+ const body = delegate.metrics(data);
9153
+ terminalBodies.add(body);
9154
+ return body;
9155
+ }
9156
+ };
9157
+ },
9158
+ transport(client, enabled = () => true) {
9159
+ const retrying = HttpClient.transform(client, (response, request) => Effect.suspend(() => {
9160
+ if (enabled()) return response;
9161
+ budget.drop();
9162
+ return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null)));
9163
+ })).pipe(HttpClient.transformResponse((response) => Effect.tap(response, (result) => {
9164
+ let received = 0;
9165
+ return Stream.runForEach(result.stream, (chunk) => Effect.sync(() => {
9166
+ received += chunk.byteLength;
9167
+ if (received > 65536) throw new Error("Engineering response limit exceeded");
9168
+ })).pipe(Effect.catchTag("HttpClientError", (error) => error.reason._tag === "EmptyBodyError" ? Effect.void : Effect.fail(error)));
9169
+ }))).pipe(HttpClient.filterStatusOk, HttpClient.retryTransient({
9170
+ times: 1,
9171
+ schedule: Schedule.spaced("100 millis").pipe(Schedule.addDelay(({ input }) => Effect.map(Clock.currentTimeMillis, (now) => {
9172
+ if (!HttpClientError.isHttpClientError(input) || input.reason._tag !== "StatusCodeError" || input.reason.response.status !== 429) return Duration.zero;
9173
+ const header = input.reason.response.headers["retry-after"];
9174
+ const numeric = Number(header);
9175
+ const delay = header === void 0 ? 2e3 : Number.isFinite(numeric) ? numeric * 1e3 : Date.parse(header) - now;
9176
+ return Duration.millis(Number.isFinite(delay) ? Math.min(2e3, Math.max(0, delay)) : 2e3);
9177
+ })))
9178
+ }));
9179
+ return HttpClient.transform(retrying, (response, request) => Effect.suspend(() => {
9180
+ if (isClosed) {
9181
+ discardBody(request.body);
9182
+ return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null)));
9183
+ }
9184
+ const droppedResponse = () => HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }));
9185
+ if (request.body._tag === "Empty") {
9186
+ discardBody(request.body);
9187
+ return Effect.succeed(droppedResponse());
9188
+ }
9189
+ const bytes = request.body.contentLength;
9190
+ const release = budget.admitRequest(bytes ?? Number.POSITIVE_INFINITY, terminalBodies.has(request.body));
9191
+ if (release === void 0) {
9192
+ discardBody(request.body);
9193
+ return Effect.succeed(droppedResponse());
9194
+ }
9195
+ const lease = bodyLeases.get(request.body);
9196
+ if (lease !== void 0) lease.started = true;
9197
+ return response.pipe(Effect.asVoid, Effect.timeoutOption(CLI_ENGINEERING_LIMITS.requestTimeoutMs), Effect.raceFirst(Deferred.await(closed).pipe(Effect.andThen(Effect.interrupt))), Effect.tap((result) => Effect.sync(() => {
9198
+ if (Option.isNone(result)) budget.drop();
9199
+ })), Effect.catchCause(() => Effect.sync(() => {
9200
+ budget.drop();
9201
+ })), Effect.as(droppedResponse()), Effect.ensuring(Effect.sync(() => {
9202
+ release();
9203
+ discardBody(request.body);
9204
+ })));
9205
+ }));
9206
+ }
9207
+ };
9208
+ }
9209
+ //#endregion
8584
9210
  //#region ../observability/src/engineering.ts
8585
9211
  const ENGINEERING_CAPXUL_ENVS = [
8586
9212
  "development",
@@ -8755,10 +9381,13 @@ const MINIMAL_NUMBERS = /* @__PURE__ */ new Set([
8755
9381
  const MINIMAL_CORRELATIONS = /* @__PURE__ */ new Set([
8756
9382
  "correlation_id",
8757
9383
  "journey_id",
8758
- "invocation_id"
9384
+ "invocation_id",
9385
+ "posthogDistinctId"
8759
9386
  ]);
8760
9387
  const MINIMAL_METRIC_LABELS = /* @__PURE__ */ new Set([
8761
9388
  "command",
9389
+ "capability",
9390
+ "invocation_kind",
8762
9391
  "outcome",
8763
9392
  "capxul_env",
8764
9393
  "unit"
@@ -8766,7 +9395,7 @@ const MINIMAL_METRIC_LABELS = /* @__PURE__ */ new Set([
8766
9395
  const MINIMAL_METRIC_NAMES = /* @__PURE__ */ new Set(["capxul.cli.command.count", "capxul.cli.command.duration"]);
8767
9396
  const traceId = (value) => typeof value === "string" && /^(?!0+$)[0-9a-f]{32}$/u.test(value);
8768
9397
  const spanId = (value) => typeof value === "string" && /^(?!0+$)[0-9a-f]{16}$/u.test(value);
8769
- const minimalName = (value) => typeof value === "string" && (MINIMAL_LOG_NAMES.has(value) || isCapxulOperation(value)) ? value : "capxul.engineering";
9398
+ const minimalName = (value) => typeof value === "string" && (MINIMAL_LOG_NAMES.has(value) || isCapxulOperation(value) || CLI_COMMAND_NAMES.some((command) => value === `cli.command.${command}`)) ? value : "capxul.engineering";
8770
9399
  const MINIMAL_ENUM_VALUES = /* @__PURE__ */ new Map([
8771
9400
  ["outcome", [
8772
9401
  "succeeded",
@@ -8779,7 +9408,10 @@ const MINIMAL_ENUM_VALUES = /* @__PURE__ */ new Map([
8779
9408
  ["failure_mode", FAILURE_MODES$1],
8780
9409
  ["capxul_env", ENGINEERING_CAPXUL_ENVS],
8781
9410
  ["producer", ["browser", "server"]],
8782
- ["command", ["doctor"]],
9411
+ ["command", CLI_COMMAND_NAMES],
9412
+ ["capability", CLI_CAPABILITIES],
9413
+ ["invocation_kind", CLI_INVOCATION_KINDS],
9414
+ ["cli_identity_kind", ["anonymous"]],
8783
9415
  ["output_mode", ["human", "json"]],
8784
9416
  ["unit", [
8785
9417
  "1",
@@ -8996,10 +9628,12 @@ function minimalSerialization(config) {
8996
9628
  };
8997
9629
  }
8998
9630
  Effect.flatMap(OtlpExporter.Flusher, (flusher) => flusher.flush);
9631
+ var EngineeringLog = class extends Context.Service()("capxul/EngineeringLog") {};
8999
9632
  /** Shared browser/server OTLP layer. OtlpLogger merges with incumbent loggers once. */
9000
9633
  const makeEngineeringTelemetryLayer = (config) => {
9001
9634
  const validated = validateEngineeringTelemetryConfig(config);
9002
9635
  return Layer.suspend(() => {
9636
+ const bounded = validated.deliveryBudget === void 0 ? void 0 : cliEngineeringDelivery(validated.deliveryBudget, validated.serviceName === "capxul-cli");
9003
9637
  const endpoints = postHogOtlpEndpoints(validated.host);
9004
9638
  let disabled = false;
9005
9639
  const enabled = () => {
@@ -9013,7 +9647,12 @@ const makeEngineeringTelemetryLayer = (config) => {
9013
9647
  };
9014
9648
  const delivery = {
9015
9649
  ...validated.shutdownTimeout === void 0 ? {} : { shutdownTimeout: validated.shutdownTimeout },
9016
- ...validated.exportInterval === void 0 ? {} : { exportInterval: validated.exportInterval }
9650
+ ...validated.exportInterval === void 0 ? {} : { exportInterval: validated.exportInterval },
9651
+ ...bounded === void 0 ? {} : {
9652
+ maxBatchSize: Number.MAX_SAFE_INTEGER,
9653
+ exportInterval: 1e3,
9654
+ shutdownTimeout: validated.serviceName === "capxul-cli" ? 0 : 500
9655
+ }
9017
9656
  };
9018
9657
  const resource = {
9019
9658
  serviceName: validated.serviceName ?? "capxul-sdk",
@@ -9029,22 +9668,38 @@ const makeEngineeringTelemetryLayer = (config) => {
9029
9668
  headers: validated.headers,
9030
9669
  resource,
9031
9670
  ...delivery
9032
- }).pipe(Effect.map((tracer) => makeLeakSafeEngineeringTracer(tracer, enabled)))).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
9033
- const logging = Logger.layer([OtlpLogger.make({
9671
+ }).pipe(Effect.map((tracer) => makeLeakSafeEngineeringTracer(bounded?.tracer(tracer) ?? tracer, enabled)))).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
9672
+ const ownedLogging = Layer.effect(EngineeringLog, OtlpLogger.make({
9034
9673
  url: endpoints.logs,
9035
9674
  headers: validated.headers,
9036
9675
  resource,
9037
- ...delivery
9038
- }).pipe(Effect.map((logger) => Logger.make((options) => {
9039
- if (enabled()) logger.log(options);
9040
- })))], { mergeWithExisting: true }).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
9041
- const metrics = OtlpMetrics.layer({
9676
+ ...delivery,
9677
+ ...bounded === void 0 ? {} : { excludeLogSpans: true }
9678
+ }).pipe(Effect.map((nativeLogger) => {
9679
+ const logger = bounded?.logger(nativeLogger) ?? nativeLogger;
9680
+ return Logger.make((options) => {
9681
+ if (enabled()) logger.log(options);
9682
+ });
9683
+ }))).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
9684
+ const logging = Logger.layer([EngineeringLog], { mergeWithExisting: true }).pipe(Layer.provideMerge(ownedLogging));
9685
+ const metricConfig = {
9042
9686
  url: endpoints.metrics,
9043
9687
  headers: validated.headers,
9044
9688
  resource,
9045
9689
  temporality: "delta",
9046
9690
  ...delivery
9047
- });
9691
+ };
9692
+ const metrics = bounded === void 0 ? OtlpMetrics.layer(metricConfig) : validated.serviceName !== "capxul-cli" ? Layer.empty : Layer.effectDiscard(Effect.gen(function* () {
9693
+ const flusher = yield* OtlpExporter.Flusher;
9694
+ yield* OtlpMetrics.make({
9695
+ ...metricConfig,
9696
+ exportInterval: Number.POSITIVE_INFINITY,
9697
+ shutdownTimeout: 0
9698
+ }).pipe(Effect.provideService(OtlpExporter.Flusher, {
9699
+ ...flusher,
9700
+ register: (run) => flusher.register(bounded.metrics(run))
9701
+ }));
9702
+ })).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
9048
9703
  const headerPolicy = Layer.merge(Layer.succeed(HttpClient.TracerHeaderFilter, traceHeaderFilter), Layer.succeed(Headers.CurrentRedactedNames, [credentialHeaderPattern]));
9049
9704
  const browserLifecycle = Layer.effectDiscard(Effect.gen(function* () {
9050
9705
  if (validated.producer !== "browser" || !hasBrowserDocument()) return;
@@ -9067,17 +9722,25 @@ const makeEngineeringTelemetryLayer = (config) => {
9067
9722
  }));
9068
9723
  }));
9069
9724
  const transport = Layer.effect(HttpClient.HttpClient, Effect.map(HttpClient.HttpClient, (client) => {
9070
- const selectedTransport = validated.producer === "browser" && hasBrowserDocument() ? browserExportClient(client) : client;
9071
- return HttpClient.transform(selectedTransport, (response, request) => Effect.suspend(() => enabled() && request.body._tag !== "Empty" ? response : Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })))));
9725
+ const originalTransport = validated.producer === "browser" && hasBrowserDocument() ? browserExportClient(client) : client;
9726
+ const selectedTransport = bounded?.transport(originalTransport, enabled) ?? originalTransport;
9727
+ return HttpClient.transform(selectedTransport, (response, request) => Effect.suspend(() => {
9728
+ if (enabled() && request.body._tag !== "Empty") return response;
9729
+ bounded?.discardBody(request.body);
9730
+ return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })));
9731
+ }));
9072
9732
  })).pipe(Layer.provide(FetchHttpClient.layer));
9073
9733
  const serialization = Layer.effect(OtlpSerialization.OtlpSerialization, Effect.map(OtlpSerialization.OtlpSerialization, (json) => {
9074
9734
  const projected = minimalSerialization(validated);
9075
- return validated.privacy === "minimal" ? projected : {
9735
+ const selected = validated.privacy === "minimal" ? projected : {
9076
9736
  ...json,
9077
9737
  metrics: projected.metrics
9078
9738
  };
9739
+ return bounded?.serialization(selected) ?? selected;
9079
9740
  })).pipe(Layer.provide(OtlpSerialization.layerJson));
9080
- return browserLifecycle.pipe(Layer.provideMerge(Layer.mergeAll(tracing, logging, metrics, headerPolicy)), Layer.provide(serialization), Layer.provide(transport));
9741
+ const combined = browserLifecycle.pipe(Layer.provideMerge(Layer.mergeAll(tracing, logging, metrics, headerPolicy)), Layer.provide(serialization), Layer.provide(transport));
9742
+ const scoped = bounded === void 0 ? combined : combined.pipe(Layer.provideMerge(Layer.effectDiscard(Effect.addFinalizer(() => Effect.sync(bounded.close)))));
9743
+ return validated.deliveryBudget === void 0 ? scoped : scoped.pipe(Layer.provideMerge(Layer.succeed(Metric.MetricRegistry, validated.serviceName === "capxul-cli" ? validated.deliveryBudget.metricRegistry : validated.deliveryBudget.emptyMetricRegistry())));
9081
9744
  });
9082
9745
  };
9083
9746
  //#endregion
@@ -15361,6 +16024,7 @@ function postHogObservability(client, options = {}) {
15361
16024
  product: postHogProductTelemetry(policy)
15362
16025
  };
15363
16026
  Object.defineProperty(module, HOST_ENGINEERING_POLICY, { value: Object.freeze({
16027
+ ...options.engineeringDeliveryBudget === void 0 ? {} : { engineeringDeliveryBudget: options.engineeringDeliveryBudget },
15364
16028
  ...options.engineeringEnabled === void 0 ? {} : { engineeringEnabled: options.engineeringEnabled },
15365
16029
  ...options.engineeringPrivacy === void 0 ? {} : { engineeringPrivacy: options.engineeringPrivacy }
15366
16030
  }) });
@@ -15398,6 +16062,7 @@ function isPromiseLike(value) {
15398
16062
  function hostEngineeringPolicy(observability) {
15399
16063
  const policy = observability?.[HOST_ENGINEERING_POLICY];
15400
16064
  return {
16065
+ ...policy?.engineeringDeliveryBudget === void 0 ? {} : { deliveryBudget: policy.engineeringDeliveryBudget },
15401
16066
  ...policy?.engineeringEnabled === void 0 ? {} : { enabled: policy.engineeringEnabled },
15402
16067
  ...policy?.engineeringPrivacy === void 0 ? {} : { privacy: policy.engineeringPrivacy }
15403
16068
  };
@@ -1,5 +1,5 @@
1
1
  import { h as CapxulResult } from "../OAuthBearerAuthClient-C-ip-z8M.mjs";
2
- import { er as TelemetryEvent, f as CapxulClient, i as ObservationAdapter, n as ProductionSignerControls, nr as TelemetryIdentifyInput, pr as IdentityTransition, t as CapxulClientInput, tr as TelemetryGroupInput } from "../production-Cn5awmW8.mjs";
2
+ import { er as TelemetryEvent, f as CapxulClient, i as ObservationAdapter, n as ProductionSignerControls, nr as TelemetryIdentifyInput, pr as IdentityTransition, t as CapxulClientInput, tr as TelemetryGroupInput } from "../production-CJwxgI8u.mjs";
3
3
  import { Effect, Layer } from "effect";
4
4
  //#region src/testing/production-client.d.ts
5
5
  /** Create the one production client with per-client controls at its signing boundaries. */
@@ -1,5 +1,5 @@
1
- import { D as fromWei, P as redactTelemetryEvent, a as smartAccountErrorFromCapxul, c as identityErrorFromCapxul, i as assembleCapxulClient, l as convexCallErrorFromCapxul, n as createCapxulClientWithSignerControls, o as accountReadErrorFromCapxul, s as wireChainId, u as bootstrapErrorFromCapxul, v as toWei } from "../production-BQVXgcbY.mjs";
2
- import { G as toHandle, H as toEmail, I as toAuthUserId, K as toJwtToken, M as toAddress, N as toAllowedOrigin, P as toAppId, Q as toPublishableKey, R as toChainId, U as toEpochMs, V as toDurationMs, W as toEpochSeconds, ct as CapxulError, d as authClientPortFromPromiseAdapter, et as toSessionToken, it as validateHandle, j as toAccountId, n as readClockNow, q as toKycTier, r as InMemoryAuthCacheAdapter, ut as Errors, y as deriveCapxulSafeAddress, z as toCountryCode } from "../OAuthBearerAuthClient-DDD0JlaI.mjs";
1
+ import { D as fromWei, P as redactTelemetryEvent, a as smartAccountErrorFromCapxul, c as identityErrorFromCapxul, i as assembleCapxulClient, l as convexCallErrorFromCapxul, n as createCapxulClientWithSignerControls, o as accountReadErrorFromCapxul, s as wireChainId, u as bootstrapErrorFromCapxul, v as toWei } from "../production-M4dWz5g4.mjs";
2
+ import { B as toAuthUserId, F as toAccountId, G as toDurationMs, H as toChainId, I as toAddress, J as toEpochSeconds, K as toEmail, L as toAllowedOrigin, R as toAppId, U as toCountryCode, X as toJwtToken, Y as toHandle, Z as toKycTier, ct as validateHandle, d as authClientPortFromPromiseAdapter, ft as CapxulError, it as toSessionToken, mt as Errors, n as readClockNow, nt as toPublishableKey, q as toEpochMs, r as InMemoryAuthCacheAdapter, y as deriveCapxulSafeAddress } from "../OAuthBearerAuthClient-DWkofxdZ.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": "4.20.0-beta.2",
3
+ "version": "4.20.0-beta.3",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Xelmar-tech/infrastructure.git",
@@ -50,9 +50,9 @@
50
50
  "@capxul/config": "0.3.0",
51
51
  "@capxul/errors": "0.3.0",
52
52
  "@capxul/types": "0.3.0",
53
+ "@capxul/observability": "4.20.0-beta.3",
53
54
  "@capxul/typescript-config": "0.0.0",
54
- "@capxul/wire": "0.8.0-beta.0",
55
- "@capxul/observability": "4.20.0-beta.2"
55
+ "@capxul/wire": "0.8.0-beta.0"
56
56
  },
57
57
  "_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.",
58
58
  "scripts": {