@capxul/sdk 3.2.0 → 4.0.1

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.
@@ -1,5 +1,5 @@
1
- import { $ as CHAIN_UPSTREAMS, A as toBudgetId, B as toOrgId, C as ZERO_BYTES32, E as toAddress, F as toEmail, G as toRoleKey, H as toPayrollGroupId, J as CAPXUL_ERROR_CODES, M as toCountryCode, N as toCurrencyCode, Q as isCapxulError, S as WEI_RE, T as toAccountId, U as toPayrollRunId, V as toPartyId, X as EXPECTED_OPERATION_OUTCOMES, Y as CapxulError, Z as Errors, _ as deriveCapxulSafeAddress, at as failureFingerprint, b as EVM_ADDRESS_RE$1, ct as revertSummaryText, et as FAILURE_MODES$1, it as decodeChainCause, j as toChainId, k as toAuthUserId, lt as containsSensitiveMaterial, n as InMemoryAuthCacheAdapter, nt as chainCauseProperties, ot as isChainUpstream, p as orgRoleKeyForLabel, r as BrowserAuthCacheAdapter, rt as chainEvidenceLabel, st as isFailureMode, tt as boundedResponseHeaders, ut as redactSecrets, v as APP_ID_RE, x as SUPPORTED_CURRENCY_CODES, y as BYTES32_RE } from "./clock-CWpcQlLy.mjs";
2
- import { Context, Data, Deferred, Duration, Effect, Exit, Fiber, Layer, Queue, Ref, Result, Schema, SchemaGetter, Scope } from "effect";
1
+ import { $ as CapxulError, A as toAuthUserId, C as WEI_RE, D as toAddress, E as toAccountId, G as toPayrollRunId, H as toOrgId, I as toEmail, M as toChainId, N as toCountryCode, P as toCurrencyCode, Q as CAPXUL_ERROR_CODES, S as SUPPORTED_CURRENCY_CODES, U as toPartyId, W as toPayrollGroupId, _ as deriveCapxulSafeAddress, at as boundedResponseHeaders, b as BYTES32_RE, ct as decodeChainCause, dt as isFailureMode, et as EXPECTED_OPERATION_OUTCOMES, ft as revertSummaryText, it as FAILURE_MODES$1, j as toBudgetId, lt as failureFingerprint, mt as redactSecrets, n as InMemoryAuthCacheAdapter, nt as isCapxulError, ot as chainCauseProperties, p as orgRoleKeyForLabel, pt as containsSensitiveMaterial, q as toRoleKey, r as BrowserAuthCacheAdapter, rt as CHAIN_UPSTREAMS, st as chainEvidenceLabel, tt as Errors, ut as isChainUpstream, v as validateHandle, w as ZERO_BYTES32, x as EVM_ADDRESS_RE$1, y as APP_ID_RE } from "./clock-C2AUlq1V.mjs";
2
+ import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, Layer, Queue, Ref, Result, Schema, SchemaGetter, SchemaParser, Scope } from "effect";
3
3
  import { formatUnits, keccak256, parseUnits, recoverAddress, toBytes } from "viem";
4
4
  import { makeFunctionReference } from "convex/server";
5
5
  //#region src/domain/identity/model.ts
@@ -494,7 +494,6 @@ const CAPXUL_OPERATIONS = {
494
494
  current: "holdings.current",
495
495
  primary: "holdings.primary"
496
496
  },
497
- handles: { resolve: "handles.resolve" },
498
497
  identity: {
499
498
  accountAt: "identity.AccountAt",
500
499
  accountClaimed: "identity.AccountClaimed",
@@ -509,6 +508,7 @@ const CAPXUL_OPERATIONS = {
509
508
  createOrganization: "identity.CreateOrganization",
510
509
  ensureAccount: "identity.EnsureAccount",
511
510
  leaveOrganization: "identity.LeaveOrganization",
511
+ loadByAuthUserId: "identity.loadByAuthUserId",
512
512
  loadCurrent: "identity.loadCurrent",
513
513
  orgAt: "identity.OrgAt",
514
514
  orgFailed: "identity.OrgFailed",
@@ -530,7 +530,7 @@ const CAPXUL_OPERATIONS = {
530
530
  signOut: "identity.SignOut",
531
531
  signOutFailed: "identity.SignOutFailed",
532
532
  update: "identity.update",
533
- usernameAvailable: "identity.usernameAvailable",
533
+ handleAvailable: "identity.handleAvailable",
534
534
  verified: "identity.Verified",
535
535
  verifyFailed: "identity.VerifyFailed",
536
536
  verifyOtp: "identity.VerifyOtp"
@@ -546,10 +546,12 @@ const CAPXUL_OPERATIONS = {
546
546
  get: "me.get"
547
547
  },
548
548
  moneyExecution: {
549
+ abandonPaymentExecution: "moneyExecution.abandonPaymentExecution",
549
550
  prepareOrganizationPaymentExecution: "moneyExecution.prepareOrganizationPaymentExecution",
550
551
  preparePaymentExecution: "moneyExecution.preparePaymentExecution",
551
552
  preparePaymentLifecycleExecution: "moneyExecution.preparePaymentLifecycleExecution",
552
553
  preparePermissionExecution: "moneyExecution.preparePermissionExecution",
554
+ recoverSubmissionClaims: "moneyExecution.recoverSubmissionClaims",
553
555
  submit: "moneyExecution.submit",
554
556
  submitPaymentCommandExecution: "moneyExecution.submitPaymentCommandExecution",
555
557
  submitPaymentExecution: "moneyExecution.submitPaymentExecution",
@@ -568,9 +570,14 @@ const CAPXUL_OPERATIONS = {
568
570
  quote: "offramp.quote",
569
571
  status: "offramp.status"
570
572
  },
571
- onboarding: { completePerson: "onboarding.completePerson" },
573
+ onboarding: {
574
+ completeOrganization: "onboarding.completeOrganization",
575
+ completePerson: "onboarding.completePerson"
576
+ },
572
577
  org: {
578
+ acceptInvitations: "org.acceptInvitations",
573
579
  account: { get: "org.account.get" },
580
+ activateMember: "org.activateMember",
574
581
  auditLog: "org.auditLog",
575
582
  confirmBootstrap: "org.confirmBootstrap",
576
583
  createOrg: "org.createOrg",
@@ -581,6 +588,7 @@ const CAPXUL_OPERATIONS = {
581
588
  getProofReceipt: "org.getProofReceipt",
582
589
  invite: "org.invite",
583
590
  inviteMember: "org.inviteMember",
591
+ list: "org.list",
584
592
  load: "org.load",
585
593
  me: "org.me",
586
594
  members: "org.members",
@@ -651,7 +659,8 @@ const CAPXUL_OPERATIONS = {
651
659
  organizationPayments: {
652
660
  pay: "organizationPayments.pay",
653
661
  payBatch: "organizationPayments.payBatch",
654
- prepareExecution: "organizationPayments.prepareExecution"
662
+ prepareExecution: "organizationPayments.prepareExecution",
663
+ retry: "organizationPayments.retry"
655
664
  },
656
665
  organizationSetup: { getProofReceipt: "organizationSetup.getProofReceipt" },
657
666
  organizations: { detectAndAcceptPendingInvitations: "orgs.detectAndAcceptPendingInvitations" },
@@ -666,6 +675,7 @@ const CAPXUL_OPERATIONS = {
666
675
  prepareExecution: "payments.prepareExecution",
667
676
  prepareLifecycleExecution: "payments.prepareLifecycleExecution",
668
677
  redirect: "payments.redirect",
678
+ retry: "payments.retry",
669
679
  submitCommandExecution: "payments.submitCommandExecution",
670
680
  submitExecution: "payments.submitExecution"
671
681
  },
@@ -673,11 +683,7 @@ const CAPXUL_OPERATIONS = {
673
683
  render: "paymentDocuments.render",
674
684
  verify: "paymentDocuments.verify"
675
685
  },
676
- payees: {
677
- create: "payees.create",
678
- get: "payees.get",
679
- resolve: "payees.resolve"
680
- },
686
+ recipient: { resolve: "recipient.resolve" },
681
687
  payroll: {
682
688
  authorizeRun: "payroll.authorizeRun",
683
689
  groups: {
@@ -751,6 +757,7 @@ const CAPXUL_OPERATIONS = {
751
757
  smartAccount: {
752
758
  claim: "smartAccount.claim",
753
759
  confirmDeployment: "smartAccount.confirmDeployment",
760
+ loadByAuthUserId: "smartAccount.loadByAuthUserId",
754
761
  loadCurrent: "smartAccount.loadCurrent",
755
762
  provision: "smartAccount.provision"
756
763
  },
@@ -759,12 +766,6 @@ const CAPXUL_OPERATIONS = {
759
766
  ping: "system.ping",
760
767
  runtimeChain: "system.runtimeChain"
761
768
  },
762
- targets: { resolve: {
763
- email: "targets.resolve.email",
764
- handle: "targets.resolve.handle",
765
- organization: "targets.resolve.organization",
766
- payee: "targets.resolve.payee"
767
- } },
768
769
  testUsdc: { mint: "TestUSDC.mint" },
769
770
  _internal: {
770
771
  accounts: { fund: "_internal.accounts.fund" },
@@ -1192,32 +1193,116 @@ const OrgInviteExpiredProps = Schema.Struct({
1192
1193
  role: OptionalString,
1193
1194
  status: OptionalString
1194
1195
  });
1196
+ const RecipientLocatorKindSchema = Schema.Literals([
1197
+ "handle",
1198
+ "email",
1199
+ "address",
1200
+ "party"
1201
+ ]);
1202
+ const RecipientResolutionStatusSchema = Schema.Literals([
1203
+ "known_party",
1204
+ "new_email",
1205
+ "external_address"
1206
+ ]);
1207
+ const RecipientPartyKindSchema = Schema.Literals([
1208
+ "person",
1209
+ "organization",
1210
+ "unresolved"
1211
+ ]);
1212
+ const RecipientTelemetryProps = {
1213
+ recipient_locator_kind: Schema.optional(RecipientLocatorKindSchema),
1214
+ recipient_resolution_status: Schema.optional(RecipientResolutionStatusSchema),
1215
+ recipient_party_id: OptionalString,
1216
+ recipient_party_kind: Schema.optional(RecipientPartyKindSchema),
1217
+ recipient_is_capxul_account: Schema.optional(Schema.Boolean),
1218
+ recipient_handle: OptionalString,
1219
+ recipient_address: OptionalAddress,
1220
+ external_address_acknowledged: Schema.optional(Schema.Boolean)
1221
+ };
1195
1222
  const PaymentInitiatedProps = Schema.Struct({
1223
+ command_id: OptionalString,
1224
+ execution_id: OptionalString,
1225
+ payment_lifecycle_id: OptionalString,
1196
1226
  ...TelemetryEnvelopeProps,
1227
+ ...RecipientTelemetryProps,
1197
1228
  kind: Schema.String,
1198
1229
  payment_id: Schema.String
1199
1230
  });
1231
+ const PaymentLifecycleProps = {
1232
+ payment_state: OptionalString,
1233
+ execution_state: OptionalString,
1234
+ occurred_at: Schema.optional(Schema.Number),
1235
+ causal_sequence: Schema.optional(Schema.Number),
1236
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1237
+ terminal_event_id: OptionalString
1238
+ };
1200
1239
  const PaymentSettledL2Props = Schema.Struct({
1240
+ ...PaymentLifecycleProps,
1201
1241
  ...TelemetryEnvelopeProps,
1242
+ ...RecipientTelemetryProps,
1202
1243
  kind: Schema.String,
1203
1244
  chain_id: Schema.Number,
1204
- settlement_id: Schema.String
1245
+ settlement_id: Schema.String,
1246
+ payment_id: OptionalString,
1247
+ payment_ids: OptionalString,
1248
+ command_id: OptionalString,
1249
+ payment_lifecycle_id: OptionalString,
1250
+ execution_id: OptionalString,
1251
+ user_op_hash: OptionalString,
1252
+ transaction_hash: OptionalString
1205
1253
  });
1206
1254
  const PaymentFailedL2Props = Schema.Struct({
1255
+ ...PaymentLifecycleProps,
1207
1256
  ...TelemetryEnvelopeProps,
1208
1257
  ...ChainCauseTelemetryProps,
1258
+ ...RecipientTelemetryProps,
1209
1259
  kind: Schema.String,
1210
1260
  payment_id: Schema.String,
1211
- reason_code: Schema.String
1261
+ payment_ids: OptionalString,
1262
+ reason_code: Schema.String,
1263
+ command_id: OptionalString,
1264
+ payment_lifecycle_id: OptionalString,
1265
+ execution_id: OptionalString,
1266
+ user_op_hash: OptionalString
1212
1267
  });
1213
1268
  const PaymentVerificationRetryProps = Schema.Struct({
1269
+ ...PaymentLifecycleProps,
1214
1270
  ...TelemetryEnvelopeProps,
1271
+ ...RecipientTelemetryProps,
1215
1272
  command_id: Schema.String,
1273
+ payment_lifecycle_id: Schema.String,
1216
1274
  attempt: Schema.Number,
1217
1275
  reason_code: Schema.String,
1218
1276
  chain_id: Schema.Number,
1219
1277
  delay_ms: DurationMsSchema$1,
1220
- outcome: Schema.Literals(["scheduled", "unresolved"])
1278
+ outcome: Schema.Literals(["scheduled", "unresolved"]),
1279
+ payment_id: OptionalString,
1280
+ payment_ids: OptionalString,
1281
+ execution_id: OptionalString,
1282
+ user_op_hash: OptionalString
1283
+ });
1284
+ const PaymentLifecycleTransitionProps = Schema.Struct({
1285
+ ...TelemetryEnvelopeProps,
1286
+ ...RecipientTelemetryProps,
1287
+ payment_id: Schema.String,
1288
+ payment_lifecycle_id: Schema.String,
1289
+ command_id: Schema.String,
1290
+ payment_state: Schema.String,
1291
+ occurred_at: Schema.Number,
1292
+ causal_sequence: Schema.Number,
1293
+ execution_id: OptionalString,
1294
+ execution_state: OptionalString,
1295
+ user_op_hash: OptionalString,
1296
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1297
+ reason_code: OptionalString
1298
+ });
1299
+ const QuickPayExternalAddressAcknowledgedProps = Schema.Struct({
1300
+ ...TelemetryEnvelopeProps,
1301
+ recipient_locator_kind: Schema.Literal("address"),
1302
+ recipient_resolution_status: Schema.Literal("external_address"),
1303
+ recipient_address: AddressSchema$1,
1304
+ external_address_acknowledged: Schema.Literal(true),
1305
+ organization_id: OptionalOrgId
1221
1306
  });
1222
1307
  const DepositInitiatedProps = Schema.Struct({ ...TelemetryEnvelopeProps });
1223
1308
  const DepositSettledProps = Schema.Struct({
@@ -1425,6 +1510,14 @@ Schema.Struct({
1425
1510
  name: Schema.Literal("payment_verification_retry"),
1426
1511
  props: PaymentVerificationRetryProps
1427
1512
  });
1513
+ Schema.Struct({
1514
+ name: Schema.Literal("payment_lifecycle_transition"),
1515
+ props: PaymentLifecycleTransitionProps
1516
+ });
1517
+ Schema.Struct({
1518
+ name: Schema.Literal("quick_pay_external_address_acknowledged"),
1519
+ props: QuickPayExternalAddressAcknowledgedProps
1520
+ });
1428
1521
  Schema.Struct({
1429
1522
  name: Schema.Literal("deposit_initiated"),
1430
1523
  props: DepositInitiatedProps
@@ -1774,16 +1867,13 @@ const CAPXUL_FUNCTIONS = {
1774
1867
  list: "financialOps/destinations:list",
1775
1868
  remove: "financialOps/destinations:remove"
1776
1869
  },
1777
- "financialOps/mutations": { createPayee: "financialOps/mutations:createPayee" },
1778
1870
  "financialOps/queries": {
1779
1871
  depositInstructions: "financialOps/queries:depositInstructions",
1780
- getPayee: "financialOps/queries:getPayee",
1781
1872
  getPayment: "financialOps/queries:getPayment",
1782
1873
  listPayments: "financialOps/queries:listPayments",
1783
1874
  me: "financialOps/queries:me",
1784
1875
  renderStoredDocument: "financialOps/queries:renderStoredDocument",
1785
- resolveHandle: "financialOps/queries:resolveHandle",
1786
- resolvePayee: "financialOps/queries:resolvePayee",
1876
+ resolveRecipient: "financialOps/queries:resolveRecipient",
1787
1877
  verifyPaymentDocument: "financialOps/queries:verifyPaymentDocument"
1788
1878
  },
1789
1879
  "financialOps/requestsInbox": {
@@ -1802,7 +1892,7 @@ const CAPXUL_FUNCTIONS = {
1802
1892
  },
1803
1893
  "identity/queries": {
1804
1894
  loadByAuthUserId: "identity/queries:loadByAuthUserId",
1805
- usernameAvailable: "identity/queries:usernameAvailable"
1895
+ handleAvailable: "identity/queries:handleAvailable"
1806
1896
  },
1807
1897
  "holdings/actions": { current: "holdings/actions:current" },
1808
1898
  "movement/activity": {
@@ -1812,6 +1902,7 @@ const CAPXUL_FUNCTIONS = {
1812
1902
  summary: "movement/activity:summary"
1813
1903
  },
1814
1904
  "moneyExecution/actions": {
1905
+ abandonPaymentExecution: "moneyExecution/actions:abandonPaymentExecution",
1815
1906
  preparePermissionExecution: "moneyExecution/actions:preparePermissionExecution",
1816
1907
  preparePaymentExecution: "moneyExecution/actions:preparePaymentExecution",
1817
1908
  submitPermissionExecution: "moneyExecution/actions:submitPermissionExecution",
@@ -1889,6 +1980,7 @@ const CAPXUL_FUNCTIONS = {
1889
1980
  const PAYMENT_STATUSES = [
1890
1981
  "pending",
1891
1982
  "settling",
1983
+ "unresolved",
1892
1984
  "scheduled",
1893
1985
  "streaming",
1894
1986
  "pending_claim",
@@ -1896,6 +1988,30 @@ const PAYMENT_STATUSES = [
1896
1988
  "cancelled",
1897
1989
  "failed"
1898
1990
  ];
1991
+ /** The lifecycle of one signed Payment execution attempt. */
1992
+ const PAYMENT_EXECUTION_STATUS = {
1993
+ PENDING: "pending",
1994
+ INCLUDED: "included",
1995
+ DROPPED: "dropped",
1996
+ REPLACED: "replaced",
1997
+ EXPIRED: "expired",
1998
+ UNRESOLVED: "unresolved",
1999
+ SUPERSEDED: "superseded",
2000
+ FAILED: "failed",
2001
+ SETTLED: "settled"
2002
+ };
2003
+ const PAYMENT_EXECUTION_STATUSES = [
2004
+ PAYMENT_EXECUTION_STATUS.PENDING,
2005
+ PAYMENT_EXECUTION_STATUS.INCLUDED,
2006
+ PAYMENT_EXECUTION_STATUS.DROPPED,
2007
+ PAYMENT_EXECUTION_STATUS.REPLACED,
2008
+ PAYMENT_EXECUTION_STATUS.EXPIRED,
2009
+ PAYMENT_EXECUTION_STATUS.UNRESOLVED,
2010
+ PAYMENT_EXECUTION_STATUS.SUPERSEDED,
2011
+ PAYMENT_EXECUTION_STATUS.FAILED,
2012
+ PAYMENT_EXECUTION_STATUS.SETTLED
2013
+ ];
2014
+ PAYMENT_EXECUTION_STATUS.DROPPED, PAYMENT_EXECUTION_STATUS.REPLACED, PAYMENT_EXECUTION_STATUS.EXPIRED, PAYMENT_EXECUTION_STATUS.SUPERSEDED;
1899
2015
  /** The payment direction relative to the current actor. */
1900
2016
  const PAYMENT_DIRECTIONS = [
1901
2017
  "in",
@@ -1931,22 +2047,16 @@ const EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
1931
2047
  */
1932
2048
  const PAYMENT_DOCUMENT_VERIFYING_CONTRACT = "0x7a5c25aB7ce91d7a475B71cd1ec33E230291f8a4";
1933
2049
  const PAYMENT_ID_RE = /^payment_[0-9A-Za-z]+$/;
1934
- const PAYEE_ID_RE = /^payee_[0-9A-Za-z]+$/;
1935
2050
  const ORG_ID_RE = /^org_[0-9A-Za-z]+$/;
1936
- const USER_ID_RE = /^user_[0-9A-Za-z]+$/;
1937
2051
  const PARTY_ID_RE = /^party_[0-9A-Za-z]+$/;
1938
- const HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;
1939
- const ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;
2052
+ const HANDLE_RE = /^@?[a-z0-9_-]{3,30}$/;
1940
2053
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1941
2054
  const MinorUnitStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => MINOR_UNIT_STRING_RE.test(value), { message: "must be a non-negative integer minor-unit string" })));
1942
2055
  const PaymentIdSchema$1 = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYMENT_ID_RE.test(value), { message: "must be payment_ plus an alphanumeric id" })));
1943
- const PayeeIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PAYEE_ID_RE.test(value), { message: "must be payee_ plus an alphanumeric id" })));
1944
2056
  const OrgIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => ORG_ID_RE.test(value), { message: "must be org_ plus an alphanumeric id" })));
1945
- const UserIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => USER_ID_RE.test(value), { message: "must be user_ plus an alphanumeric id" })));
1946
2057
  const PartyIdSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => PARTY_ID_RE.test(value), { message: "must be party_ plus an alphanumeric id" })));
1947
2058
  const DecimalStringSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => DECIMAL_STRING_RE.test(value), { message: "must be a non-negative decimal string" })));
1948
2059
  const HandleValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && HANDLE_RE.test(value), { message: "must be a handle; raw addresses are not accepted" })));
1949
- const OrgHandleValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && ORG_HANDLE_RE.test(value), { message: "must be an org handle; raw addresses are not accepted" })));
1950
2060
  const EmailValueSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => !EVM_ADDRESS_RE.test(value) && EMAIL_RE.test(value), { message: "must be an email; raw addresses are not accepted" })));
1951
2061
  const Uint8Schema$1 = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: "must be a uint8" })));
1952
2062
  const Uint64Schema = Schema.Number.pipe(Schema.check(Schema.makeFilter((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" })));
@@ -2066,42 +2176,39 @@ const WithdrawalDocumentEnvelope = Schema.Struct({
2066
2176
  primaryType: Schema.Literal("Withdrawal"),
2067
2177
  message: WithdrawalDocument
2068
2178
  });
2069
- Schema.Union([AttachablePaymentDocumentEnvelope, WithdrawalDocumentEnvelope]);
2070
- Schema.Struct({
2071
- payeeId: PayeeIdSchema,
2072
- label: Schema.String,
2073
- trustState: Schema.Literals([
2074
- "unverified",
2075
- "trusted",
2076
- "blocked"
2077
- ]),
2078
- destinationKind: Schema.Literals([
2079
- "handle",
2080
- "email",
2081
- "saved-payee",
2082
- "org"
2083
- ])
2084
- });
2085
- const PaymentRecipient = Schema.Struct({
2086
- kind: Schema.Literals([
2087
- "handle",
2088
- "email",
2089
- "payee",
2090
- "capxulUserId",
2091
- "me",
2092
- "org",
2093
- "party",
2094
- "external_address"
2095
- ]),
2096
- label: Schema.String,
2097
- payeeId: Schema.optional(PayeeIdSchema)
2098
- });
2179
+ const PaymentDocumentEnvelope = Schema.Union([AttachablePaymentDocumentEnvelope, WithdrawalDocumentEnvelope]);
2180
+ const ENVELOPE_PRIMARY_TYPE_TO_KIND = {
2181
+ Memo: "memo",
2182
+ Invoice: "invoice",
2183
+ Payslip: "payslip",
2184
+ Receipt: "receipt",
2185
+ Withdrawal: "withdrawal"
2186
+ };
2099
2187
  /**
2100
- * A raw external EVM address for the B3 withdraw lane — the cash-out
2101
- * destination. This is the ONE schema that ACCEPTS a bare 0x (the withdraw
2102
- * mutation args use it), as opposed to `PaymentRecipientRefSchema` which
2103
- * REJECTS bare addresses to protect the pay lane. The full address never
2104
- * crosses the model wire; it lives on the kind:4 Withdrawal document only.
2188
+ * Derive the wire `paymentType` an UNKNOWN document envelope classifies to
2189
+ * (payment-document-spec.md D11: memo/withdrawal → unspecified, invoice →
2190
+ * invoice, payslip → payroll, receipt → reimbursement), or `undefined` if the
2191
+ * envelope is absent / malformed — the same tolerance as
2192
+ * `tryHashPaymentDocument`. Callers holding an untyped envelope (e.g. the MCP
2193
+ * org spend port, #712) use this so the type they record agrees with the type
2194
+ * the backend re-derives from the same document.
2195
+ */
2196
+ function paymentTypeForDocumentEnvelope(envelope) {
2197
+ if (envelope === void 0 || envelope === null) return void 0;
2198
+ const decoded = SchemaParser.decodeUnknownResult(PaymentDocumentEnvelope)(envelope);
2199
+ if (decoded._tag === "Failure") return void 0;
2200
+ return paymentTypeForDocumentKind(ENVELOPE_PRIMARY_TYPE_TO_KIND[decoded.success.primaryType]);
2201
+ }
2202
+ const PaymentRecipient = Schema.Union([Schema.Struct({
2203
+ kind: Schema.Literal("party"),
2204
+ partyId: PartyIdSchema,
2205
+ label: Schema.String
2206
+ }), Schema.Struct({
2207
+ kind: Schema.Literal("external_address"),
2208
+ label: Schema.String
2209
+ })]);
2210
+ /**
2211
+ * A raw external EVM address for a payment or withdrawal destination.
2105
2212
  */
2106
2213
  const ExternalAddressSchema = Schema.String.pipe(Schema.check(Schema.makeFilter((value) => EVM_ADDRESS_RE.test(value), { message: "must be a 0x EVM address (40 hex chars)" })));
2107
2214
  const PaymentTiming = Schema.Union([
@@ -2127,16 +2234,8 @@ const PaymentRef = Schema.Union([
2127
2234
  email: EmailValueSchema
2128
2235
  }),
2129
2236
  Schema.Struct({
2130
- kind: Schema.Literal("orgHandle"),
2131
- orgHandle: OrgHandleValueSchema
2132
- }),
2133
- Schema.Struct({
2134
- kind: Schema.Literal("capxulUserId"),
2135
- capxulUserId: UserIdSchema
2136
- }),
2137
- Schema.Struct({
2138
- kind: Schema.Literal("payeeId"),
2139
- payeeId: PayeeIdSchema
2237
+ kind: Schema.Literal("address"),
2238
+ address: ExternalAddressSchema
2140
2239
  }),
2141
2240
  Schema.Struct({
2142
2241
  kind: Schema.Literal("party"),
@@ -2159,6 +2258,10 @@ const Payment = Schema.Struct({
2159
2258
  timing: PaymentTiming,
2160
2259
  released: FinancialOpsMoney,
2161
2260
  availableToClaim: FinancialOpsMoney,
2261
+ execution: Schema.optional(Schema.Struct({
2262
+ status: Schema.Literals(PAYMENT_EXECUTION_STATUSES),
2263
+ retryRequired: Schema.Boolean
2264
+ })),
2162
2265
  createdAt: EpochMsSchema,
2163
2266
  updatedAt: EpochMsSchema
2164
2267
  }).pipe(Schema.check(Schema.makeFilter((payment) => payment.documents.every((document) => paymentTypeForDocumentKind(document.kind) === payment.paymentType), { message: "document kind must map to paymentType" })));
@@ -2303,11 +2406,21 @@ const MovementIdentitySchema = Schema.Struct({
2303
2406
  txHash: TxHashSchema,
2304
2407
  logIndex: LogIndexSchema
2305
2408
  });
2306
- const MovementCanonicalStateSchema = Schema.Literals([
2409
+ const MovementCanonicalStateInputSchema = Schema.Literals([
2307
2410
  "observed",
2411
+ "included",
2308
2412
  "finalized",
2309
2413
  "removed"
2310
2414
  ]);
2415
+ const MovementCanonicalStateOutputSchema = Schema.Literals([
2416
+ "observed",
2417
+ "included",
2418
+ "removed"
2419
+ ]);
2420
+ const MovementCanonicalStateSchema = MovementCanonicalStateInputSchema.pipe(Schema.decodeTo(MovementCanonicalStateOutputSchema, {
2421
+ decode: SchemaGetter.transform((state) => state === "finalized" ? "included" : state),
2422
+ encode: SchemaGetter.transform((state) => state)
2423
+ }));
2311
2424
  const MovementSchema = Schema.Struct({
2312
2425
  ...MovementIdentitySchema.fields,
2313
2426
  movementId: MovementIdSchema,
@@ -2658,7 +2771,7 @@ Schema.Struct({
2658
2771
  transfers: Schema.Array(TransferEvidenceSchema),
2659
2772
  requestCount: nonNegativeInteger("requestCount")
2660
2773
  });
2661
- const FinalizedMoneyEvidenceCommonSchema = Schema.Struct({
2774
+ const VerifiedMoneyEvidenceCommonSchema = Schema.Struct({
2662
2775
  chainId: BaseSepoliaChainIdSchema,
2663
2776
  contractAddress: AddressSchema,
2664
2777
  userOpHash: Bytes32Schema,
@@ -2668,8 +2781,8 @@ const FinalizedMoneyEvidenceCommonSchema = Schema.Struct({
2668
2781
  blockTimestamp: Uint48Schema,
2669
2782
  eventLogIndex: LogIndexSchema
2670
2783
  });
2671
- const FinalizedPaymentEvidenceSchema = Schema.Struct({
2672
- ...FinalizedMoneyEvidenceCommonSchema.fields,
2784
+ const VerifiedPaymentEvidenceSchema = Schema.Struct({
2785
+ ...VerifiedMoneyEvidenceCommonSchema.fields,
2673
2786
  operation: Schema.Literal("send"),
2674
2787
  settlementId: SettlementIdSchema,
2675
2788
  purposeKind: PaymentPurposeKindSchema,
@@ -2681,8 +2794,8 @@ const FinalizedPaymentEvidenceSchema = Schema.Struct({
2681
2794
  destination: AddressSchema,
2682
2795
  rawAmount: WeiAmountSchema
2683
2796
  });
2684
- const FinalizedCommitmentCreationEvidenceSchema = Schema.Struct({
2685
- ...FinalizedMoneyEvidenceCommonSchema.fields,
2797
+ const VerifiedCommitmentCreationEvidenceSchema = Schema.Struct({
2798
+ ...VerifiedMoneyEvidenceCommonSchema.fields,
2686
2799
  operation: Schema.Literal("create_commitment"),
2687
2800
  commitmentId: Uint256StringSchema,
2688
2801
  settlementId: SettlementIdSchema,
@@ -2698,8 +2811,8 @@ const FinalizedCommitmentCreationEvidenceSchema = Schema.Struct({
2698
2811
  documentHash: NonzeroDocumentHashSchema,
2699
2812
  transferLogIndex: LogIndexSchema
2700
2813
  });
2701
- const FinalizedCommitmentClaimEvidenceSchema = Schema.Struct({
2702
- ...FinalizedMoneyEvidenceCommonSchema.fields,
2814
+ const VerifiedCommitmentClaimEvidenceSchema = Schema.Struct({
2815
+ ...VerifiedMoneyEvidenceCommonSchema.fields,
2703
2816
  operation: Schema.Literal("claim_commitment"),
2704
2817
  commitmentId: Uint256StringSchema,
2705
2818
  settlementId: SettlementIdSchema,
@@ -2712,8 +2825,8 @@ const FinalizedCommitmentClaimEvidenceSchema = Schema.Struct({
2712
2825
  documentHash: NonzeroDocumentHashSchema,
2713
2826
  transferLogIndex: LogIndexSchema
2714
2827
  });
2715
- const FinalizedCommitmentCancelEvidenceSchema = Schema.Struct({
2716
- ...FinalizedMoneyEvidenceCommonSchema.fields,
2828
+ const VerifiedCommitmentCancelEvidenceSchema = Schema.Struct({
2829
+ ...VerifiedMoneyEvidenceCommonSchema.fields,
2717
2830
  operation: Schema.Literal("cancel_commitment"),
2718
2831
  commitmentId: Uint256StringSchema,
2719
2832
  settlementId: SettlementIdSchema,
@@ -2727,8 +2840,8 @@ const FinalizedCommitmentCancelEvidenceSchema = Schema.Struct({
2727
2840
  documentHash: NonzeroDocumentHashSchema,
2728
2841
  transfer: Schema.NullOr(TransferEvidenceSchema)
2729
2842
  });
2730
- const FinalizedCommitmentRedirectEvidenceSchema = Schema.Struct({
2731
- ...FinalizedMoneyEvidenceCommonSchema.fields,
2843
+ const VerifiedCommitmentRedirectEvidenceSchema = Schema.Struct({
2844
+ ...VerifiedMoneyEvidenceCommonSchema.fields,
2732
2845
  operation: Schema.Literal("redirect_commitment"),
2733
2846
  commitmentId: Uint256StringSchema,
2734
2847
  settlementId: SettlementIdSchema,
@@ -2739,12 +2852,12 @@ const FinalizedCommitmentRedirectEvidenceSchema = Schema.Struct({
2739
2852
  documentHash: NonzeroDocumentHashSchema,
2740
2853
  transfer: Schema.Null
2741
2854
  });
2742
- const FinalizedMoneyEvidenceSchema = Schema.Union([
2743
- FinalizedPaymentEvidenceSchema,
2744
- FinalizedCommitmentCreationEvidenceSchema,
2745
- FinalizedCommitmentClaimEvidenceSchema,
2746
- FinalizedCommitmentCancelEvidenceSchema,
2747
- FinalizedCommitmentRedirectEvidenceSchema
2855
+ const VerifiedMoneyEvidenceSchema = Schema.Union([
2856
+ VerifiedPaymentEvidenceSchema,
2857
+ VerifiedCommitmentCreationEvidenceSchema,
2858
+ VerifiedCommitmentClaimEvidenceSchema,
2859
+ VerifiedCommitmentCancelEvidenceSchema,
2860
+ VerifiedCommitmentRedirectEvidenceSchema
2748
2861
  ]);
2749
2862
  Schema.Union([
2750
2863
  Schema.Struct({
@@ -2754,7 +2867,7 @@ Schema.Union([
2754
2867
  }),
2755
2868
  Schema.Struct({
2756
2869
  status: Schema.Literal("verified"),
2757
- evidence: FinalizedMoneyEvidenceSchema
2870
+ evidence: VerifiedMoneyEvidenceSchema
2758
2871
  }),
2759
2872
  Schema.Struct({
2760
2873
  status: Schema.Literal("mismatch"),
@@ -2766,7 +2879,7 @@ Schema.Union([
2766
2879
  retryable: Schema.Literal(true)
2767
2880
  })
2768
2881
  ]);
2769
- const FinalizedAttributedInboundMovementSchema = Schema.Struct({
2882
+ const VerifiedAttributedInboundMovementSchema = Schema.Struct({
2770
2883
  movement: MovementSchema,
2771
2884
  attribution: MovementAttributionSchema
2772
2885
  });
@@ -2792,6 +2905,25 @@ const ProtocolBirthInputSchema = Schema.Struct({
2792
2905
  release: ReleaseTermsSchema,
2793
2906
  lineage: Schema.optional(PaymentCommandLineageSchema)
2794
2907
  }).pipe(Schema.refine((birth) => hasActorBoundPermission(birth.actor, birth.actor.kind === "organization" ? birth.actor.orgId : void 0, birth.permissionId), { message: "Organization Payment and Payout births require permissionId; personal births forbid it" }));
2908
+ const ApplyVerifiedEvidenceCommandSchema = Schema.Struct({
2909
+ kind: Schema.Literal("apply_verified_evidence"),
2910
+ paymentId: PaymentIdSchema,
2911
+ evidence: VerifiedMoneyEvidenceSchema
2912
+ });
2913
+ const ApplyFinalizedEvidenceCommandSchema = Schema.Struct({
2914
+ kind: Schema.Literal("apply_finalized_evidence"),
2915
+ paymentId: PaymentIdSchema,
2916
+ evidence: VerifiedMoneyEvidenceSchema
2917
+ }).pipe(Schema.decodeTo(ApplyVerifiedEvidenceCommandSchema, {
2918
+ decode: SchemaGetter.transform((value) => ({
2919
+ ...value,
2920
+ kind: "apply_verified_evidence"
2921
+ })),
2922
+ encode: SchemaGetter.transform((value) => ({
2923
+ ...value,
2924
+ kind: "apply_finalized_evidence"
2925
+ }))
2926
+ }));
2795
2927
  Schema.Union([
2796
2928
  Schema.Struct({
2797
2929
  kind: Schema.Literal("birth"),
@@ -2799,7 +2931,7 @@ Schema.Union([
2799
2931
  }),
2800
2932
  Schema.Struct({
2801
2933
  kind: Schema.Literal("birth_deposit"),
2802
- movement: FinalizedAttributedInboundMovementSchema
2934
+ movement: VerifiedAttributedInboundMovementSchema
2803
2935
  }),
2804
2936
  Schema.Struct({
2805
2937
  kind: Schema.Literal("rollback_deposit"),
@@ -2811,11 +2943,8 @@ Schema.Union([
2811
2943
  paymentIds: Schema.Array(PaymentIdSchema),
2812
2944
  userOpHash: Bytes32Schema
2813
2945
  }),
2814
- Schema.Struct({
2815
- kind: Schema.Literal("apply_finalized_evidence"),
2816
- paymentId: PaymentIdSchema,
2817
- evidence: FinalizedMoneyEvidenceSchema
2818
- }),
2946
+ ApplyVerifiedEvidenceCommandSchema,
2947
+ ApplyFinalizedEvidenceCommandSchema,
2819
2948
  Schema.Struct({
2820
2949
  kind: Schema.Literal("transition"),
2821
2950
  paymentId: PaymentIdSchema,
@@ -2957,6 +3086,7 @@ const MoneyExecutionIdSchema = Schema.String.pipe(Schema.refine((value) => /^mon
2957
3086
  const OwnerSignatureSchema = Schema.String.pipe(Schema.refine((value) => /^0x[0-9a-fA-F]{130}$/u.test(value), { message: "signature must be a 65-byte 0x value" }));
2958
3087
  const PaymentExecutionIntentSchema = Schema.Struct({
2959
3088
  to: PaymentRef,
3089
+ externalAddressAcknowledged: Schema.optional(Schema.Literal(true)),
2960
3090
  amount: FinancialOpsMoney,
2961
3091
  paymentType: Schema.optional(Schema.Literals([
2962
3092
  "unspecified",
@@ -2973,7 +3103,31 @@ Schema.Struct({
2973
3103
  signerAddress: AddressSchema,
2974
3104
  payment: PaymentExecutionIntentSchema
2975
3105
  });
3106
+ const RecipientObservationSchema = Schema.Struct({
3107
+ recipient_locator_kind: Schema.Literals([
3108
+ "handle",
3109
+ "email",
3110
+ "party",
3111
+ "address"
3112
+ ]),
3113
+ recipient_resolution_status: Schema.Literals([
3114
+ "known_party",
3115
+ "new_email",
3116
+ "external_address"
3117
+ ]),
3118
+ recipient_is_capxul_account: Schema.Boolean,
3119
+ recipient_party_id: Schema.optional(Schema.String),
3120
+ recipient_party_kind: Schema.optional(Schema.Literals([
3121
+ "person",
3122
+ "organization",
3123
+ "unresolved"
3124
+ ])),
3125
+ recipient_handle: Schema.optional(Schema.String),
3126
+ recipient_address: AddressSchema,
3127
+ external_address_acknowledged: Schema.Boolean
3128
+ });
2976
3129
  Schema.Struct({
3130
+ recipientObservation: RecipientObservationSchema,
2977
3131
  executionId: MoneyExecutionIdSchema,
2978
3132
  commandId: PaymentCommandIdSchema,
2979
3133
  paymentId: PaymentIdSchema,
@@ -2990,6 +3144,14 @@ Schema.Struct({
2990
3144
  executionId: MoneyExecutionIdSchema,
2991
3145
  signature: OwnerSignatureSchema
2992
3146
  });
3147
+ Schema.Struct({
3148
+ executionId: MoneyExecutionIdSchema,
3149
+ reason: Schema.Literals([
3150
+ "signer_rejected",
3151
+ "cancelled",
3152
+ "prepared_mismatch"
3153
+ ])
3154
+ });
2993
3155
  Schema.Struct({
2994
3156
  executionId: MoneyExecutionIdSchema,
2995
3157
  commandId: PaymentCommandIdSchema,
@@ -3003,6 +3165,10 @@ Schema.Struct({
3003
3165
  payments: Schema.Array(Payment)
3004
3166
  });
3005
3167
  const PaymentLifecycleExecutionIntentSchema = Schema.Union([
3168
+ Schema.Struct({
3169
+ kind: Schema.Literal("retry"),
3170
+ paymentId: PaymentIdSchema
3171
+ }),
3006
3172
  Schema.Struct({
3007
3173
  kind: Schema.Literal("claim"),
3008
3174
  paymentId: PaymentIdSchema
@@ -3023,6 +3189,7 @@ Schema.Struct({
3023
3189
  });
3024
3190
  const OrganizationPaymentExecutionItemSchema = Schema.Struct({
3025
3191
  to: PaymentRef,
3192
+ externalAddressAcknowledged: Schema.optional(Schema.Literal(true)),
3026
3193
  amount: FinancialOpsMoney,
3027
3194
  paymentType: Schema.optional(Schema.Literals([
3028
3195
  "unspecified",
@@ -3041,6 +3208,8 @@ Schema.Struct({
3041
3208
  lineage: Schema.optional(PaymentCommandLineageSchema)
3042
3209
  });
3043
3210
  const PreparedPaymentCommandExecutionSchema = Schema.Struct({
3211
+ recipientObservations: Schema.Array(RecipientObservationSchema),
3212
+ emitPaymentInitiated: Schema.Boolean,
3044
3213
  executionId: MoneyExecutionIdSchema,
3045
3214
  commandId: PaymentCommandIdSchema,
3046
3215
  paymentIds: Schema.Array(PaymentIdSchema),
@@ -3076,7 +3245,8 @@ const PermissionCommandSchema = Schema.Union([
3076
3245
  operation: Schema.Literal("assign"),
3077
3246
  requestKey: nonEmpty("requestKey"),
3078
3247
  permissionId: PermissionIdSchema,
3079
- accountId: nonEmpty("accountId")
3248
+ accountId: nonEmpty("accountId"),
3249
+ expectedMemberEmail: Schema.optional(nonEmpty("expectedMemberEmail"))
3080
3250
  }),
3081
3251
  Schema.Struct({
3082
3252
  operation: Schema.Literal("revoke"),
@@ -3331,9 +3501,10 @@ const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
3331
3501
  const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
3332
3502
  /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
3333
3503
  function attachInvocationObservation(target, source) {
3334
- const snapshot = Object.freeze(source.context === void 0 ? { active: source.active } : {
3504
+ const snapshot = Object.freeze({
3335
3505
  active: source.active,
3336
- context: Object.freeze({ ...source.context })
3506
+ ...source.actorId === void 0 ? {} : { actorId: source.actorId },
3507
+ ...source.context === void 0 ? {} : { context: Object.freeze({ ...source.context }) }
3337
3508
  });
3338
3509
  Object.defineProperty(target, INVOCATION_OBSERVATION, {
3339
3510
  configurable: false,
@@ -3585,10 +3756,10 @@ const logIdentityTransition = (record) => (record.outcome === "applied" ? Effect
3585
3756
  //#region src/domain/machine/shell.ts
3586
3757
  const INVOCATION_PARENT_SPAN = Symbol("@capxul/sdk/identity-invocation-parent-span");
3587
3758
  function carryInvocationParentSpan(controls, parent) {
3588
- return {
3759
+ return copyInvocationObservation(controls, {
3589
3760
  ...controls,
3590
3761
  [INVOCATION_PARENT_SPAN]: parent
3591
- };
3762
+ });
3592
3763
  }
3593
3764
  function withInvocationParentSpan(effect, controls) {
3594
3765
  const parent = controls?.[INVOCATION_PARENT_SPAN];
@@ -3939,13 +4110,13 @@ async function toCapxulResult(program, layer) {
3939
4110
  * with `{ publicError }` rather than a bare `CapxulError`, so the wrapper is
3940
4111
  * unwrapped here — once — instead of at every call site.
3941
4112
  */
3942
- async function runIfActive(signal, operation, effect, runPromise = Effect.runPromise) {
3943
- if (signal?.aborted === true) return {
4113
+ async function runIfActive(signal, operation, effect, runPromise = Effect.runPromise, observe) {
4114
+ if (signal?.aborted === true && observe === void 0) return {
3944
4115
  ok: false,
3945
4116
  error: Errors.cancelled({ operation })
3946
4117
  };
3947
- const program = effect().pipe(Effect.mapError((error) => error.publicError));
3948
- return runProgram(signal === void 0 ? program : Effect.raceFirst(program, Effect.callback((resume) => {
4118
+ const program = signal?.aborted === true ? Effect.fail(Errors.cancelled({ operation })) : Effect.suspend(effect).pipe(Effect.mapError((error) => error.publicError));
4119
+ const controlled = signal === void 0 ? program : Effect.raceFirst(program, Effect.callback((resume) => {
3949
4120
  if (signal.aborted) {
3950
4121
  resume(Effect.fail(Errors.cancelled({ operation })));
3951
4122
  return Effect.void;
@@ -3953,7 +4124,8 @@ async function runIfActive(signal, operation, effect, runPromise = Effect.runPro
3953
4124
  const onAbort = () => resume(Effect.fail(Errors.cancelled({ operation })));
3954
4125
  signal.addEventListener("abort", onAbort, { once: true });
3955
4126
  return Effect.sync(() => signal.removeEventListener("abort", onAbort));
3956
- })), runPromise);
4127
+ }));
4128
+ return runProgram(observe === void 0 ? controlled : observe(controlled), runPromise);
3957
4129
  }
3958
4130
  //#endregion
3959
4131
  //#region src/surface/_shared/effect-actor-bridge.ts
@@ -4004,22 +4176,52 @@ async function runPortEffect(effect, controls, operation = CAPXUL_OPERATIONS.run
4004
4176
  orElse: () => Effect.fail({ publicError: Errors.providerTimeout("sdk", operation, timeoutMs) })
4005
4177
  }))).pipe(Effect.mapError((failure) => failure.publicError)), controls, operation, runPromise);
4006
4178
  }
4179
+ /** Keep observation metadata while the compound operation owns cancellation. */
4180
+ function observationOnlyControls(controls) {
4181
+ const { signal: _signal, timeoutMs: _timeoutMs, deadlineMs: _deadlineMs, ...observation } = controls ?? {};
4182
+ return copyInvocationObservation(controls, observation);
4183
+ }
4007
4184
  /** Observe a public Effect that already uses the canonical CapxulError channel. */
4008
4185
  async function runCapxulEffect(effect, controls, operation = CAPXUL_OPERATIONS.runtime.port, runPromise = Effect.runPromise) {
4009
4186
  const invocation = readInvocationObservation(controls);
4010
- const correlationId = safeEngineeringIdentifier(controls?.correlation_id ?? invocation?.context?.correlationId);
4011
- const observed = effect.pipe(Effect.tap(() => Effect.annotateCurrentSpan({ outcome: "succeeded" })), Effect.tapError((error) => {
4012
- const mode = error.mode ?? error.details?.failure_mode;
4013
- return Effect.annotateCurrentSpan({
4014
- outcome: portFailureOutcome(error.code),
4015
- failure_code: error.code,
4016
- ...typeof mode === "string" ? { mode } : {}
4017
- });
4018
- }), Effect.tapDefect(() => Effect.annotateCurrentSpan({
4019
- outcome: "failed",
4020
- failure_code: "UNKNOWN"
4021
- })), Effect.withSpan(`identity.port.${operation}`), Effect.annotateSpans(correlationId === void 0 ? {} : { correlation_id: correlationId }));
4022
- return runIfActive(controls?.signal, operation, () => withInvocationParentSpan(observed, controls).pipe(Effect.mapError((publicError) => ({ publicError }))), runPromise);
4187
+ const correlationId = safeEngineeringIdentifier(invocation?.context?.correlationId ?? controls?.correlation_id);
4188
+ const context = invocation?.active === false ? void 0 : sanitizeObservationContext(invocation?.context);
4189
+ const fields = {
4190
+ operation,
4191
+ ...correlationId === void 0 ? {} : { correlation_id: correlationId },
4192
+ ...context?.sessionId === void 0 ? {} : {
4193
+ session_id: context.sessionId,
4194
+ sessionId: context.sessionId
4195
+ },
4196
+ ...context?.journeyId === void 0 ? {} : { journey_id: context.journeyId },
4197
+ ...context?.release === void 0 ? {} : { release: context.release },
4198
+ ...context?.application === void 0 ? {} : { application: context.application },
4199
+ ...safeEngineeringIdentifier(invocation?.actorId) === void 0 ? {} : {
4200
+ actor_id: invocation.actorId,
4201
+ actor_kind: "authenticated",
4202
+ posthogDistinctId: invocation.actorId
4203
+ }
4204
+ };
4205
+ const result = await runIfActive(controls?.signal, operation, () => effect.pipe(Effect.mapError((publicError) => ({ publicError }))), runPromise, (program) => withInvocationParentSpan(Effect.gen(function* () {
4206
+ const startedAt = yield* Clock.currentTimeMillis;
4207
+ const exit = yield* Effect.exit(program.pipe(Effect.catchDefect((cause) => Effect.fail(Errors.unknown(cause)))));
4208
+ const duration_ms = (yield* Clock.currentTimeMillis) - startedAt;
4209
+ const error = Exit.isFailure(exit) ? Cause.squash(exit.cause) : void 0;
4210
+ const failure = error instanceof CapxulError ? error : void 0;
4211
+ const outcome = Exit.isSuccess(exit) ? "succeeded" : failure?.code === "CANCELLED" ? "cancelled" : failure !== void 0 && EXPECTED_OPERATION_OUTCOMES.has(failure.code) ? "refused" : "failed";
4212
+ const completion = {
4213
+ ...fields,
4214
+ duration_ms,
4215
+ outcome,
4216
+ ...failure === void 0 ? {} : { failure_code: failure.code },
4217
+ ...typeof failure?.mode === "string" ? { mode: failure.mode } : {},
4218
+ ...failure?.mode === void 0 && typeof failure?.details?.failure_mode === "string" ? { mode: failure.details.failure_mode } : {}
4219
+ };
4220
+ yield* Effect.annotateCurrentSpan(completion).pipe(Effect.catchCause(() => Effect.void));
4221
+ yield* (outcome === "failed" ? Effect.logError("capxul_sdk_operation") : Effect.logInfo("capxul_sdk_operation")).pipe(Effect.annotateLogs(completion), Effect.catchCause(() => Effect.void));
4222
+ return yield* Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause);
4223
+ }).pipe(Effect.withSpan(operation)), controls));
4224
+ return !result.ok && invocation !== void 0 ? markFailureInvocationSnapshot(result, invocation) : result;
4023
4225
  }
4024
4226
  /** Map machine-internal failure state onto the public SDK error vocabulary. */
4025
4227
  function publicIdentityFailure(failure) {
@@ -4233,76 +4435,110 @@ function makeActorRelationshipMethods(deps) {
4233
4435
  const fns = actorScopeContract;
4234
4436
  return {
4235
4437
  addressBook: {
4236
- list: (input, options) => mapOk$1(CAPXUL_OPERATIONS.addressBook.list, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.list, () => convexCall.query(fns.addressBookList, {
4237
- actor,
4238
- ...input?.includeHidden === void 0 ? {} : { includeHidden: input.includeHidden }
4239
- })), (entries) => entries.map(mapAddressBookEntry)),
4240
- get: (entryId, options) => mapOk$1(CAPXUL_OPERATIONS.addressBook.get, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.get, () => convexCall.query(fns.addressBookGet, {
4241
- actor,
4242
- partyId: entryId
4243
- })), (entry) => entry === null ? null : mapAddressBookEntry(entry)),
4244
- add: async (input, options) => {
4438
+ list: (input, options) => {
4439
+ const controls = deps.invocationControls?.(options) ?? options;
4440
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.list, Effect.suspend(() => convexCall.query(fns.addressBookList, copyInvocationObservation(controls, {
4441
+ actor,
4442
+ ...input?.includeHidden === void 0 ? {} : { includeHidden: input.includeHidden }
4443
+ }))), (entries) => entries.map(mapAddressBookEntry)), controls, CAPXUL_OPERATIONS.addressBook.list, deps.runPromise);
4444
+ },
4445
+ get: (entryId, options) => {
4446
+ const controls = deps.invocationControls?.(options) ?? options;
4447
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.get, Effect.suspend(() => convexCall.query(fns.addressBookGet, copyInvocationObservation(controls, {
4448
+ actor,
4449
+ partyId: entryId
4450
+ }))), (entry) => entry === null ? null : mapAddressBookEntry(entry)), controls, CAPXUL_OPERATIONS.addressBook.get, deps.runPromise);
4451
+ },
4452
+ add: (input, options) => {
4453
+ const controls = deps.invocationControls?.(options) ?? options;
4245
4454
  const ref = normalizeRefForBackend$1(input.ref, "ref");
4246
- if (!ref.ok) return ref;
4247
- return mapOk$1(CAPXUL_OPERATIONS.addressBook.add, await awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.add, () => convexCall.mutation(fns.addressBookAdd, {
4455
+ if (!ref.ok) return runCapxulEffect(Effect.fail(ref.error), controls, CAPXUL_OPERATIONS.addressBook.add, deps.runPromise);
4456
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.add, Effect.suspend(() => convexCall.mutation(fns.addressBookAdd, copyInvocationObservation(controls, {
4248
4457
  actor,
4249
4458
  ref: ref.value,
4250
4459
  ...input.label === void 0 ? {} : { label: input.label }
4251
- })), mapAddressBookEntry);
4460
+ }))), mapAddressBookEntry), controls, CAPXUL_OPERATIONS.addressBook.add, deps.runPromise);
4252
4461
  },
4253
- hide: (entryId, options) => mapOk$1(CAPXUL_OPERATIONS.addressBook.hide, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.hide, () => convexCall.mutation(fns.addressBookHide, {
4254
- actor,
4255
- partyId: entryId
4256
- })), mapAddressBookEntry),
4257
- unhide: (entryId, options) => mapOk$1(CAPXUL_OPERATIONS.addressBook.unhide, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.unhide, () => convexCall.mutation(fns.addressBookUnhide, {
4258
- actor,
4259
- partyId: entryId
4260
- })), mapAddressBookEntry),
4261
- label: (input, options) => mapOk$1(CAPXUL_OPERATIONS.addressBook.label, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.addressBook.label, () => convexCall.mutation(fns.addressBookLabel, {
4262
- actor,
4263
- partyId: input.entryId,
4264
- label: input.label
4265
- })), mapAddressBookEntry)
4462
+ hide: (entryId, options) => {
4463
+ const controls = deps.invocationControls?.(options) ?? options;
4464
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.hide, Effect.suspend(() => convexCall.mutation(fns.addressBookHide, copyInvocationObservation(controls, {
4465
+ actor,
4466
+ partyId: entryId
4467
+ }))), mapAddressBookEntry), controls, CAPXUL_OPERATIONS.addressBook.hide, deps.runPromise);
4468
+ },
4469
+ unhide: (entryId, options) => {
4470
+ const controls = deps.invocationControls?.(options) ?? options;
4471
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.unhide, Effect.suspend(() => convexCall.mutation(fns.addressBookUnhide, copyInvocationObservation(controls, {
4472
+ actor,
4473
+ partyId: entryId
4474
+ }))), mapAddressBookEntry), controls, CAPXUL_OPERATIONS.addressBook.unhide, deps.runPromise);
4475
+ },
4476
+ label: (input, options) => {
4477
+ const controls = deps.invocationControls?.(options) ?? options;
4478
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.addressBook.label, Effect.suspend(() => convexCall.mutation(fns.addressBookLabel, copyInvocationObservation(controls, {
4479
+ actor,
4480
+ partyId: input.entryId,
4481
+ label: input.label
4482
+ }))), mapAddressBookEntry), controls, CAPXUL_OPERATIONS.addressBook.label, deps.runPromise);
4483
+ }
4266
4484
  },
4267
4485
  requests: {
4268
- issue: async (input, options) => {
4486
+ issue: (input, options) => {
4487
+ const controls = deps.invocationControls?.(options) ?? options;
4269
4488
  const payer = normalizeRefForBackend$1(input.payer, "payer");
4270
- if (!payer.ok) return payer;
4271
- return mapOk$1(CAPXUL_OPERATIONS.requests.issue, await awaitableConvex(options?.signal, CAPXUL_OPERATIONS.requests.issue, () => convexCall.mutation(fns.requestsIssue, {
4489
+ if (!payer.ok) return runCapxulEffect(Effect.fail(payer.error), controls, CAPXUL_OPERATIONS.requests.issue, deps.runPromise);
4490
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.requests.issue, Effect.suspend(() => convexCall.mutation(fns.requestsIssue, copyInvocationObservation(controls, {
4272
4491
  actor,
4273
4492
  payer: payer.value,
4274
4493
  amount: input.amount,
4275
4494
  reference: input.reference,
4276
4495
  ...input.memo === void 0 ? {} : { memo: input.memo },
4277
4496
  ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
4278
- })), (request) => mapActorRequest(request, input.payer));
4497
+ }))), (request) => mapActorRequest(request, input.payer)), controls, CAPXUL_OPERATIONS.requests.issue, deps.runPromise);
4498
+ },
4499
+ list: (options) => {
4500
+ const controls = deps.invocationControls?.(options) ?? options;
4501
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.requests.list, Effect.suspend(() => convexCall.query(fns.requestsList, copyInvocationObservation(controls, { actor }))), (requests) => requests.map((request) => mapActorRequest(request))), controls, CAPXUL_OPERATIONS.requests.list, deps.runPromise);
4502
+ },
4503
+ get: (requestId, options) => {
4504
+ const controls = deps.invocationControls?.(options) ?? options;
4505
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.requests.get, Effect.suspend(() => convexCall.query(fns.requestsGet, copyInvocationObservation(controls, {
4506
+ actor,
4507
+ paymentRequestId: requestId
4508
+ }))), (request) => request === null ? null : mapActorRequest(request)), controls, CAPXUL_OPERATIONS.requests.get, deps.runPromise);
4279
4509
  },
4280
- list: (options) => mapOk$1(CAPXUL_OPERATIONS.requests.list, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.requests.list, () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
4281
- get: (requestId, options) => mapOk$1(CAPXUL_OPERATIONS.requests.get, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.requests.get, () => convexCall.query(fns.requestsGet, {
4282
- actor,
4283
- paymentRequestId: requestId
4284
- })), (request) => request === null ? null : mapActorRequest(request)),
4285
- cancel: (requestId, options) => mapOk$1(CAPXUL_OPERATIONS.requests.cancel, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.requests.cancel, () => convexCall.mutation(fns.requestsCancel, {
4286
- actor,
4287
- paymentRequestId: requestId
4288
- })), (request) => mapActorRequest(request))
4510
+ cancel: (requestId, options) => {
4511
+ const controls = deps.invocationControls?.(options) ?? options;
4512
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.requests.cancel, Effect.suspend(() => convexCall.mutation(fns.requestsCancel, copyInvocationObservation(controls, {
4513
+ actor,
4514
+ paymentRequestId: requestId
4515
+ }))), (request) => mapActorRequest(request)), controls, CAPXUL_OPERATIONS.requests.cancel, deps.runPromise);
4516
+ }
4289
4517
  },
4290
4518
  inbox: {
4291
- list: (options) => mapOk$1(CAPXUL_OPERATIONS.inbox.list, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.inbox.list, () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
4292
- approve: async (input, options) => {
4293
- const result = await awaitableConvex(options?.signal, CAPXUL_OPERATIONS.inbox.approve, () => convexCall.mutation(fns.inboxApprove, {
4519
+ list: (options) => {
4520
+ const controls = deps.invocationControls?.(options) ?? options;
4521
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.inbox.list, Effect.suspend(() => convexCall.query(fns.inboxList, copyInvocationObservation(controls, { actor }))), (items) => items.map(mapInboxItem)), controls, CAPXUL_OPERATIONS.inbox.list, deps.runPromise);
4522
+ },
4523
+ approve: (input, options) => {
4524
+ const controls = deps.invocationControls?.(options) ?? options;
4525
+ return runPortEffect(Effect.suspend(() => convexCall.mutation(fns.inboxApprove, copyInvocationObservation(controls, {
4294
4526
  actor,
4295
4527
  paymentRequestId: input.requestId,
4296
4528
  ...input.timing === void 0 ? {} : { timing: input.timing },
4297
4529
  ...input.permissionId === void 0 ? {} : { permissionId: input.permissionId }
4298
- }));
4299
- if (!result.ok) return result;
4300
- return mapApprovedInboxPayment(result.value, input);
4530
+ }))).pipe(Effect.flatMap((prepared) => {
4531
+ const result = mapApprovedInboxPayment(prepared, input);
4532
+ return result.ok ? Effect.succeed(result.value) : Effect.fail({ publicError: result.error });
4533
+ })), controls, CAPXUL_OPERATIONS.inbox.approve, deps.runPromise);
4301
4534
  },
4302
- decline: (requestId, options) => mapOk$1(CAPXUL_OPERATIONS.inbox.decline, awaitableConvex(options?.signal, CAPXUL_OPERATIONS.inbox.decline, () => convexCall.mutation(fns.inboxDecline, {
4303
- actor,
4304
- paymentRequestId: requestId
4305
- })), mapInboxItem)
4535
+ decline: (requestId, options) => {
4536
+ const controls = deps.invocationControls?.(options) ?? options;
4537
+ return runPortEffect(mapReply(CAPXUL_OPERATIONS.inbox.decline, Effect.suspend(() => convexCall.mutation(fns.inboxDecline, copyInvocationObservation(controls, {
4538
+ actor,
4539
+ paymentRequestId: requestId
4540
+ }))), mapInboxItem), controls, CAPXUL_OPERATIONS.inbox.decline, deps.runPromise);
4541
+ }
4306
4542
  },
4307
4543
  profile: {
4308
4544
  get: (options) => {
@@ -4379,22 +4615,12 @@ function missingConvexCall(operation) {
4379
4615
  * promise and the caller's `if (!result.ok)` never runs (ADR-0023: errors are
4380
4616
  * values, and a code crosses the seam).
4381
4617
  */
4382
- async function mapOk$1(operation, resultOrPromise, f) {
4383
- const result = await resultOrPromise;
4384
- if (!result.ok) return result;
4385
- try {
4386
- return {
4387
- ok: true,
4388
- value: f(result.value)
4389
- };
4390
- } catch (cause) {
4391
- return {
4392
- ok: false,
4393
- error: cause instanceof CapxulError ? cause : Errors.providerError("convex", operation, cause)
4394
- };
4395
- }
4618
+ function mapReply(operation, program, project) {
4619
+ return program.pipe(Effect.flatMap((value) => Effect.try({
4620
+ try: () => project(value),
4621
+ catch: (cause) => ({ publicError: cause instanceof CapxulError ? cause : Errors.providerError("convex", operation, cause) })
4622
+ })));
4396
4623
  }
4397
- const awaitableConvex = runIfActive;
4398
4624
  const ADDRESS_BOOK_RELATIONSHIPS = [
4399
4625
  "paid",
4400
4626
  "paidBy",
@@ -4520,25 +4746,11 @@ function normalizeRefForBackend$1(ref, field) {
4520
4746
  email: nonEmptyRefValue$1(ref.email, "email")
4521
4747
  }
4522
4748
  };
4523
- case "orgHandle": return {
4749
+ case "address": return {
4524
4750
  ok: true,
4525
4751
  value: {
4526
- kind: "orgHandle",
4527
- orgHandle: nonEmptyRefValue$1(ref.orgHandle, "orgHandle")
4528
- }
4529
- };
4530
- case "capxulUserId": return {
4531
- ok: true,
4532
- value: {
4533
- kind: "capxulUserId",
4534
- capxulUserId: nonEmptyRefValue$1(ref.capxulUserId, "capxulUserId")
4535
- }
4536
- };
4537
- case "payeeId": return {
4538
- ok: true,
4539
- value: {
4540
- kind: "payeeId",
4541
- payeeId: nonEmptyRefValue$1(ref.payeeId, "payeeId")
4752
+ kind: "address",
4753
+ address: toAddress(ref.address)
4542
4754
  }
4543
4755
  };
4544
4756
  case "party": return {
@@ -4776,6 +4988,8 @@ function makeAccountMethods(deps) {
4776
4988
  return {
4777
4989
  methods: {
4778
4990
  ...makeActorRelationshipMethods({
4991
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise },
4992
+ ...deps.invocationControls === void 0 ? {} : { invocationControls: deps.invocationControls },
4779
4993
  actor: { kind: "account" },
4780
4994
  ...deps.convexCall === void 0 ? {} : { convexCall: deps.convexCall },
4781
4995
  ...deps.profileMethods === void 0 ? {} : { accountProfileMethods: deps.profileMethods }
@@ -4802,10 +5016,7 @@ function makeAccountMethods(deps) {
4802
5016
  const financialOpsContract = {
4803
5017
  me: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].me),
4804
5018
  depositInstructions: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].depositInstructions),
4805
- resolveHandle: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].resolveHandle),
4806
- createPayee: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/mutations"].createPayee),
4807
- getPayee: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].getPayee),
4808
- resolvePayee: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].resolvePayee),
5019
+ resolveRecipient: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/queries"].resolveRecipient),
4809
5020
  addDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].add),
4810
5021
  listDestinations: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].list),
4811
5022
  removeDestination: makeFunctionReference(CAPXUL_FUNCTIONS["financialOps/destinations"].remove),
@@ -4821,6 +5032,7 @@ const financialOpsContract = {
4821
5032
  //#endregion
4822
5033
  //#region src/contract/money-execution.ts
4823
5034
  const moneyExecutionContract = {
5035
+ abandonPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].abandonPaymentExecution),
4824
5036
  preparePermissionExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePermissionExecution),
4825
5037
  preparePaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/actions"].preparePaymentExecution),
4826
5038
  prepareOrganizationPaymentExecution: makeFunctionReference(CAPXUL_FUNCTIONS["moneyExecution/paymentCommandActions"].prepareOrganizationPaymentExecution),
@@ -4831,7 +5043,7 @@ const moneyExecutionContract = {
4831
5043
  };
4832
5044
  //#endregion
4833
5045
  //#region package.json
4834
- var version = "3.2.0";
5046
+ var version = "4.0.1";
4835
5047
  //#endregion
4836
5048
  //#region src/telemetry/exception-projection.ts
4837
5049
  /** Fixed fallback for failures that have no safe message. */
@@ -4887,7 +5099,16 @@ function postHogFailureObservation(policy, fixedSnapshot) {
4887
5099
  const directSnapshot = callStartSnapshot === void 0 ? policy.snapshot() : void 0;
4888
5100
  if (!(callStartSnapshot?.active ?? directSnapshot?.active) || policy.client === null || policy.client === void 0) return;
4889
5101
  const safeFailure = sanitizeFailureObservation(failure);
4890
- return [safeFailure, postHogProperties(safeFailure, callStartSnapshot?.context ?? directSnapshot?.context)];
5102
+ const directContext = callStartSnapshot?.context ?? directSnapshot?.context;
5103
+ const actorId = callStartSnapshot?.actorId;
5104
+ return [safeFailure, {
5105
+ ...postHogProperties(safeFailure, directContext),
5106
+ ...actorId !== void 0 && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(actorId) ? {
5107
+ actor_id: actorId,
5108
+ actor_kind: "authenticated",
5109
+ distinct_id: actorId
5110
+ } : {}
5111
+ }];
4891
5112
  };
4892
5113
  const captureOperationFailure = (failure) => {
4893
5114
  const prepared = prepare(failure);
@@ -4992,7 +5213,8 @@ function observeSdkClient(client, adapter, snapshot) {
4992
5213
  };
4993
5214
  const processOutput = (output, path, invocation) => {
4994
5215
  if (isFailedResult(output)) {
4995
- report(adapter, "operation", path.join("."), output.error, invocation);
5216
+ const captured = readFailureInvocationSnapshot(output);
5217
+ report(adapter, "operation", path.join("."), output.error, captured ?? invocation, void 0, captured !== void 0);
4996
5218
  return output;
4997
5219
  }
4998
5220
  if (isCapxulResult(output)) return output;
@@ -5024,7 +5246,7 @@ function reportedByMachine(cause) {
5024
5246
  }
5025
5247
  return false;
5026
5248
  }
5027
- function report(adapter, kind, operation, cause, invocation, origin) {
5249
+ function report(adapter, kind, operation, cause, invocation, origin, authoritativeSnapshot = false) {
5028
5250
  if (origin === "machine") {
5029
5251
  let link = cause;
5030
5252
  for (let depth = 0; depth < 8 && typeof link === "object" && link !== null; depth++) {
@@ -5036,7 +5258,7 @@ function report(adapter, kind, operation, cause, invocation, origin) {
5036
5258
  const kindName = normalizeErrorKind(errorKind(cause));
5037
5259
  const context = sanitizeObservationContext({
5038
5260
  ...invocation.context,
5039
- ...isCapxulError(cause) && cause.correlationId !== void 0 ? { correlationId: cause.correlationId } : {}
5261
+ ...!authoritativeSnapshot && isCapxulError(cause) && cause.correlationId !== void 0 ? { correlationId: cause.correlationId } : {}
5040
5262
  });
5041
5263
  const detail = failureDetail(cause);
5042
5264
  const evidence = failureEvidence(cause);
@@ -5050,6 +5272,7 @@ function report(adapter, kind, operation, cause, invocation, origin) {
5050
5272
  ...evidence
5051
5273
  }, {
5052
5274
  active: invocation.active,
5275
+ ...invocation.actorId === void 0 ? {} : { actorId: invocation.actorId },
5053
5276
  ...context === void 0 ? {} : { context }
5054
5277
  });
5055
5278
  try {
@@ -5542,7 +5765,11 @@ function emitPaymentInitiated(telemetry, input) {
5542
5765
  name: "payment_initiated",
5543
5766
  props: {
5544
5767
  kind: input.kind,
5545
- payment_id: input.paymentId
5768
+ payment_id: input.paymentId,
5769
+ payment_lifecycle_id: `payment_lifecycle_${input.paymentId}`,
5770
+ ...input.commandId === void 0 ? {} : { command_id: input.commandId },
5771
+ ...input.executionId === void 0 ? {} : { execution_id: input.executionId },
5772
+ ...input.recipient
5546
5773
  }
5547
5774
  });
5548
5775
  }
@@ -5574,7 +5801,17 @@ async function fingerprintPaymentIntent(intent) {
5574
5801
  function matchesIntent(expected) {
5575
5802
  return async (request) => await fingerprintPaymentIntent(request) === await fingerprintPaymentIntent(expected);
5576
5803
  }
5577
- async function executePrepared(deps, prepare, isExpectedRequest, signal) {
5804
+ async function abandonPrepared$1(deps, executionId, closePayment, reason, result, onPreparedClosed, controls) {
5805
+ if (!closePayment) return result;
5806
+ const abandoned = await runIfActive(void 0, CAPXUL_OPERATIONS.moneyExecution.abandonPaymentExecution, () => withInvocationParentSpan(Effect.suspend(() => deps.convexCall.action(deps.functions.abandonPaymentExecution, copyInvocationObservation(controls, { input: {
5807
+ executionId,
5808
+ reason
5809
+ } }))), controls), deps.runPromise);
5810
+ if (!abandoned.ok) return abandoned;
5811
+ if (abandoned.value) onPreparedClosed?.();
5812
+ return result;
5813
+ }
5814
+ async function executePrepared(deps, prepare, isExpectedRequest, closePaymentOnExit, onPreparedClosed, signal, controls) {
5578
5815
  if (isAborted$2(signal)) return {
5579
5816
  ok: false,
5580
5817
  error: Errors.cancelled({ operation: "payments" })
@@ -5595,48 +5832,61 @@ async function executePrepared(deps, prepare, isExpectedRequest, signal) {
5595
5832
  }
5596
5833
  const prepared = await prepare(signerAddress);
5597
5834
  if (!prepared.ok) return prepared;
5598
- if (!await isExpectedRequest(prepared.value.request)) return {
5835
+ if (!await isExpectedRequest(prepared.value.request)) return abandonPrepared$1(deps, prepared.value.executionId, closePaymentOnExit, "prepared_mismatch", {
5599
5836
  ok: false,
5600
5837
  error: Errors.invalidInput("payment", "prepared command mismatch")
5601
- };
5838
+ }, onPreparedClosed, controls);
5602
5839
  const expectedSafe = deriveCapxulSafeAddress({ email: session.email });
5603
- if (prepared.value.chainId !== deps.chainId || prepared.value.signerAddress.toLowerCase() !== signerAddress.toLowerCase() || prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return {
5840
+ if (prepared.value.chainId !== deps.chainId || prepared.value.signerAddress.toLowerCase() !== signerAddress.toLowerCase() || prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return abandonPrepared$1(deps, prepared.value.executionId, closePaymentOnExit, "prepared_mismatch", {
5604
5841
  ok: false,
5605
5842
  error: Errors.invalidInput("payment", "prepared authority mismatch")
5606
- };
5607
- if (isAborted$2(signal)) return {
5843
+ }, onPreparedClosed, controls);
5844
+ if (isAborted$2(signal)) return abandonPrepared$1(deps, prepared.value.executionId, closePaymentOnExit, "cancelled", {
5608
5845
  ok: false,
5609
5846
  error: Errors.cancelled({ operation: "payments" })
5610
- };
5847
+ }, onPreparedClosed, controls);
5848
+ if (prepared.value.emitPaymentInitiated && "items" in prepared.value.request) for (const [index, item] of prepared.value.request.items.entries()) {
5849
+ const paymentId = prepared.value.paymentIds[index];
5850
+ const recipient = prepared.value.recipientObservations[index];
5851
+ if (paymentId === void 0 || recipient === void 0) continue;
5852
+ const paymentType = paymentTypeForDocumentEnvelope(item.document) ?? item.paymentType ?? "unspecified";
5853
+ await emitPaymentInitiated(deps.telemetry, {
5854
+ commandId: prepared.value.commandId,
5855
+ executionId: prepared.value.executionId,
5856
+ paymentId,
5857
+ kind: paymentType === "unspecified" ? "quick_pay" : paymentType,
5858
+ recipient
5859
+ });
5860
+ }
5611
5861
  let signature;
5612
5862
  try {
5613
5863
  signature = await deps.signer.signUserOpHash(prepared.value.digest);
5614
5864
  } catch (cause) {
5615
- return {
5865
+ return abandonPrepared$1(deps, prepared.value.executionId, closePaymentOnExit, "signer_rejected", {
5616
5866
  ok: false,
5617
5867
  error: signerFailure(deps.signer.source, "signUserOpHash", cause)
5618
- };
5868
+ }, onPreparedClosed, controls);
5619
5869
  }
5620
- if (isAborted$2(signal)) return {
5870
+ if (isAborted$2(signal)) return abandonPrepared$1(deps, prepared.value.executionId, closePaymentOnExit, "cancelled", {
5621
5871
  ok: false,
5622
5872
  error: Errors.cancelled({ operation: "payments" })
5623
- };
5624
- return runIfActive(void 0, CAPXUL_OPERATIONS.payments.submitCommandExecution, () => deps.convexCall.action(deps.functions.submitPaymentCommandExecution, { input: {
5873
+ }, onPreparedClosed, controls);
5874
+ return runIfActive(void 0, CAPXUL_OPERATIONS.payments.submitCommandExecution, () => withInvocationParentSpan(Effect.suspend(() => deps.convexCall.action(deps.functions.submitPaymentCommandExecution, copyInvocationObservation(controls, { input: {
5625
5875
  executionId: prepared.value.executionId,
5626
5876
  signature
5627
- } }));
5877
+ } }))), controls), deps.runPromise);
5628
5878
  }
5629
- function executePaymentLifecycle(deps, intent, signal) {
5630
- return executePrepared(deps, (signerAddress) => runIfActive(signal, CAPXUL_OPERATIONS.payments.prepareLifecycleExecution, () => deps.convexCall.action(deps.functions.preparePaymentLifecycleExecution, { input: {
5879
+ function executePaymentLifecycle(deps, intent, signal, controls) {
5880
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, CAPXUL_OPERATIONS.payments.prepareLifecycleExecution, () => withInvocationParentSpan(Effect.suspend(() => deps.convexCall.action(deps.functions.preparePaymentLifecycleExecution, copyInvocationObservation(controls, { input: {
5631
5881
  signerAddress,
5632
5882
  intent
5633
- } })), matchesIntent(intent), signal);
5883
+ } }))), controls), deps.runPromise), matchesIntent(intent), false, void 0, signal, controls);
5634
5884
  }
5635
- function executeOrganizationPayment(deps, input, signal) {
5636
- return executePrepared(deps, (signerAddress) => runIfActive(signal, CAPXUL_OPERATIONS.organizationPayments.prepareExecution, () => deps.convexCall.action(deps.functions.prepareOrganizationPaymentExecution, { input: {
5885
+ function executeOrganizationPayment(deps, input, signal, onPreparedClosed, controls) {
5886
+ return executePrepared(deps, (signerAddress) => runIfActive(signal, CAPXUL_OPERATIONS.organizationPayments.prepareExecution, () => withInvocationParentSpan(Effect.suspend(() => deps.convexCall.action(deps.functions.prepareOrganizationPaymentExecution, copyInvocationObservation(controls, { input: {
5637
5887
  ...input,
5638
5888
  signerAddress
5639
- } })), matchesIntent(input), signal);
5889
+ } }))), controls), deps.runPromise), matchesIntent(input), true, onPreparedClosed, signal, controls);
5640
5890
  }
5641
5891
  //#endregion
5642
5892
  //#region src/surface/payment-execution.ts
@@ -5668,7 +5918,16 @@ async function signerCall(source, operation, run) {
5668
5918
  };
5669
5919
  }
5670
5920
  }
5671
- async function executePersonalPayment(deps, payment, signal, requestKey) {
5921
+ async function abandonPrepared(deps, executionId, reason, result, onPreparedClosed) {
5922
+ const abandoned = await runIfActive(void 0, CAPXUL_OPERATIONS.moneyExecution.abandonPaymentExecution, () => deps.convexCall.action(deps.functions.abandonPaymentExecution, { input: {
5923
+ executionId,
5924
+ reason
5925
+ } }));
5926
+ if (!abandoned.ok) return abandoned;
5927
+ if (abandoned.value) onPreparedClosed?.();
5928
+ return result;
5929
+ }
5930
+ async function executePersonalPayment(deps, payment, signal, requestKey, onPreparedClosed) {
5672
5931
  if (isAborted$1(signal)) return cancelled(CAPXUL_OPERATIONS.payments.pay);
5673
5932
  if (deps.signer === void 0) return mismatch("signer", "payments.pay requires a configured CapxulSigner");
5674
5933
  const session = deps.actor.authSession();
@@ -5686,18 +5945,21 @@ async function executePersonalPayment(deps, payment, signal, requestKey) {
5686
5945
  payment
5687
5946
  } }));
5688
5947
  if (!prepared.ok) return prepared;
5689
- if (prepared.value.requestKey !== resolvedRequestKey || canonicalJson(prepared.value.payment) !== canonicalJson(payment)) return mismatch("payment", "prepared Payment execution uses another request");
5690
- if (prepared.value.chainId !== deps.chainId) return mismatch("chainId", "prepared Payment execution uses another chain");
5691
- if (prepared.value.signerAddress.toLowerCase() !== signerAddress.value.toLowerCase()) return mismatch("signerAddress", "prepared Payment execution uses another signer");
5692
- if (prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return mismatch("userOpSenderSafe", "prepared Payment execution uses another Account Safe");
5948
+ if (prepared.value.requestKey !== resolvedRequestKey || canonicalJson(prepared.value.payment) !== canonicalJson(payment)) return abandonPrepared(deps, prepared.value.executionId, "prepared_mismatch", mismatch("payment", "prepared Payment execution uses another request"), onPreparedClosed);
5949
+ if (prepared.value.chainId !== deps.chainId) return abandonPrepared(deps, prepared.value.executionId, "prepared_mismatch", mismatch("chainId", "prepared Payment execution uses another chain"), onPreparedClosed);
5950
+ if (prepared.value.signerAddress.toLowerCase() !== signerAddress.value.toLowerCase()) return abandonPrepared(deps, prepared.value.executionId, "prepared_mismatch", mismatch("signerAddress", "prepared Payment execution uses another signer"), onPreparedClosed);
5951
+ if (prepared.value.userOpSenderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return abandonPrepared(deps, prepared.value.executionId, "prepared_mismatch", mismatch("userOpSenderSafe", "prepared Payment execution uses another Account Safe"), onPreparedClosed);
5693
5952
  if (prepared.value.emitPaymentInitiated) await emitPaymentInitiated(deps.telemetry, {
5694
5953
  kind: prepared.value.purposeKind,
5695
- paymentId: prepared.value.paymentId
5954
+ paymentId: prepared.value.paymentId,
5955
+ commandId: prepared.value.commandId,
5956
+ executionId: prepared.value.executionId,
5957
+ recipient: prepared.value.recipientObservation
5696
5958
  });
5697
- if (isAborted$1(signal)) return cancelled(CAPXUL_OPERATIONS.payments.pay);
5959
+ if (isAborted$1(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
5698
5960
  const signature = await signerCall(deps.signer.source, "signUserOpHash", () => deps.signer.signUserOpHash(prepared.value.digest));
5699
- if (!signature.ok) return signature;
5700
- if (isAborted$1(signal)) return cancelled(CAPXUL_OPERATIONS.payments.pay);
5961
+ if (!signature.ok) return abandonPrepared(deps, prepared.value.executionId, "signer_rejected", signature, onPreparedClosed);
5962
+ if (isAborted$1(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
5701
5963
  return runIfActive(void 0, CAPXUL_OPERATIONS.payments.submitExecution, () => deps.convexCall.action(deps.functions.submitPaymentExecution, { input: {
5702
5964
  executionId: prepared.value.executionId,
5703
5965
  signature: signature.value
@@ -5925,6 +6187,30 @@ async function waitForPaymentSubmission(submission, signal, operation, onCancel
5925
6187
  });
5926
6188
  });
5927
6189
  }
6190
+ function normalizeActivityDetail(detail) {
6191
+ if (detail === null) return null;
6192
+ if (detail.kind === "payment") {
6193
+ if (detail.evidence === null) return detail;
6194
+ return {
6195
+ ...detail,
6196
+ evidence: {
6197
+ ...detail.evidence,
6198
+ inclusion: "included",
6199
+ verification: "verified",
6200
+ finality: "finalized"
6201
+ }
6202
+ };
6203
+ }
6204
+ return {
6205
+ ...detail,
6206
+ evidence: {
6207
+ ...detail.evidence,
6208
+ inclusion: "included",
6209
+ verification: "verified",
6210
+ canonicalState: "finalized"
6211
+ }
6212
+ };
6213
+ }
5928
6214
  function paymentExecutionIntent(input) {
5929
6215
  if (actorReferenceToBackend(input.actor)?.kind === "org") return {
5930
6216
  ok: false,
@@ -5937,6 +6223,7 @@ function paymentExecutionIntent(input) {
5937
6223
  value: {
5938
6224
  to: to.value,
5939
6225
  amount: input.amount,
6226
+ ...input.externalAddressAcknowledged === void 0 ? {} : { externalAddressAcknowledged: input.externalAddressAcknowledged },
5940
6227
  ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
5941
6228
  ...input.document === void 0 ? {} : { document: input.document },
5942
6229
  ...input.timing === void 0 ? {} : { timing: input.timing },
@@ -5974,6 +6261,7 @@ function makeFinancialOpsMethods(deps) {
5974
6261
  let flight = inFlightPersonalPayments.get(sharedKey);
5975
6262
  if (flight === void 0) {
5976
6263
  const controller = new AbortController();
6264
+ const requestState = { resolved: false };
5977
6265
  const submission = executePersonalPayment({
5978
6266
  actor: deps.actor,
5979
6267
  chainId: deps.chainId,
@@ -5981,10 +6269,11 @@ function makeFinancialOpsMethods(deps) {
5981
6269
  functions: executionFns,
5982
6270
  ...deps.signer === void 0 ? {} : { signer: deps.signer },
5983
6271
  ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
5984
- }, payment.value, controller.signal, requestKey.key);
6272
+ }, payment.value, controller.signal, requestKey.key, () => requestState.resolved = true);
5985
6273
  flight = {
5986
6274
  controller,
5987
6275
  promise: submission,
6276
+ requestState,
5988
6277
  waiters: 0,
5989
6278
  settled: false
5990
6279
  };
@@ -6022,7 +6311,7 @@ function makeFinancialOpsMethods(deps) {
6022
6311
  }
6023
6312
  release(false);
6024
6313
  try {
6025
- await requestKey.finish(submitted.ok);
6314
+ await requestKey.finish(submitted.ok || flight.requestState.resolved);
6026
6315
  } catch {}
6027
6316
  return mapOk(submitted, (value) => normalizePaymentTiming(value.payment));
6028
6317
  };
@@ -6036,87 +6325,61 @@ function makeFinancialOpsMethods(deps) {
6036
6325
  chainId: deps.chainId,
6037
6326
  convexCall: deps.convexCall,
6038
6327
  functions: executionFns,
6039
- signer: deps.signer
6040
- }
6041
- };
6042
- const runLifecycle = async (intent, signal) => {
6043
- const execution = lifecycleDependencies();
6044
- if (!execution.ok) return execution;
6045
- try {
6046
- const submitted = await executePaymentLifecycle(execution.value, intent, signal);
6047
- if (!submitted.ok) return submitted;
6048
- const payments = submitted.value.payments;
6049
- const payment = payments[0];
6050
- if (payment === void 0 || payments.length !== 1) return {
6051
- ok: false,
6052
- error: Errors.unknown()
6053
- };
6054
- return {
6055
- ok: true,
6056
- value: normalizePaymentTiming(payment)
6057
- };
6058
- } catch (cause) {
6059
- return {
6060
- ok: false,
6061
- error: cause instanceof CapxulError ? cause : Errors.unknown(cause)
6062
- };
6328
+ signer: deps.signer,
6329
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise }
6063
6330
  }
6064
6331
  };
6332
+ const runLifecycle = (intent, controls, operation) => runCapxulEffect(Effect.gen(function* () {
6333
+ const captured = carryInvocationParentSpan(controls, yield* Effect.currentSpan.pipe(Effect.orDie));
6334
+ const result = yield* Effect.tryPromise({
6335
+ try: async () => {
6336
+ const execution = lifecycleDependencies();
6337
+ if (!execution.ok) return execution;
6338
+ const submitted = await executePaymentLifecycle(execution.value, intent, controls?.signal, captured);
6339
+ if (!submitted.ok) return submitted;
6340
+ const payments = submitted.value.payments;
6341
+ const payment = payments[0];
6342
+ if (payment === void 0 || payments.length !== 1) return {
6343
+ ok: false,
6344
+ error: Errors.unknown()
6345
+ };
6346
+ return {
6347
+ ok: true,
6348
+ value: normalizePaymentTiming(payment)
6349
+ };
6350
+ },
6351
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
6352
+ });
6353
+ return yield* result.ok ? Effect.succeed(result.value) : Effect.fail(result.error);
6354
+ }), observationOnlyControls(controls), operation, deps.runPromise);
6355
+ const retryPayment = (paymentId, controls) => runCapxulEffect(Effect.gen(function* () {
6356
+ const captured = carryInvocationParentSpan(controls, yield* Effect.currentSpan.pipe(Effect.orDie));
6357
+ const result = yield* Effect.tryPromise({
6358
+ try: async () => {
6359
+ const execution = lifecycleDependencies();
6360
+ if (!execution.ok) return execution;
6361
+ const submitted = await executePaymentLifecycle(execution.value, {
6362
+ kind: "retry",
6363
+ paymentId
6364
+ }, controls?.signal, captured);
6365
+ return submitted.ok ? {
6366
+ ok: true,
6367
+ value: submitted.value.payments.map((payment) => normalizePaymentTiming(payment))
6368
+ } : submitted;
6369
+ },
6370
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
6371
+ });
6372
+ return yield* result.ok ? Effect.succeed(result.value) : Effect.fail(result.error);
6373
+ }), observationOnlyControls(controls), CAPXUL_OPERATIONS.payments.retry, deps.runPromise);
6065
6374
  return {
6066
6375
  me: {
6067
6376
  get: (options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.me.get, () => deps.convexCall.query(fns.me, {})),
6068
6377
  depositInstructions: (options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.me.depositInstructions, () => deps.convexCall.query(fns.depositInstructions, {}).pipe(Effect.tap(() => Effect.promise(() => emitDepositInitiated(deps.telemetry)))))
6069
6378
  },
6070
- handles: { resolve: (handle, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.handles.resolve, () => deps.convexCall.query(fns.resolveHandle, { handle })) },
6071
- payees: {
6072
- create: (input, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payees.create, () => deps.convexCall.mutation(fns.createPayee, {
6073
- label: input.label,
6074
- recipient: input.recipient,
6075
- ...input.handle === void 0 ? {} : { handle: input.handle }
6076
- })),
6077
- get: (payeeId, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payees.get, () => deps.convexCall.query(fns.getPayee, { payeeId })),
6078
- resolve: (recipient, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payees.resolve, () => deps.convexCall.query(fns.resolvePayee, { recipient }))
6079
- },
6080
6379
  targets: { resolve: async (reference, options) => {
6081
- switch (reference.kind) {
6082
- case "handle": return mapOk(await runIfActive(options?.signal, CAPXUL_OPERATIONS.targets.resolve.handle, () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
6083
- case "email": return mapOk(await runIfActive(options?.signal, CAPXUL_OPERATIONS.targets.resolve.email, () => deps.convexCall.query(fns.resolvePayee, { recipient: reference.email })), (target) => resolvedTargetFromResolution(reference, target));
6084
- case "organization": {
6085
- const resolved = await runIfActive(options?.signal, CAPXUL_OPERATIONS.targets.resolve.organization, () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }));
6086
- if (!resolved.ok) return {
6087
- ok: false,
6088
- error: resolved.error
6089
- };
6090
- if (resolved.value.kind !== "org") return {
6091
- ok: false,
6092
- error: Errors.invalidInput("reference", "organization handle could not be resolved")
6093
- };
6094
- return {
6095
- ok: true,
6096
- value: resolvedTargetFromResolution(reference, resolved.value)
6097
- };
6098
- }
6099
- case "payee": {
6100
- const payee = await runIfActive(options?.signal, CAPXUL_OPERATIONS.targets.resolve.payee, () => deps.convexCall.query(fns.getPayee, { payeeId: reference.id }));
6101
- if (!payee.ok) return {
6102
- ok: false,
6103
- error: payee.error
6104
- };
6105
- if (payee.value === null) return {
6106
- ok: false,
6107
- error: Errors.invalidInput("reference", "payee not found")
6108
- };
6109
- return {
6110
- ok: true,
6111
- value: resolvedTargetFromPayee(reference, payee.value)
6112
- };
6113
- }
6114
- case "party":
6115
- case "destination": return Promise.resolve({
6116
- ok: false,
6117
- error: Errors.notImplemented("targets", `resolve.${reference.kind}`)
6118
- });
6119
- }
6380
+ const recipient = normalizeTargetForBackend(reference, "reference");
6381
+ if (!recipient.ok) return recipient;
6382
+ return mapOk(await runIfActive(options?.signal, CAPXUL_OPERATIONS.recipient.resolve, () => deps.convexCall.query(fns.resolveRecipient, { recipient: recipient.value })), resolvedTargetFromResolution);
6120
6383
  } },
6121
6384
  destinations: {
6122
6385
  add: async (input, options) => {
@@ -6159,57 +6422,64 @@ function makeFinancialOpsMethods(deps) {
6159
6422
  },
6160
6423
  payments: {
6161
6424
  pay,
6425
+ retry: (paymentId, options) => retryPayment(paymentId, deps.invocationControls?.(options) ?? options),
6162
6426
  createCommitment: (input, options) => pay(input, options),
6163
6427
  claim: (paymentId, options) => runLifecycle({
6164
6428
  kind: "claim",
6165
6429
  paymentId
6166
- }, options?.signal),
6430
+ }, deps.invocationControls?.(options) ?? options, CAPXUL_OPERATIONS.payments.claim),
6167
6431
  list: async (options) => mapOk(await runIfActive(options?.signal, CAPXUL_OPERATIONS.payments.list, () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming)),
6168
6432
  get: async (paymentId, options) => mapOk(await runIfActive(options?.signal, CAPXUL_OPERATIONS.payments.get, () => deps.convexCall.query(fns.getPayment, { paymentId })), (payment) => payment === null ? null : normalizePaymentTiming(payment)),
6169
6433
  cancel: (paymentId, options) => runLifecycle({
6170
6434
  kind: "cancel",
6171
6435
  paymentId
6172
- }, options?.signal),
6436
+ }, deps.invocationControls?.(options) ?? options, CAPXUL_OPERATIONS.payments.cancel),
6173
6437
  redirect: async (input, options) => {
6438
+ const controls = deps.invocationControls?.(options) ?? options;
6174
6439
  const recipient = normalizeTargetForBackend(input.to, "to");
6175
- if (!recipient.ok) return recipient;
6440
+ if (!recipient.ok) return runCapxulEffect(Effect.fail(recipient.error), observationOnlyControls(controls), CAPXUL_OPERATIONS.payments.redirect, deps.runPromise);
6176
6441
  return runLifecycle({
6177
6442
  kind: "redirect",
6178
6443
  paymentId: input.paymentId,
6179
6444
  recipient: recipient.value
6180
- }, options?.signal);
6445
+ }, controls, CAPXUL_OPERATIONS.payments.redirect);
6181
6446
  }
6182
6447
  },
6183
6448
  activity: {
6184
- list: (params, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.activity.list, () => deps.convexCall.query(fns.activityList, { input: {
6185
- ...activityActorField(params?.actor),
6186
- ...params?.cursor === void 0 ? {} : { cursor: params.cursor },
6187
- ...params?.limit === void 0 ? {} : { limit: params.limit },
6188
- ...params?.range === void 0 ? {} : { range: params.range },
6189
- ...params?.filter === void 0 ? {} : { filter: params.filter }
6190
- } })),
6191
- summary: (params, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.activity.summary, () => deps.convexCall.query(fns.activitySummary, { input: {
6192
- ...activityActorField(params?.actor),
6193
- ...params?.window === void 0 ? {} : { window: params.window }
6194
- } })),
6449
+ list: (params, options) => {
6450
+ const controls = deps.invocationControls?.(options) ?? options;
6451
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(fns.activityList, copyInvocationObservation(controls, { input: {
6452
+ ...activityActorField(params?.actor),
6453
+ ...params?.cursor === void 0 ? {} : { cursor: params.cursor },
6454
+ ...params?.limit === void 0 ? {} : { limit: params.limit },
6455
+ ...params?.range === void 0 ? {} : { range: params.range },
6456
+ ...params?.filter === void 0 ? {} : { filter: params.filter }
6457
+ } }))), controls, CAPXUL_OPERATIONS.activity.list, deps.runPromise);
6458
+ },
6459
+ summary: (params, options) => {
6460
+ const controls = deps.invocationControls?.(options) ?? options;
6461
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(fns.activitySummary, copyInvocationObservation(controls, { input: {
6462
+ ...activityActorField(params?.actor),
6463
+ ...params?.window === void 0 ? {} : { window: params.window }
6464
+ } }))), controls, CAPXUL_OPERATIONS.activity.summary, deps.runPromise);
6465
+ },
6195
6466
  get: (reference, options) => {
6467
+ const controls = deps.invocationControls?.(options) ?? options;
6196
6468
  const actor = actorReferenceToBackend(options?.actor);
6197
- return runIfActive(options?.signal, CAPXUL_OPERATIONS.activity.get, () => deps.convexCall.query(fns.activityGet, {
6469
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(fns.activityGet, copyInvocationObservation(controls, {
6198
6470
  input: {
6199
6471
  kind: reference.kind,
6200
6472
  id: reference.id,
6201
6473
  ...reference.kind === "payment" ? activityActorField(reference.actor) : {}
6202
6474
  },
6203
6475
  ...actor === void 0 ? {} : { actor }
6204
- }));
6476
+ }))).pipe(Effect.map(normalizeActivityDetail)), controls, CAPXUL_OPERATIONS.activity.get, deps.runPromise);
6205
6477
  },
6206
6478
  annotate: (input, options) => {
6207
- if (input.actor !== void 0 && input.reference.kind === "payment" && input.reference.actor !== void 0 && !sameActor(input.actor, input.reference.actor)) return Promise.resolve({
6208
- ok: false,
6209
- error: Errors.invalidInput("reference.actor", "must match the annotation actor")
6210
- });
6479
+ const controls = deps.invocationControls?.(options) ?? options;
6480
+ if (input.actor !== void 0 && input.reference.kind === "payment" && input.reference.actor !== void 0 && !sameActor(input.actor, input.reference.actor)) return runCapxulEffect(Effect.fail(Errors.invalidInput("reference.actor", "must match the annotation actor")), controls, CAPXUL_OPERATIONS.activity.annotate, deps.runPromise);
6211
6481
  const referenceActor = input.reference.kind === "payment" ? activityActorField(input.reference.actor).actor : void 0;
6212
- return runIfActive(options?.signal, CAPXUL_OPERATIONS.activity.annotate, () => deps.convexCall.mutation(fns.activityAnnotate, { input: {
6482
+ return runPortEffect(Effect.suspend(() => deps.convexCall.mutation(fns.activityAnnotate, copyInvocationObservation(controls, { input: {
6213
6483
  ...activityActorField(input.actor),
6214
6484
  reference: input.reference.kind === "payment" && referenceActor !== void 0 ? {
6215
6485
  kind: "payment",
@@ -6222,7 +6492,7 @@ function makeFinancialOpsMethods(deps) {
6222
6492
  ...input.counterpartyLabel === void 0 ? {} : { counterpartyLabel: input.counterpartyLabel },
6223
6493
  ...input.accountingCategory === void 0 ? {} : { accountingCategory: input.accountingCategory },
6224
6494
  ...input.memo === void 0 ? {} : { memo: input.memo }
6225
- } }));
6495
+ } }))), controls, CAPXUL_OPERATIONS.activity.annotate, deps.runPromise);
6226
6496
  }
6227
6497
  },
6228
6498
  offramp: {
@@ -6248,8 +6518,14 @@ function makeFinancialOpsMethods(deps) {
6248
6518
  }
6249
6519
  },
6250
6520
  paymentDocuments: {
6251
- verify: (documentHash, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.paymentDocuments.verify, () => deps.convexCall.query(fns.verifyPaymentDocument, { documentHash })),
6252
- render: (documentHash, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.paymentDocuments.render, () => deps.convexCall.query(fns.renderStoredDocument, { documentHash }))
6521
+ verify: (documentHash, options) => {
6522
+ const controls = deps.invocationControls?.(options) ?? options;
6523
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(fns.verifyPaymentDocument, copyInvocationObservation(controls, { documentHash }))), controls, CAPXUL_OPERATIONS.paymentDocuments.verify, deps.runPromise);
6524
+ },
6525
+ render: (documentHash, options) => {
6526
+ const controls = deps.invocationControls?.(options) ?? options;
6527
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(fns.renderStoredDocument, copyInvocationObservation(controls, { documentHash }))), controls, CAPXUL_OPERATIONS.paymentDocuments.render, deps.runPromise);
6528
+ }
6253
6529
  }
6254
6530
  };
6255
6531
  }
@@ -6288,18 +6564,11 @@ function refFromTargetReference(reference, field) {
6288
6564
  email: reference.email
6289
6565
  }
6290
6566
  };
6291
- case "organization": return {
6567
+ case "address": return {
6292
6568
  ok: true,
6293
6569
  value: {
6294
- kind: "orgHandle",
6295
- orgHandle: reference.handle
6296
- }
6297
- };
6298
- case "payee": return {
6299
- ok: true,
6300
- value: {
6301
- kind: "payeeId",
6302
- payeeId: reference.id
6570
+ kind: "address",
6571
+ address: reference.address
6303
6572
  }
6304
6573
  };
6305
6574
  case "party": return {
@@ -6309,10 +6578,6 @@ function refFromTargetReference(reference, field) {
6309
6578
  partyId: reference.partyId
6310
6579
  }
6311
6580
  };
6312
- case "destination": return {
6313
- ok: false,
6314
- error: Errors.notImplemented("targets", "reference.destination")
6315
- };
6316
6581
  default: return {
6317
6582
  ok: false,
6318
6583
  error: Errors.invalidInput(field, "target must be a known TargetReference variant")
@@ -6367,39 +6632,28 @@ function targetReferenceFromBackendRef(ref) {
6367
6632
  kind: "email",
6368
6633
  email: ref.email
6369
6634
  };
6370
- case "orgHandle": return {
6371
- kind: "organization",
6372
- handle: ref.orgHandle
6373
- };
6374
- case "payeeId": return {
6375
- kind: "payee",
6376
- id: ref.payeeId
6635
+ case "address": return {
6636
+ kind: "address",
6637
+ address: ref.address
6377
6638
  };
6378
6639
  case "party": return {
6379
6640
  kind: "party",
6380
6641
  partyId: ref.partyId
6381
6642
  };
6382
- case "capxulUserId": throw Errors.notImplemented("targets", "reference.capxulUserId");
6383
6643
  }
6384
6644
  }
6385
- function resolvedTargetFromResolution(reference, resolution) {
6386
- const kind = resolution.kind === "org" ? "organization" : resolution.kind === "payee" ? "payee" : "person";
6645
+ function resolvedTargetFromResolution(resolution) {
6646
+ const kind = resolution.status === "known_party" ? resolution.partyKind === "org" ? "organization" : "person" : resolution.status === "external_address" ? "external_address" : "unresolved";
6387
6647
  return {
6388
- reference,
6648
+ reference: targetReferenceFromBackendRef(resolution.recipient),
6389
6649
  label: resolution.label,
6650
+ status: resolution.status,
6390
6651
  kind,
6391
- capabilities: {
6392
- canPay: true,
6393
- canRequest: true,
6394
- canPayout: false
6395
- }
6396
- };
6397
- }
6398
- function resolvedTargetFromPayee(reference, payee) {
6399
- return {
6400
- reference,
6401
- label: payee.label,
6402
- kind: "payee",
6652
+ safeAddress: toAddress(resolution.safeAddress),
6653
+ isCapxulAccount: resolution.isCapxulAccount,
6654
+ ...resolution.partyId === void 0 ? {} : { partyId: toPartyId(resolution.partyId) },
6655
+ ...resolution.handle === void 0 ? {} : { handle: resolution.handle },
6656
+ ...resolution.requiresAcknowledgement === void 0 ? {} : { requiresAcknowledgement: resolution.requiresAcknowledgement },
6403
6657
  capabilities: {
6404
6658
  canPay: true,
6405
6659
  canRequest: true,
@@ -6457,10 +6711,6 @@ function destinationFromBackend(destination) {
6457
6711
  };
6458
6712
  }
6459
6713
  function normalizeDestinationRefForBackend(ref, field) {
6460
- if (typeof ref === "object" && ref !== null && "kind" in ref && ref.kind === "capxulUserId") return {
6461
- ok: false,
6462
- error: Errors.notImplemented("targets", "reference.capxulUserId")
6463
- };
6464
6714
  return normalizeRefForBackend(ref, field);
6465
6715
  }
6466
6716
  function normalizeRefForBackend(ref, field) {
@@ -6488,25 +6738,11 @@ function normalizeRefForBackend(ref, field) {
6488
6738
  email: nonEmptyRefValue(ref.email, "email")
6489
6739
  }
6490
6740
  };
6491
- case "orgHandle": return {
6741
+ case "address": return {
6492
6742
  ok: true,
6493
6743
  value: {
6494
- kind: "orgHandle",
6495
- orgHandle: nonEmptyRefValue(ref.orgHandle, "orgHandle")
6496
- }
6497
- };
6498
- case "capxulUserId": return {
6499
- ok: true,
6500
- value: {
6501
- kind: "capxulUserId",
6502
- capxulUserId: nonEmptyRefValue(ref.capxulUserId, "capxulUserId")
6503
- }
6504
- };
6505
- case "payeeId": return {
6506
- ok: true,
6507
- value: {
6508
- kind: "payeeId",
6509
- payeeId: nonEmptyRefValue(ref.payeeId, "payeeId")
6744
+ kind: "address",
6745
+ address: toAddress(ref.address)
6510
6746
  }
6511
6747
  };
6512
6748
  case "party": return {
@@ -7553,7 +7789,7 @@ function makeSmartAccountMethods(deps) {
7553
7789
  }
7554
7790
  //#endregion
7555
7791
  //#region src/contract/identity.ts
7556
- const usernameAvailableQuery = makeFunctionReference(CAPXUL_FUNCTIONS["identity/queries"].usernameAvailable);
7792
+ const handleAvailableQuery = makeFunctionReference(CAPXUL_FUNCTIONS["identity/queries"].handleAvailable);
7557
7793
  //#endregion
7558
7794
  //#region src/surface/identity-deps.ts
7559
7795
  /** The single Context tag the profile atom + `identity.loadCurrent` resolve. */
@@ -7597,19 +7833,19 @@ function makeIdentityMethods(deps) {
7597
7833
  ok: false,
7598
7834
  error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.identity.completeProfile })
7599
7835
  };
7600
- if (typeof profile !== "object" || profile === null || typeof profile.displayName !== "string" || typeof profile.country !== "string" || typeof profile.username !== "string") return {
7836
+ if (typeof profile !== "object" || profile === null || typeof profile.displayName !== "string" || typeof profile.country !== "string" || typeof profile.handle !== "string") return {
7601
7837
  ok: false,
7602
7838
  error: Errors.invalidInput("profile", "invalid profile")
7603
7839
  };
7604
7840
  const displayName = profile.displayName.trim();
7605
- const username = profile.username.trim();
7841
+ const handle = profile.handle.trim();
7606
7842
  if (displayName.length === 0) return {
7607
7843
  ok: false,
7608
7844
  error: Errors.invalidInput("displayName", "must not be empty")
7609
7845
  };
7610
- if (username.length === 0) return {
7846
+ if (handle.length === 0) return {
7611
7847
  ok: false,
7612
- error: Errors.invalidInput("username", "must not be empty")
7848
+ error: Errors.invalidInput("handle", "must not be empty")
7613
7849
  };
7614
7850
  let country;
7615
7851
  try {
@@ -7630,98 +7866,259 @@ function makeIdentityMethods(deps) {
7630
7866
  email: session.email,
7631
7867
  displayName,
7632
7868
  country,
7633
- username
7869
+ handle
7634
7870
  }), options, CAPXUL_OPERATIONS.identity.completeProfile);
7635
7871
  },
7636
- async usernameAvailable(username, options) {
7872
+ async handleAvailable(handle, options) {
7637
7873
  if (options?.signal?.aborted) return {
7638
7874
  ok: false,
7639
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.identity.usernameAvailable })
7875
+ error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.identity.handleAvailable })
7640
7876
  };
7641
7877
  if (convexCall === void 0) return {
7642
7878
  ok: false,
7643
- error: Errors.notImplemented("identity", "usernameAvailable")
7879
+ error: Errors.notImplemented("identity", "handleAvailable")
7644
7880
  };
7645
- return runPortEffect(convexCall.query(usernameAvailableQuery, { username }));
7881
+ return runPortEffect(convexCall.query(handleAvailableQuery, { handle }));
7646
7882
  }
7647
7883
  };
7648
7884
  }
7649
7885
  //#endregion
7650
7886
  //#region src/surface/onboarding.ts
7651
- const USERNAME_PATTERN = /^[a-z0-9_]{3,30}$/;
7652
- function makeOnboardingMethods(deps) {
7653
- return { async completePerson(input, options) {
7654
- const isCancelled = () => options?.signal?.aborted === true;
7655
- if (typeof input !== "object" || input === null || typeof input.displayName !== "string" || typeof input.country !== "string" || typeof input.username !== "string" || !USERNAME_PATTERN.test(input.username.trim())) return {
7656
- ok: false,
7657
- error: Errors.invalidInput("username", "must be 3-30 characters of a-z, 0-9, or underscore")
7887
+ function normalizeHandleInput(input) {
7888
+ if (typeof input !== "string") return {
7889
+ ok: false,
7890
+ error: Errors.invalidInput("handle", "is required")
7891
+ };
7892
+ try {
7893
+ return {
7894
+ ok: true,
7895
+ value: validateHandle(input)
7658
7896
  };
7659
- const username = input.username.trim();
7660
- const session = await deps.restoreSession(options);
7661
- if (!session.ok) return session;
7662
- if (session.value === null) return {
7897
+ } catch (error) {
7898
+ if (isCapxulError(error)) return {
7663
7899
  ok: false,
7664
- error: Errors.notAuthenticated()
7900
+ error
7665
7901
  };
7666
- const available = await deps.usernameAvailable(username, options);
7667
- if (!available.ok) return available;
7668
- if (!available.value.available) return {
7902
+ return {
7669
7903
  ok: false,
7670
- error: Errors.invalidInput("username", "username is already taken")
7904
+ error: Errors.unknown(error)
7671
7905
  };
7672
- const completed = await deps.completeProfile({
7673
- ...input,
7674
- username: available.value.normalized
7675
- }, options);
7676
- if (!completed.ok) return completed;
7677
- const refreshed = await deps.refreshIdentity(options);
7678
- if (!refreshed.ok) return refreshed;
7679
- if (isCancelled()) return {
7906
+ }
7907
+ }
7908
+ function normalizeOrganization(input) {
7909
+ if (typeof input !== "object" || input === null) return {
7910
+ ok: false,
7911
+ error: Errors.invalidInput("organization", "is required")
7912
+ };
7913
+ const name = typeof input.name === "string" ? input.name.trim() : "";
7914
+ if (name.length === 0) return {
7915
+ ok: false,
7916
+ error: Errors.invalidInput("name", "is required")
7917
+ };
7918
+ const handle = normalizeHandleInput(input.handle);
7919
+ if (!handle.ok) return handle;
7920
+ if (input.bio !== void 0 && typeof input.bio !== "string") return {
7921
+ ok: false,
7922
+ error: Errors.invalidInput("bio", "must be text")
7923
+ };
7924
+ if (input.size !== void 0 && typeof input.size !== "string") return {
7925
+ ok: false,
7926
+ error: Errors.invalidInput("size", "must be text")
7927
+ };
7928
+ let country;
7929
+ try {
7930
+ country = toCountryCode(input.country);
7931
+ } catch {
7932
+ return {
7680
7933
  ok: false,
7681
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
7934
+ error: Errors.invalidInput("country", "must be an ISO country code")
7682
7935
  };
7683
- const ensured = await deps.ensureAccount();
7936
+ }
7937
+ const bio = input.bio?.trim() ?? "";
7938
+ const size = input.size?.trim() ?? "";
7939
+ return {
7940
+ ok: true,
7941
+ value: {
7942
+ name,
7943
+ handle: handle.value,
7944
+ country,
7945
+ ...bio.length === 0 ? {} : { bio },
7946
+ ...size.length === 0 ? {} : { size }
7947
+ }
7948
+ };
7949
+ }
7950
+ function isClaimedIdentityState(state) {
7951
+ return state.phase === "authenticated" && state.account.at === "claimed";
7952
+ }
7953
+ function organizationWrongState(currentState, validStates) {
7954
+ return {
7955
+ ok: false,
7956
+ error: Errors.wrongState({
7957
+ method: CAPXUL_OPERATIONS.onboarding.completeOrganization,
7958
+ currentState,
7959
+ validStates: [...validStates]
7960
+ })
7961
+ };
7962
+ }
7963
+ function requestCancelled(options) {
7964
+ return options?.signal?.aborted === true;
7965
+ }
7966
+ async function reachClaimedAccount(deps, options) {
7967
+ let state = deps.snapshotIdentity();
7968
+ if (state.phase !== "authenticated" || state.account.at === "unknown") {
7969
+ const ensured = await deps.sendIdentity({ _tag: "EnsureAccount" }, options);
7684
7970
  if (!ensured.ok) return ensured;
7685
- if (isCancelled()) return {
7686
- ok: false,
7687
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
7688
- };
7689
- const lifecycle = await deps.getLifecycle();
7690
- if (!lifecycle.ok) return lifecycle;
7691
- if (isCancelled()) return {
7692
- ok: false,
7693
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
7694
- };
7695
- if (lifecycle.value.status !== "ready") return {
7696
- ok: false,
7697
- error: Errors.wrongState({
7698
- method: CAPXUL_OPERATIONS.onboarding.completePerson,
7699
- currentState: lifecycle.value.status,
7700
- validStates: ["ready"]
7701
- })
7702
- };
7703
- const profile = await deps.loadProfile(options);
7704
- if (!profile.ok) return profile;
7705
- if (profile.value === null || profile.value.displayName === null || profile.value.username !== available.value.normalized) return {
7706
- ok: false,
7707
- error: Errors.wrongState({
7708
- method: CAPXUL_OPERATIONS.onboarding.completePerson,
7709
- currentState: "profile-incomplete",
7710
- validStates: ["profile-complete"]
7711
- })
7712
- };
7713
- return {
7714
- ok: true,
7715
- value: {
7716
- profile: {
7717
- ...profile.value,
7718
- displayName: profile.value.displayName,
7719
- username: profile.value.username
7720
- },
7721
- account: lifecycle.value
7722
- }
7723
- };
7724
- } };
7971
+ state = ensured.value;
7972
+ }
7973
+ if (state.phase !== "authenticated") return organizationWrongState(state.phase, ["authenticated:claimed"]);
7974
+ if (state.account.at !== "claimed") {
7975
+ const event = state.account.at === "failed" ? { _tag: "RetryAccount" } : state.account.at === "counterfactual" ? { _tag: "ClaimAccount" } : { _tag: "EnsureAccount" };
7976
+ const claimed = await deps.sendIdentity(event, options);
7977
+ if (!claimed.ok) return claimed;
7978
+ state = claimed.value;
7979
+ }
7980
+ return isClaimedIdentityState(state) ? {
7981
+ ok: true,
7982
+ value: state
7983
+ } : organizationWrongState(state.phase === "authenticated" ? state.account.at : state.phase, ["claimed"]);
7984
+ }
7985
+ async function createOrResumeOrganization(deps, state, draft, options) {
7986
+ const active = state.account.org;
7987
+ if (active?.at === "ready") return {
7988
+ ok: true,
7989
+ value: { organizationId: active.orgId }
7990
+ };
7991
+ if (active?.at === "failed" && !active.retryable) return {
7992
+ ok: false,
7993
+ error: publicIdentityFailure(active.failure)
7994
+ };
7995
+ if (active?.at === "failed" && active.orgId === null) {
7996
+ const cleared = await deps.sendIdentity({ _tag: "LeaveOrganization" }, options);
7997
+ if (!cleared.ok) return cleared;
7998
+ }
7999
+ const event = active?.at === "failed" && active.orgId !== null ? { _tag: "RetryOrganization" } : {
8000
+ _tag: "CreateOrganization",
8001
+ draft
8002
+ };
8003
+ const created = await deps.sendIdentity(event, options);
8004
+ if (!created.ok) return created;
8005
+ const final = created.value;
8006
+ const organization = isClaimedIdentityState(final) ? final.account.org : null;
8007
+ return organization?.at === "ready" ? {
8008
+ ok: true,
8009
+ value: { organizationId: organization.orgId }
8010
+ } : organizationWrongState(organization?.at ?? "organization-missing", ["ready"]);
8011
+ }
8012
+ function makeOnboardingMethods(deps) {
8013
+ return {
8014
+ async completePerson(input, options) {
8015
+ const isCancelled = () => options?.signal?.aborted === true;
8016
+ if (typeof input !== "object" || input === null || typeof input.displayName !== "string" || typeof input.country !== "string") return {
8017
+ ok: false,
8018
+ error: Errors.invalidInput("profile", "displayName and country are required")
8019
+ };
8020
+ const handle = normalizeHandleInput(input.handle);
8021
+ if (!handle.ok) return handle;
8022
+ const session = await deps.restoreSession(options);
8023
+ if (!session.ok) return session;
8024
+ if (session.value === null) return {
8025
+ ok: false,
8026
+ error: Errors.notAuthenticated()
8027
+ };
8028
+ const available = await deps.handleAvailable(handle.value, options);
8029
+ if (!available.ok) return available;
8030
+ if (!available.value.available) return {
8031
+ ok: false,
8032
+ error: Errors.invalidInput("handle", "handle is already taken")
8033
+ };
8034
+ const completed = await deps.completeProfile({
8035
+ ...input,
8036
+ handle: available.value.normalized
8037
+ }, options);
8038
+ if (!completed.ok) return completed;
8039
+ const refreshed = await deps.refreshIdentity(options);
8040
+ if (!refreshed.ok) return refreshed;
8041
+ if (isCancelled()) return {
8042
+ ok: false,
8043
+ error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
8044
+ };
8045
+ const ensured = await deps.ensureAccount();
8046
+ if (!ensured.ok) return ensured;
8047
+ if (isCancelled()) return {
8048
+ ok: false,
8049
+ error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
8050
+ };
8051
+ const lifecycle = await deps.getLifecycle();
8052
+ if (!lifecycle.ok) return lifecycle;
8053
+ if (isCancelled()) return {
8054
+ ok: false,
8055
+ error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completePerson })
8056
+ };
8057
+ if (lifecycle.value.status !== "ready") return {
8058
+ ok: false,
8059
+ error: Errors.wrongState({
8060
+ method: CAPXUL_OPERATIONS.onboarding.completePerson,
8061
+ currentState: lifecycle.value.status,
8062
+ validStates: ["ready"]
8063
+ })
8064
+ };
8065
+ const profile = await deps.loadProfile(options);
8066
+ if (!profile.ok) return profile;
8067
+ if (profile.value === null || profile.value.displayName === null || profile.value.handle !== available.value.normalized) return {
8068
+ ok: false,
8069
+ error: Errors.wrongState({
8070
+ method: CAPXUL_OPERATIONS.onboarding.completePerson,
8071
+ currentState: "profile-incomplete",
8072
+ validStates: ["profile-complete"]
8073
+ })
8074
+ };
8075
+ return {
8076
+ ok: true,
8077
+ value: {
8078
+ profile: {
8079
+ ...profile.value,
8080
+ displayName: profile.value.displayName,
8081
+ handle: profile.value.handle
8082
+ },
8083
+ account: lifecycle.value
8084
+ }
8085
+ };
8086
+ },
8087
+ async completeOrganization(input, options) {
8088
+ const operation = CAPXUL_OPERATIONS.onboarding.completeOrganization;
8089
+ const normalized = normalizeOrganization(input);
8090
+ if (!normalized.ok) return normalized;
8091
+ const session = await deps.restoreSession(options);
8092
+ if (!session.ok) return session;
8093
+ if (session.value === null) return {
8094
+ ok: false,
8095
+ error: Errors.notAuthenticated()
8096
+ };
8097
+ const profile = await deps.loadProfile(options);
8098
+ if (!profile.ok) return profile;
8099
+ if (profile.value === null || profile.value.displayName === null || profile.value.handle === null) return {
8100
+ ok: false,
8101
+ error: Errors.wrongState({
8102
+ method: operation,
8103
+ currentState: "profile-incomplete",
8104
+ validStates: ["profile-complete"]
8105
+ })
8106
+ };
8107
+ const refreshed = await deps.refreshIdentity(options);
8108
+ if (!refreshed.ok) return refreshed;
8109
+ if (requestCancelled(options)) return {
8110
+ ok: false,
8111
+ error: Errors.cancelled({ operation })
8112
+ };
8113
+ const claimed = await reachClaimedAccount(deps, options);
8114
+ if (!claimed.ok) return claimed;
8115
+ if (requestCancelled(options)) return {
8116
+ ok: false,
8117
+ error: Errors.cancelled({ operation })
8118
+ };
8119
+ return createOrResumeOrganization(deps, claimed.value, normalized.value, options);
8120
+ }
8121
+ };
7725
8122
  }
7726
8123
  //#endregion
7727
8124
  //#region src/surface/accounts-deps.ts
@@ -8024,13 +8421,15 @@ function executionDependencies$1(input) {
8024
8421
  chainId: input.chainId,
8025
8422
  convexCall: input.convexCall,
8026
8423
  functions: moneyExecutionContract,
8027
- signer: input.signer
8424
+ signer: input.signer,
8425
+ ...input.runPromise === void 0 ? {} : { runPromise: input.runPromise },
8426
+ ...input.telemetry === void 0 ? {} : { telemetry: input.telemetry }
8028
8427
  };
8029
8428
  }
8030
8429
  function makeOrganizationPaymentsMethods(deps, orgId) {
8031
8430
  const requestKeyScope = deps.requestKeyScope ?? `client-${crypto.randomUUID()}`;
8032
8431
  const inFlightOrganizationPayments = /* @__PURE__ */ new Map();
8033
- const execute = async (input, signal, operation = "organization-pay-batch") => {
8432
+ const execute = async (input, signal, operation = "organization-pay-batch", controls) => {
8034
8433
  if (signal?.aborted === true) return {
8035
8434
  ok: false,
8036
8435
  error: Errors.cancelled({ operation })
@@ -8056,16 +8455,18 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
8056
8455
  let flight = inFlightOrganizationPayments.get(flightKey);
8057
8456
  if (flight === void 0) {
8058
8457
  const controller = new AbortController();
8458
+ const requestState = { resolved: false };
8059
8459
  const submission = executeOrganizationPayment(execution, {
8060
8460
  orgId,
8061
8461
  permissionId: input.permissionId,
8062
8462
  requestKey: requestKey.key,
8063
8463
  items: input.items,
8064
8464
  ...input.lineage === void 0 ? {} : { lineage: input.lineage }
8065
- }, controller.signal);
8465
+ }, controller.signal, () => requestState.resolved = true, controls);
8066
8466
  flight = {
8067
8467
  controller,
8068
8468
  promise: submission,
8469
+ requestState,
8069
8470
  waiters: 0,
8070
8471
  settled: false
8071
8472
  };
@@ -8103,30 +8504,80 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
8103
8504
  }
8104
8505
  release(false);
8105
8506
  try {
8106
- await requestKey.finish(result.ok);
8507
+ await requestKey.finish(result.ok || flight.requestState.resolved);
8107
8508
  } catch {}
8108
- return mapOk(result, (value) => value.payments.map((payment) => normalizePaymentTiming(payment)));
8509
+ const normalized = mapOk(result, (value) => value.payments.map((payment) => normalizePaymentTiming(payment)));
8510
+ if (!normalized.ok) return normalized;
8511
+ return normalized;
8109
8512
  };
8110
8513
  return {
8111
- pay: async (input, options) => {
8112
- const { permissionId, requestKey: providedRequestKey, lineage, ...item } = input;
8113
- const result = await execute({
8114
- permissionId,
8115
- ...providedRequestKey === void 0 ? {} : { requestKey: providedRequestKey },
8116
- items: [item],
8117
- ...lineage === void 0 ? {} : { lineage }
8118
- }, options?.signal, "organization-pay");
8119
- if (!result.ok) return result;
8120
- const payment = result.value[0];
8121
- return payment === void 0 ? {
8122
- ok: false,
8123
- error: Errors.unknown()
8124
- } : {
8125
- ok: true,
8126
- value: payment
8127
- };
8514
+ retry: (paymentId, options) => {
8515
+ const controls = deps.invocationControls?.(options) ?? options;
8516
+ return runCapxulEffect(Effect.gen(function* () {
8517
+ const parent = yield* Effect.currentSpan.pipe(Effect.orDie);
8518
+ const captured = carryInvocationParentSpan(controls, parent);
8519
+ const completed = yield* Effect.tryPromise({
8520
+ try: async () => {
8521
+ const execution = executionDependencies$1(deps);
8522
+ if (execution === null) return {
8523
+ ok: false,
8524
+ error: Errors.notImplemented("organizationPayments", "executionComposition")
8525
+ };
8526
+ const result = await executePaymentLifecycle(execution, {
8527
+ kind: "retry",
8528
+ paymentId
8529
+ }, controls?.signal, captured);
8530
+ if (!result.ok) return result;
8531
+ return {
8532
+ ok: true,
8533
+ value: result.value.payments.map((payment) => normalizePaymentTiming(payment))
8534
+ };
8535
+ },
8536
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
8537
+ });
8538
+ return yield* completed.ok ? Effect.succeed(completed.value) : Effect.fail(completed.error);
8539
+ }), observationOnlyControls(controls), CAPXUL_OPERATIONS.organizationPayments.retry, deps.runPromise);
8128
8540
  },
8129
- payBatch: (input, options) => execute(input, options?.signal)
8541
+ pay: (input, options) => {
8542
+ const controls = deps.invocationControls?.(options) ?? options;
8543
+ return runCapxulEffect(Effect.gen(function* () {
8544
+ const parent = yield* Effect.currentSpan.pipe(Effect.orDie);
8545
+ const captured = carryInvocationParentSpan(controls, parent);
8546
+ const completed = yield* Effect.tryPromise({
8547
+ try: async () => {
8548
+ const { permissionId, requestKey: providedRequestKey, lineage, ...item } = input;
8549
+ const result = await execute({
8550
+ permissionId,
8551
+ ...providedRequestKey === void 0 ? {} : { requestKey: providedRequestKey },
8552
+ items: [item],
8553
+ ...lineage === void 0 ? {} : { lineage }
8554
+ }, controls?.signal, "organization-pay", captured);
8555
+ if (!result.ok) return result;
8556
+ const payment = result.value[0];
8557
+ return payment === void 0 ? {
8558
+ ok: false,
8559
+ error: Errors.unknown()
8560
+ } : {
8561
+ ok: true,
8562
+ value: payment
8563
+ };
8564
+ },
8565
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
8566
+ });
8567
+ return yield* completed.ok ? Effect.succeed(completed.value) : Effect.fail(completed.error);
8568
+ }), observationOnlyControls(controls), CAPXUL_OPERATIONS.organizationPayments.pay, deps.runPromise);
8569
+ },
8570
+ payBatch: (input, options) => {
8571
+ const controls = deps.invocationControls?.(options) ?? options;
8572
+ return runCapxulEffect(Effect.gen(function* () {
8573
+ const parent = yield* Effect.currentSpan.pipe(Effect.orDie);
8574
+ const completed = yield* Effect.tryPromise({
8575
+ try: () => execute(input, controls?.signal, void 0, carryInvocationParentSpan(controls, parent)),
8576
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
8577
+ });
8578
+ return yield* completed.ok ? Effect.succeed(completed.value) : Effect.fail(completed.error);
8579
+ }), observationOnlyControls(controls), CAPXUL_OPERATIONS.organizationPayments.payBatch, deps.runPromise);
8580
+ }
8130
8581
  };
8131
8582
  }
8132
8583
  //#endregion
@@ -8223,12 +8674,14 @@ function executionDependencies(deps) {
8223
8674
  chainId: deps.chainId,
8224
8675
  convexCall: deps.convexCall,
8225
8676
  functions: moneyExecutionContract,
8677
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise },
8226
8678
  signer: deps.signer
8227
8679
  };
8228
8680
  }
8229
8681
  function makePayrollMethods(deps, orgId) {
8230
8682
  const requestKeyScope = deps.requestKeyScope ?? `client-${crypto.randomUUID()}`;
8231
- async function authorize(input, signal) {
8683
+ async function authorize(input, controls) {
8684
+ const signal = controls?.signal;
8232
8685
  const execution = executionDependencies(deps);
8233
8686
  if (execution === null) return {
8234
8687
  ok: false,
@@ -8239,15 +8692,16 @@ function makePayrollMethods(deps, orgId) {
8239
8692
  input
8240
8693
  }, input.requestKey);
8241
8694
  let authorized;
8695
+ let preparedClosed = false;
8242
8696
  const submitted = await executePrepared(execution, async (signerAddress) => {
8243
- const prepared = await runIfActive(signal, AUTHORIZE_RUN, () => deps.convexCall.action(payrollContract.authorizeRun, { input: {
8697
+ const prepared = await runIfActive(signal, AUTHORIZE_RUN, () => withInvocationParentSpan(Effect.suspend(() => deps.convexCall.action(payrollContract.authorizeRun, copyInvocationObservation(controls, { input: {
8244
8698
  orgId,
8245
8699
  permissionId: input.permissionId,
8246
8700
  requestKey: requestKey.key,
8247
8701
  signerAddress,
8248
8702
  period: input.period,
8249
8703
  items: input.items
8250
- } }));
8704
+ } }))), controls), deps.runPromise);
8251
8705
  if (!prepared.ok) return prepared;
8252
8706
  authorized = prepared.value.run;
8253
8707
  return {
@@ -8260,9 +8714,9 @@ function makePayrollMethods(deps, orgId) {
8260
8714
  requestKey: requestKey.key,
8261
8715
  runId: authorized.id,
8262
8716
  items: input.items
8263
- })(request), signal);
8717
+ })(request), true, () => preparedClosed = true, signal, controls);
8264
8718
  try {
8265
- await requestKey.finish(submitted.ok);
8719
+ await requestKey.finish(submitted.ok || preparedClosed);
8266
8720
  } catch {}
8267
8721
  if (!submitted.ok) return submitted;
8268
8722
  return authorized === void 0 ? {
@@ -8274,35 +8728,48 @@ function makePayrollMethods(deps, orgId) {
8274
8728
  };
8275
8729
  }
8276
8730
  return {
8277
- runs: (options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payroll.runs, () => Effect.map(deps.convexCall.query(payrollContract.runs, { orgId }), toPayrollRuns)),
8278
- authorizeRun: async (input, options) => {
8279
- if (options?.signal?.aborted === true) return {
8280
- ok: false,
8281
- error: Errors.cancelled({ operation: AUTHORIZE_RUN })
8282
- };
8283
- try {
8284
- return await authorize(input, options?.signal);
8285
- } catch (cause) {
8286
- return {
8287
- ok: false,
8288
- error: cause instanceof CapxulError ? cause : Errors.unknown(cause)
8289
- };
8290
- }
8731
+ runs: (options) => {
8732
+ const controls = deps.invocationControls?.(options) ?? options;
8733
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(payrollContract.runs, copyInvocationObservation(controls, { orgId }))).pipe(Effect.map(toPayrollRuns)), controls, CAPXUL_OPERATIONS.payroll.runs, deps.runPromise);
8734
+ },
8735
+ authorizeRun: (input, options) => {
8736
+ const controls = deps.invocationControls?.(options) ?? options;
8737
+ return runCapxulEffect(Effect.gen(function* () {
8738
+ if (controls?.signal?.aborted === true) return yield* Effect.fail(Errors.cancelled({ operation: AUTHORIZE_RUN }));
8739
+ const parent = yield* Effect.currentSpan.pipe(Effect.orDie);
8740
+ const result = yield* Effect.tryPromise({
8741
+ try: () => authorize(input, carryInvocationParentSpan(controls, parent)),
8742
+ catch: (cause) => cause instanceof CapxulError ? cause : Errors.unknown(cause)
8743
+ });
8744
+ return yield* result.ok ? Effect.succeed(result.value) : Effect.fail(result.error);
8745
+ }), observationOnlyControls(controls), AUTHORIZE_RUN, deps.runPromise);
8746
+ },
8747
+ terms: (options) => {
8748
+ const controls = deps.invocationControls?.(options) ?? options;
8749
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(payrollContract.terms, copyInvocationObservation(controls, { orgId }))), controls, CAPXUL_OPERATIONS.payroll.terms, deps.runPromise);
8291
8750
  },
8292
- terms: (options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payroll.terms, () => deps.convexCall.query(payrollContract.terms, { orgId })),
8293
8751
  groups: {
8294
- list: (options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payroll.groups.list, () => Effect.map(deps.convexCall.query(payrollContract.groups, { orgId }), (groups) => groups.map(toPayrollGroup))),
8295
- save: (input, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payroll.groups.save, () => Effect.map(deps.convexCall.mutation(payrollContract.saveGroup, {
8296
- orgId,
8297
- ...input.id === void 0 ? {} : { id: String(input.id) },
8298
- name: input.name,
8299
- tone: input.tone,
8300
- members: input.members
8301
- }), toPayrollGroup)),
8302
- remove: (id, options) => runIfActive(options?.signal, CAPXUL_OPERATIONS.payroll.groups.remove, () => Effect.map(deps.convexCall.mutation(payrollContract.removeGroup, {
8303
- orgId,
8304
- id
8305
- }), () => void 0))
8752
+ list: (options) => {
8753
+ const controls = deps.invocationControls?.(options) ?? options;
8754
+ return runPortEffect(Effect.suspend(() => deps.convexCall.query(payrollContract.groups, copyInvocationObservation(controls, { orgId }))).pipe(Effect.map((groups) => groups.map(toPayrollGroup))), controls, CAPXUL_OPERATIONS.payroll.groups.list, deps.runPromise);
8755
+ },
8756
+ save: (input, options) => {
8757
+ const controls = deps.invocationControls?.(options) ?? options;
8758
+ return runPortEffect(Effect.suspend(() => deps.convexCall.mutation(payrollContract.saveGroup, copyInvocationObservation(controls, {
8759
+ orgId,
8760
+ ...input.id === void 0 ? {} : { id: String(input.id) },
8761
+ name: input.name,
8762
+ tone: input.tone,
8763
+ members: input.members
8764
+ }))).pipe(Effect.map(toPayrollGroup)), controls, CAPXUL_OPERATIONS.payroll.groups.save, deps.runPromise);
8765
+ },
8766
+ remove: (id, options) => {
8767
+ const controls = deps.invocationControls?.(options) ?? options;
8768
+ return runPortEffect(Effect.suspend(() => deps.convexCall.mutation(payrollContract.removeGroup, copyInvocationObservation(controls, {
8769
+ orgId,
8770
+ id
8771
+ }))).pipe(Effect.asVoid), controls, CAPXUL_OPERATIONS.payroll.groups.remove, deps.runPromise);
8772
+ }
8306
8773
  }
8307
8774
  };
8308
8775
  }
@@ -8751,6 +9218,8 @@ function makeOrgMethods(deps) {
8751
9218
  const convexCall = deps.convexCall;
8752
9219
  return {
8753
9220
  ...makeActorRelationshipMethods({
9221
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise },
9222
+ ...deps.invocationControls === void 0 ? {} : { invocationControls: deps.invocationControls },
8754
9223
  actor: {
8755
9224
  kind: "org",
8756
9225
  orgId: String(orgId)
@@ -8880,13 +9349,18 @@ function makeOrgMethods(deps) {
8880
9349
  }, String(orgId)),
8881
9350
  payments: convexCall === void 0 ? makeNotImplementedOrganizationPaymentsMethods() : makeOrganizationPaymentsMethods({
8882
9351
  convexCall,
9352
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise },
9353
+ ...deps.invocationControls === void 0 ? {} : { invocationControls: deps.invocationControls },
8883
9354
  ...deps.requestKeyScope === void 0 ? {} : { requestKeyScope: deps.requestKeyScope },
8884
9355
  ...deps.actor === void 0 ? {} : { actor: deps.actor },
8885
9356
  ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
8886
- ...deps.signer === void 0 ? {} : { signer: deps.signer }
9357
+ ...deps.signer === void 0 ? {} : { signer: deps.signer },
9358
+ ...deps.telemetry === void 0 ? {} : { telemetry: deps.telemetry }
8887
9359
  }, String(orgId)),
8888
9360
  payroll: convexCall === void 0 ? makeUnavailablePayrollMethods() : makePayrollMethods({
8889
9361
  convexCall,
9362
+ ...deps.runPromise === void 0 ? {} : { runPromise: deps.runPromise },
9363
+ ...deps.invocationControls === void 0 ? {} : { invocationControls: deps.invocationControls },
8890
9364
  ...deps.requestKeyScope === void 0 ? {} : { requestKeyScope: deps.requestKeyScope },
8891
9365
  ...deps.actor === void 0 ? {} : { actor: deps.actor },
8892
9366
  ...deps.chainId === void 0 ? {} : { chainId: Number(deps.chainId) },
@@ -8910,7 +9384,8 @@ function makeNotImplementedPermissionMethods() {
8910
9384
  function makeNotImplementedOrganizationPaymentsMethods() {
8911
9385
  return {
8912
9386
  pay: organizationPaymentExecutionUnavailable,
8913
- payBatch: organizationPaymentExecutionUnavailable
9387
+ payBatch: organizationPaymentExecutionUnavailable,
9388
+ retry: organizationPaymentExecutionUnavailable
8914
9389
  };
8915
9390
  }
8916
9391
  const orgMeUnavailable = () => Promise.resolve({
@@ -9187,6 +9662,8 @@ function assembleCapxulClient(input) {
9187
9662
  let detectPendingOrgInvitations;
9188
9663
  let kickProvisioning;
9189
9664
  const financialOps = makeFinancialOpsMethods({
9665
+ runPromise: effectRunner.runPromise,
9666
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls, actor.authSession()?.authUserId),
9190
9667
  actor,
9191
9668
  chainId: input.bootstrap.chainId,
9192
9669
  convexCall: input.ports.convexCall,
@@ -9206,7 +9683,7 @@ function assembleCapxulClient(input) {
9206
9683
  profileMethods: financialOps.me,
9207
9684
  convexCall: input.ports.convexCall,
9208
9685
  runPromise: effectRunner.runPromise,
9209
- invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
9686
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls, actor.authSession()?.authUserId),
9210
9687
  ...input.signer === void 0 ? {} : { signer: input.signer }
9211
9688
  });
9212
9689
  kickProvisioning = accountBundle.kickProvisioning;
@@ -9245,11 +9722,13 @@ function assembleCapxulClient(input) {
9245
9722
  const onboarding = makeOnboardingMethods({
9246
9723
  restoreSession: auth.getSession,
9247
9724
  refreshIdentity: (options) => runCapxulEffect(askIdentity(actor, { _tag: "ReadSession" }, options).pipe(Effect.asVoid), options, CAPXUL_OPERATIONS.identity.readSession, effectRunner.runPromise),
9248
- usernameAvailable: identity.usernameAvailable,
9725
+ handleAvailable: identity.handleAvailable,
9249
9726
  completeProfile: identity.completeProfile,
9250
9727
  loadProfile: identity.loadCurrent,
9251
9728
  ensureAccount: account._internal.ensureReady,
9252
- getLifecycle: account.getLifecycle
9729
+ getLifecycle: account.getLifecycle,
9730
+ snapshotIdentity: actor.snapshot,
9731
+ sendIdentity: (event, options) => runCapxulEffect(askIdentity(actor, event, options), options, CAPXUL_OPERATIONS._internal.identity.send, effectRunner.runPromise)
9253
9732
  });
9254
9733
  const system = makeSystemMethods({ convexCall: input.ports.convexCall });
9255
9734
  const media = makeMediaMethods({ convexCall: input.ports.convexCall });
@@ -9257,21 +9736,21 @@ function assembleCapxulClient(input) {
9257
9736
  convexCall: input.ports.convexCall,
9258
9737
  telemetry: input.ports.telemetry,
9259
9738
  runPromise: effectRunner.runPromise,
9260
- invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls)
9739
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls, actor.authSession()?.authUserId)
9261
9740
  });
9262
9741
  const accounts = makeAccountsMethods({
9263
9742
  accountReadPort: input.ports.accountRead,
9264
9743
  chainId: input.bootstrap.chainId,
9265
9744
  telemetry: input.ports.telemetry,
9266
9745
  runPromise: effectRunner.runPromise,
9267
- invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls)
9746
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls, actor.authSession()?.authUserId)
9268
9747
  });
9269
9748
  const orgMethods = makeOrgMethods({
9270
9749
  actor,
9271
9750
  chainId: input.bootstrap.chainId,
9272
9751
  telemetry: input.ports.telemetry,
9273
9752
  runPromise: effectRunner.runPromise,
9274
- invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls),
9753
+ invocationControls: (controls) => withHostObservationControls(observation.hostObservationSnapshot, controls, actor.authSession()?.authUserId),
9275
9754
  requestKeyScope: `${input.bootstrap.convexUrl}:${String(input.bootstrap.chainId)}`,
9276
9755
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
9277
9756
  convexCall: input.ports.convexCall,
@@ -9308,7 +9787,7 @@ function assembleCapxulClient(input) {
9308
9787
  }
9309
9788
  },
9310
9789
  async completeProfile(profile, controls) {
9311
- if (typeof profile !== "object" || profile === null || typeof profile.displayName !== "string" || typeof profile.country !== "string" || profile.username !== void 0 && typeof profile.username !== "string") return {
9790
+ if (typeof profile !== "object" || profile === null || typeof profile.displayName !== "string" || typeof profile.country !== "string" || typeof profile.handle !== "string") return {
9312
9791
  ok: false,
9313
9792
  reason: "INVALID_INPUT"
9314
9793
  };
@@ -9326,8 +9805,8 @@ function assembleCapxulClient(input) {
9326
9805
  reason: "INVALID_INPUT"
9327
9806
  };
9328
9807
  }
9329
- const username = profile.username?.trim();
9330
- if (profile.username !== void 0 && username?.length === 0) return {
9808
+ const handle = profile.handle.trim();
9809
+ if (handle.length === 0) return {
9331
9810
  ok: false,
9332
9811
  reason: "INVALID_INPUT"
9333
9812
  };
@@ -9341,7 +9820,7 @@ function assembleCapxulClient(input) {
9341
9820
  email: session.email,
9342
9821
  displayName,
9343
9822
  country,
9344
- ...username === void 0 ? {} : { username }
9823
+ handle
9345
9824
  }), controls, CAPXUL_OPERATIONS.identity.completeProfile, effectRunner.runPromise);
9346
9825
  return result.ok ? { ok: true } : {
9347
9826
  ok: false,
@@ -9360,8 +9839,6 @@ function assembleCapxulClient(input) {
9360
9839
  accounts,
9361
9840
  currentUser,
9362
9841
  me: financialOps.me,
9363
- handles: financialOps.handles,
9364
- payees: financialOps.payees,
9365
9842
  targets: financialOps.targets,
9366
9843
  destinations: financialOps.destinations,
9367
9844
  payments: financialOps.payments,
@@ -9380,6 +9857,20 @@ function assembleCapxulClient(input) {
9380
9857
  accounts: { fund: accounts.fund },
9381
9858
  organizationSetup: { getProofReceipt: (orgId) => runPortEffect(input.ports.convexCall.query(organizationSetupProofReceiptQuery, { orgId })) },
9382
9859
  telemetry: input.ports.telemetry,
9860
+ captureExternalAddressAcknowledged: (address, organizationId) => {
9861
+ const telemetry = input.ports.telemetry;
9862
+ if (telemetry === void 0) return;
9863
+ Effect.runPromise(Effect.suspend(() => telemetry.emit({
9864
+ name: "quick_pay_external_address_acknowledged",
9865
+ props: {
9866
+ recipient_locator_kind: "address",
9867
+ recipient_resolution_status: "external_address",
9868
+ recipient_address: address,
9869
+ external_address_acknowledged: true,
9870
+ ...organizationId === void 0 ? {} : { organization_id: organizationId }
9871
+ }
9872
+ })).pipe(Effect.catchCause(() => Effect.void)));
9873
+ },
9383
9874
  close: stopActor
9384
9875
  }
9385
9876
  }, observation.failureObservation, observation.hostObservationSnapshot);
@@ -9410,7 +9901,7 @@ function transitionError(record) {
9410
9901
  }
9411
9902
  function withHostObservation(actor, snapshot) {
9412
9903
  if (snapshot === void 0) return actor;
9413
- const controls = (input) => withHostObservationControls(snapshot, input);
9904
+ const controls = (input) => withHostObservationControls(snapshot, input, actor.authSession()?.authUserId);
9414
9905
  return {
9415
9906
  ...actor,
9416
9907
  ask: (event, input) => actor.ask(event, controls(input)),
@@ -9418,10 +9909,14 @@ function withHostObservation(actor, snapshot) {
9418
9909
  restoreAuthSession: (session, input) => actor.restoreAuthSession(session, controls(input))
9419
9910
  };
9420
9911
  }
9421
- function withHostObservationControls(snapshot, input) {
9422
- const copied = { ...input };
9423
- const captured = snapshot?.();
9424
- return captured === void 0 ? copied : attachInvocationObservation(copied, captured);
9912
+ function withHostObservationControls(snapshot, input, actorId) {
9913
+ const previous = readInvocationObservation(input);
9914
+ if (previous !== void 0) return attachInvocationObservation({ ...input }, previous);
9915
+ const captured = snapshot?.() ?? { active: true };
9916
+ return attachInvocationObservation({ ...input }, {
9917
+ ...captured,
9918
+ ...actorId === void 0 ? {} : { actorId }
9919
+ });
9425
9920
  }
9426
9921
  //#endregion
9427
9922
  export { stampTelemetryEnvelope as $, safeExceptionLabel as A, resolveFailureMode as B, observeFailedResult as C, normalizeExceptionErrorKind as D, SDK_VERSION as E, causeChain as F, sanitizeObservationContext as G, readInvocationObservation as H, injectedWalletSigner as I, CAPXUL_FUNCTIONS as J, PAYMENT_DIRECTIONS as K, isSignerNotReadySignal as L, fromWei as M, isSettingUpLifecycle as N, normalizeExceptionOperation as O, formatTraceparent as P, redactTelemetryProps as Q, openfortSignerNotReadyCode as R, observationContextProps as S, EXCEPTION_MESSAGE as T, OBSERVATION_CONTEXT_HEADER as U, copyInvocationObservation as V, encodeObservationContextHeader as W, EngineeringTelemetryBootstrapPolicy as X, BootstrapEnvelope as Y, redactTelemetryEvent as Z, fingerprintPaymentIntent as _, AccountReadPortTag as a, isRestoring as at, failureDetail as b, retryIdempotentRead as c, IdentityPortTag as d, CAPXUL_OPERATIONS as et, identityErrorFromCapxul as f, bootstrapErrorFromCapxul as g, BootstrapPortTag as h, smartAccountErrorFromCapxul as i, isClaimed as it, version as j, projectSdkException as k, PRODUCT_INVOCATION as l, convexCallErrorFromCapxul as m, detectAuthCacheAdapter as n, normalizeCapxulOperation as nt, accountReadErrorFromCapxul as o, ConvexCallPortTag as p, PAYMENT_STATUSES as q, SmartAccountPortTag as r, destination as rt, TelemetryPortTag as s, assembleCapxulClient as t, isCapxulOperation as tt, wireChainId as u, toWei as v, postHogFailureObservation as w, failureEvidenceProps as x, CAPXUL_SDK_EXPECTED_OUTCOME_EVENT as y, signerFailure as z };