@capxul/mcp 1.0.0-alpha.1 → 1.0.0-alpha.12

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.
package/dist/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { $ as packSafe4337OwnerSignature, A as buildCapxulCommitmentRedirectCallData, C as ERC20_APPROVE_ABI, F as buildOrgPersonalMultiCallData, G as SAFE_L2_SINGLETON, I as buildOrgRoleSpendPersonalCallData, J as SAFE_PROXY_FACTORY, K as SAFE_MODULE_SETUP, M as buildCapxulPaymentsPersonalSendCallData, N as buildCapxulPaymentsRoleBatchSpendCall, O as buildCapxulCommitmentCancelCallData, R as normalizeBindingEmail, U as MULTI_SEND, W as SAFE_4337_MODULE, X as deriveCapxulSafeAddress, Y as computeCapxulSafeSaltNonce, at as USDX_ADDRESS_BASE_SEPOLIA, b as CAPXUL_PAYMENTS_ADDRESS, c as orgRoleKeyForLabel, ct as CapxulError, dt as isCapxulError, h as deriveCapxulOrgAddress, i as computeOrgRolesModuleAddress, j as buildCapxulCreateCommitmentPersonalCallData, k as buildCapxulCommitmentClaimCallData, l as orgRoleTemplateDefinitions, lt as Errors, m as computeCapxulOrgSaltNonce, n as buildOrgRoleAssignmentCall, nt as safe4337SafeOpDigest, o as compileOrgRoleDefinitions, ot as isExactTransferTokenAllowed, p as buildCapxulOrgInitializer, r as buildOrgRolesDeployCalls, rt as safe4337StubSignature, st as decodeConvexError, v as DIRECT_BASE_ROUTE, z as BASE_SEPOLIA_CHAIN_ID } from "./src-CJVATdCb.mjs";
3
- import { a as fetchEntryPointNonce, c as fetchUserOperationReceipt, d as sendUserOperation, i as fetchCommitmentState, l as getPaymasterData, n as estimateUserOperationGas, o as fetchErc20Balance, s as fetchUserOperationFees, u as getPaymasterStubData } from "./alchemy-rpc-DEpqt2Jx.mjs";
2
+ import { $ as packSafe4337OwnerSignature, A as buildCapxulCommitmentRedirectCallData, C as ERC20_APPROVE_ABI, F as buildOrgPersonalMultiCallData, G as SAFE_L2_SINGLETON, I as buildOrgRoleSpendPersonalCallData, J as SAFE_PROXY_FACTORY, K as SAFE_MODULE_SETUP, M as buildCapxulPaymentsPersonalSendCallData, N as buildCapxulPaymentsRoleBatchSpendCall, O as buildCapxulCommitmentCancelCallData, R as normalizeBindingEmail, U as MULTI_SEND, W as SAFE_4337_MODULE, X as deriveCapxulSafeAddress, Y as computeCapxulSafeSaltNonce, at as USDX_ADDRESS_BASE_SEPOLIA, b as CAPXUL_PAYMENTS_ADDRESS, c as orgRoleKeyForLabel, ct as CapxulError, dt as isCapxulError, h as deriveCapxulOrgAddress, i as computeOrgRolesModuleAddress, j as buildCapxulCreateCommitmentPersonalCallData, k as buildCapxulCommitmentClaimCallData, l as orgRoleTemplateDefinitions, lt as Errors, m as computeCapxulOrgSaltNonce, n as buildOrgRoleAssignmentCall, nt as safe4337SafeOpDigest, o as compileOrgRoleDefinitions, ot as isExactTransferTokenAllowed, p as buildCapxulOrgInitializer, r as buildOrgRolesDeployCalls, rt as safe4337StubSignature, st as decodeConvexError, v as DIRECT_BASE_ROUTE, z as BASE_SEPOLIA_CHAIN_ID } from "./src-BDIKpZXn.mjs";
3
+ import { a as fetchEntryPointNonce, c as fetchUserOperationReceipt, d as sendUserOperation, i as fetchCommitmentState, l as getPaymasterData, n as estimateUserOperationGas, o as fetchErc20Balance, s as fetchUserOperationFees, u as getPaymasterStubData } from "./alchemy-rpc-mjuofdCf.mjs";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
6
  import { createServer } from "node:http";
@@ -10,9 +10,9 @@ import { concat, concatHex, createPublicClient, createWalletClient, custom, deco
10
10
  import { z } from "zod";
11
11
  import { Schema, TreeFormatter } from "@effect/schema";
12
12
  import { Context, Data, Deferred, Duration, Effect, Either, Exit, Layer, Ref, Request, Scope } from "effect";
13
+ import { getFunctionName, makeFunctionReference } from "convex/server";
13
14
  import { privateKeyToAccount, toAccount } from "viem/accounts";
14
15
  import { ConvexClient } from "convex/browser";
15
- import { getFunctionName, makeFunctionReference } from "convex/server";
16
16
  import { AccountTypeEnum, ChainTypeEnum, EmbeddedState, Openfort, RecoveryMethod, ThirdPartyOAuthProvider } from "@openfort/openfort-js";
17
17
  import { Machine } from "@effect/experimental";
18
18
  import { createBundlerClient, createPaymasterClient, entryPoint06Abi, entryPoint07Abi, entryPoint07Address, toSmartAccount } from "viem/account-abstraction";
@@ -232,7 +232,7 @@ function normalizeEmail(email) {
232
232
  }
233
233
  //#endregion
234
234
  //#region package.json
235
- var version$1 = "1.0.0-alpha.1";
235
+ var version$1 = "1.0.0-alpha.12";
236
236
  //#endregion
237
237
  //#region src/tool-result.ts
238
238
  function okResult(structured) {
@@ -425,7 +425,7 @@ function registerAccountTools(server, deps) {
425
425
  }
426
426
  //#endregion
427
427
  //#region src/tools/auth.ts
428
- function unknownSessionError$5() {
428
+ function unknownSessionError$6() {
429
429
  return Errors.notAuthenticated("unknown or expired session token");
430
430
  }
431
431
  function requireSession(deps, sessionToken) {
@@ -489,7 +489,7 @@ function registerAuthTools(server, deps) {
489
489
  }, ({ sessionToken }) => guarded(async () => {
490
490
  if (sessionToken === void 0) return okResult({ authenticated: false });
491
491
  const entry = requireSession(deps, sessionToken);
492
- if (entry === void 0) return errorResult(unknownSessionError$5());
492
+ if (entry === void 0) return errorResult(unknownSessionError$6());
493
493
  const session = await entry.handle.getSession();
494
494
  if (!session.ok) return errorResult(session.error);
495
495
  if (session.value === null) return okResult({ authenticated: false });
@@ -506,7 +506,7 @@ function registerAuthTools(server, deps) {
506
506
  outputSchema: { signedOut: z.literal(true) }
507
507
  }, ({ sessionToken }) => guarded(async () => {
508
508
  const entry = requireSession(deps, sessionToken);
509
- if (entry === void 0) return errorResult(unknownSessionError$5());
509
+ if (entry === void 0) return errorResult(unknownSessionError$6());
510
510
  const result = await entry.handle.signOut();
511
511
  if (!result.ok) return errorResult(result.error);
512
512
  deps.sessionStore.revoke(sessionToken);
@@ -546,26 +546,28 @@ function registerFaucetTools(server, deps) {
546
546
  }
547
547
  //#endregion
548
548
  //#region src/tools/financial-ops.ts
549
- function unknownSessionError$4() {
549
+ function unknownSessionError$5() {
550
550
  return Errors.notAuthenticated("unknown or expired session token");
551
551
  }
552
552
  function registerFinancialOpsTools(server, deps) {
553
553
  server.registerTool("me.get", {
554
554
  title: "Current Capxul identity",
555
- description: "Return the authenticated user's Capxul identity and personal Safe deposit address.",
555
+ description: "Return the authenticated user's Capxul identity. Deposit target data lives on me.depositInstructions.",
556
556
  inputSchema: { sessionToken: z.string() },
557
557
  outputSchema: {
558
558
  authUserId: z.string(),
559
559
  email: z.string(),
560
- displayName: z.string().nullable(),
561
- personalSafeAddress: z.string(),
562
- chainId: z.number()
560
+ displayName: z.string().nullable()
563
561
  }
564
562
  }, ({ sessionToken }) => guarded(async () => {
565
563
  const entry = requireSession(deps, sessionToken);
566
- if (entry === void 0) return errorResult(unknownSessionError$4());
564
+ if (entry === void 0) return errorResult(unknownSessionError$5());
567
565
  const result = await entry.handle.getMe();
568
- return result.ok ? okResult({ ...result.value }) : errorResult(result.error);
566
+ return result.ok ? okResult({
567
+ authUserId: result.value.authUserId,
568
+ email: result.value.email,
569
+ displayName: result.value.displayName
570
+ }) : errorResult(result.error);
569
571
  }, "me.get", deps.onToolCall));
570
572
  server.registerTool("me.depositInstructions", {
571
573
  title: "Deposit instructions",
@@ -581,7 +583,7 @@ function registerFinancialOpsTools(server, deps) {
581
583
  }
582
584
  }, ({ sessionToken }) => guarded(async () => {
583
585
  const entry = requireSession(deps, sessionToken);
584
- if (entry === void 0) return errorResult(unknownSessionError$4());
586
+ if (entry === void 0) return errorResult(unknownSessionError$5());
585
587
  const result = await entry.handle.getDepositInstructions();
586
588
  return result.ok ? okResult({ ...result.value }) : errorResult(result.error);
587
589
  }, "me.depositInstructions", deps.onToolCall));
@@ -595,7 +597,7 @@ function registerFinancialOpsTools(server, deps) {
595
597
  outputSchema: recipientResolutionSchema()
596
598
  }, ({ sessionToken, handle }) => guarded(async () => {
597
599
  const entry = requireSession(deps, sessionToken);
598
- if (entry === void 0) return errorResult(unknownSessionError$4());
600
+ if (entry === void 0) return errorResult(unknownSessionError$5());
599
601
  const result = await entry.handle.resolveHandle(handle);
600
602
  return result.ok ? okResult({ ...result.value }) : errorResult(result.error);
601
603
  }, "handles.resolve", deps.onToolCall));
@@ -624,7 +626,7 @@ function registerFinancialOpsTools(server, deps) {
624
626
  }
625
627
  }, ({ sessionToken, label, recipient, handle }) => guarded(async () => {
626
628
  const entry = requireSession(deps, sessionToken);
627
- if (entry === void 0) return errorResult(unknownSessionError$4());
629
+ if (entry === void 0) return errorResult(unknownSessionError$5());
628
630
  const result = await entry.handle.createPayee({
629
631
  label,
630
632
  recipient,
@@ -655,7 +657,7 @@ function registerFinancialOpsTools(server, deps) {
655
657
  }).nullable() }
656
658
  }, ({ sessionToken, payeeId }) => guarded(async () => {
657
659
  const entry = requireSession(deps, sessionToken);
658
- if (entry === void 0) return errorResult(unknownSessionError$4());
660
+ if (entry === void 0) return errorResult(unknownSessionError$5());
659
661
  const result = await entry.handle.getPayee(payeeId);
660
662
  return result.ok ? okResult({ payee: result.value }) : errorResult(result.error);
661
663
  }, "payees.get", deps.onToolCall));
@@ -669,7 +671,7 @@ function registerFinancialOpsTools(server, deps) {
669
671
  outputSchema: recipientResolutionSchema()
670
672
  }, ({ sessionToken, recipient }) => guarded(async () => {
671
673
  const entry = requireSession(deps, sessionToken);
672
- if (entry === void 0) return errorResult(unknownSessionError$4());
674
+ if (entry === void 0) return errorResult(unknownSessionError$5());
673
675
  const result = await entry.handle.resolvePayee(recipient);
674
676
  return result.ok ? okResult({ ...result.value }) : errorResult(result.error);
675
677
  }, "payees.resolve", deps.onToolCall));
@@ -693,7 +695,7 @@ function recipientResolutionSchema() {
693
695
  //#endregion
694
696
  //#region ../../packages/types/src/index.ts
695
697
  const EVM_ADDRESS_RE$1 = /^0x[0-9a-f]{40}$/i;
696
- const BYTES32_RE$1 = /^0x[0-9a-f]{64}$/i;
698
+ const BYTES32_RE$2 = /^0x[0-9a-f]{64}$/i;
697
699
  const PUBLISHABLE_KEY_PATTERN = /^cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]{32}$/;
698
700
  const SUPPORTED_CURRENCIES = [
699
701
  {
@@ -810,7 +812,7 @@ function toKycTier(raw) {
810
812
  return raw;
811
813
  }
812
814
  function toRoleKey(raw) {
813
- if (typeof raw !== "string" || !BYTES32_RE$1.test(raw)) throw Errors.invalidInput("roleKey", invalidValueReason("must be 0x + 64 hex chars", raw));
815
+ if (typeof raw !== "string" || !BYTES32_RE$2.test(raw)) throw Errors.invalidInput("roleKey", invalidValueReason("must be 0x + 64 hex chars", raw));
814
816
  return raw.toLowerCase();
815
817
  }
816
818
  function toSessionToken(raw) {
@@ -870,7 +872,7 @@ const DocumentHashSchema$1 = Schema.String.pipe(Schema.transform(Schema.String,
870
872
  return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;
871
873
  },
872
874
  encode: (s) => s
873
- }), Schema.filter((s) => BYTES32_RE$1.test(s), { message: () => "must be 32 bytes of hex" }));
875
+ }), Schema.filter((s) => BYTES32_RE$2.test(s), { message: () => "must be 32 bytes of hex" }));
874
876
  /**
875
877
  * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.
876
878
  * Issuance source distinguishes SDK-handshake tokens from auth-session
@@ -932,14 +934,18 @@ const PAYMENT_ID_RE = /^payment_[0-9A-Za-z]+$/;
932
934
  const PAYEE_ID_RE = /^payee_[0-9A-Za-z]+$/;
933
935
  const ORG_ID_RE = /^org_[0-9A-Za-z]+$/;
934
936
  const USER_ID_RE = /^user_[0-9A-Za-z]+$/;
935
- const HANDLE_RE = /^@[0-9A-Za-z][0-9A-Za-z_.-]{0,63}$/;
937
+ const HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;
938
+ const ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;
936
939
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
937
940
  const MinorUnitStringSchema = Schema.String.pipe(Schema.filter((value) => MINOR_UNIT_STRING_RE.test(value), { message: () => "must be a non-negative integer minor-unit string" }));
938
941
  const PaymentIdSchema = Schema.String.pipe(Schema.filter((value) => PAYMENT_ID_RE.test(value), { message: () => "must be payment_ plus an alphanumeric id" }));
939
942
  const PayeeIdSchema = Schema.String.pipe(Schema.filter((value) => PAYEE_ID_RE.test(value), { message: () => "must be payee_ plus an alphanumeric id" }));
940
943
  const OrgIdSchema = Schema.String.pipe(Schema.filter((value) => ORG_ID_RE.test(value), { message: () => "must be org_ plus an alphanumeric id" }));
944
+ const UserIdSchema = Schema.String.pipe(Schema.filter((value) => USER_ID_RE.test(value), { message: () => "must be user_ plus an alphanumeric id" }));
941
945
  const DecimalStringSchema = Schema.String.pipe(Schema.filter((value) => DECIMAL_STRING_RE.test(value), { message: () => "must be a non-negative decimal string" }));
942
- const PaymentRecipientRefSchema = Schema.String.pipe(Schema.filter((value) => !EVM_ADDRESS_RE.test(value) && (PAYEE_ID_RE.test(value) || ORG_ID_RE.test(value) || USER_ID_RE.test(value) || HANDLE_RE.test(value) || EMAIL_RE.test(value)), { message: () => "must be a handle, email, user id, org id, or payee id; raw addresses are not accepted" }));
946
+ const HandleValueSchema = Schema.String.pipe(Schema.filter((value) => !EVM_ADDRESS_RE.test(value) && HANDLE_RE.test(value), { message: () => "must be a handle; raw addresses are not accepted" }));
947
+ const OrgHandleValueSchema = Schema.String.pipe(Schema.filter((value) => !EVM_ADDRESS_RE.test(value) && ORG_HANDLE_RE.test(value), { message: () => "must be an org handle; raw addresses are not accepted" }));
948
+ const EmailValueSchema = Schema.String.pipe(Schema.filter((value) => !EVM_ADDRESS_RE.test(value) && EMAIL_RE.test(value), { message: () => "must be an email; raw addresses are not accepted" }));
943
949
  const Uint8Schema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0 && value <= 255, { message: () => "must be a uint8" }));
944
950
  const Uint64Schema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0, { message: () => "must be a non-negative safe integer" }));
945
951
  const PaymentDocumentDomain = Schema.Struct({
@@ -1021,7 +1027,7 @@ function paymentTypeForDocumentKind(kind) {
1021
1027
  case "withdrawal": return "unspecified";
1022
1028
  }
1023
1029
  }
1024
- const PaymentDocumentEnvelope = Schema.Union(Schema.Struct({
1030
+ const AttachablePaymentDocumentEnvelope = Schema.Union(Schema.Struct({
1025
1031
  protocol: Schema.Literal("capxul.payment-document"),
1026
1032
  version: Schema.Literal(1),
1027
1033
  domain: PaymentDocumentDomain,
@@ -1045,13 +1051,15 @@ const PaymentDocumentEnvelope = Schema.Union(Schema.Struct({
1045
1051
  domain: PaymentDocumentDomain,
1046
1052
  primaryType: Schema.Literal("Receipt"),
1047
1053
  message: ReceiptDocument
1048
- }), Schema.Struct({
1054
+ }));
1055
+ const WithdrawalDocumentEnvelope = Schema.Struct({
1049
1056
  protocol: Schema.Literal("capxul.payment-document"),
1050
1057
  version: Schema.Literal(1),
1051
1058
  domain: PaymentDocumentDomain,
1052
1059
  primaryType: Schema.Literal("Withdrawal"),
1053
1060
  message: WithdrawalDocument
1054
- }));
1061
+ });
1062
+ const PaymentDocumentEnvelope = Schema.Union(AttachablePaymentDocumentEnvelope, WithdrawalDocumentEnvelope);
1055
1063
  Schema.Struct({
1056
1064
  payeeId: PayeeIdSchema,
1057
1065
  label: Schema.String,
@@ -1059,7 +1067,7 @@ Schema.Struct({
1059
1067
  destinationKind: Schema.Literal("handle", "email", "saved-payee", "org")
1060
1068
  });
1061
1069
  const PaymentRecipient = Schema.Struct({
1062
- kind: Schema.Literal("handle", "email", "payee", "me", "org", "external_address"),
1070
+ kind: Schema.Literal("handle", "email", "payee", "capxulUserId", "me", "org", "external_address"),
1063
1071
  label: Schema.String,
1064
1072
  payeeId: Schema.optional(PayeeIdSchema)
1065
1073
  });
@@ -1071,7 +1079,7 @@ const PaymentRecipient = Schema.Struct({
1071
1079
  * crosses the model wire; it lives on the kind:4 Withdrawal document only.
1072
1080
  */
1073
1081
  const ExternalAddressSchema = Schema.String.pipe(Schema.filter((value) => EVM_ADDRESS_RE.test(value), { message: () => "must be a 0x EVM address (40 hex chars)" }));
1074
- const PaymentRelease = Schema.Union(Schema.Struct({ kind: Schema.Literal("instant") }), Schema.Struct({
1082
+ const PaymentTiming = Schema.Union(Schema.Struct({ kind: Schema.Literal("instant") }), Schema.Struct({
1075
1083
  kind: Schema.Literal("scheduled"),
1076
1084
  at: EpochMsSchema$1
1077
1085
  }), Schema.Struct({
@@ -1080,6 +1088,22 @@ const PaymentRelease = Schema.Union(Schema.Struct({ kind: Schema.Literal("instan
1080
1088
  endsAt: EpochMsSchema$1,
1081
1089
  cliffAt: Schema.optional(EpochMsSchema$1)
1082
1090
  }));
1091
+ const PaymentRef = Schema.Union(Schema.Struct({
1092
+ kind: Schema.Literal("handle"),
1093
+ handle: HandleValueSchema
1094
+ }), Schema.Struct({
1095
+ kind: Schema.Literal("email"),
1096
+ email: EmailValueSchema
1097
+ }), Schema.Struct({
1098
+ kind: Schema.Literal("orgHandle"),
1099
+ orgHandle: OrgHandleValueSchema
1100
+ }), Schema.Struct({
1101
+ kind: Schema.Literal("capxulUserId"),
1102
+ capxulUserId: UserIdSchema
1103
+ }), Schema.Struct({
1104
+ kind: Schema.Literal("payeeId"),
1105
+ payeeId: PayeeIdSchema
1106
+ }));
1083
1107
  const Payment = Schema.Struct({
1084
1108
  id: PaymentIdSchema,
1085
1109
  status: Schema.Literal("pending", "submitted", "pending_claim", "scheduled", "streaming", "settled", "cancelled", "redirected", "expired", "failed"),
@@ -1087,7 +1111,7 @@ const Payment = Schema.Struct({
1087
1111
  paymentType: PaymentType,
1088
1112
  recipient: PaymentRecipient,
1089
1113
  documents: Schema.Array(PaymentDocument),
1090
- release: PaymentRelease,
1114
+ timing: PaymentTiming,
1091
1115
  released: FinancialOpsMoney,
1092
1116
  availableToClaim: FinancialOpsMoney,
1093
1117
  createdAt: EpochMsSchema$1,
@@ -1115,16 +1139,16 @@ const LineItem = Schema.Struct({
1115
1139
  });
1116
1140
  Schema.Struct({
1117
1141
  from: Schema.optional(PaymentSource),
1118
- to: Schema.Union(PaymentRecipientRefSchema, Schema.Array(PaymentRecipientRefSchema)),
1142
+ to: PaymentRef,
1119
1143
  amount: FinancialOpsMoney,
1120
- release: Schema.optional(PaymentRelease),
1121
- document: Schema.optional(PaymentDocument),
1144
+ timing: Schema.optional(PaymentTiming),
1145
+ document: Schema.optional(AttachablePaymentDocumentEnvelope),
1122
1146
  lineItems: Schema.optional(Schema.Array(LineItem))
1123
1147
  });
1124
1148
  Schema.Struct({
1125
1149
  to: ExternalAddressSchema,
1126
1150
  amount: FinancialOpsMoney,
1127
- document: PaymentDocumentEnvelope
1151
+ document: WithdrawalDocumentEnvelope
1128
1152
  });
1129
1153
  Schema.Struct({
1130
1154
  protocol: Schema.Literal("capxul.me"),
@@ -1441,7 +1465,8 @@ function makeWirePayment(input) {
1441
1465
  documents: input.documents.map((doc) => ({
1442
1466
  documentHash: doc.documentHash,
1443
1467
  kind: doc.kind
1444
- }))
1468
+ })),
1469
+ timing: cloneTiming(input.timing)
1445
1470
  };
1446
1471
  const safe = assertWireSafe(wire);
1447
1472
  if (!safe.ok) throw new Error(`wire Payment leaked a forbidden custody field: ${safe.leakedField}`);
@@ -1454,6 +1479,21 @@ function cloneMoney(money) {
1454
1479
  decimals: money.decimals
1455
1480
  };
1456
1481
  }
1482
+ function cloneTiming(timing) {
1483
+ switch (timing.kind) {
1484
+ case "instant": return { kind: "instant" };
1485
+ case "scheduled": return {
1486
+ kind: "scheduled",
1487
+ at: timing.at
1488
+ };
1489
+ case "stream": return {
1490
+ kind: "stream",
1491
+ startsAt: timing.startsAt,
1492
+ endsAt: timing.endsAt,
1493
+ ...timing.cliffAt === void 0 ? {} : { cliffAt: timing.cliffAt }
1494
+ };
1495
+ }
1496
+ }
1457
1497
  /** The ONE way to brand a userOp/tx hash pair as internal on-chain evidence. */
1458
1498
  function makeOnchainEvidence(pair) {
1459
1499
  return {
@@ -1554,6 +1594,19 @@ const MONEY_SCHEMA = z.object({
1554
1594
  value: z.string(),
1555
1595
  decimals: z.number().int()
1556
1596
  });
1597
+ const TIMING_SCHEMA = z.union([
1598
+ z.object({ kind: z.literal("instant") }),
1599
+ z.object({
1600
+ kind: z.literal("scheduled"),
1601
+ at: z.number().int().nonnegative()
1602
+ }),
1603
+ z.object({
1604
+ kind: z.literal("stream"),
1605
+ startsAt: z.number().int().nonnegative(),
1606
+ endsAt: z.number().int().nonnegative(),
1607
+ cliffAt: z.number().int().nonnegative().optional()
1608
+ })
1609
+ ]);
1557
1610
  /**
1558
1611
  * The ONE Zod `outputSchema` for the leak-safe wire Payment, built from the
1559
1612
  * canonical `WIRE_PAYMENT_SCHEMA_FIELDS` so the field set is declared once.
@@ -1576,6 +1629,7 @@ const PAYMENT_OUTPUT = {
1576
1629
  "handle",
1577
1630
  "email",
1578
1631
  "payee",
1632
+ "capxulUserId",
1579
1633
  "me",
1580
1634
  "org",
1581
1635
  "external_address"
@@ -1592,7 +1646,8 @@ const PAYMENT_OUTPUT = {
1592
1646
  "receipt",
1593
1647
  "withdrawal"
1594
1648
  ])
1595
- }))
1649
+ })),
1650
+ timing: TIMING_SCHEMA
1596
1651
  };
1597
1652
  /**
1598
1653
  * Project an SDK Payment to the leak-safe wire Payment via the ONE
@@ -1645,7 +1700,7 @@ function parsePaymentAmount(raw) {
1645
1700
  }
1646
1701
  //#endregion
1647
1702
  //#region src/tools/org.ts
1648
- function unknownSessionError$3() {
1703
+ function unknownSessionError$4() {
1649
1704
  return Errors.notAuthenticated("unknown or expired session token");
1650
1705
  }
1651
1706
  const ORG_VIEW = {
@@ -1696,7 +1751,7 @@ function registerOrgTools(server, deps) {
1696
1751
  outputSchema: ORG_VIEW
1697
1752
  }, ({ sessionToken, name, handle, template, country }) => guarded(async () => {
1698
1753
  const entry = requireSession(deps, sessionToken);
1699
- if (entry === void 0) return errorResult(unknownSessionError$3());
1754
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1700
1755
  const createOrg = entry.handle.createOrg;
1701
1756
  if (createOrg === void 0) return errorResult(Errors.notImplemented("org", "create"));
1702
1757
  const result = await createOrg({
@@ -1714,7 +1769,7 @@ function registerOrgTools(server, deps) {
1714
1769
  outputSchema: { orgs: z.array(z.object(ORG_VIEW)) }
1715
1770
  }, ({ sessionToken }) => guarded(async () => {
1716
1771
  const entry = requireSession(deps, sessionToken);
1717
- if (entry === void 0) return errorResult(unknownSessionError$3());
1772
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1718
1773
  const orgList = entry.handle.orgList;
1719
1774
  if (orgList === void 0) return errorResult(Errors.notImplemented("org", "list"));
1720
1775
  const result = await orgList();
@@ -1730,7 +1785,7 @@ function registerOrgTools(server, deps) {
1730
1785
  outputSchema: { members: z.array(z.object(MEMBER_VIEW)) }
1731
1786
  }, ({ sessionToken, orgId }) => guarded(async () => {
1732
1787
  const entry = requireSession(deps, sessionToken);
1733
- if (entry === void 0) return errorResult(unknownSessionError$3());
1788
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1734
1789
  const orgMembers = entry.handle.orgMembers;
1735
1790
  if (orgMembers === void 0) return errorResult(Errors.notImplemented("org", "members"));
1736
1791
  const result = await orgMembers(orgId);
@@ -1746,7 +1801,7 @@ function registerOrgTools(server, deps) {
1746
1801
  outputSchema: { roles: z.array(z.object(ROLE_VIEW)) }
1747
1802
  }, ({ sessionToken, orgId }) => guarded(async () => {
1748
1803
  const entry = requireSession(deps, sessionToken);
1749
- if (entry === void 0) return errorResult(unknownSessionError$3());
1804
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1750
1805
  const orgRoles = entry.handle.orgRoles;
1751
1806
  if (orgRoles === void 0) return errorResult(Errors.notImplemented("org", "roles"));
1752
1807
  const result = await orgRoles(orgId);
@@ -1764,7 +1819,7 @@ function registerOrgTools(server, deps) {
1764
1819
  outputSchema: MEMBER_VIEW
1765
1820
  }, ({ sessionToken, orgId, email, role }) => guarded(async () => {
1766
1821
  const entry = requireSession(deps, sessionToken);
1767
- if (entry === void 0) return errorResult(unknownSessionError$3());
1822
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1768
1823
  const orgInvite = entry.handle.orgInvite;
1769
1824
  if (orgInvite === void 0) return errorResult(Errors.notImplemented("org", "invite"));
1770
1825
  const result = await orgInvite({
@@ -1786,7 +1841,7 @@ function registerOrgTools(server, deps) {
1786
1841
  outputSchema: MEMBER_VIEW
1787
1842
  }, ({ sessionToken, orgId, email, role }) => guarded(async () => {
1788
1843
  const entry = requireSession(deps, sessionToken);
1789
- if (entry === void 0) return errorResult(unknownSessionError$3());
1844
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1790
1845
  const assign = entry.handle.orgAssignRole;
1791
1846
  if (assign === void 0) return errorResult(Errors.notImplemented("org", "assignRole"));
1792
1847
  const result = await assign({
@@ -1807,7 +1862,7 @@ function registerOrgTools(server, deps) {
1807
1862
  outputSchema: { removed: z.boolean() }
1808
1863
  }, ({ sessionToken, orgId, email }) => guarded(async () => {
1809
1864
  const entry = requireSession(deps, sessionToken);
1810
- if (entry === void 0) return errorResult(unknownSessionError$3());
1865
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1811
1866
  const remove = entry.handle.orgRemoveMember;
1812
1867
  if (remove === void 0) return errorResult(Errors.notImplemented("org", "removeMember"));
1813
1868
  const result = await remove({
@@ -1830,7 +1885,7 @@ function registerOrgTools(server, deps) {
1830
1885
  outputSchema: PAYMENT_OUTPUT
1831
1886
  }, ({ sessionToken, orgId, from, to, amount, document }) => guarded(async () => {
1832
1887
  const entry = requireSession(deps, sessionToken);
1833
- if (entry === void 0) return errorResult(unknownSessionError$3());
1888
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1834
1889
  const parsed = parsePaymentAmount(amount);
1835
1890
  if (!parsed.ok) return errorResult(parsed.error);
1836
1891
  const ready = await requireCanTransact(entry.handle, "org.spendViaPayments");
@@ -1863,7 +1918,7 @@ function registerOrgTools(server, deps) {
1863
1918
  outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
1864
1919
  }, ({ sessionToken, orgId, from, runs }) => guarded(async () => {
1865
1920
  const entry = requireSession(deps, sessionToken);
1866
- if (entry === void 0) return errorResult(unknownSessionError$3());
1921
+ if (entry === void 0) return errorResult(unknownSessionError$4());
1867
1922
  const parsedRuns = [];
1868
1923
  for (const run of runs) {
1869
1924
  const parsed = parsePaymentAmount(run.amount);
@@ -1911,7 +1966,7 @@ const RELEASE_SCHEMA = z.union([
1911
1966
  cliffAt: z.number().int().nonnegative().optional()
1912
1967
  })
1913
1968
  ]).optional();
1914
- function unknownSessionError$2() {
1969
+ function unknownSessionError$3() {
1915
1970
  return Errors.notAuthenticated("unknown or expired session token");
1916
1971
  }
1917
1972
  function registerPaymentTools(server, deps) {
@@ -1934,7 +1989,7 @@ function registerPaymentTools(server, deps) {
1934
1989
  outputSchema: PAYMENT_OUTPUT
1935
1990
  }, ({ sessionToken, to, amount, document, release, lineItems }) => guarded(async () => {
1936
1991
  const entry = requireSession(deps, sessionToken);
1937
- if (entry === void 0) return errorResult(unknownSessionError$2());
1992
+ if (entry === void 0) return errorResult(unknownSessionError$3());
1938
1993
  const parsedAmount = parsePaymentAmount(amount);
1939
1994
  if (!parsedAmount.ok) return errorResult(parsedAmount.error);
1940
1995
  const lifecycle = await entry.handle.getLifecycle();
@@ -1968,7 +2023,7 @@ function registerPaymentTools(server, deps) {
1968
2023
  outputSchema: PAYMENT_OUTPUT
1969
2024
  }, ({ sessionToken, to, amount, document }) => guarded(async () => {
1970
2025
  const entry = requireSession(deps, sessionToken);
1971
- if (entry === void 0) return errorResult(unknownSessionError$2());
2026
+ if (entry === void 0) return errorResult(unknownSessionError$3());
1972
2027
  const parsedAmount = parsePaymentAmount(amount);
1973
2028
  if (!parsedAmount.ok) return errorResult(parsedAmount.error);
1974
2029
  const lifecycle = await entry.handle.getLifecycle();
@@ -1995,7 +2050,7 @@ function registerPaymentTools(server, deps) {
1995
2050
  outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
1996
2051
  }, ({ sessionToken }) => guarded(async () => {
1997
2052
  const entry = requireSession(deps, sessionToken);
1998
- if (entry === void 0) return errorResult(unknownSessionError$2());
2053
+ if (entry === void 0) return errorResult(unknownSessionError$3());
1999
2054
  const list = entry.handle.listPayments;
2000
2055
  if (list === void 0) return errorResult(Errors.notImplemented("payments", "list"));
2001
2056
  const result = await list();
@@ -2012,7 +2067,7 @@ function registerPaymentTools(server, deps) {
2012
2067
  outputSchema: { payment: z.object(PAYMENT_OUTPUT).nullable() }
2013
2068
  }, ({ sessionToken, paymentId }) => guarded(async () => {
2014
2069
  const entry = requireSession(deps, sessionToken);
2015
- if (entry === void 0) return errorResult(unknownSessionError$2());
2070
+ if (entry === void 0) return errorResult(unknownSessionError$3());
2016
2071
  const get = entry.handle.getPayment;
2017
2072
  if (get === void 0) return errorResult(Errors.notImplemented("payments", "get"));
2018
2073
  const result = await get(paymentId);
@@ -2070,7 +2125,7 @@ function registerPaymentTools(server, deps) {
2070
2125
  }
2071
2126
  }, ({ sessionToken, documentHash }) => guarded(async () => {
2072
2127
  const entry = requireSession(deps, sessionToken);
2073
- if (entry === void 0) return errorResult(unknownSessionError$2());
2128
+ if (entry === void 0) return errorResult(unknownSessionError$3());
2074
2129
  const verify = entry.handle.verifyPaymentDocument;
2075
2130
  if (verify === void 0) return errorResult(Errors.notImplemented("paymentDocuments", "verify"));
2076
2131
  const result = await verify(documentHash);
@@ -2096,7 +2151,7 @@ function registerPaymentTools(server, deps) {
2096
2151
  }
2097
2152
  }, ({ sessionToken, documentHash }) => guarded(async () => {
2098
2153
  const entry = requireSession(deps, sessionToken);
2099
- if (entry === void 0) return errorResult(unknownSessionError$2());
2154
+ if (entry === void 0) return errorResult(unknownSessionError$3());
2100
2155
  const render = entry.handle.renderPaymentDocument;
2101
2156
  if (render === void 0) return errorResult(Errors.notImplemented("paymentDocuments", "render"));
2102
2157
  const result = await render(documentHash);
@@ -2110,7 +2165,7 @@ function registerPaymentTools(server, deps) {
2110
2165
  }
2111
2166
  async function runCommitmentOp(deps, sessionToken, action, invoke) {
2112
2167
  const entry = requireSession(deps, sessionToken);
2113
- if (entry === void 0) return errorResult(unknownSessionError$2());
2168
+ if (entry === void 0) return errorResult(unknownSessionError$3());
2114
2169
  const lifecycle = await entry.handle.getLifecycle();
2115
2170
  if (!lifecycle.ok) return errorResult(lifecycle.error);
2116
2171
  if (lifecycle.value.status !== "ready" || lifecycle.value.canTransact !== true) return errorResult(Errors.wrongState({
@@ -2165,7 +2220,7 @@ function toRequestOutput(request) {
2165
2220
  expiresAt: request.expiresAt
2166
2221
  };
2167
2222
  }
2168
- function unknownSessionError$1() {
2223
+ function unknownSessionError$2() {
2169
2224
  return Errors.notAuthenticated("unknown or expired session token");
2170
2225
  }
2171
2226
  function requestErrorResult(error) {
@@ -2204,7 +2259,7 @@ function parseAmount(raw) {
2204
2259
  /** Session-gated driver for a request-id lifecycle op. */
2205
2260
  async function runRequestOp(deps, sessionToken, invoke, method) {
2206
2261
  const entry = requireSession(deps, sessionToken);
2207
- if (entry === void 0) return errorResult(unknownSessionError$1());
2262
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2208
2263
  const pending = invoke(entry.handle);
2209
2264
  if (pending === void 0) return errorResult(Errors.notImplemented("paymentRequests", method));
2210
2265
  const result = await pending;
@@ -2226,7 +2281,7 @@ function registerPaymentRequestTools(server, deps) {
2226
2281
  outputSchema: PAYMENT_REQUEST_OUTPUT
2227
2282
  }, ({ sessionToken, amount, reference, memo, expiresAt }) => guarded(async () => {
2228
2283
  const entry = requireSession(deps, sessionToken);
2229
- if (entry === void 0) return errorResult(unknownSessionError$1());
2284
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2230
2285
  const parsed = parseAmount(amount);
2231
2286
  if (!parsed.ok) return errorResult(parsed.error);
2232
2287
  const create = entry.handle.createPaymentRequest;
@@ -2283,7 +2338,7 @@ function registerPaymentRequestTools(server, deps) {
2283
2338
  outputSchema: { paymentRequests: z.array(z.object(PAYMENT_REQUEST_OUTPUT)) }
2284
2339
  }, ({ sessionToken }) => guarded(async () => {
2285
2340
  const entry = requireSession(deps, sessionToken);
2286
- if (entry === void 0) return errorResult(unknownSessionError$1());
2341
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2287
2342
  const list = entry.handle.listPaymentRequests;
2288
2343
  if (list === void 0) return errorResult(Errors.notImplemented("paymentRequests", "list"));
2289
2344
  const result = await list();
@@ -2300,7 +2355,7 @@ function registerPaymentRequestTools(server, deps) {
2300
2355
  outputSchema: { paymentRequest: z.object(PAYMENT_REQUEST_OUTPUT).nullable() }
2301
2356
  }, ({ sessionToken, paymentRequestId }) => guarded(async () => {
2302
2357
  const entry = requireSession(deps, sessionToken);
2303
- if (entry === void 0) return errorResult(unknownSessionError$1());
2358
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2304
2359
  const get = entry.handle.getPaymentRequest;
2305
2360
  if (get === void 0) return errorResult(Errors.notImplemented("paymentRequests", "get"));
2306
2361
  const result = await get(paymentRequestId);
@@ -2320,7 +2375,7 @@ function registerPaymentRequestTools(server, deps) {
2320
2375
  })) }
2321
2376
  }, ({ sessionToken }) => guarded(async () => {
2322
2377
  const entry = requireSession(deps, sessionToken);
2323
- if (entry === void 0) return errorResult(unknownSessionError$1());
2378
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2324
2379
  const reconcile = entry.handle.reconcilePaymentRequests;
2325
2380
  if (reconcile === void 0) return errorResult(Errors.notImplemented("paymentRequests", "reconcile"));
2326
2381
  const result = await reconcile();
@@ -2329,6 +2384,662 @@ function registerPaymentRequestTools(server, deps) {
2329
2384
  }, "paymentRequests.reconcile", deps.onToolCall));
2330
2385
  }
2331
2386
  //#endregion
2387
+ //#region src/tools/sdk-restart.ts
2388
+ const MONEY = z.object({
2389
+ currency: z.string(),
2390
+ value: z.string(),
2391
+ decimals: z.number().int()
2392
+ });
2393
+ const REF = z.union([
2394
+ z.object({
2395
+ kind: z.literal("handle"),
2396
+ handle: z.string()
2397
+ }),
2398
+ z.object({
2399
+ kind: z.literal("email"),
2400
+ email: z.string()
2401
+ }),
2402
+ z.object({
2403
+ kind: z.literal("orgHandle"),
2404
+ orgHandle: z.string()
2405
+ }),
2406
+ z.object({
2407
+ kind: z.literal("capxulUserId"),
2408
+ capxulUserId: z.string()
2409
+ }),
2410
+ z.object({
2411
+ kind: z.literal("payeeId"),
2412
+ payeeId: z.string()
2413
+ })
2414
+ ]);
2415
+ const TIMING = z.union([
2416
+ z.object({ kind: z.literal("instant") }),
2417
+ z.object({
2418
+ kind: z.literal("scheduled"),
2419
+ at: z.number().int().nonnegative()
2420
+ }),
2421
+ z.object({
2422
+ kind: z.literal("stream"),
2423
+ startsAt: z.number().int().nonnegative(),
2424
+ endsAt: z.number().int().nonnegative(),
2425
+ cliffAt: z.number().int().nonnegative().optional()
2426
+ })
2427
+ ]);
2428
+ const ADDRESS_BOOK_ENTRY = z.object({
2429
+ id: z.string(),
2430
+ ref: REF,
2431
+ label: z.string(),
2432
+ relationship: z.array(z.enum([
2433
+ "paid",
2434
+ "paidBy",
2435
+ "requested",
2436
+ "member",
2437
+ "employee"
2438
+ ])),
2439
+ hidden: z.boolean()
2440
+ });
2441
+ const ACTOR_REQUEST = z.object({
2442
+ id: z.string(),
2443
+ payer: REF.optional(),
2444
+ amount: MONEY,
2445
+ reference: z.string(),
2446
+ status: z.enum([
2447
+ "draft",
2448
+ "sent",
2449
+ "viewed",
2450
+ "pending_settlement",
2451
+ "paid",
2452
+ "declined",
2453
+ "cancelled",
2454
+ "expired"
2455
+ ]),
2456
+ expiresAt: z.number().nullable()
2457
+ });
2458
+ const INBOX_ITEM = z.object({
2459
+ id: z.string(),
2460
+ issuer: REF,
2461
+ amount: MONEY,
2462
+ reference: z.string(),
2463
+ status: z.enum([
2464
+ "open",
2465
+ "approved",
2466
+ "declined",
2467
+ "paid",
2468
+ "cancelled",
2469
+ "expired"
2470
+ ])
2471
+ });
2472
+ const RECONCILIATION_ENTRY = z.object({
2473
+ paymentRequestId: z.string(),
2474
+ reference: z.string(),
2475
+ status: z.enum(["paid", "exception"]),
2476
+ settledPaymentId: z.string().nullable(),
2477
+ receiptDocumentHash: z.string().nullable()
2478
+ });
2479
+ const INSIGHTS_SUMMARY = z.object({
2480
+ pending: z.object({
2481
+ count: z.number().int(),
2482
+ total: MONEY
2483
+ }),
2484
+ paidThisMonth: z.object({
2485
+ count: z.number().int(),
2486
+ total: MONEY
2487
+ }),
2488
+ drafts: z.object({ count: z.number().int() }),
2489
+ reconciliation: z.object({
2490
+ open: z.number().int(),
2491
+ exceptions: z.number().int()
2492
+ })
2493
+ });
2494
+ const DESTINATION_PAYLOAD = z.union([
2495
+ z.object({
2496
+ accountHolderName: z.string(),
2497
+ bankName: z.string(),
2498
+ country: z.string(),
2499
+ currency: z.string(),
2500
+ accountNumberLast4: z.string()
2501
+ }),
2502
+ z.object({
2503
+ provider: z.string(),
2504
+ country: z.string(),
2505
+ currency: z.string(),
2506
+ phoneNumberLast4: z.string()
2507
+ }),
2508
+ z.object({
2509
+ network: z.literal("base-sepolia"),
2510
+ address: z.string()
2511
+ })
2512
+ ]);
2513
+ const DESTINATION = z.object({
2514
+ id: z.string(),
2515
+ counterpartyId: z.string(),
2516
+ ref: REF,
2517
+ kind: z.enum([
2518
+ "bank_account",
2519
+ "mobile_money",
2520
+ "external_account"
2521
+ ]),
2522
+ label: z.string().nullable(),
2523
+ payload: DESTINATION_PAYLOAD,
2524
+ createdAt: z.number(),
2525
+ updatedAt: z.number()
2526
+ });
2527
+ const PAYROLL_LINE = z.object({
2528
+ id: z.string(),
2529
+ employee: REF,
2530
+ amount: MONEY,
2531
+ timing: TIMING,
2532
+ status: z.enum([
2533
+ "active",
2534
+ "paused",
2535
+ "ended"
2536
+ ])
2537
+ });
2538
+ const TRANSFER_RESULT = z.object({
2539
+ available: MONEY,
2540
+ from: z.unknown().nullable(),
2541
+ to: z.unknown().nullable()
2542
+ });
2543
+ function unknownSessionError$1() {
2544
+ return Errors.notAuthenticated("unknown or expired session token");
2545
+ }
2546
+ function actor(kind, orgId) {
2547
+ return kind === "account" ? { kind: "account" } : {
2548
+ kind: "org",
2549
+ orgId: orgId ?? ""
2550
+ };
2551
+ }
2552
+ function orgIdArg(args) {
2553
+ return typeof args === "object" && args !== null && "orgId" in args && typeof args.orgId === "string" ? args.orgId : void 0;
2554
+ }
2555
+ function requireMethod(handle, method, domain) {
2556
+ const value = handle[method];
2557
+ if (value === void 0) return {
2558
+ ok: false,
2559
+ error: Errors.notImplemented(domain, String(method))
2560
+ };
2561
+ return {
2562
+ ok: true,
2563
+ value
2564
+ };
2565
+ }
2566
+ async function withSession(deps, sessionToken, operation, invoke) {
2567
+ return guarded(async () => {
2568
+ const entry = requireSession(deps, sessionToken);
2569
+ if (entry === void 0) return errorResult(unknownSessionError$1());
2570
+ return invoke(entry.handle);
2571
+ }, operation, deps.onToolCall);
2572
+ }
2573
+ function result(res) {
2574
+ return res.ok ? okResult(project(res.value)) : errorResult(res.error);
2575
+ }
2576
+ function paymentResult(res) {
2577
+ return res.ok ? okResult({ ...toPaymentOutput(res.value) }) : errorResult(redactPaymentError(res.error, "sdk-restart"));
2578
+ }
2579
+ function project(value) {
2580
+ if (Array.isArray(value)) return { items: value };
2581
+ if (typeof value === "object" && value !== null) return value;
2582
+ return { value };
2583
+ }
2584
+ function methodNotImplemented(domain, method) {
2585
+ return errorResult(Errors.notImplemented(domain, method));
2586
+ }
2587
+ function registerSdkRestartTools(server, deps) {
2588
+ if (deps.paymentsEnabled !== true) return;
2589
+ registerAddressBookTools(server, deps, "account");
2590
+ registerAddressBookTools(server, deps, "org");
2591
+ registerRequestsTools(server, deps, "account");
2592
+ registerRequestsTools(server, deps, "org");
2593
+ registerInboxTools(server, deps, "account");
2594
+ registerInboxTools(server, deps, "org");
2595
+ registerInsightsTools(server, deps, "account");
2596
+ registerInsightsTools(server, deps, "org");
2597
+ registerDestinationTools(server, deps);
2598
+ registerMoneyTools(server, deps);
2599
+ registerPayrollTools(server, deps);
2600
+ }
2601
+ function registerAddressBookTools(server, deps, scope) {
2602
+ const prefix = `${scope}.addressBook`;
2603
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2604
+ server.registerTool(`${prefix}.list`, {
2605
+ title: `${scope} address book list`,
2606
+ description: "List relationship entries for one actor scope using Capxul refs and labels only.",
2607
+ inputSchema: {
2608
+ sessionToken: z.string(),
2609
+ ...scopeInput
2610
+ },
2611
+ outputSchema: { entries: z.array(ADDRESS_BOOK_ENTRY) }
2612
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.list`, async (handle) => {
2613
+ const method = requireMethod(handle, "addressBookList", prefix);
2614
+ if (!method.ok) return methodNotImplemented(prefix, "list");
2615
+ const res = await method.value(actor(scope, orgIdArg(args)));
2616
+ return res.ok ? okResult({ entries: res.value }) : errorResult(res.error);
2617
+ }));
2618
+ server.registerTool(`${prefix}.get`, {
2619
+ title: `${scope} address book get`,
2620
+ description: "Read one relationship entry by opaque entry id.",
2621
+ inputSchema: {
2622
+ sessionToken: z.string(),
2623
+ ...scopeInput,
2624
+ entryId: z.string()
2625
+ },
2626
+ outputSchema: { entry: ADDRESS_BOOK_ENTRY.nullable() }
2627
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.get`, async (handle) => {
2628
+ const method = requireMethod(handle, "addressBookGet", prefix);
2629
+ if (!method.ok) return methodNotImplemented(prefix, "get");
2630
+ const res = await method.value(actor(scope, orgIdArg(args)), args.entryId);
2631
+ return res.ok ? okResult({ entry: res.value }) : errorResult(res.error);
2632
+ }));
2633
+ server.registerTool(`${prefix}.add`, {
2634
+ title: `${scope} address book add`,
2635
+ description: "Manually add a typed Ref to an actor relationship book.",
2636
+ inputSchema: {
2637
+ sessionToken: z.string(),
2638
+ ...scopeInput,
2639
+ ref: REF,
2640
+ label: z.string().optional()
2641
+ },
2642
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2643
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.add`, async (handle) => {
2644
+ const method = requireMethod(handle, "addressBookAdd", prefix);
2645
+ if (!method.ok) return methodNotImplemented(prefix, "add");
2646
+ return result(await method.value({
2647
+ actor: actor(scope, orgIdArg(args)),
2648
+ ref: args.ref,
2649
+ label: args.label
2650
+ }));
2651
+ }));
2652
+ for (const action of ["hide", "unhide"]) server.registerTool(`${prefix}.${action}`, {
2653
+ title: `${scope} address book ${action}`,
2654
+ description: `${action} a relationship entry without deleting ledger facts.`,
2655
+ inputSchema: {
2656
+ sessionToken: z.string(),
2657
+ ...scopeInput,
2658
+ entryId: z.string()
2659
+ },
2660
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2661
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2662
+ const method = requireMethod(handle, action === "hide" ? "addressBookHide" : "addressBookUnhide", prefix);
2663
+ if (!method.ok) return methodNotImplemented(prefix, action);
2664
+ return result(await method.value(actor(scope, orgIdArg(args)), args.entryId));
2665
+ }));
2666
+ server.registerTool(`${prefix}.label`, {
2667
+ title: `${scope} address book label`,
2668
+ description: "Set a private label for a relationship entry.",
2669
+ inputSchema: {
2670
+ sessionToken: z.string(),
2671
+ ...scopeInput,
2672
+ entryId: z.string(),
2673
+ label: z.string()
2674
+ },
2675
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2676
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.label`, async (handle) => {
2677
+ const method = requireMethod(handle, "addressBookLabel", prefix);
2678
+ if (!method.ok) return methodNotImplemented(prefix, "label");
2679
+ return result(await method.value({
2680
+ actor: actor(scope, orgIdArg(args)),
2681
+ entryId: args.entryId,
2682
+ label: args.label
2683
+ }));
2684
+ }));
2685
+ }
2686
+ function registerRequestsTools(server, deps, scope) {
2687
+ const prefix = `${scope}.requests`;
2688
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2689
+ server.registerTool(`${prefix}.issue`, {
2690
+ title: `${scope} request issue`,
2691
+ description: "Issue a request to a typed payer Ref; payer inbox state is derived by the backend.",
2692
+ inputSchema: {
2693
+ sessionToken: z.string(),
2694
+ ...scopeInput,
2695
+ payer: REF,
2696
+ amount: z.string(),
2697
+ reference: z.string(),
2698
+ memo: z.string().optional(),
2699
+ expiresAt: z.number().int().nonnegative().optional()
2700
+ },
2701
+ outputSchema: ACTOR_REQUEST.shape
2702
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.issue`, async (handle) => {
2703
+ const parsed = parsePaymentAmount(args.amount);
2704
+ if (!parsed.ok) return errorResult(parsed.error);
2705
+ const method = requireMethod(handle, "actorRequestIssue", prefix);
2706
+ if (!method.ok) return methodNotImplemented(prefix, "issue");
2707
+ return result(await method.value({
2708
+ actor: actor(scope, orgIdArg(args)),
2709
+ payer: args.payer,
2710
+ amount: parsed.value,
2711
+ reference: args.reference,
2712
+ memo: args.memo,
2713
+ expiresAt: args.expiresAt
2714
+ }));
2715
+ }));
2716
+ for (const action of ["list", "reconcile"]) server.registerTool(`${prefix}.${action}`, {
2717
+ title: `${scope} requests ${action}`,
2718
+ description: `${action} request projections for one actor scope.`,
2719
+ inputSchema: {
2720
+ sessionToken: z.string(),
2721
+ ...scopeInput
2722
+ },
2723
+ outputSchema: action === "list" ? { requests: z.array(ACTOR_REQUEST) } : { entries: z.array(RECONCILIATION_ENTRY) }
2724
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2725
+ const method = requireMethod(handle, action === "list" ? "actorRequestsList" : "actorRequestsReconcile", prefix);
2726
+ if (!method.ok) return methodNotImplemented(prefix, action);
2727
+ const res = await method.value(actor(scope, orgIdArg(args)));
2728
+ return res.ok ? okResult(action === "list" ? { requests: res.value } : { entries: res.value }) : errorResult(res.error);
2729
+ }));
2730
+ for (const action of ["get", "cancel"]) server.registerTool(`${prefix}.${action}`, {
2731
+ title: `${scope} request ${action}`,
2732
+ description: `${action} one actor request by id.`,
2733
+ inputSchema: {
2734
+ sessionToken: z.string(),
2735
+ ...scopeInput,
2736
+ requestId: z.string()
2737
+ },
2738
+ outputSchema: action === "get" ? { request: ACTOR_REQUEST.nullable() } : ACTOR_REQUEST.shape
2739
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2740
+ const method = requireMethod(handle, action === "get" ? "actorRequestsGet" : "actorRequestsCancel", prefix);
2741
+ if (!method.ok) return methodNotImplemented(prefix, action);
2742
+ const res = await method.value(actor(scope, orgIdArg(args)), args.requestId);
2743
+ return res.ok ? okResult(action === "get" ? { request: res.value } : project(res.value)) : errorResult(res.error);
2744
+ }));
2745
+ }
2746
+ function registerInboxTools(server, deps, scope) {
2747
+ const prefix = `${scope}.inbox`;
2748
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2749
+ server.registerTool(`${prefix}.list`, {
2750
+ title: `${scope} inbox list`,
2751
+ description: "List payable inbox items for one actor scope.",
2752
+ inputSchema: {
2753
+ sessionToken: z.string(),
2754
+ ...scopeInput
2755
+ },
2756
+ outputSchema: { inbox: z.array(INBOX_ITEM) }
2757
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.list`, async (handle) => {
2758
+ const method = requireMethod(handle, "inboxList", prefix);
2759
+ if (!method.ok) return methodNotImplemented(prefix, "list");
2760
+ const res = await method.value(actor(scope, orgIdArg(args)));
2761
+ return res.ok ? okResult({ inbox: res.value }) : errorResult(res.error);
2762
+ }));
2763
+ server.registerTool(`${prefix}.approve`, {
2764
+ title: `${scope} inbox approve`,
2765
+ description: "Approve a payable request; backend settlement-build produces settlement inputs.",
2766
+ inputSchema: {
2767
+ sessionToken: z.string(),
2768
+ ...scopeInput,
2769
+ requestId: z.string(),
2770
+ timing: TIMING.optional()
2771
+ },
2772
+ outputSchema: PAYMENT_OUTPUT
2773
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.approve`, async (handle) => {
2774
+ const method = requireMethod(handle, "inboxApprove", prefix);
2775
+ if (!method.ok) return methodNotImplemented(prefix, "approve");
2776
+ return paymentResult(await method.value(actor(scope, orgIdArg(args)), args.requestId, args.timing));
2777
+ }));
2778
+ server.registerTool(`${prefix}.decline`, {
2779
+ title: `${scope} inbox decline`,
2780
+ description: "Decline a payable request as a typed terminal non-settling decision.",
2781
+ inputSchema: {
2782
+ sessionToken: z.string(),
2783
+ ...scopeInput,
2784
+ requestId: z.string()
2785
+ },
2786
+ outputSchema: INBOX_ITEM.shape
2787
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.decline`, async (handle) => {
2788
+ const method = requireMethod(handle, "inboxDecline", prefix);
2789
+ if (!method.ok) return methodNotImplemented(prefix, "decline");
2790
+ return result(await method.value(actor(scope, orgIdArg(args)), args.requestId));
2791
+ }));
2792
+ }
2793
+ function registerInsightsTools(server, deps, scope) {
2794
+ const prefix = `${scope}.insights`;
2795
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2796
+ server.registerTool(`${prefix}.summary`, {
2797
+ title: `${scope} insights summary`,
2798
+ description: "Read-only finance summary projection.",
2799
+ inputSchema: {
2800
+ sessionToken: z.string(),
2801
+ ...scopeInput
2802
+ },
2803
+ outputSchema: INSIGHTS_SUMMARY.shape
2804
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.summary`, async (handle) => {
2805
+ const method = requireMethod(handle, "insightsSummary", prefix);
2806
+ if (!method.ok) return methodNotImplemented(prefix, "summary");
2807
+ return result(await method.value(actor(scope, orgIdArg(args))));
2808
+ }));
2809
+ server.registerTool(`${prefix}.history`, {
2810
+ title: `${scope} insights history`,
2811
+ description: "Read-only payment history projection.",
2812
+ inputSchema: {
2813
+ sessionToken: z.string(),
2814
+ ...scopeInput
2815
+ },
2816
+ outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
2817
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.history`, async (handle) => {
2818
+ const method = requireMethod(handle, "insightsHistory", prefix);
2819
+ if (!method.ok) return methodNotImplemented(prefix, "history");
2820
+ const res = await method.value(actor(scope, orgIdArg(args)));
2821
+ return res.ok ? okResult({ payments: res.value.map(toPaymentOutput) }) : errorResult(res.error);
2822
+ }));
2823
+ }
2824
+ function registerDestinationTools(server, deps) {
2825
+ const actorSchema = z.object({ kind: z.literal("account") }).or(z.object({
2826
+ kind: z.literal("org"),
2827
+ orgId: z.string()
2828
+ }));
2829
+ server.registerTool("destinations.add", {
2830
+ title: "Add destination",
2831
+ description: "Attach a bank account, mobile-money account, or external chain destination to a typed counterparty.",
2832
+ inputSchema: {
2833
+ sessionToken: z.string(),
2834
+ actor: actorSchema.optional(),
2835
+ ref: REF,
2836
+ kind: z.enum([
2837
+ "bank_account",
2838
+ "mobile_money",
2839
+ "external_account"
2840
+ ]),
2841
+ label: z.string().optional(),
2842
+ payload: DESTINATION_PAYLOAD
2843
+ },
2844
+ outputSchema: DESTINATION.shape
2845
+ }, (args) => withSession(deps, args.sessionToken, "destinations.add", async (handle) => {
2846
+ const method = requireMethod(handle, "addDestination", "destinations");
2847
+ if (!method.ok) return methodNotImplemented("destinations", "add");
2848
+ return result(await method.value({
2849
+ actor: args.actor,
2850
+ ref: args.ref,
2851
+ kind: args.kind,
2852
+ label: args.label,
2853
+ payload: args.payload
2854
+ }));
2855
+ }));
2856
+ server.registerTool("destinations.list", {
2857
+ title: "List destinations",
2858
+ description: "List selectable destinations attached to a counterparty.",
2859
+ inputSchema: {
2860
+ sessionToken: z.string(),
2861
+ actor: actorSchema.optional(),
2862
+ ref: REF
2863
+ },
2864
+ outputSchema: { destinations: z.array(DESTINATION) }
2865
+ }, (args) => withSession(deps, args.sessionToken, "destinations.list", async (handle) => {
2866
+ const method = requireMethod(handle, "listDestinations", "destinations");
2867
+ if (!method.ok) return methodNotImplemented("destinations", "list");
2868
+ const res = await method.value({
2869
+ actor: args.actor,
2870
+ ref: args.ref
2871
+ });
2872
+ return res.ok ? okResult({ destinations: res.value }) : errorResult(res.error);
2873
+ }));
2874
+ server.registerTool("destinations.remove", {
2875
+ title: "Remove destination",
2876
+ description: "Remove one selectable destination without deleting its counterparty.",
2877
+ inputSchema: {
2878
+ sessionToken: z.string(),
2879
+ actor: actorSchema.optional(),
2880
+ destinationId: z.string()
2881
+ },
2882
+ outputSchema: { id: z.string() }
2883
+ }, (args) => withSession(deps, args.sessionToken, "destinations.remove", async (handle) => {
2884
+ const method = requireMethod(handle, "removeDestination", "destinations");
2885
+ if (!method.ok) return methodNotImplemented("destinations", "remove");
2886
+ return result(await method.value({
2887
+ actor: args.actor,
2888
+ destinationId: args.destinationId
2889
+ }));
2890
+ }));
2891
+ }
2892
+ function registerMoneyTools(server, deps) {
2893
+ const actorSchema = z.object({ kind: z.literal("account") }).or(z.object({
2894
+ kind: z.literal("org"),
2895
+ orgId: z.string()
2896
+ }));
2897
+ server.registerTool("payments.payout", {
2898
+ title: "Payout",
2899
+ description: "Payout through a saved destination id using backend settlement-build.",
2900
+ inputSchema: {
2901
+ sessionToken: z.string(),
2902
+ actor: actorSchema.optional(),
2903
+ destinationId: z.string(),
2904
+ amount: z.string()
2905
+ },
2906
+ outputSchema: PAYMENT_OUTPUT
2907
+ }, (args) => withSession(deps, args.sessionToken, "payments.payout", async (handle) => {
2908
+ const parsed = parsePaymentAmount(args.amount);
2909
+ if (!parsed.ok) return errorResult(parsed.error);
2910
+ const method = requireMethod(handle, "payout", "payments");
2911
+ if (!method.ok) return methodNotImplemented("payments", "payout");
2912
+ return paymentResult(await method.value({
2913
+ actor: args.actor,
2914
+ destinationId: args.destinationId,
2915
+ amount: parsed.value
2916
+ }));
2917
+ }));
2918
+ server.registerTool("subAccounts.transfer", {
2919
+ title: "Transfer",
2920
+ description: "Move money within an account between main and sub-account envelopes.",
2921
+ inputSchema: {
2922
+ sessionToken: z.string(),
2923
+ from: z.string(),
2924
+ to: z.string(),
2925
+ amount: z.string()
2926
+ },
2927
+ outputSchema: TRANSFER_RESULT.shape
2928
+ }, (args) => withSession(deps, args.sessionToken, "subAccounts.transfer", async (handle) => {
2929
+ const parsed = parsePaymentAmount(args.amount);
2930
+ if (!parsed.ok) return errorResult(parsed.error);
2931
+ const method = requireMethod(handle, "transfer", "subAccounts");
2932
+ if (!method.ok) return methodNotImplemented("subAccounts", "transfer");
2933
+ return result(await method.value({
2934
+ from: args.from,
2935
+ to: args.to,
2936
+ amount: parsed.value
2937
+ }));
2938
+ }));
2939
+ }
2940
+ function registerPayrollTools(server, deps) {
2941
+ server.registerTool("org.payroll.roster.add", {
2942
+ title: "Add payroll roster line",
2943
+ description: "Add an employee Ref, amount, timing, and optional payslip template to org payroll.",
2944
+ inputSchema: {
2945
+ sessionToken: z.string(),
2946
+ orgId: z.string(),
2947
+ employee: REF,
2948
+ amount: z.string(),
2949
+ timing: TIMING,
2950
+ payslipTemplate: z.record(z.string(), z.unknown()).optional()
2951
+ },
2952
+ outputSchema: PAYROLL_LINE.shape
2953
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.add", async (handle) => {
2954
+ const parsed = parsePaymentAmount(args.amount);
2955
+ if (!parsed.ok) return errorResult(parsed.error);
2956
+ const method = requireMethod(handle, "payrollRosterAdd", "payroll");
2957
+ if (!method.ok) return methodNotImplemented("payroll", "roster.add");
2958
+ return result(await method.value({
2959
+ orgId: args.orgId,
2960
+ employee: args.employee,
2961
+ amount: parsed.value,
2962
+ timing: args.timing,
2963
+ payslipTemplate: args.payslipTemplate
2964
+ }));
2965
+ }));
2966
+ server.registerTool("org.payroll.roster.list", {
2967
+ title: "List payroll roster",
2968
+ description: "List active payroll roster lines for an org.",
2969
+ inputSchema: {
2970
+ sessionToken: z.string(),
2971
+ orgId: z.string()
2972
+ },
2973
+ outputSchema: { lines: z.array(PAYROLL_LINE) }
2974
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.list", async (handle) => {
2975
+ const method = requireMethod(handle, "payrollRosterList", "payroll");
2976
+ if (!method.ok) return methodNotImplemented("payroll", "roster.list");
2977
+ const res = await method.value(args.orgId);
2978
+ return res.ok ? okResult({ lines: res.value }) : errorResult(res.error);
2979
+ }));
2980
+ server.registerTool("org.payroll.roster.update", {
2981
+ title: "Update payroll roster line",
2982
+ description: "Update an employee Ref, amount, timing, or payslip template for one payroll roster line.",
2983
+ inputSchema: {
2984
+ sessionToken: z.string(),
2985
+ orgId: z.string(),
2986
+ rosterLineId: z.string(),
2987
+ employee: REF.optional(),
2988
+ amount: z.string().optional(),
2989
+ timing: TIMING.optional(),
2990
+ payslipTemplate: z.record(z.string(), z.unknown()).optional()
2991
+ },
2992
+ outputSchema: PAYROLL_LINE.shape
2993
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.update", async (handle) => {
2994
+ const parsed = args.amount === void 0 ? void 0 : parsePaymentAmount(args.amount);
2995
+ if (parsed !== void 0 && !parsed.ok) return errorResult(parsed.error);
2996
+ const method = requireMethod(handle, "payrollRosterUpdate", "payroll");
2997
+ if (!method.ok) return methodNotImplemented("payroll", "roster.update");
2998
+ return result(await method.value({
2999
+ orgId: args.orgId,
3000
+ rosterLineId: args.rosterLineId,
3001
+ employee: args.employee,
3002
+ amount: parsed?.value,
3003
+ timing: args.timing,
3004
+ payslipTemplate: args.payslipTemplate
3005
+ }));
3006
+ }));
3007
+ server.registerTool("org.payroll.roster.remove", {
3008
+ title: "Remove payroll roster line",
3009
+ description: "Remove one payroll roster line without deleting payment history.",
3010
+ inputSchema: {
3011
+ sessionToken: z.string(),
3012
+ orgId: z.string(),
3013
+ rosterLineId: z.string()
3014
+ },
3015
+ outputSchema: PAYROLL_LINE.shape
3016
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.remove", async (handle) => {
3017
+ const method = requireMethod(handle, "payrollRosterRemove", "payroll");
3018
+ if (!method.ok) return methodNotImplemented("payroll", "roster.remove");
3019
+ return result(await method.value(args.orgId, args.rosterLineId));
3020
+ }));
3021
+ server.registerTool("org.payroll.run", {
3022
+ title: "Run payroll",
3023
+ description: "Materialize active roster lines into one authorized batch settlement.",
3024
+ inputSchema: {
3025
+ sessionToken: z.string(),
3026
+ orgId: z.string(),
3027
+ period: z.string(),
3028
+ from: z.string()
3029
+ },
3030
+ outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
3031
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.run", async (handle) => {
3032
+ const method = requireMethod(handle, "payrollRun", "payroll");
3033
+ if (!method.ok) return methodNotImplemented("payroll", "run");
3034
+ const res = await method.value({
3035
+ orgId: args.orgId,
3036
+ period: args.period,
3037
+ from: args.from
3038
+ });
3039
+ return res.ok ? okResult({ payments: res.value.map(toPaymentOutput) }) : errorResult(redactPaymentError(res.error, "org.payroll.run"));
3040
+ }));
3041
+ }
3042
+ //#endregion
2332
3043
  //#region src/tools/system.ts
2333
3044
  function registerSystemTools(server, _deps) {
2334
3045
  server.registerTool("system.ping", {
@@ -2544,6 +3255,7 @@ const registrars = [
2544
3255
  registerPaymentTools,
2545
3256
  registerOrgTools,
2546
3257
  registerPaymentRequestTools,
3258
+ registerSdkRestartTools,
2547
3259
  registerWorkbenchTools
2548
3260
  ];
2549
3261
  function registerAllTools(server, deps) {
@@ -3601,41 +4313,482 @@ function mapProvisioningFailureStep(step) {
3601
4313
  case "deploy": return "activating";
3602
4314
  }
3603
4315
  }
3604
- function mapProvisioningPhaseToSetupStep(phase) {
3605
- switch (phase.status) {
3606
- case "idle":
3607
- case "wallet": return "connecting";
3608
- case "identity": return "registering";
3609
- case "provision":
3610
- case "deploy": return "activating";
3611
- case "ready":
3612
- case "failed": return "connecting";
4316
+ function mapProvisioningPhaseToSetupStep(phase) {
4317
+ switch (phase.status) {
4318
+ case "idle":
4319
+ case "wallet": return "connecting";
4320
+ case "identity": return "registering";
4321
+ case "provision":
4322
+ case "deploy": return "activating";
4323
+ case "ready":
4324
+ case "failed": return "connecting";
4325
+ }
4326
+ }
4327
+ function readyLifecycle(status, accountId) {
4328
+ return {
4329
+ status: "ready",
4330
+ accountId,
4331
+ canTransact: status.status === "accountReady" && status.deployment.status === "deployed"
4332
+ };
4333
+ }
4334
+ function mapAccountLifecycle(input) {
4335
+ const { status, phase, requirement, accountId } = input;
4336
+ if (status.status === "notAuthenticated") return { status: "loading" };
4337
+ if (phase.status === "failed") return {
4338
+ status: "failed",
4339
+ at: mapProvisioningFailureStep(phase.at),
4340
+ error: phase.error
4341
+ };
4342
+ if (isRequirementMet(status, requirement) || phase.status === "ready") {
4343
+ if (accountId === void 0) return { status: "loading" };
4344
+ return readyLifecycle(status, accountId);
4345
+ }
4346
+ if (isActiveProvisioningPhase(phase) || phase.status === "idle") return {
4347
+ status: "settingUp",
4348
+ step: mapProvisioningPhaseToSetupStep(phase)
4349
+ };
4350
+ return { status: "loading" };
4351
+ }
4352
+ //#endregion
4353
+ //#region ../../packages/sdk/src/client/actor-scope.ts
4354
+ function makeActorRelationshipMethods(deps) {
4355
+ const domain = deps.actor.kind === "account" ? "account" : "org";
4356
+ const actor = deps.actor;
4357
+ const convexCall = deps.convexCall;
4358
+ if (convexCall === void 0) return makeNotImplementedActorRelationshipMethods(deps, domain);
4359
+ const fns = ACTOR_RELATIONSHIP_FUNCTIONS;
4360
+ return {
4361
+ addressBook: {
4362
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
4363
+ get: async (entryId, options) => {
4364
+ const ref = refFromEntryId(entryId);
4365
+ if (!ref.ok) return ref;
4366
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
4367
+ actor,
4368
+ ref: ref.value
4369
+ })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
4370
+ },
4371
+ add: async (input, options) => {
4372
+ const ref = normalizeRefForBackend$1(input.ref, "ref");
4373
+ if (!ref.ok) return ref;
4374
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
4375
+ actor,
4376
+ ref: ref.value,
4377
+ ...input.label === void 0 ? {} : { label: input.label }
4378
+ })), mapAddressBookEntry);
4379
+ },
4380
+ hide: async (entryId, options) => {
4381
+ const ref = refFromEntryId(entryId);
4382
+ if (!ref.ok) return ref;
4383
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
4384
+ actor,
4385
+ ref: ref.value
4386
+ })), mapAddressBookEntry);
4387
+ },
4388
+ unhide: async (entryId, options) => {
4389
+ const ref = refFromEntryId(entryId);
4390
+ if (!ref.ok) return ref;
4391
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
4392
+ actor,
4393
+ ref: ref.value
4394
+ })), mapAddressBookEntry);
4395
+ },
4396
+ label: async (input, options) => {
4397
+ const ref = refFromEntryId(input.entryId);
4398
+ if (!ref.ok) return ref;
4399
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
4400
+ actor,
4401
+ ref: ref.value,
4402
+ label: input.label
4403
+ })), mapAddressBookEntry);
4404
+ }
4405
+ },
4406
+ requests: {
4407
+ issue: async (input, options) => {
4408
+ const payer = normalizeRefForBackend$1(input.payer, "payer");
4409
+ if (!payer.ok) return payer;
4410
+ return mapOk$2(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
4411
+ actor,
4412
+ payer: payer.value,
4413
+ amount: input.amount,
4414
+ reference: input.reference,
4415
+ ...input.memo === void 0 ? {} : { memo: input.memo },
4416
+ ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
4417
+ })), (request) => mapActorRequest(request, input.payer));
4418
+ },
4419
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
4420
+ get: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.get", () => convexCall.query(fns.requestsGet, {
4421
+ actor,
4422
+ paymentRequestId: requestId
4423
+ })), (request) => request === null ? null : mapActorRequest(request)),
4424
+ cancel: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
4425
+ actor,
4426
+ paymentRequestId: requestId
4427
+ })), (request) => mapActorRequest(request)),
4428
+ reconcile: async (options) => {
4429
+ return mapOk$2(awaitableConvex(options?.signal, "requests.reconcile", () => convexCall.query(fns.requestsReconcile, { actor })), (entries) => entries.map(mapReconciliationEntry));
4430
+ }
4431
+ },
4432
+ inbox: {
4433
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
4434
+ approve: (input, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.approve", () => convexCall.mutation(fns.inboxApprove, {
4435
+ actor,
4436
+ paymentRequestId: input.requestId,
4437
+ ...input.timing === void 0 ? {} : { timing: input.timing }
4438
+ })), mapApprovedInboxPayment),
4439
+ decline: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
4440
+ actor,
4441
+ paymentRequestId: requestId
4442
+ })), mapInboxItem)
4443
+ },
4444
+ insights: {
4445
+ summary: (options) => awaitableConvex(options?.signal, "insights.summary", () => convexCall.query(fns.insightsSummary, { actor })),
4446
+ history: (options) => mapOk$2(awaitableConvex(options?.signal, "insights.history", () => convexCall.query(fns.insightsHistory, { actor })), (history) => history.transactions.map(normalizePaymentTiming$2))
4447
+ },
4448
+ profile: {
4449
+ get: (options) => {
4450
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
4451
+ return missingConvexCall$1(`${domain}.profile.get`);
4452
+ },
4453
+ depositInstructions: (options) => {
4454
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
4455
+ return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4456
+ }
4457
+ }
4458
+ };
4459
+ }
4460
+ function makeNotImplementedActorRelationshipMethods(deps, domain) {
4461
+ return {
4462
+ addressBook: {
4463
+ list: () => missingConvexCall$1("addressBook.list"),
4464
+ get: () => missingConvexCall$1("addressBook.get"),
4465
+ add: () => missingConvexCall$1("addressBook.add"),
4466
+ hide: () => missingConvexCall$1("addressBook.hide"),
4467
+ unhide: () => missingConvexCall$1("addressBook.unhide"),
4468
+ label: () => missingConvexCall$1("addressBook.label")
4469
+ },
4470
+ requests: {
4471
+ issue: () => missingConvexCall$1("requests.issue"),
4472
+ list: () => missingConvexCall$1("requests.list"),
4473
+ get: () => missingConvexCall$1("requests.get"),
4474
+ cancel: () => missingConvexCall$1("requests.cancel"),
4475
+ reconcile: () => missingConvexCall$1("requests.reconcile")
4476
+ },
4477
+ inbox: {
4478
+ list: () => missingConvexCall$1("inbox.list"),
4479
+ approve: () => missingConvexCall$1("inbox.approve"),
4480
+ decline: () => missingConvexCall$1("inbox.decline")
4481
+ },
4482
+ insights: {
4483
+ summary: () => missingConvexCall$1("insights.summary"),
4484
+ history: () => missingConvexCall$1("insights.history")
4485
+ },
4486
+ profile: {
4487
+ get: (options) => {
4488
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
4489
+ return missingConvexCall$1(`${domain}.profile.get`);
4490
+ },
4491
+ depositInstructions: (options) => {
4492
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
4493
+ return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4494
+ }
4495
+ }
4496
+ };
4497
+ }
4498
+ async function mapAccountProfile(resultPromise) {
4499
+ const result = await resultPromise;
4500
+ if (!result.ok) return result;
4501
+ return {
4502
+ ok: true,
4503
+ value: {
4504
+ actor: { kind: "account" },
4505
+ displayName: result.value.displayName,
4506
+ email: result.value.email
4507
+ }
4508
+ };
4509
+ }
4510
+ function missingConvexCall$1(operation) {
4511
+ return Promise.resolve({
4512
+ ok: false,
4513
+ error: Errors.providerError("convex", operation, "ConvexCallPort is required")
4514
+ });
4515
+ }
4516
+ const ACTOR_RELATIONSHIP_FUNCTIONS = {
4517
+ addressBookList: makeFunctionReference("financialOps/addressBook:list"),
4518
+ addressBookGet: makeFunctionReference("financialOps/addressBook:get"),
4519
+ addressBookAdd: makeFunctionReference("financialOps/addressBook:add"),
4520
+ addressBookHide: makeFunctionReference("financialOps/addressBook:hide"),
4521
+ addressBookUnhide: makeFunctionReference("financialOps/addressBook:unhide"),
4522
+ addressBookLabel: makeFunctionReference("financialOps/addressBook:label"),
4523
+ requestsIssue: makeFunctionReference("financialOps/requestsInbox:issue"),
4524
+ requestsList: makeFunctionReference("financialOps/requestsInbox:list"),
4525
+ requestsGet: makeFunctionReference("financialOps/requestsInbox:get"),
4526
+ requestsCancel: makeFunctionReference("financialOps/requestsInbox:cancel"),
4527
+ requestsReconcile: makeFunctionReference("financialOps/requestsInbox:reconcile"),
4528
+ inboxList: makeFunctionReference("financialOps/requestsInbox:inboxList"),
4529
+ inboxApprove: makeFunctionReference("financialOps/requestsInbox:approve"),
4530
+ inboxDecline: makeFunctionReference("financialOps/requestsInbox:decline"),
4531
+ insightsSummary: makeFunctionReference("financialOps/insights:summary"),
4532
+ insightsHistory: makeFunctionReference("financialOps/insights:history")
4533
+ };
4534
+ async function mapOk$2(resultOrPromise, f) {
4535
+ const result = await resultOrPromise;
4536
+ if (!result.ok) return result;
4537
+ return {
4538
+ ok: true,
4539
+ value: f(result.value)
4540
+ };
4541
+ }
4542
+ async function runConvexIfActive(signal, operation, effect) {
4543
+ if (signal?.aborted === true) return {
4544
+ ok: false,
4545
+ error: Errors.cancelled({ operation })
4546
+ };
4547
+ const result = await Effect.runPromise(effect().pipe(Effect.mapError((error) => error.publicError), Effect.catchAllDefect((defect) => Effect.fail(Errors.unknown(defect))), Effect.either));
4548
+ if (Either.isLeft(result)) return {
4549
+ ok: false,
4550
+ error: result.left
4551
+ };
4552
+ return {
4553
+ ok: true,
4554
+ value: result.right
4555
+ };
4556
+ }
4557
+ const awaitableConvex = runConvexIfActive;
4558
+ function mapAddressBookEntry(entry) {
4559
+ const relationship = /* @__PURE__ */ new Set();
4560
+ for (const edge of entry.edges) {
4561
+ if (edge === "paid") relationship.add("paid");
4562
+ if (edge === "paidBy") relationship.add("paidBy");
4563
+ if (edge === "requested" || edge === "requestedBy") relationship.add("requested");
4564
+ if (edge === "member") relationship.add("member");
4565
+ if (edge === "employee") relationship.add("employee");
4566
+ }
4567
+ return {
4568
+ id: entry.id,
4569
+ ref: entry.ref,
4570
+ label: entry.label ?? entry.identity?.label ?? refLabel(entry.ref),
4571
+ relationship: [...relationship],
4572
+ hidden: entry.hidden
4573
+ };
4574
+ }
4575
+ function mapActorRequest(request, payer) {
4576
+ const resolvedPayer = request.payer ?? payer;
4577
+ return {
4578
+ id: request.id,
4579
+ ...resolvedPayer === void 0 ? {} : { payer: resolvedPayer },
4580
+ amount: request.amount,
4581
+ reference: request.reference,
4582
+ status: mapActorRequestStatus(request.status),
4583
+ expiresAt: request.expiresAt ?? null
4584
+ };
4585
+ }
4586
+ function mapInboxItem(item) {
4587
+ return {
4588
+ id: item.id,
4589
+ issuer: item.issuer,
4590
+ amount: item.amount,
4591
+ reference: item.reference,
4592
+ status: mapInboxStatus(item.status)
4593
+ };
4594
+ }
4595
+ function mapReconciliationEntry(entry) {
4596
+ return {
4597
+ paymentRequestId: entry.paymentRequestId,
4598
+ reference: entry.reference,
4599
+ status: entry.status,
4600
+ settledPaymentId: entry.settledPaymentId ?? null,
4601
+ receiptDocumentHash: entry.receiptDocumentHash ?? null
4602
+ };
4603
+ }
4604
+ function mapApprovedInboxPayment(item) {
4605
+ if (item.settledPayment !== void 0) return normalizePaymentTiming$2(item.settledPayment);
4606
+ const zero = {
4607
+ ...item.amount,
4608
+ value: "0"
4609
+ };
4610
+ const status = item.settledPaymentStatus ?? (item.status === "paid" ? "settled" : "pending");
4611
+ const timing = item.settledPaymentTiming ?? { kind: "instant" };
4612
+ return {
4613
+ id: item.settledPaymentId ?? `payment_${item.id}`,
4614
+ status,
4615
+ amount: item.amount,
4616
+ paymentType: "invoice",
4617
+ recipient: paymentRecipientFromRef(item.issuer),
4618
+ documents: [],
4619
+ timing,
4620
+ released: status === "settled" ? item.amount : zero,
4621
+ availableToClaim: zero,
4622
+ createdAt: item.createdAt ?? 0,
4623
+ updatedAt: item.updatedAt ?? item.createdAt ?? 0
4624
+ };
4625
+ }
4626
+ function paymentRecipientFromRef(ref) {
4627
+ switch (ref.kind) {
4628
+ case "handle": return {
4629
+ kind: "handle",
4630
+ label: ref.handle
4631
+ };
4632
+ case "email": return {
4633
+ kind: "email",
4634
+ label: ref.email
4635
+ };
4636
+ case "orgHandle": return {
4637
+ kind: "org",
4638
+ label: ref.orgHandle
4639
+ };
4640
+ case "capxulUserId": return {
4641
+ kind: "capxulUserId",
4642
+ label: ref.capxulUserId
4643
+ };
4644
+ case "payeeId": return {
4645
+ kind: "payee",
4646
+ label: ref.payeeId,
4647
+ payeeId: ref.payeeId
4648
+ };
4649
+ }
4650
+ }
4651
+ function mapActorRequestStatus(status) {
4652
+ switch (status) {
4653
+ case "draft":
4654
+ case "sent":
4655
+ case "viewed":
4656
+ case "paid":
4657
+ case "pending_settlement":
4658
+ case "declined":
4659
+ case "cancelled":
4660
+ case "expired": return status;
4661
+ default: return "sent";
4662
+ }
4663
+ }
4664
+ function mapInboxStatus(status) {
4665
+ switch (status) {
4666
+ case "approved":
4667
+ case "declined":
4668
+ case "paid":
4669
+ case "cancelled":
4670
+ case "expired": return status;
4671
+ case "pending_settlement": return "approved";
4672
+ default: return "open";
4673
+ }
4674
+ }
4675
+ function normalizePaymentTiming$2(payment) {
4676
+ const { release: _release, ...rest } = payment;
4677
+ return {
4678
+ ...rest,
4679
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
4680
+ };
4681
+ }
4682
+ function normalizeRefForBackend$1(ref, field) {
4683
+ try {
4684
+ if (typeof ref === "string") throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
4685
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
4686
+ switch (ref.kind) {
4687
+ case "handle": return {
4688
+ ok: true,
4689
+ value: {
4690
+ kind: "handle",
4691
+ handle: handleRefValue$1(ref.handle, "handle")
4692
+ }
4693
+ };
4694
+ case "email": return {
4695
+ ok: true,
4696
+ value: {
4697
+ kind: "email",
4698
+ email: nonEmptyRefValue$1(ref.email, "email")
4699
+ }
4700
+ };
4701
+ case "orgHandle": return {
4702
+ ok: true,
4703
+ value: {
4704
+ kind: "orgHandle",
4705
+ orgHandle: nonEmptyRefValue$1(ref.orgHandle, "orgHandle")
4706
+ }
4707
+ };
4708
+ case "capxulUserId": return {
4709
+ ok: true,
4710
+ value: {
4711
+ kind: "capxulUserId",
4712
+ capxulUserId: nonEmptyRefValue$1(ref.capxulUserId, "capxulUserId")
4713
+ }
4714
+ };
4715
+ case "payeeId": return {
4716
+ ok: true,
4717
+ value: {
4718
+ kind: "payeeId",
4719
+ payeeId: nonEmptyRefValue$1(ref.payeeId, "payeeId")
4720
+ }
4721
+ };
4722
+ default: throw Errors.invalidInput(field, "recipient must be a known Ref variant");
4723
+ }
4724
+ } catch (cause) {
4725
+ if (cause instanceof Error && "code" in cause) return {
4726
+ ok: false,
4727
+ error: cause
4728
+ };
4729
+ return {
4730
+ ok: false,
4731
+ error: Errors.invalidInput(field, "recipient must be a typed Ref variant")
4732
+ };
4733
+ }
4734
+ }
4735
+ function refFromEntryId(entryId) {
4736
+ try {
4737
+ const parsed = JSON.parse(entryId);
4738
+ if (typeof parsed === "object" && parsed !== null && "kind" in parsed) return normalizeRefForBackend$1(parsed, "entryId");
4739
+ } catch {}
4740
+ const separator = entryId.indexOf(":");
4741
+ if (separator === -1) return {
4742
+ ok: false,
4743
+ error: Errors.invalidInput("entryId", "must be an address-book entry id")
4744
+ };
4745
+ const prefix = entryId.slice(0, separator);
4746
+ const value = entryId.slice(separator + 1);
4747
+ switch (prefix) {
4748
+ case "email": return normalizeRefForBackend$1({
4749
+ kind: "email",
4750
+ email: value
4751
+ }, "entryId");
4752
+ case "user": return normalizeRefForBackend$1({
4753
+ kind: "capxulUserId",
4754
+ capxulUserId: value
4755
+ }, "entryId");
4756
+ case "org": return normalizeRefForBackend$1({
4757
+ kind: "orgHandle",
4758
+ orgHandle: value
4759
+ }, "entryId");
4760
+ case "payee": return normalizeRefForBackend$1({
4761
+ kind: "payeeId",
4762
+ payeeId: value
4763
+ }, "entryId");
4764
+ case "handle": return normalizeRefForBackend$1({
4765
+ kind: "handle",
4766
+ handle: value
4767
+ }, "entryId");
4768
+ default: return {
4769
+ ok: false,
4770
+ error: Errors.invalidInput("entryId", "must be an address-book entry id")
4771
+ };
3613
4772
  }
3614
4773
  }
3615
- function readyLifecycle(status, accountId) {
3616
- return {
3617
- status: "ready",
3618
- accountId,
3619
- canTransact: status.status === "accountReady" && status.deployment.status === "deployed"
3620
- };
4774
+ function nonEmptyRefValue$1(value, field) {
4775
+ const trimmed = value.trim();
4776
+ if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
4777
+ if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) throw Errors.invalidInput(field, "raw 0x addresses are not valid Ref values");
4778
+ return trimmed;
3621
4779
  }
3622
- function mapAccountLifecycle(input) {
3623
- const { status, phase, requirement, accountId } = input;
3624
- if (status.status === "notAuthenticated") return { status: "loading" };
3625
- if (phase.status === "failed") return {
3626
- status: "failed",
3627
- at: mapProvisioningFailureStep(phase.at),
3628
- error: phase.error
3629
- };
3630
- if (isRequirementMet(status, requirement) || phase.status === "ready") {
3631
- if (accountId === void 0) return { status: "loading" };
3632
- return readyLifecycle(status, accountId);
4780
+ function handleRefValue$1(value, field) {
4781
+ const trimmed = nonEmptyRefValue$1(value, field);
4782
+ return trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
4783
+ }
4784
+ function refLabel(ref) {
4785
+ switch (ref.kind) {
4786
+ case "handle": return ref.handle;
4787
+ case "email": return ref.email;
4788
+ case "orgHandle": return ref.orgHandle;
4789
+ case "capxulUserId": return ref.capxulUserId;
4790
+ case "payeeId": return ref.payeeId;
3633
4791
  }
3634
- if (isActiveProvisioningPhase(phase) || phase.status === "idle") return {
3635
- status: "settingUp",
3636
- step: mapProvisioningPhaseToSetupStep(phase)
3637
- };
3638
- return { status: "loading" };
3639
4792
  }
3640
4793
  //#endregion
3641
4794
  //#region ../../packages/sdk/src/client/to-capxul-result.ts
@@ -3829,6 +4982,11 @@ function makeAccountMethods(deps) {
3829
4982
  };
3830
4983
  return {
3831
4984
  methods: {
4985
+ ...makeActorRelationshipMethods({
4986
+ actor: { kind: "account" },
4987
+ ...deps.convexCall === void 0 ? {} : { convexCall: deps.convexCall },
4988
+ ...deps.profileMethods === void 0 ? {} : { accountProfileMethods: deps.profileMethods }
4989
+ }),
3832
4990
  getLifecycle,
3833
4991
  retrySetup,
3834
4992
  _internal: {
@@ -4012,7 +5170,7 @@ async function recoverRawDigestSigner(input) {
4012
5170
  }
4013
5171
  //#endregion
4014
5172
  //#region ../../packages/sdk/package.json
4015
- var version = "1.0.0-alpha.7";
5173
+ var version = "1.0.0-alpha.12";
4016
5174
  //#endregion
4017
5175
  //#region ../../packages/sdk/src/ports/auth-client.ts
4018
5176
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -5505,6 +6663,7 @@ var IdentityPortTag = class extends Context.Tag("@capxul/sdk/ports/IdentityPort"
5505
6663
  const identityLoadByAuthUserIdQuery = makeFunctionReference("identity/queries:loadByAuthUserId");
5506
6664
  const identityCreateMutation = makeFunctionReference("identity/mutations:create");
5507
6665
  const identityUpdateMutation = makeFunctionReference("identity/mutations:update");
6666
+ const identityCompleteOnboardingMutation = makeFunctionReference("identity/mutations:completeOnboarding");
5508
6667
  var ConvexIdentityAdapter = class {
5509
6668
  #convex;
5510
6669
  constructor(deps) {
@@ -5528,6 +6687,12 @@ var ConvexIdentityAdapter = class {
5528
6687
  catch: (cause) => identityErrorFromUnknown("update", cause)
5529
6688
  })), Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown("update", cause))));
5530
6689
  }
6690
+ completeOnboarding(input) {
6691
+ return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(Effect.mapError((error) => identityErrorFromCapxul("completeOnboarding", error.publicError, error)), Effect.flatMap((row) => Effect.try({
6692
+ try: () => brandProfile(row),
6693
+ catch: (cause) => identityErrorFromUnknown("completeOnboarding", cause)
6694
+ })), Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown("completeOnboarding", cause))));
6695
+ }
5531
6696
  };
5532
6697
  function ConvexIdentityLayer() {
5533
6698
  return Layer.effect(IdentityPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })));
@@ -5851,7 +7016,7 @@ const ChainIdSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeI
5851
7016
  const DurationMsSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0, { message: () => "must be a non-negative safe integer" }));
5852
7017
  const EpochMsSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0, { message: () => "must be a non-negative safe integer" }));
5853
7018
  const PublishableKeyIdSchema = Schema.String.pipe(Schema.filter((value) => value.length > 0, { message: () => "must be a non-empty string" }));
5854
- const TxHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$1.test(value), { message: () => "must be 0x + 64 hex chars" }));
7019
+ const TxHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$2.test(value), { message: () => "must be 0x + 64 hex chars" }));
5855
7020
  const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
5856
7021
  const SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;
5857
7022
  const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
@@ -5882,7 +7047,7 @@ const PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;
5882
7047
  const PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;
5883
7048
  const PaymentIdTelemetrySchema = Schema.String.pipe(Schema.filter((value) => PAYMENT_ID_TELEMETRY_RE.test(value), { message: () => "must be payment_ plus an alphanumeric id" }));
5884
7049
  const PayeeIdTelemetrySchema = Schema.String.pipe(Schema.filter((value) => PAYEE_ID_TELEMETRY_RE.test(value), { message: () => "must be payee_ plus an alphanumeric id" }));
5885
- const DocumentHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$1.test(value), { message: () => "must be 0x + 64 hex chars" }));
7050
+ const DocumentHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$2.test(value), { message: () => "must be 0x + 64 hex chars" }));
5886
7051
  const TelemetryEnvelopeProps = {
5887
7052
  capxul_e2e_run_id: OptionalString,
5888
7053
  correlationId: OptionalString,
@@ -7943,7 +9108,77 @@ function makeAccountsMethods(deps) {
7943
9108
  };
7944
9109
  }
7945
9110
  //#endregion
9111
+ //#region ../../packages/sdk/src/client/current-user.ts
9112
+ function makeCurrentUserMethods(deps) {
9113
+ return { async get(options) {
9114
+ if (options?.signal?.aborted) return {
9115
+ ok: false,
9116
+ error: Errors.cancelled({ operation: "currentUser.get" })
9117
+ };
9118
+ const user = await deps.me.get(options);
9119
+ if (!user.ok) return {
9120
+ ok: false,
9121
+ error: user.error
9122
+ };
9123
+ const [account, smartAccount, organizations] = await Promise.all([
9124
+ deps.accounts.read(options),
9125
+ deps.smartAccount.loadCurrent(options),
9126
+ deps.orgs(options)
9127
+ ]);
9128
+ if (!account.ok) return {
9129
+ ok: false,
9130
+ error: account.error
9131
+ };
9132
+ if (!smartAccount.ok) return {
9133
+ ok: false,
9134
+ error: smartAccount.error
9135
+ };
9136
+ if (!organizations.ok) return {
9137
+ ok: false,
9138
+ error: organizations.error
9139
+ };
9140
+ return {
9141
+ ok: true,
9142
+ value: {
9143
+ user: {
9144
+ id: user.value.authUserId,
9145
+ email: user.value.email,
9146
+ displayName: user.value.displayName,
9147
+ handle: null,
9148
+ paymentLink: null
9149
+ },
9150
+ personalAccount: {
9151
+ id: account.value.id,
9152
+ address: smartAccount.value?.smartAccountAddress ?? null
9153
+ },
9154
+ organizations: organizations.value.map((organization) => ({
9155
+ id: organization.id,
9156
+ name: organization.name,
9157
+ handle: organization.handle,
9158
+ role: organization.role,
9159
+ account: {
9160
+ id: organization.treasury.id,
9161
+ address: organization.safeAddress
9162
+ }
9163
+ }))
9164
+ }
9165
+ };
9166
+ } };
9167
+ }
9168
+ //#endregion
7946
9169
  //#region ../../packages/sdk/src/client/financial-ops.ts
9170
+ function actorReferenceToBackend(actor) {
9171
+ if (actor === void 0) return void 0;
9172
+ switch (actor.kind) {
9173
+ case "personal": return { kind: "account" };
9174
+ case "organization": return {
9175
+ kind: "org",
9176
+ orgId: actor.organizationId
9177
+ };
9178
+ case "account":
9179
+ case "org": return actor;
9180
+ }
9181
+ }
7947
9182
  const DEFAULT_FUNCTIONS = {
7948
9183
  me: makeFunctionReference("financialOps/queries:me"),
7949
9184
  depositInstructions: makeFunctionReference("financialOps/queries:depositInstructions"),
@@ -7951,7 +9186,11 @@ const DEFAULT_FUNCTIONS = {
7951
9186
  createPayee: makeFunctionReference("financialOps/mutations:createPayee"),
7952
9187
  getPayee: makeFunctionReference("financialOps/queries:getPayee"),
7953
9188
  resolvePayee: makeFunctionReference("financialOps/queries:resolvePayee"),
9189
+ addDestination: makeFunctionReference("financialOps/destinations:add"),
9190
+ listDestinations: makeFunctionReference("financialOps/destinations:list"),
9191
+ removeDestination: makeFunctionReference("financialOps/destinations:remove"),
7954
9192
  pay: makeFunctionReference("financialOps/mutations:pay"),
9193
+ payout: makeFunctionReference("financialOps/destinations:payout"),
7955
9194
  withdraw: makeFunctionReference("financialOps/mutations:withdraw"),
7956
9195
  markPaymentSettled: makeFunctionReference("financialOps/actions:markPaymentSettled"),
7957
9196
  markWithdrawalSettled: makeFunctionReference("financialOps/actions:markWithdrawalSettled"),
@@ -7999,21 +9238,123 @@ function makeFinancialOpsMethods(deps) {
7999
9238
  get: (payeeId, options) => runIfActive(options?.signal, "payees.get", () => deps.convexCall.query(fns.getPayee, { payeeId })),
8000
9239
  resolve: (recipient, options) => runIfActive(options?.signal, "payees.resolve", () => deps.convexCall.query(fns.resolvePayee, { recipient }))
8001
9240
  },
9241
+ targets: { resolve: async (reference, options) => {
9242
+ switch (reference.kind) {
9243
+ case "handle": return mapOk$1(await runIfActive(options?.signal, "targets.resolve.handle", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle })), (target) => resolvedTargetFromResolution(reference, target));
9244
+ case "email": return mapOk$1(await runIfActive(options?.signal, "targets.resolve.email", () => deps.convexCall.query(fns.resolvePayee, { recipient: reference.email })), (target) => resolvedTargetFromResolution(reference, target));
9245
+ case "organization": {
9246
+ const resolved = await runIfActive(options?.signal, "targets.resolve.organization", () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }));
9247
+ if (!resolved.ok) return {
9248
+ ok: false,
9249
+ error: resolved.error
9250
+ };
9251
+ if (resolved.value.kind !== "org") return {
9252
+ ok: false,
9253
+ error: Errors.invalidInput("reference", "organization handle could not be resolved")
9254
+ };
9255
+ return {
9256
+ ok: true,
9257
+ value: resolvedTargetFromResolution(reference, resolved.value)
9258
+ };
9259
+ }
9260
+ case "payee": {
9261
+ const payee = await runIfActive(options?.signal, "targets.resolve.payee", () => deps.convexCall.query(fns.getPayee, { payeeId: reference.id }));
9262
+ if (!payee.ok) return {
9263
+ ok: false,
9264
+ error: payee.error
9265
+ };
9266
+ if (payee.value === null) return {
9267
+ ok: false,
9268
+ error: Errors.invalidInput("reference", "payee not found")
9269
+ };
9270
+ return {
9271
+ ok: true,
9272
+ value: resolvedTargetFromPayee(reference, payee.value)
9273
+ };
9274
+ }
9275
+ case "destination": return Promise.resolve({
9276
+ ok: false,
9277
+ error: Errors.notImplemented("targets", "resolve.destination")
9278
+ });
9279
+ }
9280
+ } },
9281
+ destinations: {
9282
+ add: async (input, options) => {
9283
+ const ref = normalizeDestinationInputRef(input, "target");
9284
+ if (!ref.ok) return {
9285
+ ok: false,
9286
+ error: ref.error
9287
+ };
9288
+ if (ref.value === void 0) return {
9289
+ ok: false,
9290
+ error: Errors.invalidInput("target", "required for destinations.add")
9291
+ };
9292
+ return mapOk$1(await runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
9293
+ ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
9294
+ ref: ref.value,
9295
+ kind: destinationKindToBackend(input.kind),
9296
+ ...input.label === void 0 ? {} : { label: input.label },
9297
+ payload: input.payload
9298
+ })), destinationFromBackend);
9299
+ },
9300
+ list: async (input, options) => {
9301
+ const ref = normalizeDestinationInputRef(input, "target");
9302
+ if (!ref.ok) return {
9303
+ ok: false,
9304
+ error: ref.error
9305
+ };
9306
+ return mapOk$1(await runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
9307
+ ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
9308
+ ...ref.value === void 0 ? {} : { ref: ref.value }
9309
+ })), (destinations) => destinations.map(destinationFromBackend).filter((destination) => input.kind === void 0 || destination.kind === input.kind));
9310
+ },
9311
+ remove: (input, options) => runIfActive(options?.signal, "destinations.remove", () => deps.convexCall.mutation(fns.removeDestination, {
9312
+ ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
9313
+ destinationId: input.destinationId
9314
+ }))
9315
+ },
8002
9316
  payments: {
8003
- pay: (input, options) => runIfActive(options?.signal, "payments.pay", () => deps.convexCall.mutation(fns.pay, {
8004
- to: input.to,
8005
- amount: input.amount,
8006
- ...input.document === void 0 ? {} : { document: input.document },
8007
- ...input.release === void 0 ? {} : { release: input.release },
8008
- ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
8009
- })),
9317
+ pay: async (input, options) => {
9318
+ if (actorReferenceToBackend(input.actor)?.kind === "org") return {
9319
+ ok: false,
9320
+ error: Errors.notImplemented("payments", "pay.organizationActor")
9321
+ };
9322
+ const to = normalizeTargetForBackend(input.to, "to");
9323
+ if (!to.ok) return {
9324
+ ok: false,
9325
+ error: to.error
9326
+ };
9327
+ return mapOk$1(await runIfActive(options?.signal, "payments.pay", () => deps.convexCall.mutation(fns.pay, {
9328
+ to: to.value,
9329
+ amount: input.amount,
9330
+ ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
9331
+ ...input.document === void 0 ? {} : { document: input.document },
9332
+ ...input.timing === void 0 ? {} : { timing: input.timing },
9333
+ ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
9334
+ })), normalizePaymentTiming$1);
9335
+ },
9336
+ payout: async (input, options) => mapOk$1(await runIfActive(options?.signal, "payments.payout", () => deps.convexCall.mutation(fns.payout, {
9337
+ ...input.actor === void 0 ? {} : { actor: actorReferenceToBackend(input.actor) },
9338
+ destinationId: input.destinationId,
9339
+ amount: input.amount
9340
+ })), normalizePaymentTiming$1),
8010
9341
  withdraw: (input, options) => runIfActive(options?.signal, "payments.withdraw", () => deps.convexCall.mutation(fns.withdraw, {
8011
9342
  to: input.to,
8012
9343
  amount: input.amount,
8013
9344
  document: input.document
8014
9345
  })),
8015
- list: (options) => runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})),
8016
- get: (paymentId, options) => runIfActive(options?.signal, "payments.get", () => deps.convexCall.query(fns.getPayment, { paymentId })),
9346
+ list: async (options) => mapOk$1(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming$1)),
9347
+ get: async (paymentId, options) => mapOk$1(await runIfActive(options?.signal, "payments.get", () => deps.convexCall.query(fns.getPayment, { paymentId })), (payment) => payment === null ? null : normalizePaymentTiming$1(payment)),
9348
+ cancel: (paymentId, options) => {
9349
+ if (options?.signal?.aborted) return Promise.resolve({
9350
+ ok: false,
9351
+ error: Errors.cancelled({ operation: "payments.cancel" })
9352
+ });
9353
+ return Promise.resolve({
9354
+ ok: false,
9355
+ error: Errors.notImplemented("payments", "cancel")
9356
+ });
9357
+ },
8017
9358
  _internal: {
8018
9359
  markSettled: (input, options) => runIfActive(options?.signal, "payments.markSettled", () => deps.convexCall.action(fns.markPaymentSettled, {
8019
9360
  paymentId: input.paymentId,
@@ -8028,6 +9369,9 @@ function makeFinancialOpsMethods(deps) {
8028
9369
  recordOrgPayment: (input, options) => runIfActive(options?.signal, "payments.recordOrgPayment", () => deps.convexCall.action(fns.recordOrgPayment, {
8029
9370
  orgId: input.orgId,
8030
9371
  recipientLabel: input.recipientLabel,
9372
+ ...input.recipientKind === void 0 ? {} : { recipientKind: input.recipientKind },
9373
+ ...input.recipientRef === void 0 ? {} : { recipientRef: input.recipientRef },
9374
+ ...input.recipientPayeeId === void 0 ? {} : { recipientPayeeId: input.recipientPayeeId },
8031
9375
  recipientSafeAddress: input.recipientSafeAddress,
8032
9376
  amount: input.amount,
8033
9377
  paymentType: input.paymentType,
@@ -8054,16 +9398,55 @@ function makeFinancialOpsMethods(deps) {
8054
9398
  txHash: input.evidence.txHash,
8055
9399
  ...input.document === void 0 ? {} : { document: input.document }
8056
9400
  })),
8057
- redirect: (input, options) => runIfActive(options?.signal, "payments.redirect", () => deps.convexCall.action(fns.redirectCommitment, {
8058
- paymentId: input.paymentId,
8059
- to: input.to,
8060
- userOpHash: input.evidence.userOpHash,
8061
- txHash: input.evidence.txHash,
8062
- ...input.document === void 0 ? {} : { document: input.document }
8063
- })),
9401
+ redirect: async (input, options) => {
9402
+ const to = normalizeRefForBackend(input.to, "to");
9403
+ if (!to.ok) return {
9404
+ ok: false,
9405
+ error: to.error
9406
+ };
9407
+ return mapOk$1(await runIfActive(options?.signal, "payments.redirect", () => deps.convexCall.action(fns.redirectCommitment, {
9408
+ paymentId: input.paymentId,
9409
+ to: to.value,
9410
+ userOpHash: input.evidence.userOpHash,
9411
+ txHash: input.evidence.txHash,
9412
+ ...input.document === void 0 ? {} : { document: input.document }
9413
+ })), normalizePaymentTiming$1);
9414
+ },
8064
9415
  commitmentRef: (paymentId, options) => runIfActive(options?.signal, "payments.commitmentRef", () => deps.convexCall.query(fns.getCommitmentRef, { paymentId }))
8065
9416
  }
8066
9417
  },
9418
+ activity: { list: (params, options) => {
9419
+ if (options?.signal?.aborted) return Promise.resolve({
9420
+ ok: false,
9421
+ error: Errors.cancelled({ operation: "activity.list" })
9422
+ });
9423
+ return Promise.resolve({
9424
+ ok: false,
9425
+ error: Errors.notImplemented("activity", "list")
9426
+ });
9427
+ } },
9428
+ offramp: {
9429
+ quote: (input, options) => {
9430
+ if (options?.signal?.aborted) return Promise.resolve({
9431
+ ok: false,
9432
+ error: Errors.cancelled({ operation: "offramp.quote" })
9433
+ });
9434
+ return Promise.resolve({
9435
+ ok: false,
9436
+ error: Errors.notImplemented("offramp", "quote")
9437
+ });
9438
+ },
9439
+ status: (offrampId, options) => {
9440
+ if (options?.signal?.aborted) return Promise.resolve({
9441
+ ok: false,
9442
+ error: Errors.cancelled({ operation: "offramp.status" })
9443
+ });
9444
+ return Promise.resolve({
9445
+ ok: false,
9446
+ error: Errors.notImplemented("offramp", "status")
9447
+ });
9448
+ }
9449
+ },
8067
9450
  paymentDocuments: {
8068
9451
  verify: (documentHash, options) => runIfActive(options?.signal, "paymentDocuments.verify", () => deps.convexCall.query(fns.verifyPaymentDocument, { documentHash })),
8069
9452
  render: (documentHash, options) => runIfActive(options?.signal, "paymentDocuments.render", () => deps.convexCall.query(fns.renderStoredDocument, { documentHash }))
@@ -8085,35 +9468,302 @@ function makeFinancialOpsMethods(deps) {
8085
9468
  reconcile: (options) => runIfActive(options?.signal, "paymentRequests.reconcile", () => deps.convexCall.query(fns.reconcileRequests, {}))
8086
9469
  },
8087
9470
  workbench: {
8088
- draft: (input, options) => runIfActive(options?.signal, "workbench.draft", () => deps.convexCall.mutation(fns.draftPayment, {
8089
- clientId: input.clientId,
8090
- audience: input.audience,
8091
- scopes: input.scopes,
8092
- to: input.to,
8093
- amount: input.amount,
8094
- idempotencyKey: input.idempotencyKey,
8095
- ...input.document === void 0 ? {} : { document: input.document },
8096
- ...input.tainted === void 0 ? {} : { tainted: input.tainted }
8097
- })),
9471
+ draft: async (input, options) => {
9472
+ const to = normalizeRefForBackend(input.to, "to");
9473
+ if (!to.ok) return {
9474
+ ok: false,
9475
+ error: to.error
9476
+ };
9477
+ return runIfActive(options?.signal, "workbench.draft", () => deps.convexCall.mutation(fns.draftPayment, {
9478
+ clientId: input.clientId,
9479
+ audience: input.audience,
9480
+ scopes: input.scopes,
9481
+ to: to.value,
9482
+ amount: input.amount,
9483
+ idempotencyKey: input.idempotencyKey,
9484
+ ...input.document === void 0 ? {} : { document: input.document },
9485
+ ...input.tainted === void 0 ? {} : { tainted: input.tainted }
9486
+ }));
9487
+ },
8098
9488
  simulate: (draftId, options) => runIfActive(options?.signal, "workbench.simulate", () => deps.convexCall.action(fns.simulatePayment, { draftId })),
8099
9489
  requestApproval: (draftId, options) => runIfActive(options?.signal, "workbench.requestApproval", () => deps.convexCall.mutation(fns.requestApproval, { draftId })),
8100
9490
  mint: (draftId, capability, options) => runIfActive(options?.signal, "workbench.mint", () => deps.convexCall.mutation(fns.mintApprovalToken, {
8101
9491
  draftId,
8102
9492
  capability
8103
9493
  })),
8104
- execute: (input, options) => runIfActive(options?.signal, "workbench.execute", () => deps.convexCall.action(fns.executePayment, {
9494
+ execute: async (input, options) => mapOk$1(await runIfActive(options?.signal, "workbench.execute", () => deps.convexCall.action(fns.executePayment, {
8105
9495
  draftId: input.draftId,
8106
9496
  clientId: input.clientId,
8107
9497
  approvalToken: input.approvalToken,
8108
9498
  readModelVersion: input.readModelVersion,
8109
9499
  userOpHash: input.userOpHash,
8110
9500
  txHash: input.txHash
8111
- })),
9501
+ })), normalizePaymentTiming$1),
8112
9502
  status: (draftId, options) => runIfActive(options?.signal, "workbench.status", () => deps.convexCall.query(fns.getDraft, { draftId })),
8113
9503
  cancel: (draftId, options) => runIfActive(options?.signal, "workbench.cancel", () => deps.convexCall.mutation(fns.cancelApproval, { draftId }))
8114
9504
  }
8115
9505
  };
8116
9506
  }
9507
+ function refToRecipientString(ref) {
9508
+ if (typeof ref === "string") throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
9509
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
9510
+ switch (ref.kind) {
9511
+ case "handle": return handleRefValue(ref.handle, "handle");
9512
+ case "email": return nonEmptyRefValue(ref.email, "email");
9513
+ case "orgHandle": return nonEmptyRefValue(ref.orgHandle, "orgHandle");
9514
+ case "capxulUserId": return nonEmptyRefValue(ref.capxulUserId, "capxulUserId");
9515
+ case "payeeId": return nonEmptyRefValue(ref.payeeId, "payeeId");
9516
+ default: throw Errors.invalidInput("to", "recipient must be a known Ref variant");
9517
+ }
9518
+ }
9519
+ function nonEmptyRefValue(value, field) {
9520
+ const trimmed = value.trim();
9521
+ if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
9522
+ if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) throw Errors.invalidInput(field, "raw 0x addresses are not valid Ref values");
9523
+ return trimmed;
9524
+ }
9525
+ function handleRefValue(value, field) {
9526
+ const trimmed = nonEmptyRefValue(value, field);
9527
+ return trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
9528
+ }
9529
+ function refFromTargetReference(reference, field) {
9530
+ try {
9531
+ if (typeof reference === "string") throw Errors.invalidInput(field, "target must be a typed TargetReference variant");
9532
+ if (typeof reference !== "object" || reference === null || !("kind" in reference)) throw Errors.invalidInput(field, "target must be a typed TargetReference variant");
9533
+ switch (reference.kind) {
9534
+ case "handle": return {
9535
+ ok: true,
9536
+ value: {
9537
+ kind: "handle",
9538
+ handle: reference.handle
9539
+ }
9540
+ };
9541
+ case "email": return {
9542
+ ok: true,
9543
+ value: {
9544
+ kind: "email",
9545
+ email: reference.email
9546
+ }
9547
+ };
9548
+ case "organization": return {
9549
+ ok: true,
9550
+ value: {
9551
+ kind: "orgHandle",
9552
+ orgHandle: reference.handle
9553
+ }
9554
+ };
9555
+ case "payee": return {
9556
+ ok: true,
9557
+ value: {
9558
+ kind: "payeeId",
9559
+ payeeId: reference.id
9560
+ }
9561
+ };
9562
+ case "destination": return {
9563
+ ok: false,
9564
+ error: Errors.notImplemented("targets", "reference.destination")
9565
+ };
9566
+ default: throw Errors.invalidInput(field, "target must be a known TargetReference variant");
9567
+ }
9568
+ } catch (cause) {
9569
+ if (cause instanceof Error && "code" in cause) return {
9570
+ ok: false,
9571
+ error: cause
9572
+ };
9573
+ return {
9574
+ ok: false,
9575
+ error: Errors.invalidInput(field, "target must be a typed TargetReference variant")
9576
+ };
9577
+ }
9578
+ }
9579
+ function normalizeTargetForBackend(reference, field) {
9580
+ const ref = refFromTargetReference(reference, field);
9581
+ return ref.ok ? normalizeRefForBackend(ref.value, field) : ref;
9582
+ }
9583
+ function normalizeDestinationInputRef(input, field) {
9584
+ if (input.target !== void 0) return normalizeTargetForBackend(input.target, field);
9585
+ if (input.ref !== void 0) return normalizeDestinationRefForBackend(input.ref, "ref");
9586
+ return {
9587
+ ok: true,
9588
+ value: void 0
9589
+ };
9590
+ }
9591
+ function targetReferenceFromBackendRef(ref) {
9592
+ switch (ref.kind) {
9593
+ case "handle": return {
9594
+ kind: "handle",
9595
+ handle: ref.handle
9596
+ };
9597
+ case "email": return {
9598
+ kind: "email",
9599
+ email: ref.email
9600
+ };
9601
+ case "orgHandle": return {
9602
+ kind: "organization",
9603
+ handle: ref.orgHandle
9604
+ };
9605
+ case "payeeId": return {
9606
+ kind: "payee",
9607
+ id: ref.payeeId
9608
+ };
9609
+ case "capxulUserId": throw Errors.notImplemented("targets", "reference.capxulUserId");
9610
+ }
9611
+ }
9612
+ function resolvedTargetFromResolution(reference, resolution) {
9613
+ const kind = resolution.kind === "org" ? "organization" : resolution.kind === "payee" ? "payee" : "person";
9614
+ return {
9615
+ reference,
9616
+ label: resolution.label,
9617
+ kind,
9618
+ capabilities: {
9619
+ canPay: true,
9620
+ canRequest: true,
9621
+ canPayout: false
9622
+ }
9623
+ };
9624
+ }
9625
+ function resolvedTargetFromPayee(reference, payee) {
9626
+ return {
9627
+ reference,
9628
+ label: payee.label,
9629
+ kind: "payee",
9630
+ capabilities: {
9631
+ canPay: true,
9632
+ canRequest: true,
9633
+ canPayout: false
9634
+ }
9635
+ };
9636
+ }
9637
+ function destinationKindToBackend(kind) {
9638
+ switch (kind) {
9639
+ case "bank_account": return "bank";
9640
+ case "mobile_money": return "mobile-money";
9641
+ case "external_account": return "wallet";
9642
+ }
9643
+ }
9644
+ function destinationKindFromBackend(kind) {
9645
+ switch (kind) {
9646
+ case "bank": return "bank_account";
9647
+ case "mobile-money": return "mobile_money";
9648
+ case "wallet": return "external_account";
9649
+ }
9650
+ }
9651
+ function destinationRailFromBackend(destination) {
9652
+ switch (destination.kind) {
9653
+ case "bank": {
9654
+ const payload = destination.payload;
9655
+ return {
9656
+ kind: "bank",
9657
+ country: payload.country,
9658
+ currency: payload.currency
9659
+ };
9660
+ }
9661
+ case "mobile-money": {
9662
+ const payload = destination.payload;
9663
+ return {
9664
+ kind: "mobile_money",
9665
+ country: payload.country,
9666
+ currency: payload.currency,
9667
+ provider: payload.provider
9668
+ };
9669
+ }
9670
+ case "wallet": return {
9671
+ kind: "chain",
9672
+ network: destination.payload.network,
9673
+ asset: "USD"
9674
+ };
9675
+ }
9676
+ }
9677
+ function destinationFromBackend(destination) {
9678
+ return {
9679
+ ...destination,
9680
+ target: targetReferenceFromBackendRef(destination.ref),
9681
+ kind: destinationKindFromBackend(destination.kind),
9682
+ rail: destinationRailFromBackend(destination)
9683
+ };
9684
+ }
9685
+ function normalizeDestinationRefForBackend(ref, field) {
9686
+ if (typeof ref === "object" && ref !== null && "kind" in ref && ref.kind === "capxulUserId") return {
9687
+ ok: false,
9688
+ error: Errors.notImplemented("targets", "reference.capxulUserId")
9689
+ };
9690
+ return normalizeRefForBackend(ref, field);
9691
+ }
9692
+ function normalizeRefForBackend(ref, field) {
9693
+ try {
9694
+ if (typeof ref === "string") throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
9695
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
9696
+ switch (ref.kind) {
9697
+ case "handle": return {
9698
+ ok: true,
9699
+ value: {
9700
+ kind: "handle",
9701
+ handle: handleRefValue(ref.handle, "handle")
9702
+ }
9703
+ };
9704
+ case "email": return {
9705
+ ok: true,
9706
+ value: {
9707
+ kind: "email",
9708
+ email: nonEmptyRefValue(ref.email, "email")
9709
+ }
9710
+ };
9711
+ case "orgHandle": return {
9712
+ ok: true,
9713
+ value: {
9714
+ kind: "orgHandle",
9715
+ orgHandle: nonEmptyRefValue(ref.orgHandle, "orgHandle")
9716
+ }
9717
+ };
9718
+ case "capxulUserId": return {
9719
+ ok: true,
9720
+ value: {
9721
+ kind: "capxulUserId",
9722
+ capxulUserId: nonEmptyRefValue(ref.capxulUserId, "capxulUserId")
9723
+ }
9724
+ };
9725
+ case "payeeId": return {
9726
+ ok: true,
9727
+ value: {
9728
+ kind: "payeeId",
9729
+ payeeId: nonEmptyRefValue(ref.payeeId, "payeeId")
9730
+ }
9731
+ };
9732
+ default: throw Errors.invalidInput(field, "recipient must be a known Ref variant");
9733
+ }
9734
+ } catch (cause) {
9735
+ if (cause instanceof Error && "code" in cause) return {
9736
+ ok: false,
9737
+ error: cause
9738
+ };
9739
+ return {
9740
+ ok: false,
9741
+ error: Errors.invalidInput(field, "recipient must be a typed Ref variant")
9742
+ };
9743
+ }
9744
+ }
9745
+ function normalizePaymentTiming$1(payment) {
9746
+ const { release: _release, ...rest } = payment;
9747
+ return {
9748
+ ...rest,
9749
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
9750
+ };
9751
+ }
9752
+ function mapOk$1(result, f) {
9753
+ if (!result.ok) return result;
9754
+ try {
9755
+ return {
9756
+ ok: true,
9757
+ value: f(result.value)
9758
+ };
9759
+ } catch (cause) {
9760
+ if (cause instanceof Error && "code" in cause) return {
9761
+ ok: false,
9762
+ error: cause
9763
+ };
9764
+ throw cause;
9765
+ }
9766
+ }
8117
9767
  async function runIfActive(signal, operation, effect) {
8118
9768
  if (signal?.aborted === true) return {
8119
9769
  ok: false,
@@ -8556,6 +10206,41 @@ function readTreasuryProgram(orgId) {
8556
10206
  return zeroTreasury(orgId);
8557
10207
  });
8558
10208
  }
10209
+ function findOrgById(orgs, orgId) {
10210
+ return orgs.find((org) => String(org.id) === String(orgId));
10211
+ }
10212
+ function orgNotFound(orgId) {
10213
+ return Errors.invalidInput("orgId", `org ${String(orgId)} was not found for this session`);
10214
+ }
10215
+ function readOrgProfileProgram(orgId) {
10216
+ return Effect.gen(function* () {
10217
+ const org = findOrgById(yield* listOrgsProgram(), orgId);
10218
+ if (org === void 0) return yield* Effect.fail(orgNotFound(orgId));
10219
+ return {
10220
+ actor: {
10221
+ kind: "org",
10222
+ orgId: String(orgId)
10223
+ },
10224
+ displayName: org.name,
10225
+ handle: org.handle
10226
+ };
10227
+ });
10228
+ }
10229
+ function readOrgDepositInstructionsProgram(orgId) {
10230
+ return Effect.gen(function* () {
10231
+ const deps = yield* OrgDepsTag;
10232
+ const org = findOrgById(yield* listOrgsProgram(), orgId);
10233
+ if (org === void 0) return yield* Effect.fail(orgNotFound(orgId));
10234
+ return {
10235
+ accountKind: "orgTreasury",
10236
+ chainId: Number(deps.chainId ?? 84532),
10237
+ network: "base-sepolia",
10238
+ currency: "USD",
10239
+ address: String(org.safeAddress).toLowerCase(),
10240
+ label: "Capxul org treasury"
10241
+ };
10242
+ });
10243
+ }
8559
10244
  function listRolesProgram(orgId) {
8560
10245
  return Effect.gen(function* () {
8561
10246
  const deps = yield* OrgDepsTag;
@@ -8660,7 +10345,7 @@ function leakSafeOrgPayment(input) {
8660
10345
  documentHash: input.documentHash,
8661
10346
  kind: input.paymentType === "payroll" ? "payslip" : "memo"
8662
10347
  }],
8663
- release: { kind: "instant" },
10348
+ timing: { kind: "instant" },
8664
10349
  released: money,
8665
10350
  availableToClaim: {
8666
10351
  ...money,
@@ -8720,11 +10405,15 @@ function spendViaPaymentsProgram(orgId, input) {
8720
10405
  return Effect.gen(function* () {
8721
10406
  const deps = yield* OrgDepsTag;
8722
10407
  if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
10408
+ const to = yield* Effect.try({
10409
+ try: () => refToRecipientString(input.to),
10410
+ catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
10411
+ });
8723
10412
  const gated = yield* gateOneRun({
8724
10413
  deps,
8725
10414
  orgId,
8726
10415
  from: input.from,
8727
- to: input.to,
10416
+ to,
8728
10417
  amount: input.amount
8729
10418
  });
8730
10419
  const paymentType = input.paymentType ?? "unspecified";
@@ -8736,7 +10425,7 @@ function spendViaPaymentsProgram(orgId, input) {
8736
10425
  }).pipe(Effect.mapError((error) => error.publicError));
8737
10426
  return leakSafeOrgPayment({
8738
10427
  orgId,
8739
- to: input.to,
10428
+ to,
8740
10429
  amount: input.amount,
8741
10430
  paymentType,
8742
10431
  index: 0
@@ -8749,13 +10438,17 @@ function batchPayrollProgram(orgId, input) {
8749
10438
  if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
8750
10439
  if (input.runs.length === 0) return yield* Effect.fail(Errors.invalidInput("runs", "payroll batch must include at least one run"));
8751
10440
  const gated = [];
10441
+ const recipients = yield* Effect.try({
10442
+ try: () => input.runs.map((run) => refToRecipientString(run.to)),
10443
+ catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
10444
+ });
8752
10445
  let accumulatedRaw = 0n;
8753
- for (const run of input.runs) {
10446
+ for (const [index, run] of input.runs.entries()) {
8754
10447
  const result = yield* gateOneRun({
8755
10448
  deps,
8756
10449
  orgId,
8757
10450
  from: input.from,
8758
- to: run.to,
10451
+ to: recipients[index],
8759
10452
  amount: run.amount,
8760
10453
  accumulatedRaw: accumulatedRaw.toString(10)
8761
10454
  });
@@ -8773,7 +10466,7 @@ function batchPayrollProgram(orgId, input) {
8773
10466
  }).pipe(Effect.mapError((error) => error.publicError));
8774
10467
  return input.runs.map((run, index) => leakSafeOrgPayment({
8775
10468
  orgId,
8776
- to: run.to,
10469
+ to: recipients[index],
8777
10470
  amount: run.amount,
8778
10471
  paymentType: "payroll",
8779
10472
  index
@@ -8827,7 +10520,31 @@ function makeOrgMethods(deps) {
8827
10520
  return toCapxulResult(detectAndAcceptPendingInvitationsProgram(), layer);
8828
10521
  } }),
8829
10522
  org(orgId) {
10523
+ const convexCall = deps.convexCall;
8830
10524
  return {
10525
+ ...makeActorRelationshipMethods({
10526
+ actor: {
10527
+ kind: "org",
10528
+ orgId: String(orgId)
10529
+ },
10530
+ ...convexCall === void 0 ? {} : { convexCall }
10531
+ }),
10532
+ profile: {
10533
+ get(_options) {
10534
+ if (_options?.signal?.aborted) return Promise.resolve({
10535
+ ok: false,
10536
+ error: Errors.cancelled({ operation: "org.profile.get" })
10537
+ });
10538
+ return toCapxulResult(readOrgProfileProgram(orgId), layer);
10539
+ },
10540
+ depositInstructions(_options) {
10541
+ if (_options?.signal?.aborted) return Promise.resolve({
10542
+ ok: false,
10543
+ error: Errors.cancelled({ operation: "org.profile.depositInstructions" })
10544
+ });
10545
+ return toCapxulResult(readOrgDepositInstructionsProgram(orgId), layer);
10546
+ }
10547
+ },
8831
10548
  treasury(options) {
8832
10549
  if (options?.signal?.aborted) return Promise.resolve({
8833
10550
  ok: false,
@@ -8835,6 +10552,32 @@ function makeOrgMethods(deps) {
8835
10552
  });
8836
10553
  return toCapxulResult(readTreasuryProgram(orgId), layer);
8837
10554
  },
10555
+ account: { async get(options) {
10556
+ if (options?.signal?.aborted) return {
10557
+ ok: false,
10558
+ error: Errors.cancelled({ operation: "org.account.get" })
10559
+ };
10560
+ const treasury = await toCapxulResult(readTreasuryProgram(orgId), layer);
10561
+ if (!treasury.ok) return {
10562
+ ok: false,
10563
+ error: treasury.error
10564
+ };
10565
+ const orgs = await toCapxulResult(listOrgsProgram(), layer);
10566
+ if (!orgs.ok) return {
10567
+ ok: false,
10568
+ error: orgs.error
10569
+ };
10570
+ const org = orgs.value.find((candidate) => candidate.id === orgId);
10571
+ return {
10572
+ ok: true,
10573
+ value: {
10574
+ id: treasury.value.id,
10575
+ address: org?.safeAddress ?? null,
10576
+ balance: treasury.value.balance,
10577
+ available: treasury.value.available
10578
+ }
10579
+ };
10580
+ } },
8838
10581
  members(_options) {
8839
10582
  if (_options?.signal?.aborted) return Promise.resolve({
8840
10583
  ok: false,
@@ -8890,11 +10633,291 @@ function makeOrgMethods(deps) {
8890
10633
  error: Errors.cancelled({ operation: "org.batchPayroll" })
8891
10634
  });
8892
10635
  return toCapxulResult(batchPayrollProgram(orgId, _input), layer);
8893
- }
10636
+ },
10637
+ auditLog(_options) {
10638
+ if (_options?.signal?.aborted) return Promise.resolve({
10639
+ ok: false,
10640
+ error: Errors.cancelled({ operation: "org.auditLog" })
10641
+ });
10642
+ return Promise.resolve({
10643
+ ok: false,
10644
+ error: Errors.notImplemented("organizationAuditLog", "list")
10645
+ });
10646
+ },
10647
+ payroll: convexCall === void 0 ? makeNotImplementedPayrollMethods() : makePayrollMethods({
10648
+ orgId: String(orgId),
10649
+ convexCall
10650
+ })
8894
10651
  };
8895
10652
  }
8896
10653
  };
8897
10654
  }
10655
+ const PAYROLL_FUNCTIONS = {
10656
+ add: makeFunctionReference("financialOps/payrollRoster:add"),
10657
+ list: makeFunctionReference("financialOps/payrollRoster:list"),
10658
+ update: makeFunctionReference("financialOps/payrollRoster:update"),
10659
+ remove: makeFunctionReference("financialOps/payrollRoster:remove"),
10660
+ run: makeFunctionReference("financialOps/payrollRoster:run")
10661
+ };
10662
+ function makePayrollMethods(deps) {
10663
+ const fns = PAYROLL_FUNCTIONS;
10664
+ return {
10665
+ roster: {
10666
+ add: async (input, options) => {
10667
+ const employee = normalizeRefForBackend$1(input.employee, "employee");
10668
+ if (!employee.ok) return employee;
10669
+ return mapOk(runConvexIfActive(options?.signal, "payroll.roster.add", () => deps.convexCall.mutation(fns.add, {
10670
+ orgId: deps.orgId,
10671
+ employee: employee.value,
10672
+ amount: input.amount,
10673
+ timing: input.timing,
10674
+ payslipTemplate: toPayrollTemplate(input.payslipTemplate)
10675
+ })), mapPayrollRosterLine);
10676
+ },
10677
+ list: (options) => mapOk(runConvexIfActive(options?.signal, "payroll.roster.list", () => deps.convexCall.query(fns.list, { orgId: deps.orgId })), (lines) => lines.map(mapPayrollRosterLine)),
10678
+ update: async (rosterLineId, input, options) => {
10679
+ const employee = input.employee === void 0 ? void 0 : normalizeRefForBackend$1(input.employee, "employee");
10680
+ if (employee !== void 0 && !employee.ok) return employee;
10681
+ return mapOk(runConvexIfActive(options?.signal, "payroll.roster.update", () => deps.convexCall.mutation(fns.update, {
10682
+ orgId: deps.orgId,
10683
+ rosterLineId,
10684
+ ...employee === void 0 ? {} : { employee: employee.value },
10685
+ ...input.amount === void 0 ? {} : { amount: input.amount },
10686
+ ...input.timing === void 0 ? {} : { timing: input.timing },
10687
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: toPayrollTemplate(input.payslipTemplate) }
10688
+ })), mapPayrollRosterLine);
10689
+ },
10690
+ remove: (rosterLineId, options) => mapOk(runConvexIfActive(options?.signal, "payroll.roster.remove", () => deps.convexCall.mutation(fns.remove, {
10691
+ orgId: deps.orgId,
10692
+ rosterLineId
10693
+ })), mapPayrollRosterLine)
10694
+ },
10695
+ run: (input, options) => mapOk(runConvexIfActive(options?.signal, "payroll.run", () => deps.convexCall.mutation(fns.run, {
10696
+ orgId: deps.orgId,
10697
+ period: input.period,
10698
+ from: String(input.from)
10699
+ })), (run) => run.payments.map(normalizePaymentTiming))
10700
+ };
10701
+ }
10702
+ function makeNotImplementedPayrollMethods() {
10703
+ return {
10704
+ roster: {
10705
+ add: () => missingConvexCall("payroll.roster.add"),
10706
+ list: () => missingConvexCall("payroll.roster.list"),
10707
+ update: () => missingConvexCall("payroll.roster.update"),
10708
+ remove: () => missingConvexCall("payroll.roster.remove")
10709
+ },
10710
+ run: () => missingConvexCall("payroll.run")
10711
+ };
10712
+ }
10713
+ function missingConvexCall(operation) {
10714
+ return Promise.resolve({
10715
+ ok: false,
10716
+ error: Errors.providerError("convex", operation, "ConvexCallPort is required")
10717
+ });
10718
+ }
10719
+ async function mapOk(resultOrPromise, f) {
10720
+ const result = await resultOrPromise;
10721
+ if (!result.ok) return result;
10722
+ return {
10723
+ ok: true,
10724
+ value: f(result.value)
10725
+ };
10726
+ }
10727
+ function mapPayrollRosterLine(line) {
10728
+ return {
10729
+ id: line.id,
10730
+ employee: line.employee,
10731
+ amount: line.amount,
10732
+ timing: line.timing,
10733
+ status: line.status === "removed" ? "ended" : line.status
10734
+ };
10735
+ }
10736
+ function toPayrollTemplate(document) {
10737
+ if (document === void 0) return { title: "Payroll" };
10738
+ if ("title" in document) return {
10739
+ title: document.title,
10740
+ ...typeof document.memo === "string" ? { memo: document.memo } : {}
10741
+ };
10742
+ if (document.primaryType === "Payslip") return { title: `Payslip ${document.message.period}` };
10743
+ if ("reference" in document.message) return {
10744
+ title: document.primaryType,
10745
+ memo: document.message.reference
10746
+ };
10747
+ return { title: document.primaryType };
10748
+ }
10749
+ function normalizePaymentTiming(payment) {
10750
+ const { release: _release, ...rest } = payment;
10751
+ return {
10752
+ ...rest,
10753
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
10754
+ };
10755
+ }
10756
+ //#endregion
10757
+ //#region ../../packages/sdk/src/flows/onboarding.ts
10758
+ const DEFAULT_ORG_TEMPLATE = "Startup";
10759
+ async function runCompletePersonalOnboarding(ops, input) {
10760
+ const validated = validatePersonalInput(input);
10761
+ if (!validated.ok) return validated;
10762
+ const session = await ops.currentSession();
10763
+ if (session === null) return fail(Errors.notAuthenticated());
10764
+ const written = await ops.completeIdentityOnboarding({
10765
+ authUserId: session.authUserId,
10766
+ email: session.email,
10767
+ displayName: validated.value.displayName,
10768
+ country: validated.value.country,
10769
+ ...validated.value.withdrawalAddress === void 0 ? {} : { withdrawalAddress: validated.value.withdrawalAddress }
10770
+ });
10771
+ if (!written.ok) return fail(written.error);
10772
+ const provisioned = await ops.triggerProvisioning();
10773
+ if (!provisioned.ok) return fail(provisioned.error);
10774
+ ops.kickProvisioning();
10775
+ const lifecycle = await ops.readLifecycle();
10776
+ if (!lifecycle.ok) return fail(lifecycle.error);
10777
+ return {
10778
+ ok: true,
10779
+ value: { lifecycle: lifecycle.value }
10780
+ };
10781
+ }
10782
+ async function runCompleteOrganizationOnboarding(ops, input) {
10783
+ const validated = validateOrganizationInput(input);
10784
+ if (!validated.ok) return validated;
10785
+ const session = await ops.currentSession();
10786
+ if (session === null) return fail(Errors.notAuthenticated());
10787
+ const written = await ops.completeIdentityOnboarding({
10788
+ authUserId: session.authUserId,
10789
+ email: session.email,
10790
+ displayName: validated.value.ownerDisplayName,
10791
+ country: validated.value.country
10792
+ });
10793
+ if (!written.ok) return fail(written.error);
10794
+ const provisioned = await ops.triggerProvisioning();
10795
+ if (!provisioned.ok) return fail(provisioned.error);
10796
+ const org = await ops.createOrg({
10797
+ name: validated.value.organizationName,
10798
+ handle: validated.value.handle,
10799
+ template: DEFAULT_ORG_TEMPLATE,
10800
+ country: validated.value.country
10801
+ });
10802
+ if (!org.ok) return fail(org.error);
10803
+ ops.kickProvisioning();
10804
+ const lifecycle = await ops.readLifecycle();
10805
+ if (!lifecycle.ok) return fail(lifecycle.error);
10806
+ return {
10807
+ ok: true,
10808
+ value: {
10809
+ org: org.value,
10810
+ lifecycle: lifecycle.value
10811
+ }
10812
+ };
10813
+ }
10814
+ function validatePersonalInput(input) {
10815
+ const displayName = requireNonEmpty(input.displayName, "displayName");
10816
+ if (!displayName.ok) return displayName;
10817
+ const country = parseCountry(input.country);
10818
+ if (!country.ok) return country;
10819
+ if (input.withdrawalAddress === void 0) return {
10820
+ ok: true,
10821
+ value: {
10822
+ displayName: displayName.value,
10823
+ country: country.value
10824
+ }
10825
+ };
10826
+ const withdrawalAddress = parseAddress(input.withdrawalAddress, "withdrawalAddress");
10827
+ if (!withdrawalAddress.ok) return withdrawalAddress;
10828
+ return {
10829
+ ok: true,
10830
+ value: {
10831
+ displayName: displayName.value,
10832
+ country: country.value,
10833
+ withdrawalAddress: withdrawalAddress.value
10834
+ }
10835
+ };
10836
+ }
10837
+ function validateOrganizationInput(input) {
10838
+ const organizationName = requireNonEmpty(input.organizationName, "organizationName");
10839
+ if (!organizationName.ok) return organizationName;
10840
+ const handle = requireNonEmpty(input.handle, "handle");
10841
+ if (!handle.ok) return handle;
10842
+ const ownerDisplayName = requireNonEmpty(input.ownerDisplayName, "ownerDisplayName");
10843
+ if (!ownerDisplayName.ok) return ownerDisplayName;
10844
+ const country = parseCountry(input.country);
10845
+ if (!country.ok) return country;
10846
+ return {
10847
+ ok: true,
10848
+ value: {
10849
+ organizationName: organizationName.value,
10850
+ handle: handle.value,
10851
+ country: country.value,
10852
+ ownerDisplayName: ownerDisplayName.value
10853
+ }
10854
+ };
10855
+ }
10856
+ function requireNonEmpty(value, field) {
10857
+ const trimmed = typeof value === "string" ? value.trim() : "";
10858
+ if (trimmed.length === 0) return fail(Errors.invalidInput(field, "must be a non-empty string"));
10859
+ return {
10860
+ ok: true,
10861
+ value: trimmed
10862
+ };
10863
+ }
10864
+ function parseCountry(value) {
10865
+ try {
10866
+ return {
10867
+ ok: true,
10868
+ value: toCountryCode(value)
10869
+ };
10870
+ } catch (cause) {
10871
+ return fail(invalidFrom("country", cause, "must be an ISO-3166 alpha-2 code"));
10872
+ }
10873
+ }
10874
+ function parseAddress(value, field) {
10875
+ try {
10876
+ return {
10877
+ ok: true,
10878
+ value: toAddress(value)
10879
+ };
10880
+ } catch (cause) {
10881
+ return fail(invalidFrom(field, cause, "must be a 0x-prefixed 20-byte address"));
10882
+ }
10883
+ }
10884
+ function invalidFrom(field, cause, fallback) {
10885
+ const message = cause instanceof Error && cause.message.length > 0 ? cause.message : fallback;
10886
+ return Errors.invalidInput(field, message);
10887
+ }
10888
+ function fail(error) {
10889
+ return {
10890
+ ok: false,
10891
+ error: error instanceof CapxulError ? error : Errors.unknown(error)
10892
+ };
10893
+ }
10894
+ //#endregion
10895
+ //#region ../../packages/sdk/src/client/onboarding.ts
10896
+ /**
10897
+ * Onboarding method surface. The thin namespace over the `flows/onboarding.ts`
10898
+ * choreography: it adds the `signal`-abort pre-check and delegates to the run
10899
+ * functions. The `OnboardingOps` seam is supplied by `assembleCapxulClient`
10900
+ * (real ops over the account lane + createOrg + IdentityPort) or by tests
10901
+ * (in-memory double).
10902
+ */
10903
+ function makeOnboardingMethods(ops) {
10904
+ return {
10905
+ completePersonal(input, options) {
10906
+ if (options?.signal?.aborted) return Promise.resolve({
10907
+ ok: false,
10908
+ error: Errors.cancelled({ operation: "onboarding.completePersonal" })
10909
+ });
10910
+ return runCompletePersonalOnboarding(ops, input);
10911
+ },
10912
+ completeOrganization(input, options) {
10913
+ if (options?.signal?.aborted) return Promise.resolve({
10914
+ ok: false,
10915
+ error: Errors.cancelled({ operation: "onboarding.completeOrganization" })
10916
+ });
10917
+ return runCompleteOrganizationOnboarding(ops, input);
10918
+ }
10919
+ };
10920
+ }
8898
10921
  //#endregion
8899
10922
  //#region ../../packages/sdk/src/ports/auth-cache.ts
8900
10923
  var AuthCacheError = class extends Data.TaggedError("AuthCacheError") {};
@@ -9021,6 +11044,7 @@ function assembleCapxulClient(input) {
9021
11044
  const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
9022
11045
  let detectPendingOrgInvitations;
9023
11046
  let kickProvisioning;
11047
+ const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
9024
11048
  const accountBundle = makeAccountMethods({
9025
11049
  actor,
9026
11050
  authCache,
@@ -9030,6 +11054,8 @@ function assembleCapxulClient(input) {
9030
11054
  chainId: input.bootstrap.chainId,
9031
11055
  requirement: input.requirement,
9032
11056
  accountReadPort: input.ports.accountRead,
11057
+ profileMethods: financialOps.me,
11058
+ convexCall: input.ports.convexCall,
9033
11059
  ...input.signer === void 0 ? {} : { signer: input.signer }
9034
11060
  });
9035
11061
  kickProvisioning = accountBundle.kickProvisioning;
@@ -9065,7 +11091,6 @@ function assembleCapxulClient(input) {
9065
11091
  chainId: input.bootstrap.chainId,
9066
11092
  telemetry: input.ports.telemetry
9067
11093
  });
9068
- const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
9069
11094
  const subAccounts = makeSubAccountsMethods({
9070
11095
  subAccountPort: input.ports.subAccount,
9071
11096
  telemetry: input.ports.telemetry
@@ -9075,21 +11100,47 @@ function assembleCapxulClient(input) {
9075
11100
  telemetry: input.ports.telemetry,
9076
11101
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
9077
11102
  ...input.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: input.orgRolesDeploymentPort },
9078
- ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort }
11103
+ ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort },
11104
+ convexCall: input.ports.convexCall
9079
11105
  });
9080
11106
  if (selectedOrgPort !== void 0) detectPendingOrgInvitations = async () => {
9081
11107
  await orgMethods.orgs.detectAndAcceptPendingInvitations();
9082
11108
  };
11109
+ const currentUser = makeCurrentUserMethods({
11110
+ me: financialOps.me,
11111
+ accounts,
11112
+ smartAccount,
11113
+ orgs: orgMethods.orgs
11114
+ });
11115
+ const onboarding = makeOnboardingMethods({
11116
+ currentSession: async () => {
11117
+ const session = await currentSession(actor, authCache);
11118
+ return session === null ? null : {
11119
+ authUserId: session.authUserId,
11120
+ email: session.email
11121
+ };
11122
+ },
11123
+ completeIdentityOnboarding: (write) => runPortEffect(input.ports.identity.completeOnboarding(write)),
11124
+ triggerProvisioning: () => account._internal.provision(),
11125
+ kickProvisioning: () => kickProvisioning?.(),
11126
+ readLifecycle: () => account.getLifecycle(),
11127
+ createOrg: (createOrgInput) => orgMethods.createOrg(createOrgInput)
11128
+ });
9083
11129
  return {
9084
11130
  auth,
9085
11131
  smartAccount,
9086
11132
  identity,
9087
11133
  account,
9088
11134
  accounts,
11135
+ currentUser,
9089
11136
  me: financialOps.me,
9090
11137
  handles: financialOps.handles,
9091
11138
  payees: financialOps.payees,
11139
+ targets: financialOps.targets,
11140
+ destinations: financialOps.destinations,
9092
11141
  payments: financialOps.payments,
11142
+ activity: financialOps.activity,
11143
+ offramp: financialOps.offramp,
9093
11144
  paymentDocuments: financialOps.paymentDocuments,
9094
11145
  paymentRequests: financialOps.paymentRequests,
9095
11146
  workbench: financialOps.workbench,
@@ -9097,6 +11148,7 @@ function assembleCapxulClient(input) {
9097
11148
  createOrg: orgMethods.createOrg,
9098
11149
  orgs: orgMethods.orgs,
9099
11150
  org: orgMethods.org,
11151
+ onboarding,
9100
11152
  _internal: {
9101
11153
  authActor: {
9102
11154
  input: actor.input,
@@ -9616,7 +11668,7 @@ function toPublicError(cause, operation) {
9616
11668
  return Errors.providerError("sdk-org-deployment-client", operation, cause);
9617
11669
  }
9618
11670
  //#endregion
9619
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/actions/public/getAccountNonce.js
11671
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/actions/public/getAccountNonce.js
9620
11672
  /**
9621
11673
  * Returns the nonce of the account with the entry point.
9622
11674
  *
@@ -9668,7 +11720,7 @@ const getAccountNonce = async (client, args) => {
9668
11720
  });
9669
11721
  };
9670
11722
  //#endregion
9671
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/toOwner.js
11723
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/toOwner.js
9672
11724
  async function toOwner({ owner, address }) {
9673
11725
  if ("type" in owner && owner.type === "local") return owner;
9674
11726
  let walletClient = void 0;
@@ -9699,7 +11751,7 @@ async function toOwner({ owner, address }) {
9699
11751
  });
9700
11752
  }
9701
11753
  //#endregion
9702
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/decode7579Calls.js
11754
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/decode7579Calls.js
9703
11755
  function decode7579Calls(callData) {
9704
11756
  const decoded = decodeFunctionData({
9705
11757
  abi: [{
@@ -9782,7 +11834,7 @@ function decode7579Calls(callData) {
9782
11834
  };
9783
11835
  }
9784
11836
  //#endregion
9785
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/actions/erc7579/supportsExecutionMode.js
11837
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/actions/erc7579/supportsExecutionMode.js
9786
11838
  function getCallType(callType) {
9787
11839
  switch (callType) {
9788
11840
  case "call": return "0x00";
@@ -9806,7 +11858,7 @@ function encodeExecutionMode({ type, revertOnError, selector, context }) {
9806
11858
  ]);
9807
11859
  }
9808
11860
  //#endregion
9809
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/encode7579Calls.js
11861
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/encode7579Calls.js
9810
11862
  function encode7579Calls({ mode, callData }) {
9811
11863
  if (callData.length > 1 && mode?.type !== "batchcall") throw new Error(`mode ${JSON.stringify(mode)} does not supported for batchcall calldata`);
9812
11864
  const executeAbi = [{
@@ -9865,20 +11917,20 @@ function encode7579Calls({ mode, callData }) {
9865
11917
  });
9866
11918
  }
9867
11919
  //#endregion
9868
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/isSmartAccountDeployed.js
11920
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/isSmartAccountDeployed.js
9869
11921
  const isSmartAccountDeployed = async (client, address) => {
9870
11922
  const contractCode = await getCode(client, { address });
9871
11923
  return Boolean(contractCode);
9872
11924
  };
9873
11925
  //#endregion
9874
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/ox.js
11926
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/utils/ox.js
9875
11927
  /**
9876
11928
  * Utility module for handling optional ox imports
9877
11929
  * This allows the library to work without ox being installed
9878
11930
  */
9879
11931
  let oxModule = null;
9880
11932
  try {
9881
- oxModule = { importPromise: import("./_esm-CA4cvybV.mjs") };
11933
+ oxModule = { importPromise: import("./_esm-DUwdnl5L.mjs") };
9882
11934
  } catch (error) {}
9883
11935
  async function getOxModule() {
9884
11936
  if (!oxModule) throw new Error("The 'ox' package is required for WebAuthn functionality. Please install it: npm install ox");
@@ -9899,7 +11951,7 @@ async function getOxExports() {
9899
11951
  };
9900
11952
  }
9901
11953
  //#endregion
9902
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/accounts/safe/signUserOperation.js
11954
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/accounts/safe/signUserOperation.js
9903
11955
  const concatSignatures = (signatures) => {
9904
11956
  signatures.sort((left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase()));
9905
11957
  const SIGNATURE_LENGTH_BYTES = 65;
@@ -10064,7 +12116,7 @@ async function signUserOperation(parameters) {
10064
12116
  ]);
10065
12117
  }
10066
12118
  //#endregion
10067
- //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.51.0_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/accounts/safe/toSafeSmartAccount.js
12119
+ //#region ../../node_modules/.pnpm/permissionless@0.3.4_viem@2.53.1_typescript@5.9.2_zod@4.4.3_/node_modules/permissionless/_esm/accounts/safe/toSafeSmartAccount.js
10068
12120
  const multiSendAbi$1 = [{
10069
12121
  inputs: [{
10070
12122
  internalType: "bytes",
@@ -11430,6 +13482,7 @@ function toViemHexAddress(value) {
11430
13482
  const orgCreateMutation = makeFunctionReference("org/mutations:createOrg");
11431
13483
  const orgDeployRolesAction = makeFunctionReference("org/actions:deployOrgRoles");
11432
13484
  const orgInviteMemberAction = makeFunctionReference("org/actions:inviteMember");
13485
+ const orgResendInviteTokenMutation = makeFunctionReference("org/mutations:resendInviteToken");
11433
13486
  const orgDetectAndAcceptPendingInvitationsAction = makeFunctionReference("org/actions:detectAndAcceptPendingInvitations");
11434
13487
  const orgAssignRoleAction = makeFunctionReference("org/actions:assignRole");
11435
13488
  const orgRemoveMemberAction = makeFunctionReference("org/actions:removeMember");
@@ -11647,6 +13700,9 @@ var LiveOrgDeploymentAdapter = class {
11647
13700
  listMembers(input) {
11648
13701
  return this.#convex.query(orgListMembersByOrgIdQuery, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listMembers", error.publicError, error)), Effect.map((members) => members.map(brandOrgMember)));
11649
13702
  }
13703
+ pendingMembers(input) {
13704
+ return this.listMembers(input).pipe(Effect.map((members) => members.filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant")));
13705
+ }
11650
13706
  inviteMember(input) {
11651
13707
  return this.#convex.action(orgInviteMemberAction, {
11652
13708
  orgId: input.orgId,
@@ -11655,6 +13711,12 @@ var LiveOrgDeploymentAdapter = class {
11655
13711
  ...process.env.CAPXUL_E2E_RUN_ID === void 0 ? {} : { telemetryRunId: process.env.CAPXUL_E2E_RUN_ID }
11656
13712
  }).pipe(Effect.mapError((error) => orgErrorFromCapxul("inviteMember", error.publicError, error)), Effect.map(brandOrgMember));
11657
13713
  }
13714
+ resendInviteToken(input) {
13715
+ return this.#convex.mutation(orgResendInviteTokenMutation, {
13716
+ orgId: input.orgId,
13717
+ email: input.email
13718
+ }).pipe(Effect.mapError((error) => orgErrorFromCapxul("resendInviteToken", error.publicError, error)), Effect.map(brandOrgMember));
13719
+ }
11658
13720
  detectAndAcceptPendingInvitations(_input) {
11659
13721
  return this.#convex.action(orgDetectAndAcceptPendingInvitationsAction, process.env.CAPXUL_E2E_RUN_ID === void 0 ? {} : { telemetryRunId: process.env.CAPXUL_E2E_RUN_ID }).pipe(Effect.mapError((error) => orgErrorFromCapxul("detectAndAcceptPendingInvitations", error.publicError, error)), Effect.map((result) => ({ matched: result.matched.map(toOrgId) })));
11660
13722
  }
@@ -12147,6 +14209,102 @@ function toOrgError(operation, cause) {
12147
14209
  return orgErrorFromCapxul(operation, cause instanceof CapxulError ? cause : Errors.providerError("permissionless-org-deployment", operation, cause), cause);
12148
14210
  }
12149
14211
  //#endregion
14212
+ //#region ../../packages/backend/convex/financialOps/settlementBuild.ts
14213
+ const ADDRESS_RE$2 = /^0x[0-9a-fA-F]{40}$/;
14214
+ const BYTES32_RE$1 = /^0x[0-9a-fA-F]{64}$/;
14215
+ const DECIMAL_RE$1 = /^([0-9]+)(?:\.([0-9]+))?$/;
14216
+ const ZERO_BYTES32$1 = `0x${"0".repeat(64)}`;
14217
+ const PAYMENT_TYPE_PAYROLL = 2;
14218
+ function requireAllowlistedToken() {
14219
+ const tokenAddress = DIRECT_BASE_ROUTE.token.address;
14220
+ if (!isExactTransferTokenAllowed(tokenAddress)) throw Errors.invalidInput("token", "token is not on the exact-transfer allowlist");
14221
+ return tokenAddress;
14222
+ }
14223
+ function settlementMoneyToRawUnits(amount) {
14224
+ const decimals = DIRECT_BASE_ROUTE.token.decimals;
14225
+ if (amount.decimals !== decimals) throw Errors.invalidInput("amount", `USDX payments require ${decimals} decimals`);
14226
+ if (amount.currency !== "USD" && amount.currency !== "USDX") throw Errors.invalidInput("amount", "currency must be USD or USDX");
14227
+ const match = DECIMAL_RE$1.exec(amount.value);
14228
+ if (match === null) throw Errors.invalidInput("amount", "value must be a decimal string");
14229
+ const whole = match[1] ?? "0";
14230
+ const fraction = match[2] ?? "";
14231
+ if (fraction.length > decimals) throw Errors.invalidInput("amount", `USDX supports at most ${decimals} decimals`);
14232
+ const rawUnits = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fraction.padEnd(decimals, "0"));
14233
+ if (rawUnits <= 0n) throw Errors.invalidInput("amount", "must be greater than zero");
14234
+ return rawUnits;
14235
+ }
14236
+ function normalizeSettlementRecipient(value, field = "recipient") {
14237
+ if (!ADDRESS_RE$2.test(value)) throw Errors.invalidInput(field, "must be 0x + 40 hex chars");
14238
+ return value.toLowerCase();
14239
+ }
14240
+ function normalizeSettlementBytes32(value, field = "documentHash") {
14241
+ if (value === void 0) return ZERO_BYTES32$1;
14242
+ if (!BYTES32_RE$1.test(value)) throw Errors.invalidInput(field, "must be a 32-byte 0x hex string");
14243
+ return value.toLowerCase();
14244
+ }
14245
+ function commitmentTimes$1(timing) {
14246
+ if (timing.kind === "scheduled") return {
14247
+ startTime: timing.at,
14248
+ cliffTime: timing.at,
14249
+ endTime: timing.at
14250
+ };
14251
+ return {
14252
+ startTime: timing.startsAt,
14253
+ cliffTime: timing.cliffAt ?? timing.startsAt,
14254
+ endTime: timing.endsAt
14255
+ };
14256
+ }
14257
+ function buildPaymentSettlementCallData(input) {
14258
+ const tokenAddress = requireAllowlistedToken();
14259
+ const recipientAddress = normalizeSettlementRecipient(input.recipient);
14260
+ const rawAmount = settlementMoneyToRawUnits(input.amount);
14261
+ const documentHash = normalizeSettlementBytes32(input.documentHash);
14262
+ const paymentType = input.paymentType ?? 0;
14263
+ const timing = input.timing ?? { kind: "instant" };
14264
+ if (timing.kind === "instant") return buildCapxulPaymentsPersonalSendCallData({
14265
+ tokenAddress,
14266
+ recipientAddress,
14267
+ amount: rawAmount,
14268
+ documentHash,
14269
+ paymentType
14270
+ });
14271
+ const times = commitmentTimes$1(timing);
14272
+ return buildCapxulCreateCommitmentPersonalCallData({
14273
+ tokenAddress,
14274
+ recipientAddress,
14275
+ totalAmount: rawAmount,
14276
+ startTime: times.startTime,
14277
+ cliffTime: times.cliffTime,
14278
+ endTime: times.endTime,
14279
+ documentHash,
14280
+ paymentType
14281
+ });
14282
+ }
14283
+ function buildRolePayrollSettlementCallData(input) {
14284
+ if (input.runs.length === 0) throw Errors.invalidInput("runs", "payroll batch must include at least one run");
14285
+ const tokenAddress = requireAllowlistedToken();
14286
+ return buildOrgRoleSpendPersonalCallData(buildCapxulPaymentsRoleBatchSpendCall({
14287
+ rolesModuleAddress: normalizeSettlementRecipient(input.rolesModule, "rolesModule"),
14288
+ roleKey: normalizeSettlementBytes32(input.roleKey, "roleKey"),
14289
+ tokenAddress,
14290
+ paymentType: PAYMENT_TYPE_PAYROLL,
14291
+ runs: input.runs.map((run) => ({
14292
+ recipientAddress: normalizeSettlementRecipient(run.recipient, "recipient"),
14293
+ amount: settlementMoneyToRawUnits(run.amount),
14294
+ ...run.timing === void 0 || run.timing.kind === "instant" ? {} : { timing: commitmentTimes$1(run.timing) },
14295
+ ...run.documentHash === void 0 ? {} : { documentHash: normalizeSettlementBytes32(run.documentHash, "documentHash") }
14296
+ }))
14297
+ }));
14298
+ }
14299
+ function buildCommitmentLifecycleSettlementCallData(input) {
14300
+ const commitmentId = BigInt(input.onchainCommitmentId);
14301
+ switch (input.kind) {
14302
+ case "claim": return buildCapxulCommitmentClaimCallData(commitmentId);
14303
+ case "cancel": return buildCapxulCommitmentCancelCallData(commitmentId, normalizeSettlementBytes32(input.documentHash));
14304
+ case "redirect": return buildCapxulCommitmentRedirectCallData(commitmentId, normalizeSettlementRecipient(input.newRecipient, "newRecipient"), normalizeSettlementBytes32(input.newDocumentHash, "newDocumentHash"));
14305
+ }
14306
+ }
14307
+ //#endregion
12150
14308
  //#region ../../packages/backend/convex/smartAccount/deploy.ts
12151
14309
  /** Merge only the paymaster fields a `pm_*` result actually returned (viem-style override). */
12152
14310
  function definedPaymasterFields(r) {
@@ -12433,7 +14591,6 @@ function directBaseSettlementPort() {
12433
14591
  }
12434
14592
  //#endregion
12435
14593
  //#region src/org-sender.ts
12436
- const PAYMENT_TYPE_PAYROLL = 2;
12437
14594
  /**
12438
14595
  * Execute an org payroll batch (or a single org spend, runs.length === 1) as one
12439
14596
  * sponsored UserOp through the member's role on the Org Roles modifier. The
@@ -12448,24 +14605,21 @@ const PAYMENT_TYPE_PAYROLL = 2;
12448
14605
  async function executeOrgPayrollBatch(input) {
12449
14606
  return guard$1("org.batchPayroll", async () => {
12450
14607
  const port = input.port ?? directBaseSettlementPort();
12451
- const tokenAddress = port.requireAllowlistedToken();
12452
14608
  if (input.runs.length === 0) throw Errors.invalidInput("runs", "payroll batch must include at least one run");
12453
- const call = buildCapxulPaymentsRoleBatchSpendCall({
12454
- rolesModuleAddress: port.normalizeRecipient(input.rolesModuleAddress, "rolesModuleAddress"),
12455
- roleKey: port.normalizeDocumentHash(input.roleKey, "roleKey"),
12456
- tokenAddress,
12457
- paymentType: PAYMENT_TYPE_PAYROLL,
14609
+ const callData = buildRolePayrollSettlementCallData({
14610
+ rolesModule: input.rolesModuleAddress,
14611
+ roleKey: input.roleKey,
12458
14612
  runs: input.runs.map((run) => ({
12459
- recipientAddress: port.normalizeRecipient(run.recipientAddress, "recipientAddress"),
12460
- amount: port.moneyToRawUnits(run.amount),
12461
- ...run.documentHash === void 0 ? {} : { documentHash: port.normalizeDocumentHash(run.documentHash, "documentHash") }
14613
+ recipient: run.recipientAddress,
14614
+ amount: run.amount,
14615
+ ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
12462
14616
  }))
12463
14617
  });
12464
14618
  const submitted = await port.submitAndConfirm({
12465
14619
  signer: input.signer,
12466
14620
  payerEmail: input.memberEmail,
12467
14621
  policyId: input.policyId,
12468
- callData: buildOrgRoleSpendPersonalCallData(call),
14622
+ callData,
12469
14623
  method: "org.batchPayroll",
12470
14624
  mapReverts: true,
12471
14625
  ...input.waitReceiptMs === void 0 ? {} : { waitReceiptMs: input.waitReceiptMs },
@@ -12495,6 +14649,40 @@ function guard$1(method, fn) {
12495
14649
  }
12496
14650
  //#endregion
12497
14651
  //#region src/org-spend-port.ts
14652
+ function refToMcpRecipient(ref) {
14653
+ switch (ref.kind) {
14654
+ case "handle": return ref.handle;
14655
+ case "email": return ref.email;
14656
+ case "orgHandle": return ref.orgHandle;
14657
+ case "capxulUserId": return ref.capxulUserId;
14658
+ case "payeeId": return ref.payeeId;
14659
+ }
14660
+ }
14661
+ function recipientIdentityFromRef(ref) {
14662
+ switch (ref.kind) {
14663
+ case "handle": return {
14664
+ recipientKind: "handle",
14665
+ recipientRef: ref.handle
14666
+ };
14667
+ case "email": return {
14668
+ recipientKind: "email",
14669
+ recipientRef: ref.email
14670
+ };
14671
+ case "orgHandle": return {
14672
+ recipientKind: "org",
14673
+ recipientRef: ref.orgHandle
14674
+ };
14675
+ case "capxulUserId": return {
14676
+ recipientKind: "capxulUserId",
14677
+ recipientRef: ref.capxulUserId
14678
+ };
14679
+ case "payeeId": return {
14680
+ recipientKind: "payee",
14681
+ recipientRef: ref.payeeId,
14682
+ recipientPayeeId: ref.payeeId
14683
+ };
14684
+ }
14685
+ }
12498
14686
  /**
12499
14687
  * A leak-safe authority that defers the per-tx / per-day cap to the ON-CHAIN
12500
14688
  * Roles modifier. The off-chain gate must pass everything EXCEPT a genuinely
@@ -12593,6 +14781,7 @@ function makeDevOrgSpendPort(deps) {
12593
14781
  const recorded = await recordOrgPayment({
12594
14782
  orgId,
12595
14783
  recipientLabel: run.to,
14784
+ ...run.identity,
12596
14785
  recipientSafeAddress,
12597
14786
  amount,
12598
14787
  paymentType,
@@ -12617,12 +14806,14 @@ function makeDevOrgSpendPort(deps) {
12617
14806
  catch: (cause) => orgErrorFromCapxul("readSpendAuthority", Errors.providerError("capxul-mcp", "readSpendAuthority", cause))
12618
14807
  }),
12619
14808
  submitSpendViaPayments: (input) => submitRuns(String(input.orgId), [{
12620
- to: input.input.to,
14809
+ to: refToMcpRecipient(input.input.to),
14810
+ identity: recipientIdentityFromRef(input.input.to),
12621
14811
  amount: money(input.input.amount),
12622
14812
  ...input.input.document === void 0 ? {} : { document: input.input.document }
12623
14813
  }], "org.spendViaPayments").pipe(Effect.map((payments) => payments[0])),
12624
14814
  submitBatchPayroll: (input) => submitRuns(String(input.orgId), input.runs.map(({ run }) => ({
12625
- to: run.to,
14815
+ to: refToMcpRecipient(run.to),
14816
+ identity: recipientIdentityFromRef(run.to),
12626
14817
  amount: money(run.amount),
12627
14818
  ...run.payslip === void 0 ? {} : { document: run.payslip }
12628
14819
  })), "org.batchPayroll")
@@ -12729,6 +14920,7 @@ async function submitFromMemberSafe(input) {
12729
14920
  policyId: input.deps.policyId,
12730
14921
  callData: input.callData,
12731
14922
  method: input.operation,
14923
+ mapReverts: true,
12732
14924
  waitReceiptMs: input.deps.waitReceiptMs ?? 18e4,
12733
14925
  ...input.deps.pollIntervalMs === void 0 ? {} : { pollIntervalMs: input.deps.pollIntervalMs },
12734
14926
  ...input.onUserOpHash === void 0 ? {} : { onUserOpHash: input.onUserOpHash }
@@ -12753,19 +14945,18 @@ async function sendCapxulPayment(input) {
12753
14945
  const tokenAddress = port.requireAllowlistedToken();
12754
14946
  const deps = input.deps ?? {};
12755
14947
  const readBalance = deps.fetchErc20Balance ?? fetchErc20Balance;
12756
- const rawAmount = port.moneyToRawUnits(input.amount);
12757
- const recipient = port.normalizeRecipient(input.recipientAddress);
12758
- const documentHash = port.normalizeDocumentHash(input.documentHash);
14948
+ const rawAmount = settlementMoneyToRawUnits(input.amount);
14949
+ const recipient = normalizeSettlementRecipient(input.recipientAddress);
12759
14950
  const recipientBefore = (await readBalance({
12760
14951
  chainId,
12761
14952
  tokenAddress,
12762
14953
  holderAddress: recipient
12763
14954
  })).rawBalance;
12764
- const callData = buildCapxulPaymentsPersonalSendCallData({
12765
- tokenAddress,
12766
- recipientAddress: recipient,
12767
- amount: rawAmount,
12768
- documentHash,
14955
+ const callData = buildPaymentSettlementCallData({
14956
+ recipient,
14957
+ amount: input.amount,
14958
+ timing: { kind: "instant" },
14959
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash },
12769
14960
  paymentType: input.paymentType
12770
14961
  });
12771
14962
  const confirmed = await port.submitAndConfirm({
@@ -12845,19 +15036,17 @@ function submitCommitment(port, args) {
12845
15036
  async function executeCommitmentCreate(input) {
12846
15037
  const result = await guard("payments.pay", async () => {
12847
15038
  const port = input.port ?? directBaseSettlementPort();
12848
- const tokenAddress = port.requireAllowlistedToken();
12849
15039
  const deps = input.deps ?? {};
12850
- const rawAmount = port.moneyToRawUnits(input.amount);
12851
- const recipient = port.normalizeRecipient(input.recipientAddress);
12852
- const documentHash = port.normalizeDocumentHash(input.documentHash);
12853
- const callData = buildCapxulCreateCommitmentPersonalCallData({
12854
- tokenAddress,
12855
- recipientAddress: recipient,
12856
- totalAmount: rawAmount,
12857
- startTime: input.startTime,
12858
- cliffTime: input.cliffTime,
12859
- endTime: input.endTime,
12860
- documentHash,
15040
+ const callData = buildPaymentSettlementCallData({
15041
+ recipient: input.recipientAddress,
15042
+ amount: input.amount,
15043
+ timing: {
15044
+ kind: "stream",
15045
+ startsAt: input.startTime,
15046
+ cliffAt: input.cliffTime,
15047
+ endsAt: input.endTime
15048
+ },
15049
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash },
12861
15050
  paymentType: input.paymentType
12862
15051
  });
12863
15052
  const submitted = await submitCommitment(port, {
@@ -12891,7 +15080,10 @@ async function executeCommitmentCreate(input) {
12891
15080
  async function executeCommitmentClaim(input) {
12892
15081
  return guard("payments.claim", async () => {
12893
15082
  const port = input.port ?? directBaseSettlementPort();
12894
- const callData = buildCapxulCommitmentClaimCallData(BigInt(input.onchainCommitmentId));
15083
+ const callData = buildCommitmentLifecycleSettlementCallData({
15084
+ kind: "claim",
15085
+ onchainCommitmentId: input.onchainCommitmentId
15086
+ });
12895
15087
  const submitted = await submitCommitment(port, {
12896
15088
  signer: input.signer,
12897
15089
  payerEmail: input.recipientEmail,
@@ -12913,7 +15105,11 @@ async function executeCommitmentClaim(input) {
12913
15105
  async function executeCommitmentCancel(input) {
12914
15106
  return guard("payments.cancel", async () => {
12915
15107
  const port = input.port ?? directBaseSettlementPort();
12916
- const callData = buildCapxulCommitmentCancelCallData(BigInt(input.onchainCommitmentId), port.normalizeDocumentHash(input.documentHash));
15108
+ const callData = buildCommitmentLifecycleSettlementCallData({
15109
+ kind: "cancel",
15110
+ onchainCommitmentId: input.onchainCommitmentId,
15111
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash }
15112
+ });
12917
15113
  const submitted = await submitCommitment(port, {
12918
15114
  signer: input.signer,
12919
15115
  payerEmail: input.creatorEmail,
@@ -12935,7 +15131,12 @@ async function executeCommitmentCancel(input) {
12935
15131
  async function executeCommitmentRedirect(input) {
12936
15132
  return guard("payments.redirect", async () => {
12937
15133
  const port = input.port ?? directBaseSettlementPort();
12938
- const callData = buildCapxulCommitmentRedirectCallData(BigInt(input.onchainCommitmentId), port.normalizeRecipient(input.newRecipientAddress), port.normalizeDocumentHash(input.newDocumentHash));
15134
+ const callData = buildCommitmentLifecycleSettlementCallData({
15135
+ kind: "redirect",
15136
+ onchainCommitmentId: input.onchainCommitmentId,
15137
+ newRecipient: input.newRecipientAddress,
15138
+ ...input.newDocumentHash === void 0 ? {} : { newDocumentHash: input.newDocumentHash }
15139
+ });
12939
15140
  const submitted = await submitCommitment(port, {
12940
15141
  signer: input.signer,
12941
15142
  payerEmail: input.creatorEmail,
@@ -12960,8 +15161,8 @@ async function executeCommitmentRedirect(input) {
12960
15161
  */
12961
15162
  async function fetchCommitmentCreatedIdFromLogs(input) {
12962
15163
  const { keccak256, toBytes } = await import("viem");
12963
- const { fetchCommitmentCreatedLog } = await import("./alchemy-rpc-BWwk_YTZ.mjs");
12964
- const { CAPXUL_PAYMENTS_ADDRESS } = await import("./src-D4Y3802K.mjs");
15164
+ const { fetchCommitmentCreatedLog } = await import("./alchemy-rpc-DxVP2GsG.mjs");
15165
+ const { CAPXUL_PAYMENTS_ADDRESS } = await import("./src-BmSYoMhj.mjs");
12965
15166
  const topic0 = keccak256(toBytes("CommitmentCreated(uint256,address,address,address,uint256,uint48,uint48,uint48,bytes32,uint8)"));
12966
15167
  const idTopic = (await fetchCommitmentCreatedLog({
12967
15168
  chainId: input.chainId,
@@ -12975,6 +15176,66 @@ async function fetchCommitmentCreatedIdFromLogs(input) {
12975
15176
  }
12976
15177
  //#endregion
12977
15178
  //#region src/sdk.ts
15179
+ function refFromMcpRecipient(recipient) {
15180
+ const trimmed = recipient.trim();
15181
+ if (/^payee_[0-9A-Za-z]+$/.test(trimmed)) return {
15182
+ kind: "payeeId",
15183
+ payeeId: trimmed
15184
+ };
15185
+ if (/^user_[0-9A-Za-z]+$/.test(trimmed)) return {
15186
+ kind: "capxulUserId",
15187
+ capxulUserId: trimmed
15188
+ };
15189
+ if (trimmed.startsWith("@")) return {
15190
+ kind: "handle",
15191
+ handle: trimmed.slice(1)
15192
+ };
15193
+ if (trimmed.includes("@")) return {
15194
+ kind: "email",
15195
+ email: trimmed
15196
+ };
15197
+ return {
15198
+ kind: "orgHandle",
15199
+ orgHandle: trimmed
15200
+ };
15201
+ }
15202
+ function targetFromMcpRecipient(recipient) {
15203
+ const ref = refFromMcpRecipient(recipient);
15204
+ switch (ref.kind) {
15205
+ case "handle": return {
15206
+ ok: true,
15207
+ value: {
15208
+ kind: "handle",
15209
+ handle: ref.handle
15210
+ }
15211
+ };
15212
+ case "email": return {
15213
+ ok: true,
15214
+ value: {
15215
+ kind: "email",
15216
+ email: ref.email
15217
+ }
15218
+ };
15219
+ case "orgHandle": return {
15220
+ ok: true,
15221
+ value: {
15222
+ kind: "organization",
15223
+ handle: ref.orgHandle
15224
+ }
15225
+ };
15226
+ case "payeeId": return {
15227
+ ok: true,
15228
+ value: {
15229
+ kind: "payee",
15230
+ id: ref.payeeId
15231
+ }
15232
+ };
15233
+ case "capxulUserId": return {
15234
+ ok: false,
15235
+ error: Errors.notImplemented("payments", "target.capxulUserId")
15236
+ };
15237
+ }
15238
+ }
12978
15239
  function toMcpOrgView(view) {
12979
15240
  return {
12980
15241
  orgId: String(view.id),
@@ -13035,6 +15296,26 @@ function toMcpRoleView(view) {
13035
15296
  canManageRoles: view.definition.canManageRoles ?? false
13036
15297
  };
13037
15298
  }
15299
+ function actorBundle(client, actor) {
15300
+ return actor.kind === "account" ? client.account : client.org(toOrgId(actor.orgId));
15301
+ }
15302
+ function actorForSdk(actor) {
15303
+ if (actor === void 0) return void 0;
15304
+ return actor.kind === "account" ? { kind: "personal" } : {
15305
+ kind: "organization",
15306
+ organizationId: actor.orgId
15307
+ };
15308
+ }
15309
+ function moneyForSdk(amount) {
15310
+ return {
15311
+ currency: toCurrencyCode(amount.currency),
15312
+ value: amount.value,
15313
+ decimals: amount.decimals
15314
+ };
15315
+ }
15316
+ function transferEndpoint(value) {
15317
+ return value === "main" ? "main" : toSubAccountId(value);
15318
+ }
13038
15319
  const PAYMENT_TYPE_UINT8 = {
13039
15320
  unspecified: 0,
13040
15321
  invoice: 1,
@@ -13217,13 +15498,9 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13217
15498
  getMe: async () => {
13218
15499
  const result = await client.me.get();
13219
15500
  if (!result.ok) return result;
13220
- const withChain = result.value;
13221
15501
  return {
13222
15502
  ok: true,
13223
- value: {
13224
- ...result.value,
13225
- chainId: withChain.chainId ?? 84532
13226
- }
15503
+ value: result.value
13227
15504
  };
13228
15505
  },
13229
15506
  getDepositInstructions: () => client.me.depositInstructions(),
@@ -13269,11 +15546,85 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13269
15546
  value: res.value.map(toMcpRoleView)
13270
15547
  } : res;
13271
15548
  },
15549
+ addressBookList: (actor) => actorBundle(client, actor).addressBook.list(),
15550
+ addressBookGet: (actor, entryId) => actorBundle(client, actor).addressBook.get(entryId),
15551
+ addressBookAdd: (input) => actorBundle(client, input.actor).addressBook.add({
15552
+ ref: input.ref,
15553
+ ...input.label === void 0 ? {} : { label: input.label }
15554
+ }),
15555
+ addressBookHide: (actor, entryId) => actorBundle(client, actor).addressBook.hide(entryId),
15556
+ addressBookUnhide: (actor, entryId) => actorBundle(client, actor).addressBook.unhide(entryId),
15557
+ addressBookLabel: (input) => actorBundle(client, input.actor).addressBook.label({
15558
+ entryId: input.entryId,
15559
+ label: input.label
15560
+ }),
15561
+ actorRequestIssue: (input) => actorBundle(client, input.actor).requests.issue({
15562
+ payer: input.payer,
15563
+ amount: input.amount,
15564
+ reference: input.reference,
15565
+ ...input.memo === void 0 ? {} : { memo: input.memo },
15566
+ ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
15567
+ }),
15568
+ actorRequestsList: (actor) => actorBundle(client, actor).requests.list(),
15569
+ actorRequestsGet: (actor, requestId) => actorBundle(client, actor).requests.get(requestId),
15570
+ actorRequestsCancel: (actor, requestId) => actorBundle(client, actor).requests.cancel(requestId),
15571
+ actorRequestsReconcile: (actor) => actorBundle(client, actor).requests.reconcile(),
15572
+ inboxList: (actor) => actorBundle(client, actor).inbox.list(),
15573
+ inboxApprove: (actor, requestId, timing) => actorBundle(client, actor).inbox.approve({
15574
+ requestId,
15575
+ ...timing === void 0 ? {} : { timing }
15576
+ }),
15577
+ inboxDecline: (actor, requestId) => actorBundle(client, actor).inbox.decline(requestId),
15578
+ insightsSummary: (actor) => actorBundle(client, actor).insights.summary(),
15579
+ insightsHistory: (actor) => actorBundle(client, actor).insights.history(),
15580
+ addDestination: (input) => client.destinations.add({
15581
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15582
+ ref: input.ref,
15583
+ kind: input.kind,
15584
+ ...input.label === void 0 ? {} : { label: input.label },
15585
+ payload: input.payload
15586
+ }),
15587
+ listDestinations: (input) => client.destinations.list({
15588
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15589
+ ref: input.ref
15590
+ }),
15591
+ removeDestination: (input) => client.destinations.remove({
15592
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15593
+ destinationId: input.destinationId
15594
+ }),
15595
+ payout: (input) => client.payments.payout({
15596
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15597
+ destinationId: input.destinationId,
15598
+ amount: moneyForSdk(input.amount)
15599
+ }),
15600
+ transfer: (input) => client.subAccounts.transfer({
15601
+ from: transferEndpoint(input.from),
15602
+ to: transferEndpoint(input.to),
15603
+ amount: moneyForSdk(input.amount)
15604
+ }),
15605
+ payrollRosterAdd: (input) => client.org(toOrgId(input.orgId)).payroll.roster.add({
15606
+ employee: input.employee,
15607
+ amount: moneyForSdk(input.amount),
15608
+ timing: input.timing,
15609
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: input.payslipTemplate }
15610
+ }),
15611
+ payrollRosterList: (orgId) => client.org(toOrgId(orgId)).payroll.roster.list(),
15612
+ payrollRosterUpdate: (input) => client.org(toOrgId(input.orgId)).payroll.roster.update(input.rosterLineId, {
15613
+ ...input.employee === void 0 ? {} : { employee: input.employee },
15614
+ ...input.amount === void 0 ? {} : { amount: moneyForSdk(input.amount) },
15615
+ ...input.timing === void 0 ? {} : { timing: input.timing },
15616
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: input.payslipTemplate }
15617
+ }),
15618
+ payrollRosterRemove: (orgId, rosterLineId) => client.org(toOrgId(orgId)).payroll.roster.remove(rosterLineId),
15619
+ payrollRun: (input) => client.org(toOrgId(input.orgId)).payroll.run({
15620
+ period: input.period,
15621
+ from: toSubAccountId(input.from)
15622
+ }),
13272
15623
  draftPayment: (input) => client.workbench.draft({
13273
15624
  clientId: input.clientId,
13274
15625
  audience: input.audience,
13275
15626
  scopes: input.scopes,
13276
- to: input.to,
15627
+ to: refFromMcpRecipient(input.to),
13277
15628
  amount: input.amount,
13278
15629
  idempotencyKey: input.idempotencyKey,
13279
15630
  ...input.document === void 0 ? {} : { document: input.document },
@@ -13293,11 +15644,13 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13293
15644
  ok: false,
13294
15645
  error: Errors.notAuthenticated("no active session")
13295
15646
  };
15647
+ const target = targetFromMcpRecipient(input.to);
15648
+ if (!target.ok) return target;
13296
15649
  const recorded = await client.payments.pay({
13297
- to: input.to,
15650
+ to: target.value,
13298
15651
  amount: input.amount,
13299
15652
  ...input.document === void 0 ? {} : { document: input.document },
13300
- ...input.release === void 0 ? {} : { release: input.release },
15653
+ ...input.release === void 0 ? {} : { timing: input.release },
13301
15654
  ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
13302
15655
  });
13303
15656
  if (!recorded.ok) return recorded;
@@ -13442,7 +15795,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13442
15795
  if (!executed.ok) return executed;
13443
15796
  return client.payments._internal.redirect({
13444
15797
  paymentId,
13445
- to,
15798
+ to: refFromMcpRecipient(to),
13446
15799
  evidence: makeOnchainEvidence({
13447
15800
  userOpHash: executed.value.userOpHash,
13448
15801
  txHash: executed.value.txHash
@@ -13499,7 +15852,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13499
15852
  const amount = input.amount;
13500
15853
  return client.org(toOrgId(input.orgId)).spendViaPayments({
13501
15854
  from: toSubAccountId(input.from),
13502
- to: input.to,
15855
+ to: refFromMcpRecipient(input.to),
13503
15856
  amount: {
13504
15857
  currency: toCurrencyCode(amount.currency),
13505
15858
  value: amount.value,
@@ -13512,7 +15865,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13512
15865
  orgBatchPayroll: async (input) => client.org(toOrgId(input.orgId)).batchPayroll({
13513
15866
  from: toSubAccountId(input.from),
13514
15867
  runs: input.runs.map((run) => ({
13515
- to: run.to,
15868
+ to: refFromMcpRecipient(run.to),
13516
15869
  amount: {
13517
15870
  currency: toCurrencyCode(run.amount.currency),
13518
15871
  value: run.amount.value,
@@ -13652,7 +16005,9 @@ function buildDevOrgPort(input) {
13652
16005
  listOrgs: deploymentAdapter.listOrgs.bind(deploymentAdapter),
13653
16006
  listRoles: deploymentAdapter.listRoles.bind(deploymentAdapter),
13654
16007
  listMembers: deploymentAdapter.listMembers.bind(deploymentAdapter),
16008
+ pendingMembers: deploymentAdapter.pendingMembers.bind(deploymentAdapter),
13655
16009
  inviteMember: deploymentAdapter.inviteMember.bind(deploymentAdapter),
16010
+ resendInviteToken: deploymentAdapter.resendInviteToken.bind(deploymentAdapter),
13656
16011
  detectAndAcceptPendingInvitations: deploymentAdapter.detectAndAcceptPendingInvitations.bind(deploymentAdapter),
13657
16012
  deployRoles: deploymentAdapter.deployRoles.bind(deploymentAdapter),
13658
16013
  grantRole: deploymentAdapter.grantRole.bind(deploymentAdapter),