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

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.11";
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 = {
@@ -1654,7 +1709,7 @@ const ORG_VIEW = {
1654
1709
  handle: z.string(),
1655
1710
  role: z.string()
1656
1711
  };
1657
- const MEMBER_VIEW = {
1712
+ const MEMBER_VIEW$1 = {
1658
1713
  orgId: z.string(),
1659
1714
  email: z.string(),
1660
1715
  name: z.string().nullable(),
@@ -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();
@@ -1727,10 +1782,10 @@ function registerOrgTools(server, deps) {
1727
1782
  sessionToken: z.string(),
1728
1783
  orgId: z.string()
1729
1784
  },
1730
- outputSchema: { members: z.array(z.object(MEMBER_VIEW)) }
1785
+ outputSchema: { members: z.array(z.object(MEMBER_VIEW$1)) }
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);
@@ -1761,10 +1816,10 @@ function registerOrgTools(server, deps) {
1761
1816
  email: z.string(),
1762
1817
  role: z.string()
1763
1818
  },
1764
- outputSchema: MEMBER_VIEW
1819
+ outputSchema: MEMBER_VIEW$1
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({
@@ -1783,10 +1838,10 @@ function registerOrgTools(server, deps) {
1783
1838
  email: z.string(),
1784
1839
  role: z.string()
1785
1840
  },
1786
- outputSchema: MEMBER_VIEW
1841
+ outputSchema: MEMBER_VIEW$1
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;
@@ -2254,79 +2309,777 @@ function registerPaymentRequestTools(server, deps) {
2254
2309
  description: "Record that the payer opened the payment link (sent → viewed).",
2255
2310
  inputSchema: {
2256
2311
  sessionToken: z.string(),
2257
- paymentRequestId: z.string()
2312
+ paymentRequestId: z.string()
2313
+ },
2314
+ outputSchema: PAYMENT_REQUEST_OUTPUT
2315
+ }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.markPaymentRequestViewed === void 0 ? void 0 : handle.markPaymentRequestViewed(paymentRequestId), "markViewed"), "paymentRequests.markViewed", deps.onToolCall));
2316
+ server.registerTool("paymentRequests.cancel", {
2317
+ title: "Cancel payment request",
2318
+ description: "Cancel an open receivable. A cancelled request can never be collected.",
2319
+ inputSchema: {
2320
+ sessionToken: z.string(),
2321
+ paymentRequestId: z.string()
2322
+ },
2323
+ outputSchema: PAYMENT_REQUEST_OUTPUT
2324
+ }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.cancelPaymentRequest === void 0 ? void 0 : handle.cancelPaymentRequest(paymentRequestId), "cancel"), "paymentRequests.cancel", deps.onToolCall));
2325
+ server.registerTool("paymentRequests.collect", {
2326
+ title: "Collect payment request",
2327
+ description: "Collect a sent/viewed receivable. Settles it into the Payment ledger and mints a receipt linked by documentHash, then grants the minimal entitlement. Rejected for a cancelled / expired / draft request and never double-collects. Returns the paid PaymentRequest with its receipt lineage.",
2328
+ inputSchema: {
2329
+ sessionToken: z.string(),
2330
+ paymentRequestId: z.string()
2331
+ },
2332
+ outputSchema: PAYMENT_REQUEST_OUTPUT
2333
+ }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.collectPaymentRequest === void 0 ? void 0 : handle.collectPaymentRequest(paymentRequestId), "collect"), "paymentRequests.collect", deps.onToolCall));
2334
+ server.registerTool("paymentRequests.list", {
2335
+ title: "List payment requests",
2336
+ description: "List your receivables (most recent first), each leak-safe.",
2337
+ inputSchema: { sessionToken: z.string() },
2338
+ outputSchema: { paymentRequests: z.array(z.object(PAYMENT_REQUEST_OUTPUT)) }
2339
+ }, ({ sessionToken }) => guarded(async () => {
2340
+ const entry = requireSession(deps, sessionToken);
2341
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2342
+ const list = entry.handle.listPaymentRequests;
2343
+ if (list === void 0) return errorResult(Errors.notImplemented("paymentRequests", "list"));
2344
+ const result = await list();
2345
+ if (!result.ok) return errorResult(result.error);
2346
+ return okResult({ paymentRequests: result.value.map(toRequestOutput) });
2347
+ }, "paymentRequests.list", deps.onToolCall));
2348
+ server.registerTool("paymentRequests.get", {
2349
+ title: "Get payment request",
2350
+ description: "Get one receivable by id with its current lifecycle status.",
2351
+ inputSchema: {
2352
+ sessionToken: z.string(),
2353
+ paymentRequestId: z.string()
2354
+ },
2355
+ outputSchema: { paymentRequest: z.object(PAYMENT_REQUEST_OUTPUT).nullable() }
2356
+ }, ({ sessionToken, paymentRequestId }) => guarded(async () => {
2357
+ const entry = requireSession(deps, sessionToken);
2358
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2359
+ const get = entry.handle.getPaymentRequest;
2360
+ if (get === void 0) return errorResult(Errors.notImplemented("paymentRequests", "get"));
2361
+ const result = await get(paymentRequestId);
2362
+ if (!result.ok) return errorResult(result.error);
2363
+ return okResult({ paymentRequest: result.value === null ? null : toRequestOutput(result.value) });
2364
+ }, "paymentRequests.get", deps.onToolCall));
2365
+ server.registerTool("paymentRequests.reconcile", {
2366
+ title: "Reconcile receivables",
2367
+ description: "Inbound reconciliation: per receivable, report `paid` (settled into a Payment with a receipt) or `exception` (expired/cancelled, never collected).",
2368
+ inputSchema: { sessionToken: z.string() },
2369
+ outputSchema: { entries: z.array(z.object({
2370
+ paymentRequestId: z.string(),
2371
+ reference: z.string(),
2372
+ status: z.enum(["paid", "exception"]),
2373
+ settledPaymentId: z.string().nullable(),
2374
+ receiptDocumentHash: z.string().nullable()
2375
+ })) }
2376
+ }, ({ sessionToken }) => guarded(async () => {
2377
+ const entry = requireSession(deps, sessionToken);
2378
+ if (entry === void 0) return errorResult(unknownSessionError$2());
2379
+ const reconcile = entry.handle.reconcilePaymentRequests;
2380
+ if (reconcile === void 0) return errorResult(Errors.notImplemented("paymentRequests", "reconcile"));
2381
+ const result = await reconcile();
2382
+ if (!result.ok) return errorResult(result.error);
2383
+ return okResult({ entries: result.value.map((e) => ({ ...e })) });
2384
+ }, "paymentRequests.reconcile", deps.onToolCall));
2385
+ }
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",
2519
+ "mobile-money",
2520
+ "wallet"
2521
+ ]),
2522
+ label: z.string().nullable(),
2523
+ payload: DESTINATION_PAYLOAD,
2524
+ createdAt: z.number(),
2525
+ updatedAt: z.number()
2526
+ });
2527
+ const MEMBER_VIEW = {
2528
+ orgId: z.string(),
2529
+ email: z.string(),
2530
+ name: z.string().nullable(),
2531
+ role: z.string(),
2532
+ roleKey: z.string().nullable(),
2533
+ status: z.string()
2534
+ };
2535
+ const PAYROLL_LINE = z.object({
2536
+ id: z.string(),
2537
+ employee: REF,
2538
+ amount: MONEY,
2539
+ timing: TIMING,
2540
+ status: z.enum([
2541
+ "active",
2542
+ "paused",
2543
+ "ended"
2544
+ ])
2545
+ });
2546
+ const TRANSFER_RESULT = z.object({
2547
+ available: MONEY,
2548
+ from: z.unknown().nullable(),
2549
+ to: z.unknown().nullable()
2550
+ });
2551
+ function unknownSessionError$1() {
2552
+ return Errors.notAuthenticated("unknown or expired session token");
2553
+ }
2554
+ function actor(kind, orgId) {
2555
+ return kind === "account" ? { kind: "account" } : {
2556
+ kind: "org",
2557
+ orgId: orgId ?? ""
2558
+ };
2559
+ }
2560
+ function orgIdArg(args) {
2561
+ return typeof args === "object" && args !== null && "orgId" in args && typeof args.orgId === "string" ? args.orgId : void 0;
2562
+ }
2563
+ function requireMethod(handle, method, domain) {
2564
+ const value = handle[method];
2565
+ if (value === void 0) return {
2566
+ ok: false,
2567
+ error: Errors.notImplemented(domain, String(method))
2568
+ };
2569
+ return {
2570
+ ok: true,
2571
+ value
2572
+ };
2573
+ }
2574
+ async function withSession(deps, sessionToken, operation, invoke) {
2575
+ return guarded(async () => {
2576
+ const entry = requireSession(deps, sessionToken);
2577
+ if (entry === void 0) return errorResult(unknownSessionError$1());
2578
+ return invoke(entry.handle);
2579
+ }, operation, deps.onToolCall);
2580
+ }
2581
+ function result(res) {
2582
+ return res.ok ? okResult(project(res.value)) : errorResult(res.error);
2583
+ }
2584
+ function paymentResult(res) {
2585
+ return res.ok ? okResult({ ...toPaymentOutput(res.value) }) : errorResult(redactPaymentError(res.error, "sdk-restart"));
2586
+ }
2587
+ function project(value) {
2588
+ if (Array.isArray(value)) return { items: value };
2589
+ if (typeof value === "object" && value !== null) return value;
2590
+ return { value };
2591
+ }
2592
+ function methodNotImplemented(domain, method) {
2593
+ return errorResult(Errors.notImplemented(domain, method));
2594
+ }
2595
+ function registerSdkRestartTools(server, deps) {
2596
+ if (deps.paymentsEnabled !== true) return;
2597
+ registerAddressBookTools(server, deps, "account");
2598
+ registerAddressBookTools(server, deps, "org");
2599
+ registerRequestsTools(server, deps, "account");
2600
+ registerRequestsTools(server, deps, "org");
2601
+ registerInboxTools(server, deps, "account");
2602
+ registerInboxTools(server, deps, "org");
2603
+ registerInsightsTools(server, deps, "account");
2604
+ registerInsightsTools(server, deps, "org");
2605
+ registerDestinationTools(server, deps);
2606
+ registerMoneyTools(server, deps);
2607
+ registerOrgTailTools(server, deps);
2608
+ registerPayrollTools(server, deps);
2609
+ }
2610
+ function registerAddressBookTools(server, deps, scope) {
2611
+ const prefix = `${scope}.addressBook`;
2612
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2613
+ server.registerTool(`${prefix}.list`, {
2614
+ title: `${scope} address book list`,
2615
+ description: "List relationship entries for one actor scope using Capxul refs and labels only.",
2616
+ inputSchema: {
2617
+ sessionToken: z.string(),
2618
+ ...scopeInput
2619
+ },
2620
+ outputSchema: { entries: z.array(ADDRESS_BOOK_ENTRY) }
2621
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.list`, async (handle) => {
2622
+ const method = requireMethod(handle, "addressBookList", prefix);
2623
+ if (!method.ok) return methodNotImplemented(prefix, "list");
2624
+ const res = await method.value(actor(scope, orgIdArg(args)));
2625
+ return res.ok ? okResult({ entries: res.value }) : errorResult(res.error);
2626
+ }));
2627
+ server.registerTool(`${prefix}.get`, {
2628
+ title: `${scope} address book get`,
2629
+ description: "Read one relationship entry by opaque entry id.",
2630
+ inputSchema: {
2631
+ sessionToken: z.string(),
2632
+ ...scopeInput,
2633
+ entryId: z.string()
2634
+ },
2635
+ outputSchema: { entry: ADDRESS_BOOK_ENTRY.nullable() }
2636
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.get`, async (handle) => {
2637
+ const method = requireMethod(handle, "addressBookGet", prefix);
2638
+ if (!method.ok) return methodNotImplemented(prefix, "get");
2639
+ const res = await method.value(actor(scope, orgIdArg(args)), args.entryId);
2640
+ return res.ok ? okResult({ entry: res.value }) : errorResult(res.error);
2641
+ }));
2642
+ server.registerTool(`${prefix}.add`, {
2643
+ title: `${scope} address book add`,
2644
+ description: "Manually add a typed Ref to an actor relationship book.",
2645
+ inputSchema: {
2646
+ sessionToken: z.string(),
2647
+ ...scopeInput,
2648
+ ref: REF,
2649
+ label: z.string().optional()
2650
+ },
2651
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2652
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.add`, async (handle) => {
2653
+ const method = requireMethod(handle, "addressBookAdd", prefix);
2654
+ if (!method.ok) return methodNotImplemented(prefix, "add");
2655
+ return result(await method.value({
2656
+ actor: actor(scope, orgIdArg(args)),
2657
+ ref: args.ref,
2658
+ label: args.label
2659
+ }));
2660
+ }));
2661
+ for (const action of ["hide", "unhide"]) server.registerTool(`${prefix}.${action}`, {
2662
+ title: `${scope} address book ${action}`,
2663
+ description: `${action} a relationship entry without deleting ledger facts.`,
2664
+ inputSchema: {
2665
+ sessionToken: z.string(),
2666
+ ...scopeInput,
2667
+ entryId: z.string()
2668
+ },
2669
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2670
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2671
+ const method = requireMethod(handle, action === "hide" ? "addressBookHide" : "addressBookUnhide", prefix);
2672
+ if (!method.ok) return methodNotImplemented(prefix, action);
2673
+ return result(await method.value(actor(scope, orgIdArg(args)), args.entryId));
2674
+ }));
2675
+ server.registerTool(`${prefix}.label`, {
2676
+ title: `${scope} address book label`,
2677
+ description: "Set a private label for a relationship entry.",
2678
+ inputSchema: {
2679
+ sessionToken: z.string(),
2680
+ ...scopeInput,
2681
+ entryId: z.string(),
2682
+ label: z.string()
2683
+ },
2684
+ outputSchema: ADDRESS_BOOK_ENTRY.shape
2685
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.label`, async (handle) => {
2686
+ const method = requireMethod(handle, "addressBookLabel", prefix);
2687
+ if (!method.ok) return methodNotImplemented(prefix, "label");
2688
+ return result(await method.value({
2689
+ actor: actor(scope, orgIdArg(args)),
2690
+ entryId: args.entryId,
2691
+ label: args.label
2692
+ }));
2693
+ }));
2694
+ }
2695
+ function registerRequestsTools(server, deps, scope) {
2696
+ const prefix = `${scope}.requests`;
2697
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2698
+ server.registerTool(`${prefix}.issue`, {
2699
+ title: `${scope} request issue`,
2700
+ description: "Issue a request to a typed payer Ref; payer inbox state is derived by the backend.",
2701
+ inputSchema: {
2702
+ sessionToken: z.string(),
2703
+ ...scopeInput,
2704
+ payer: REF,
2705
+ amount: z.string(),
2706
+ reference: z.string(),
2707
+ memo: z.string().optional(),
2708
+ expiresAt: z.number().int().nonnegative().optional()
2709
+ },
2710
+ outputSchema: ACTOR_REQUEST.shape
2711
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.issue`, async (handle) => {
2712
+ const parsed = parsePaymentAmount(args.amount);
2713
+ if (!parsed.ok) return errorResult(parsed.error);
2714
+ const method = requireMethod(handle, "actorRequestIssue", prefix);
2715
+ if (!method.ok) return methodNotImplemented(prefix, "issue");
2716
+ return result(await method.value({
2717
+ actor: actor(scope, orgIdArg(args)),
2718
+ payer: args.payer,
2719
+ amount: parsed.value,
2720
+ reference: args.reference,
2721
+ memo: args.memo,
2722
+ expiresAt: args.expiresAt
2723
+ }));
2724
+ }));
2725
+ for (const action of ["list", "reconcile"]) server.registerTool(`${prefix}.${action}`, {
2726
+ title: `${scope} requests ${action}`,
2727
+ description: `${action} request projections for one actor scope.`,
2728
+ inputSchema: {
2729
+ sessionToken: z.string(),
2730
+ ...scopeInput
2731
+ },
2732
+ outputSchema: action === "list" ? { requests: z.array(ACTOR_REQUEST) } : { entries: z.array(RECONCILIATION_ENTRY) }
2733
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2734
+ const method = requireMethod(handle, action === "list" ? "actorRequestsList" : "actorRequestsReconcile", prefix);
2735
+ if (!method.ok) return methodNotImplemented(prefix, action);
2736
+ const res = await method.value(actor(scope, orgIdArg(args)));
2737
+ return res.ok ? okResult(action === "list" ? { requests: res.value } : { entries: res.value }) : errorResult(res.error);
2738
+ }));
2739
+ for (const action of ["get", "cancel"]) server.registerTool(`${prefix}.${action}`, {
2740
+ title: `${scope} request ${action}`,
2741
+ description: `${action} one actor request by id.`,
2742
+ inputSchema: {
2743
+ sessionToken: z.string(),
2744
+ ...scopeInput,
2745
+ requestId: z.string()
2746
+ },
2747
+ outputSchema: action === "get" ? { request: ACTOR_REQUEST.nullable() } : ACTOR_REQUEST.shape
2748
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.${action}`, async (handle) => {
2749
+ const method = requireMethod(handle, action === "get" ? "actorRequestsGet" : "actorRequestsCancel", prefix);
2750
+ if (!method.ok) return methodNotImplemented(prefix, action);
2751
+ const res = await method.value(actor(scope, orgIdArg(args)), args.requestId);
2752
+ return res.ok ? okResult(action === "get" ? { request: res.value } : project(res.value)) : errorResult(res.error);
2753
+ }));
2754
+ }
2755
+ function registerInboxTools(server, deps, scope) {
2756
+ const prefix = `${scope}.inbox`;
2757
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2758
+ server.registerTool(`${prefix}.list`, {
2759
+ title: `${scope} inbox list`,
2760
+ description: "List payable inbox items for one actor scope.",
2761
+ inputSchema: {
2762
+ sessionToken: z.string(),
2763
+ ...scopeInput
2764
+ },
2765
+ outputSchema: { inbox: z.array(INBOX_ITEM) }
2766
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.list`, async (handle) => {
2767
+ const method = requireMethod(handle, "inboxList", prefix);
2768
+ if (!method.ok) return methodNotImplemented(prefix, "list");
2769
+ const res = await method.value(actor(scope, orgIdArg(args)));
2770
+ return res.ok ? okResult({ inbox: res.value }) : errorResult(res.error);
2771
+ }));
2772
+ server.registerTool(`${prefix}.approve`, {
2773
+ title: `${scope} inbox approve`,
2774
+ description: "Approve a payable request; backend settlement-build produces settlement inputs.",
2775
+ inputSchema: {
2776
+ sessionToken: z.string(),
2777
+ ...scopeInput,
2778
+ requestId: z.string(),
2779
+ timing: TIMING.optional()
2780
+ },
2781
+ outputSchema: PAYMENT_OUTPUT
2782
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.approve`, async (handle) => {
2783
+ const method = requireMethod(handle, "inboxApprove", prefix);
2784
+ if (!method.ok) return methodNotImplemented(prefix, "approve");
2785
+ return paymentResult(await method.value(actor(scope, orgIdArg(args)), args.requestId, args.timing));
2786
+ }));
2787
+ server.registerTool(`${prefix}.decline`, {
2788
+ title: `${scope} inbox decline`,
2789
+ description: "Decline a payable request as a typed terminal non-settling decision.",
2790
+ inputSchema: {
2791
+ sessionToken: z.string(),
2792
+ ...scopeInput,
2793
+ requestId: z.string()
2794
+ },
2795
+ outputSchema: INBOX_ITEM.shape
2796
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.decline`, async (handle) => {
2797
+ const method = requireMethod(handle, "inboxDecline", prefix);
2798
+ if (!method.ok) return methodNotImplemented(prefix, "decline");
2799
+ return result(await method.value(actor(scope, orgIdArg(args)), args.requestId));
2800
+ }));
2801
+ }
2802
+ function registerInsightsTools(server, deps, scope) {
2803
+ const prefix = `${scope}.insights`;
2804
+ const scopeInput = scope === "org" ? { orgId: z.string() } : {};
2805
+ server.registerTool(`${prefix}.summary`, {
2806
+ title: `${scope} insights summary`,
2807
+ description: "Read-only finance summary projection.",
2808
+ inputSchema: {
2809
+ sessionToken: z.string(),
2810
+ ...scopeInput
2811
+ },
2812
+ outputSchema: INSIGHTS_SUMMARY.shape
2813
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.summary`, async (handle) => {
2814
+ const method = requireMethod(handle, "insightsSummary", prefix);
2815
+ if (!method.ok) return methodNotImplemented(prefix, "summary");
2816
+ return result(await method.value(actor(scope, orgIdArg(args))));
2817
+ }));
2818
+ server.registerTool(`${prefix}.history`, {
2819
+ title: `${scope} insights history`,
2820
+ description: "Read-only payment history projection.",
2821
+ inputSchema: {
2822
+ sessionToken: z.string(),
2823
+ ...scopeInput
2824
+ },
2825
+ outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
2826
+ }, (args) => withSession(deps, args.sessionToken, `${prefix}.history`, async (handle) => {
2827
+ const method = requireMethod(handle, "insightsHistory", prefix);
2828
+ if (!method.ok) return methodNotImplemented(prefix, "history");
2829
+ const res = await method.value(actor(scope, orgIdArg(args)));
2830
+ return res.ok ? okResult({ payments: res.value.map(toPaymentOutput) }) : errorResult(res.error);
2831
+ }));
2832
+ }
2833
+ function registerDestinationTools(server, deps) {
2834
+ const actorSchema = z.object({ kind: z.literal("account") }).or(z.object({
2835
+ kind: z.literal("org"),
2836
+ orgId: z.string()
2837
+ }));
2838
+ server.registerTool("destinations.add", {
2839
+ title: "Add destination",
2840
+ description: "Attach a bank, mobile-money, or wallet destination to a typed counterparty.",
2841
+ inputSchema: {
2842
+ sessionToken: z.string(),
2843
+ actor: actorSchema.optional(),
2844
+ ref: REF,
2845
+ kind: z.enum([
2846
+ "bank",
2847
+ "mobile-money",
2848
+ "wallet"
2849
+ ]),
2850
+ label: z.string().optional(),
2851
+ payload: DESTINATION_PAYLOAD
2852
+ },
2853
+ outputSchema: DESTINATION.shape
2854
+ }, (args) => withSession(deps, args.sessionToken, "destinations.add", async (handle) => {
2855
+ const method = requireMethod(handle, "addDestination", "destinations");
2856
+ if (!method.ok) return methodNotImplemented("destinations", "add");
2857
+ return result(await method.value({
2858
+ actor: args.actor,
2859
+ ref: args.ref,
2860
+ kind: args.kind,
2861
+ label: args.label,
2862
+ payload: args.payload
2863
+ }));
2864
+ }));
2865
+ server.registerTool("destinations.list", {
2866
+ title: "List destinations",
2867
+ description: "List selectable destinations attached to a counterparty.",
2868
+ inputSchema: {
2869
+ sessionToken: z.string(),
2870
+ actor: actorSchema.optional(),
2871
+ ref: REF
2872
+ },
2873
+ outputSchema: { destinations: z.array(DESTINATION) }
2874
+ }, (args) => withSession(deps, args.sessionToken, "destinations.list", async (handle) => {
2875
+ const method = requireMethod(handle, "listDestinations", "destinations");
2876
+ if (!method.ok) return methodNotImplemented("destinations", "list");
2877
+ const res = await method.value({
2878
+ actor: args.actor,
2879
+ ref: args.ref
2880
+ });
2881
+ return res.ok ? okResult({ destinations: res.value }) : errorResult(res.error);
2882
+ }));
2883
+ server.registerTool("destinations.remove", {
2884
+ title: "Remove destination",
2885
+ description: "Remove one selectable destination without deleting its counterparty.",
2886
+ inputSchema: {
2887
+ sessionToken: z.string(),
2888
+ actor: actorSchema.optional(),
2889
+ destinationId: z.string()
2890
+ },
2891
+ outputSchema: { id: z.string() }
2892
+ }, (args) => withSession(deps, args.sessionToken, "destinations.remove", async (handle) => {
2893
+ const method = requireMethod(handle, "removeDestination", "destinations");
2894
+ if (!method.ok) return methodNotImplemented("destinations", "remove");
2895
+ return result(await method.value({
2896
+ actor: args.actor,
2897
+ destinationId: args.destinationId
2898
+ }));
2899
+ }));
2900
+ }
2901
+ function registerMoneyTools(server, deps) {
2902
+ const actorSchema = z.object({ kind: z.literal("account") }).or(z.object({
2903
+ kind: z.literal("org"),
2904
+ orgId: z.string()
2905
+ }));
2906
+ server.registerTool("payments.payout", {
2907
+ title: "Payout",
2908
+ description: "Payout through a saved destination id using backend settlement-build.",
2909
+ inputSchema: {
2910
+ sessionToken: z.string(),
2911
+ actor: actorSchema.optional(),
2912
+ destinationId: z.string(),
2913
+ amount: z.string()
2914
+ },
2915
+ outputSchema: PAYMENT_OUTPUT
2916
+ }, (args) => withSession(deps, args.sessionToken, "payments.payout", async (handle) => {
2917
+ const parsed = parsePaymentAmount(args.amount);
2918
+ if (!parsed.ok) return errorResult(parsed.error);
2919
+ const method = requireMethod(handle, "payout", "payments");
2920
+ if (!method.ok) return methodNotImplemented("payments", "payout");
2921
+ return paymentResult(await method.value({
2922
+ actor: args.actor,
2923
+ destinationId: args.destinationId,
2924
+ amount: parsed.value
2925
+ }));
2926
+ }));
2927
+ server.registerTool("subAccounts.transfer", {
2928
+ title: "Transfer",
2929
+ description: "Move money within an account between main and sub-account envelopes.",
2930
+ inputSchema: {
2931
+ sessionToken: z.string(),
2932
+ from: z.string(),
2933
+ to: z.string(),
2934
+ amount: z.string()
2935
+ },
2936
+ outputSchema: TRANSFER_RESULT.shape
2937
+ }, (args) => withSession(deps, args.sessionToken, "subAccounts.transfer", async (handle) => {
2938
+ const parsed = parsePaymentAmount(args.amount);
2939
+ if (!parsed.ok) return errorResult(parsed.error);
2940
+ const method = requireMethod(handle, "transfer", "subAccounts");
2941
+ if (!method.ok) return methodNotImplemented("subAccounts", "transfer");
2942
+ return result(await method.value({
2943
+ from: args.from,
2944
+ to: args.to,
2945
+ amount: parsed.value
2946
+ }));
2947
+ }));
2948
+ }
2949
+ function registerOrgTailTools(server, deps) {
2950
+ server.registerTool("org.pendingMembers", {
2951
+ title: "Pending org members",
2952
+ description: "List pending member invitations for an organization.",
2953
+ inputSchema: {
2954
+ sessionToken: z.string(),
2955
+ orgId: z.string()
2956
+ },
2957
+ outputSchema: { members: z.array(z.object(MEMBER_VIEW)) }
2958
+ }, (args) => withSession(deps, args.sessionToken, "org.pendingMembers", async (handle) => {
2959
+ const method = requireMethod(handle, "orgPendingMembers", "org");
2960
+ if (!method.ok) return methodNotImplemented("org", "pendingMembers");
2961
+ const res = await method.value(args.orgId);
2962
+ return res.ok ? okResult({ members: res.value }) : errorResult(res.error);
2963
+ }));
2964
+ server.registerTool("org.inviteToken.resend", {
2965
+ title: "Resend invite token",
2966
+ description: "Resend an existing pending invite token without duplicating membership.",
2967
+ inputSchema: {
2968
+ sessionToken: z.string(),
2969
+ orgId: z.string(),
2970
+ email: z.string()
2971
+ },
2972
+ outputSchema: MEMBER_VIEW
2973
+ }, (args) => withSession(deps, args.sessionToken, "org.inviteToken.resend", async (handle) => {
2974
+ const method = requireMethod(handle, "orgInviteTokenResend", "org");
2975
+ if (!method.ok) return methodNotImplemented("org", "inviteToken.resend");
2976
+ return result(await method.value({
2977
+ orgId: args.orgId,
2978
+ email: args.email
2979
+ }));
2980
+ }));
2981
+ }
2982
+ function registerPayrollTools(server, deps) {
2983
+ server.registerTool("org.payroll.roster.add", {
2984
+ title: "Add payroll roster line",
2985
+ description: "Add an employee Ref, amount, timing, and optional payslip template to org payroll.",
2986
+ inputSchema: {
2987
+ sessionToken: z.string(),
2988
+ orgId: z.string(),
2989
+ employee: REF,
2990
+ amount: z.string(),
2991
+ timing: TIMING,
2992
+ payslipTemplate: z.record(z.string(), z.unknown()).optional()
2993
+ },
2994
+ outputSchema: PAYROLL_LINE.shape
2995
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.add", async (handle) => {
2996
+ const parsed = parsePaymentAmount(args.amount);
2997
+ if (!parsed.ok) return errorResult(parsed.error);
2998
+ const method = requireMethod(handle, "payrollRosterAdd", "payroll");
2999
+ if (!method.ok) return methodNotImplemented("payroll", "roster.add");
3000
+ return result(await method.value({
3001
+ orgId: args.orgId,
3002
+ employee: args.employee,
3003
+ amount: parsed.value,
3004
+ timing: args.timing,
3005
+ payslipTemplate: args.payslipTemplate
3006
+ }));
3007
+ }));
3008
+ server.registerTool("org.payroll.roster.list", {
3009
+ title: "List payroll roster",
3010
+ description: "List active payroll roster lines for an org.",
3011
+ inputSchema: {
3012
+ sessionToken: z.string(),
3013
+ orgId: z.string()
2258
3014
  },
2259
- outputSchema: PAYMENT_REQUEST_OUTPUT
2260
- }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.markPaymentRequestViewed === void 0 ? void 0 : handle.markPaymentRequestViewed(paymentRequestId), "markViewed"), "paymentRequests.markViewed", deps.onToolCall));
2261
- server.registerTool("paymentRequests.cancel", {
2262
- title: "Cancel payment request",
2263
- description: "Cancel an open receivable. A cancelled request can never be collected.",
3015
+ outputSchema: { lines: z.array(PAYROLL_LINE) }
3016
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.list", async (handle) => {
3017
+ const method = requireMethod(handle, "payrollRosterList", "payroll");
3018
+ if (!method.ok) return methodNotImplemented("payroll", "roster.list");
3019
+ const res = await method.value(args.orgId);
3020
+ return res.ok ? okResult({ lines: res.value }) : errorResult(res.error);
3021
+ }));
3022
+ server.registerTool("org.payroll.roster.update", {
3023
+ title: "Update payroll roster line",
3024
+ description: "Update an employee Ref, amount, timing, or payslip template for one payroll roster line.",
2264
3025
  inputSchema: {
2265
3026
  sessionToken: z.string(),
2266
- paymentRequestId: z.string()
2267
- },
2268
- outputSchema: PAYMENT_REQUEST_OUTPUT
2269
- }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.cancelPaymentRequest === void 0 ? void 0 : handle.cancelPaymentRequest(paymentRequestId), "cancel"), "paymentRequests.cancel", deps.onToolCall));
2270
- server.registerTool("paymentRequests.collect", {
2271
- title: "Collect payment request",
2272
- description: "Collect a sent/viewed receivable. Settles it into the Payment ledger and mints a receipt linked by documentHash, then grants the minimal entitlement. Rejected for a cancelled / expired / draft request and never double-collects. Returns the paid PaymentRequest with its receipt lineage.",
3027
+ orgId: z.string(),
3028
+ rosterLineId: z.string(),
3029
+ employee: REF.optional(),
3030
+ amount: z.string().optional(),
3031
+ timing: TIMING.optional(),
3032
+ payslipTemplate: z.record(z.string(), z.unknown()).optional()
3033
+ },
3034
+ outputSchema: PAYROLL_LINE.shape
3035
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.update", async (handle) => {
3036
+ const parsed = args.amount === void 0 ? void 0 : parsePaymentAmount(args.amount);
3037
+ if (parsed !== void 0 && !parsed.ok) return errorResult(parsed.error);
3038
+ const method = requireMethod(handle, "payrollRosterUpdate", "payroll");
3039
+ if (!method.ok) return methodNotImplemented("payroll", "roster.update");
3040
+ return result(await method.value({
3041
+ orgId: args.orgId,
3042
+ rosterLineId: args.rosterLineId,
3043
+ employee: args.employee,
3044
+ amount: parsed?.value,
3045
+ timing: args.timing,
3046
+ payslipTemplate: args.payslipTemplate
3047
+ }));
3048
+ }));
3049
+ server.registerTool("org.payroll.roster.remove", {
3050
+ title: "Remove payroll roster line",
3051
+ description: "Remove one payroll roster line without deleting payment history.",
2273
3052
  inputSchema: {
2274
3053
  sessionToken: z.string(),
2275
- paymentRequestId: z.string()
3054
+ orgId: z.string(),
3055
+ rosterLineId: z.string()
2276
3056
  },
2277
- outputSchema: PAYMENT_REQUEST_OUTPUT
2278
- }, ({ sessionToken, paymentRequestId }) => guarded(() => runRequestOp(deps, sessionToken, (handle) => handle.collectPaymentRequest === void 0 ? void 0 : handle.collectPaymentRequest(paymentRequestId), "collect"), "paymentRequests.collect", deps.onToolCall));
2279
- server.registerTool("paymentRequests.list", {
2280
- title: "List payment requests",
2281
- description: "List your receivables (most recent first), each leak-safe.",
2282
- inputSchema: { sessionToken: z.string() },
2283
- outputSchema: { paymentRequests: z.array(z.object(PAYMENT_REQUEST_OUTPUT)) }
2284
- }, ({ sessionToken }) => guarded(async () => {
2285
- const entry = requireSession(deps, sessionToken);
2286
- if (entry === void 0) return errorResult(unknownSessionError$1());
2287
- const list = entry.handle.listPaymentRequests;
2288
- if (list === void 0) return errorResult(Errors.notImplemented("paymentRequests", "list"));
2289
- const result = await list();
2290
- if (!result.ok) return errorResult(result.error);
2291
- return okResult({ paymentRequests: result.value.map(toRequestOutput) });
2292
- }, "paymentRequests.list", deps.onToolCall));
2293
- server.registerTool("paymentRequests.get", {
2294
- title: "Get payment request",
2295
- description: "Get one receivable by id with its current lifecycle status.",
3057
+ outputSchema: PAYROLL_LINE.shape
3058
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.roster.remove", async (handle) => {
3059
+ const method = requireMethod(handle, "payrollRosterRemove", "payroll");
3060
+ if (!method.ok) return methodNotImplemented("payroll", "roster.remove");
3061
+ return result(await method.value(args.orgId, args.rosterLineId));
3062
+ }));
3063
+ server.registerTool("org.payroll.run", {
3064
+ title: "Run payroll",
3065
+ description: "Materialize active roster lines into one authorized batch settlement.",
2296
3066
  inputSchema: {
2297
3067
  sessionToken: z.string(),
2298
- paymentRequestId: z.string()
3068
+ orgId: z.string(),
3069
+ period: z.string(),
3070
+ from: z.string()
2299
3071
  },
2300
- outputSchema: { paymentRequest: z.object(PAYMENT_REQUEST_OUTPUT).nullable() }
2301
- }, ({ sessionToken, paymentRequestId }) => guarded(async () => {
2302
- const entry = requireSession(deps, sessionToken);
2303
- if (entry === void 0) return errorResult(unknownSessionError$1());
2304
- const get = entry.handle.getPaymentRequest;
2305
- if (get === void 0) return errorResult(Errors.notImplemented("paymentRequests", "get"));
2306
- const result = await get(paymentRequestId);
2307
- if (!result.ok) return errorResult(result.error);
2308
- return okResult({ paymentRequest: result.value === null ? null : toRequestOutput(result.value) });
2309
- }, "paymentRequests.get", deps.onToolCall));
2310
- server.registerTool("paymentRequests.reconcile", {
2311
- title: "Reconcile receivables",
2312
- description: "Inbound reconciliation: per receivable, report `paid` (settled into a Payment with a receipt) or `exception` (expired/cancelled, never collected).",
2313
- inputSchema: { sessionToken: z.string() },
2314
- outputSchema: { entries: z.array(z.object({
2315
- paymentRequestId: z.string(),
2316
- reference: z.string(),
2317
- status: z.enum(["paid", "exception"]),
2318
- settledPaymentId: z.string().nullable(),
2319
- receiptDocumentHash: z.string().nullable()
2320
- })) }
2321
- }, ({ sessionToken }) => guarded(async () => {
2322
- const entry = requireSession(deps, sessionToken);
2323
- if (entry === void 0) return errorResult(unknownSessionError$1());
2324
- const reconcile = entry.handle.reconcilePaymentRequests;
2325
- if (reconcile === void 0) return errorResult(Errors.notImplemented("paymentRequests", "reconcile"));
2326
- const result = await reconcile();
2327
- if (!result.ok) return errorResult(result.error);
2328
- return okResult({ entries: result.value.map((e) => ({ ...e })) });
2329
- }, "paymentRequests.reconcile", deps.onToolCall));
3072
+ outputSchema: { payments: z.array(z.object(PAYMENT_OUTPUT)) }
3073
+ }, (args) => withSession(deps, args.sessionToken, "org.payroll.run", async (handle) => {
3074
+ const method = requireMethod(handle, "payrollRun", "payroll");
3075
+ if (!method.ok) return methodNotImplemented("payroll", "run");
3076
+ const res = await method.value({
3077
+ orgId: args.orgId,
3078
+ period: args.period,
3079
+ from: args.from
3080
+ });
3081
+ return res.ok ? okResult({ payments: res.value.map(toPaymentOutput) }) : errorResult(redactPaymentError(res.error, "org.payroll.run"));
3082
+ }));
2330
3083
  }
2331
3084
  //#endregion
2332
3085
  //#region src/tools/system.ts
@@ -2544,6 +3297,7 @@ const registrars = [
2544
3297
  registerPaymentTools,
2545
3298
  registerOrgTools,
2546
3299
  registerPaymentRequestTools,
3300
+ registerSdkRestartTools,
2547
3301
  registerWorkbenchTools
2548
3302
  ];
2549
3303
  function registerAllTools(server, deps) {
@@ -3638,6 +4392,447 @@ function mapAccountLifecycle(input) {
3638
4392
  return { status: "loading" };
3639
4393
  }
3640
4394
  //#endregion
4395
+ //#region ../../packages/sdk/src/client/actor-scope.ts
4396
+ function makeActorRelationshipMethods(deps) {
4397
+ const domain = deps.actor.kind === "account" ? "account" : "org";
4398
+ const actor = deps.actor;
4399
+ const convexCall = deps.convexCall;
4400
+ if (convexCall === void 0) return makeNotImplementedActorRelationshipMethods(deps, domain);
4401
+ const fns = ACTOR_RELATIONSHIP_FUNCTIONS;
4402
+ return {
4403
+ addressBook: {
4404
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "addressBook.list", () => convexCall.query(fns.addressBookList, { actor })), (entries) => entries.map(mapAddressBookEntry)),
4405
+ get: async (entryId, options) => {
4406
+ const ref = refFromEntryId(entryId);
4407
+ if (!ref.ok) return ref;
4408
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.get", () => convexCall.query(fns.addressBookGet, {
4409
+ actor,
4410
+ ref: ref.value
4411
+ })), (entry) => entry === null ? null : mapAddressBookEntry(entry));
4412
+ },
4413
+ add: async (input, options) => {
4414
+ const ref = normalizeRefForBackend$1(input.ref, "ref");
4415
+ if (!ref.ok) return ref;
4416
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.add", () => convexCall.mutation(fns.addressBookAdd, {
4417
+ actor,
4418
+ ref: ref.value,
4419
+ ...input.label === void 0 ? {} : { label: input.label }
4420
+ })), mapAddressBookEntry);
4421
+ },
4422
+ hide: async (entryId, options) => {
4423
+ const ref = refFromEntryId(entryId);
4424
+ if (!ref.ok) return ref;
4425
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.hide", () => convexCall.mutation(fns.addressBookHide, {
4426
+ actor,
4427
+ ref: ref.value
4428
+ })), mapAddressBookEntry);
4429
+ },
4430
+ unhide: async (entryId, options) => {
4431
+ const ref = refFromEntryId(entryId);
4432
+ if (!ref.ok) return ref;
4433
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.unhide", () => convexCall.mutation(fns.addressBookUnhide, {
4434
+ actor,
4435
+ ref: ref.value
4436
+ })), mapAddressBookEntry);
4437
+ },
4438
+ label: async (input, options) => {
4439
+ const ref = refFromEntryId(input.entryId);
4440
+ if (!ref.ok) return ref;
4441
+ return mapOk$2(await awaitableConvex(options?.signal, "addressBook.label", () => convexCall.mutation(fns.addressBookLabel, {
4442
+ actor,
4443
+ ref: ref.value,
4444
+ label: input.label
4445
+ })), mapAddressBookEntry);
4446
+ }
4447
+ },
4448
+ requests: {
4449
+ issue: async (input, options) => {
4450
+ const payer = normalizeRefForBackend$1(input.payer, "payer");
4451
+ if (!payer.ok) return payer;
4452
+ return mapOk$2(await awaitableConvex(options?.signal, "requests.issue", () => convexCall.mutation(fns.requestsIssue, {
4453
+ actor,
4454
+ payer: payer.value,
4455
+ amount: input.amount,
4456
+ reference: input.reference,
4457
+ ...input.memo === void 0 ? {} : { memo: input.memo },
4458
+ ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
4459
+ })), (request) => mapActorRequest(request, input.payer));
4460
+ },
4461
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "requests.list", () => convexCall.query(fns.requestsList, { actor })), (requests) => requests.map((request) => mapActorRequest(request))),
4462
+ get: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.get", () => convexCall.query(fns.requestsGet, {
4463
+ actor,
4464
+ paymentRequestId: requestId
4465
+ })), (request) => request === null ? null : mapActorRequest(request)),
4466
+ cancel: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "requests.cancel", () => convexCall.mutation(fns.requestsCancel, {
4467
+ actor,
4468
+ paymentRequestId: requestId
4469
+ })), (request) => mapActorRequest(request)),
4470
+ reconcile: async (options) => {
4471
+ return mapOk$2(awaitableConvex(options?.signal, "requests.reconcile", () => convexCall.query(fns.requestsReconcile, { actor })), (entries) => entries.map(mapReconciliationEntry));
4472
+ }
4473
+ },
4474
+ inbox: {
4475
+ list: (options) => mapOk$2(awaitableConvex(options?.signal, "inbox.list", () => convexCall.query(fns.inboxList, { actor })), (items) => items.map(mapInboxItem)),
4476
+ approve: (input, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.approve", () => convexCall.mutation(fns.inboxApprove, {
4477
+ actor,
4478
+ paymentRequestId: input.requestId,
4479
+ ...input.timing === void 0 ? {} : { timing: input.timing }
4480
+ })), mapApprovedInboxPayment),
4481
+ decline: (requestId, options) => mapOk$2(awaitableConvex(options?.signal, "inbox.decline", () => convexCall.mutation(fns.inboxDecline, {
4482
+ actor,
4483
+ paymentRequestId: requestId
4484
+ })), mapInboxItem)
4485
+ },
4486
+ insights: {
4487
+ summary: (options) => awaitableConvex(options?.signal, "insights.summary", () => convexCall.query(fns.insightsSummary, { actor })),
4488
+ history: (options) => mapOk$2(awaitableConvex(options?.signal, "insights.history", () => convexCall.query(fns.insightsHistory, { actor })), (history) => history.transactions.map(normalizePaymentTiming$2))
4489
+ },
4490
+ profile: {
4491
+ get: (options) => {
4492
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
4493
+ return missingConvexCall$1(`${domain}.profile.get`);
4494
+ },
4495
+ depositInstructions: (options) => {
4496
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
4497
+ return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4498
+ }
4499
+ }
4500
+ };
4501
+ }
4502
+ function makeNotImplementedActorRelationshipMethods(deps, domain) {
4503
+ return {
4504
+ addressBook: {
4505
+ list: () => missingConvexCall$1("addressBook.list"),
4506
+ get: () => missingConvexCall$1("addressBook.get"),
4507
+ add: () => missingConvexCall$1("addressBook.add"),
4508
+ hide: () => missingConvexCall$1("addressBook.hide"),
4509
+ unhide: () => missingConvexCall$1("addressBook.unhide"),
4510
+ label: () => missingConvexCall$1("addressBook.label")
4511
+ },
4512
+ requests: {
4513
+ issue: () => missingConvexCall$1("requests.issue"),
4514
+ list: () => missingConvexCall$1("requests.list"),
4515
+ get: () => missingConvexCall$1("requests.get"),
4516
+ cancel: () => missingConvexCall$1("requests.cancel"),
4517
+ reconcile: () => missingConvexCall$1("requests.reconcile")
4518
+ },
4519
+ inbox: {
4520
+ list: () => missingConvexCall$1("inbox.list"),
4521
+ approve: () => missingConvexCall$1("inbox.approve"),
4522
+ decline: () => missingConvexCall$1("inbox.decline")
4523
+ },
4524
+ insights: {
4525
+ summary: () => missingConvexCall$1("insights.summary"),
4526
+ history: () => missingConvexCall$1("insights.history")
4527
+ },
4528
+ profile: {
4529
+ get: (options) => {
4530
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return mapAccountProfile(deps.accountProfileMethods.get(options));
4531
+ return missingConvexCall$1(`${domain}.profile.get`);
4532
+ },
4533
+ depositInstructions: (options) => {
4534
+ if (deps.actor.kind === "account" && deps.accountProfileMethods !== void 0) return deps.accountProfileMethods.depositInstructions(options);
4535
+ return missingConvexCall$1(`${domain}.profile.depositInstructions`);
4536
+ }
4537
+ }
4538
+ };
4539
+ }
4540
+ async function mapAccountProfile(resultPromise) {
4541
+ const result = await resultPromise;
4542
+ if (!result.ok) return result;
4543
+ return {
4544
+ ok: true,
4545
+ value: {
4546
+ actor: { kind: "account" },
4547
+ displayName: result.value.displayName,
4548
+ email: result.value.email
4549
+ }
4550
+ };
4551
+ }
4552
+ function missingConvexCall$1(operation) {
4553
+ return Promise.resolve({
4554
+ ok: false,
4555
+ error: Errors.providerError("convex", operation, "ConvexCallPort is required")
4556
+ });
4557
+ }
4558
+ const ACTOR_RELATIONSHIP_FUNCTIONS = {
4559
+ addressBookList: makeFunctionReference("financialOps/addressBook:list"),
4560
+ addressBookGet: makeFunctionReference("financialOps/addressBook:get"),
4561
+ addressBookAdd: makeFunctionReference("financialOps/addressBook:add"),
4562
+ addressBookHide: makeFunctionReference("financialOps/addressBook:hide"),
4563
+ addressBookUnhide: makeFunctionReference("financialOps/addressBook:unhide"),
4564
+ addressBookLabel: makeFunctionReference("financialOps/addressBook:label"),
4565
+ requestsIssue: makeFunctionReference("financialOps/requestsInbox:issue"),
4566
+ requestsList: makeFunctionReference("financialOps/requestsInbox:list"),
4567
+ requestsGet: makeFunctionReference("financialOps/requestsInbox:get"),
4568
+ requestsCancel: makeFunctionReference("financialOps/requestsInbox:cancel"),
4569
+ requestsReconcile: makeFunctionReference("financialOps/requestsInbox:reconcile"),
4570
+ inboxList: makeFunctionReference("financialOps/requestsInbox:inboxList"),
4571
+ inboxApprove: makeFunctionReference("financialOps/requestsInbox:approve"),
4572
+ inboxDecline: makeFunctionReference("financialOps/requestsInbox:decline"),
4573
+ insightsSummary: makeFunctionReference("financialOps/insights:summary"),
4574
+ insightsHistory: makeFunctionReference("financialOps/insights:history")
4575
+ };
4576
+ async function mapOk$2(resultOrPromise, f) {
4577
+ const result = await resultOrPromise;
4578
+ if (!result.ok) return result;
4579
+ return {
4580
+ ok: true,
4581
+ value: f(result.value)
4582
+ };
4583
+ }
4584
+ async function runConvexIfActive(signal, operation, effect) {
4585
+ if (signal?.aborted === true) return {
4586
+ ok: false,
4587
+ error: Errors.cancelled({ operation })
4588
+ };
4589
+ const result = await Effect.runPromise(effect().pipe(Effect.mapError((error) => error.publicError), Effect.catchAllDefect((defect) => Effect.fail(Errors.unknown(defect))), Effect.either));
4590
+ if (Either.isLeft(result)) return {
4591
+ ok: false,
4592
+ error: result.left
4593
+ };
4594
+ return {
4595
+ ok: true,
4596
+ value: result.right
4597
+ };
4598
+ }
4599
+ const awaitableConvex = runConvexIfActive;
4600
+ function mapAddressBookEntry(entry) {
4601
+ const relationship = /* @__PURE__ */ new Set();
4602
+ for (const edge of entry.edges) {
4603
+ if (edge === "paid") relationship.add("paid");
4604
+ if (edge === "paidBy") relationship.add("paidBy");
4605
+ if (edge === "requested" || edge === "requestedBy") relationship.add("requested");
4606
+ if (edge === "member") relationship.add("member");
4607
+ if (edge === "employee") relationship.add("employee");
4608
+ }
4609
+ return {
4610
+ id: entry.id,
4611
+ ref: entry.ref,
4612
+ label: entry.label ?? entry.identity?.label ?? refLabel(entry.ref),
4613
+ relationship: [...relationship],
4614
+ hidden: entry.hidden
4615
+ };
4616
+ }
4617
+ function mapActorRequest(request, payer) {
4618
+ const resolvedPayer = request.payer ?? payer;
4619
+ return {
4620
+ id: request.id,
4621
+ ...resolvedPayer === void 0 ? {} : { payer: resolvedPayer },
4622
+ amount: request.amount,
4623
+ reference: request.reference,
4624
+ status: mapActorRequestStatus(request.status),
4625
+ expiresAt: request.expiresAt ?? null
4626
+ };
4627
+ }
4628
+ function mapInboxItem(item) {
4629
+ return {
4630
+ id: item.id,
4631
+ issuer: item.issuer,
4632
+ amount: item.amount,
4633
+ reference: item.reference,
4634
+ status: mapInboxStatus(item.status)
4635
+ };
4636
+ }
4637
+ function mapReconciliationEntry(entry) {
4638
+ return {
4639
+ paymentRequestId: entry.paymentRequestId,
4640
+ reference: entry.reference,
4641
+ status: entry.status,
4642
+ settledPaymentId: entry.settledPaymentId ?? null,
4643
+ receiptDocumentHash: entry.receiptDocumentHash ?? null
4644
+ };
4645
+ }
4646
+ function mapApprovedInboxPayment(item) {
4647
+ if (item.settledPayment !== void 0) return normalizePaymentTiming$2(item.settledPayment);
4648
+ const zero = {
4649
+ ...item.amount,
4650
+ value: "0"
4651
+ };
4652
+ const status = item.settledPaymentStatus ?? (item.status === "paid" ? "settled" : "pending");
4653
+ const timing = item.settledPaymentTiming ?? { kind: "instant" };
4654
+ return {
4655
+ id: item.settledPaymentId ?? `payment_${item.id}`,
4656
+ status,
4657
+ amount: item.amount,
4658
+ paymentType: "invoice",
4659
+ recipient: paymentRecipientFromRef(item.issuer),
4660
+ documents: [],
4661
+ timing,
4662
+ released: status === "settled" ? item.amount : zero,
4663
+ availableToClaim: zero,
4664
+ createdAt: item.createdAt ?? 0,
4665
+ updatedAt: item.updatedAt ?? item.createdAt ?? 0
4666
+ };
4667
+ }
4668
+ function paymentRecipientFromRef(ref) {
4669
+ switch (ref.kind) {
4670
+ case "handle": return {
4671
+ kind: "handle",
4672
+ label: ref.handle
4673
+ };
4674
+ case "email": return {
4675
+ kind: "email",
4676
+ label: ref.email
4677
+ };
4678
+ case "orgHandle": return {
4679
+ kind: "org",
4680
+ label: ref.orgHandle
4681
+ };
4682
+ case "capxulUserId": return {
4683
+ kind: "capxulUserId",
4684
+ label: ref.capxulUserId
4685
+ };
4686
+ case "payeeId": return {
4687
+ kind: "payee",
4688
+ label: ref.payeeId,
4689
+ payeeId: ref.payeeId
4690
+ };
4691
+ }
4692
+ }
4693
+ function mapActorRequestStatus(status) {
4694
+ switch (status) {
4695
+ case "draft":
4696
+ case "sent":
4697
+ case "viewed":
4698
+ case "paid":
4699
+ case "pending_settlement":
4700
+ case "declined":
4701
+ case "cancelled":
4702
+ case "expired": return status;
4703
+ default: return "sent";
4704
+ }
4705
+ }
4706
+ function mapInboxStatus(status) {
4707
+ switch (status) {
4708
+ case "approved":
4709
+ case "declined":
4710
+ case "paid":
4711
+ case "cancelled":
4712
+ case "expired": return status;
4713
+ case "pending_settlement": return "approved";
4714
+ default: return "open";
4715
+ }
4716
+ }
4717
+ function normalizePaymentTiming$2(payment) {
4718
+ const { release: _release, ...rest } = payment;
4719
+ return {
4720
+ ...rest,
4721
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
4722
+ };
4723
+ }
4724
+ function normalizeRefForBackend$1(ref, field) {
4725
+ try {
4726
+ if (typeof ref === "string") throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
4727
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
4728
+ switch (ref.kind) {
4729
+ case "handle": return {
4730
+ ok: true,
4731
+ value: {
4732
+ kind: "handle",
4733
+ handle: handleRefValue$1(ref.handle, "handle")
4734
+ }
4735
+ };
4736
+ case "email": return {
4737
+ ok: true,
4738
+ value: {
4739
+ kind: "email",
4740
+ email: nonEmptyRefValue$1(ref.email, "email")
4741
+ }
4742
+ };
4743
+ case "orgHandle": return {
4744
+ ok: true,
4745
+ value: {
4746
+ kind: "orgHandle",
4747
+ orgHandle: nonEmptyRefValue$1(ref.orgHandle, "orgHandle")
4748
+ }
4749
+ };
4750
+ case "capxulUserId": return {
4751
+ ok: true,
4752
+ value: {
4753
+ kind: "capxulUserId",
4754
+ capxulUserId: nonEmptyRefValue$1(ref.capxulUserId, "capxulUserId")
4755
+ }
4756
+ };
4757
+ case "payeeId": return {
4758
+ ok: true,
4759
+ value: {
4760
+ kind: "payeeId",
4761
+ payeeId: nonEmptyRefValue$1(ref.payeeId, "payeeId")
4762
+ }
4763
+ };
4764
+ default: throw Errors.invalidInput(field, "recipient must be a known Ref variant");
4765
+ }
4766
+ } catch (cause) {
4767
+ if (cause instanceof Error && "code" in cause) return {
4768
+ ok: false,
4769
+ error: cause
4770
+ };
4771
+ return {
4772
+ ok: false,
4773
+ error: Errors.invalidInput(field, "recipient must be a typed Ref variant")
4774
+ };
4775
+ }
4776
+ }
4777
+ function refFromEntryId(entryId) {
4778
+ try {
4779
+ const parsed = JSON.parse(entryId);
4780
+ if (typeof parsed === "object" && parsed !== null && "kind" in parsed) return normalizeRefForBackend$1(parsed, "entryId");
4781
+ } catch {}
4782
+ const separator = entryId.indexOf(":");
4783
+ if (separator === -1) return {
4784
+ ok: false,
4785
+ error: Errors.invalidInput("entryId", "must be an address-book entry id")
4786
+ };
4787
+ const prefix = entryId.slice(0, separator);
4788
+ const value = entryId.slice(separator + 1);
4789
+ switch (prefix) {
4790
+ case "email": return normalizeRefForBackend$1({
4791
+ kind: "email",
4792
+ email: value
4793
+ }, "entryId");
4794
+ case "user": return normalizeRefForBackend$1({
4795
+ kind: "capxulUserId",
4796
+ capxulUserId: value
4797
+ }, "entryId");
4798
+ case "org": return normalizeRefForBackend$1({
4799
+ kind: "orgHandle",
4800
+ orgHandle: value
4801
+ }, "entryId");
4802
+ case "payee": return normalizeRefForBackend$1({
4803
+ kind: "payeeId",
4804
+ payeeId: value
4805
+ }, "entryId");
4806
+ case "handle": return normalizeRefForBackend$1({
4807
+ kind: "handle",
4808
+ handle: value
4809
+ }, "entryId");
4810
+ default: return {
4811
+ ok: false,
4812
+ error: Errors.invalidInput("entryId", "must be an address-book entry id")
4813
+ };
4814
+ }
4815
+ }
4816
+ function nonEmptyRefValue$1(value, field) {
4817
+ const trimmed = value.trim();
4818
+ if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
4819
+ if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) throw Errors.invalidInput(field, "raw 0x addresses are not valid Ref values");
4820
+ return trimmed;
4821
+ }
4822
+ function handleRefValue$1(value, field) {
4823
+ const trimmed = nonEmptyRefValue$1(value, field);
4824
+ return trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
4825
+ }
4826
+ function refLabel(ref) {
4827
+ switch (ref.kind) {
4828
+ case "handle": return ref.handle;
4829
+ case "email": return ref.email;
4830
+ case "orgHandle": return ref.orgHandle;
4831
+ case "capxulUserId": return ref.capxulUserId;
4832
+ case "payeeId": return ref.payeeId;
4833
+ }
4834
+ }
4835
+ //#endregion
3641
4836
  //#region ../../packages/sdk/src/client/to-capxul-result.ts
3642
4837
  async function toCapxulResult(program, layer) {
3643
4838
  const result = await Effect.runPromise(program.pipe(Effect.provide(layer), Effect.catchAllDefect((defect) => Effect.fail(Errors.unknown(defect))), Effect.either));
@@ -3829,6 +5024,11 @@ function makeAccountMethods(deps) {
3829
5024
  };
3830
5025
  return {
3831
5026
  methods: {
5027
+ ...makeActorRelationshipMethods({
5028
+ actor: { kind: "account" },
5029
+ ...deps.convexCall === void 0 ? {} : { convexCall: deps.convexCall },
5030
+ ...deps.profileMethods === void 0 ? {} : { accountProfileMethods: deps.profileMethods }
5031
+ }),
3832
5032
  getLifecycle,
3833
5033
  retrySetup,
3834
5034
  _internal: {
@@ -4012,7 +5212,7 @@ async function recoverRawDigestSigner(input) {
4012
5212
  }
4013
5213
  //#endregion
4014
5214
  //#region ../../packages/sdk/package.json
4015
- var version = "1.0.0-alpha.7";
5215
+ var version = "1.0.0-alpha.11";
4016
5216
  //#endregion
4017
5217
  //#region ../../packages/sdk/src/ports/auth-client.ts
4018
5218
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -5505,6 +6705,7 @@ var IdentityPortTag = class extends Context.Tag("@capxul/sdk/ports/IdentityPort"
5505
6705
  const identityLoadByAuthUserIdQuery = makeFunctionReference("identity/queries:loadByAuthUserId");
5506
6706
  const identityCreateMutation = makeFunctionReference("identity/mutations:create");
5507
6707
  const identityUpdateMutation = makeFunctionReference("identity/mutations:update");
6708
+ const identityCompleteOnboardingMutation = makeFunctionReference("identity/mutations:completeOnboarding");
5508
6709
  var ConvexIdentityAdapter = class {
5509
6710
  #convex;
5510
6711
  constructor(deps) {
@@ -5528,6 +6729,12 @@ var ConvexIdentityAdapter = class {
5528
6729
  catch: (cause) => identityErrorFromUnknown("update", cause)
5529
6730
  })), Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown("update", cause))));
5530
6731
  }
6732
+ completeOnboarding(input) {
6733
+ return this.#convex.mutation(identityCompleteOnboardingMutation, input).pipe(Effect.mapError((error) => identityErrorFromCapxul("completeOnboarding", error.publicError, error)), Effect.flatMap((row) => Effect.try({
6734
+ try: () => brandProfile(row),
6735
+ catch: (cause) => identityErrorFromUnknown("completeOnboarding", cause)
6736
+ })), Effect.catchAllDefect((cause) => Effect.fail(identityErrorFromUnknown("completeOnboarding", cause))));
6737
+ }
5531
6738
  };
5532
6739
  function ConvexIdentityLayer() {
5533
6740
  return Layer.effect(IdentityPortTag, Effect.map(ConvexCallPortTag, (convex) => new ConvexIdentityAdapter({ convex })));
@@ -5851,7 +7058,7 @@ const ChainIdSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeI
5851
7058
  const DurationMsSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0, { message: () => "must be a non-negative safe integer" }));
5852
7059
  const EpochMsSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value >= 0, { message: () => "must be a non-negative safe integer" }));
5853
7060
  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" }));
7061
+ const TxHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$2.test(value), { message: () => "must be 0x + 64 hex chars" }));
5855
7062
  const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
5856
7063
  const SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;
5857
7064
  const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
@@ -5882,7 +7089,7 @@ const PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;
5882
7089
  const PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;
5883
7090
  const PaymentIdTelemetrySchema = Schema.String.pipe(Schema.filter((value) => PAYMENT_ID_TELEMETRY_RE.test(value), { message: () => "must be payment_ plus an alphanumeric id" }));
5884
7091
  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" }));
7092
+ const DocumentHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$2.test(value), { message: () => "must be 0x + 64 hex chars" }));
5886
7093
  const TelemetryEnvelopeProps = {
5887
7094
  capxul_e2e_run_id: OptionalString,
5888
7095
  correlationId: OptionalString,
@@ -7951,7 +9158,11 @@ const DEFAULT_FUNCTIONS = {
7951
9158
  createPayee: makeFunctionReference("financialOps/mutations:createPayee"),
7952
9159
  getPayee: makeFunctionReference("financialOps/queries:getPayee"),
7953
9160
  resolvePayee: makeFunctionReference("financialOps/queries:resolvePayee"),
9161
+ addDestination: makeFunctionReference("financialOps/destinations:add"),
9162
+ listDestinations: makeFunctionReference("financialOps/destinations:list"),
9163
+ removeDestination: makeFunctionReference("financialOps/destinations:remove"),
7954
9164
  pay: makeFunctionReference("financialOps/mutations:pay"),
9165
+ payout: makeFunctionReference("financialOps/destinations:payout"),
7955
9166
  withdraw: makeFunctionReference("financialOps/mutations:withdraw"),
7956
9167
  markPaymentSettled: makeFunctionReference("financialOps/actions:markPaymentSettled"),
7957
9168
  markWithdrawalSettled: makeFunctionReference("financialOps/actions:markWithdrawalSettled"),
@@ -7999,21 +9210,64 @@ function makeFinancialOpsMethods(deps) {
7999
9210
  get: (payeeId, options) => runIfActive(options?.signal, "payees.get", () => deps.convexCall.query(fns.getPayee, { payeeId })),
8000
9211
  resolve: (recipient, options) => runIfActive(options?.signal, "payees.resolve", () => deps.convexCall.query(fns.resolvePayee, { recipient }))
8001
9212
  },
9213
+ destinations: {
9214
+ add: async (input, options) => {
9215
+ const ref = normalizeRefForBackend(input.ref, "ref");
9216
+ if (!ref.ok) return {
9217
+ ok: false,
9218
+ error: ref.error
9219
+ };
9220
+ return runIfActive(options?.signal, "destinations.add", () => deps.convexCall.mutation(fns.addDestination, {
9221
+ ...input.actor === void 0 ? {} : { actor: input.actor },
9222
+ ref: ref.value,
9223
+ kind: input.kind,
9224
+ ...input.label === void 0 ? {} : { label: input.label },
9225
+ payload: input.payload
9226
+ }));
9227
+ },
9228
+ list: async (input, options) => {
9229
+ const ref = normalizeRefForBackend(input.ref, "ref");
9230
+ if (!ref.ok) return {
9231
+ ok: false,
9232
+ error: ref.error
9233
+ };
9234
+ return runIfActive(options?.signal, "destinations.list", () => deps.convexCall.query(fns.listDestinations, {
9235
+ ...input.actor === void 0 ? {} : { actor: input.actor },
9236
+ ref: ref.value
9237
+ }));
9238
+ },
9239
+ remove: (input, options) => runIfActive(options?.signal, "destinations.remove", () => deps.convexCall.mutation(fns.removeDestination, {
9240
+ ...input.actor === void 0 ? {} : { actor: input.actor },
9241
+ destinationId: input.destinationId
9242
+ }))
9243
+ },
8002
9244
  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
- })),
9245
+ pay: async (input, options) => {
9246
+ const to = normalizeRefForBackend(input.to, "to");
9247
+ if (!to.ok) return {
9248
+ ok: false,
9249
+ error: to.error
9250
+ };
9251
+ return mapOk$1(await runIfActive(options?.signal, "payments.pay", () => deps.convexCall.mutation(fns.pay, {
9252
+ to: to.value,
9253
+ amount: input.amount,
9254
+ ...input.document === void 0 ? {} : { document: input.document },
9255
+ ...input.timing === void 0 ? {} : { timing: input.timing },
9256
+ ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
9257
+ })), normalizePaymentTiming$1);
9258
+ },
9259
+ payout: async (input, options) => mapOk$1(await runIfActive(options?.signal, "payments.payout", () => deps.convexCall.mutation(fns.payout, {
9260
+ ...input.actor === void 0 ? {} : { actor: input.actor },
9261
+ destinationId: input.destinationId,
9262
+ amount: input.amount
9263
+ })), normalizePaymentTiming$1),
8010
9264
  withdraw: (input, options) => runIfActive(options?.signal, "payments.withdraw", () => deps.convexCall.mutation(fns.withdraw, {
8011
9265
  to: input.to,
8012
9266
  amount: input.amount,
8013
9267
  document: input.document
8014
9268
  })),
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 })),
9269
+ list: async (options) => mapOk$1(await runIfActive(options?.signal, "payments.list", () => deps.convexCall.query(fns.listPayments, {})), (payments) => payments.map(normalizePaymentTiming$1)),
9270
+ 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)),
8017
9271
  _internal: {
8018
9272
  markSettled: (input, options) => runIfActive(options?.signal, "payments.markSettled", () => deps.convexCall.action(fns.markPaymentSettled, {
8019
9273
  paymentId: input.paymentId,
@@ -8028,6 +9282,9 @@ function makeFinancialOpsMethods(deps) {
8028
9282
  recordOrgPayment: (input, options) => runIfActive(options?.signal, "payments.recordOrgPayment", () => deps.convexCall.action(fns.recordOrgPayment, {
8029
9283
  orgId: input.orgId,
8030
9284
  recipientLabel: input.recipientLabel,
9285
+ ...input.recipientKind === void 0 ? {} : { recipientKind: input.recipientKind },
9286
+ ...input.recipientRef === void 0 ? {} : { recipientRef: input.recipientRef },
9287
+ ...input.recipientPayeeId === void 0 ? {} : { recipientPayeeId: input.recipientPayeeId },
8031
9288
  recipientSafeAddress: input.recipientSafeAddress,
8032
9289
  amount: input.amount,
8033
9290
  paymentType: input.paymentType,
@@ -8054,13 +9311,20 @@ function makeFinancialOpsMethods(deps) {
8054
9311
  txHash: input.evidence.txHash,
8055
9312
  ...input.document === void 0 ? {} : { document: input.document }
8056
9313
  })),
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
- })),
9314
+ redirect: async (input, options) => {
9315
+ const to = normalizeRefForBackend(input.to, "to");
9316
+ if (!to.ok) return {
9317
+ ok: false,
9318
+ error: to.error
9319
+ };
9320
+ return mapOk$1(await runIfActive(options?.signal, "payments.redirect", () => deps.convexCall.action(fns.redirectCommitment, {
9321
+ paymentId: input.paymentId,
9322
+ to: to.value,
9323
+ userOpHash: input.evidence.userOpHash,
9324
+ txHash: input.evidence.txHash,
9325
+ ...input.document === void 0 ? {} : { document: input.document }
9326
+ })), normalizePaymentTiming$1);
9327
+ },
8064
9328
  commitmentRef: (paymentId, options) => runIfActive(options?.signal, "payments.commitmentRef", () => deps.convexCall.query(fns.getCommitmentRef, { paymentId }))
8065
9329
  }
8066
9330
  },
@@ -8085,35 +9349,131 @@ function makeFinancialOpsMethods(deps) {
8085
9349
  reconcile: (options) => runIfActive(options?.signal, "paymentRequests.reconcile", () => deps.convexCall.query(fns.reconcileRequests, {}))
8086
9350
  },
8087
9351
  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
- })),
9352
+ draft: async (input, options) => {
9353
+ const to = normalizeRefForBackend(input.to, "to");
9354
+ if (!to.ok) return {
9355
+ ok: false,
9356
+ error: to.error
9357
+ };
9358
+ return runIfActive(options?.signal, "workbench.draft", () => deps.convexCall.mutation(fns.draftPayment, {
9359
+ clientId: input.clientId,
9360
+ audience: input.audience,
9361
+ scopes: input.scopes,
9362
+ to: to.value,
9363
+ amount: input.amount,
9364
+ idempotencyKey: input.idempotencyKey,
9365
+ ...input.document === void 0 ? {} : { document: input.document },
9366
+ ...input.tainted === void 0 ? {} : { tainted: input.tainted }
9367
+ }));
9368
+ },
8098
9369
  simulate: (draftId, options) => runIfActive(options?.signal, "workbench.simulate", () => deps.convexCall.action(fns.simulatePayment, { draftId })),
8099
9370
  requestApproval: (draftId, options) => runIfActive(options?.signal, "workbench.requestApproval", () => deps.convexCall.mutation(fns.requestApproval, { draftId })),
8100
9371
  mint: (draftId, capability, options) => runIfActive(options?.signal, "workbench.mint", () => deps.convexCall.mutation(fns.mintApprovalToken, {
8101
9372
  draftId,
8102
9373
  capability
8103
9374
  })),
8104
- execute: (input, options) => runIfActive(options?.signal, "workbench.execute", () => deps.convexCall.action(fns.executePayment, {
9375
+ execute: async (input, options) => mapOk$1(await runIfActive(options?.signal, "workbench.execute", () => deps.convexCall.action(fns.executePayment, {
8105
9376
  draftId: input.draftId,
8106
9377
  clientId: input.clientId,
8107
9378
  approvalToken: input.approvalToken,
8108
9379
  readModelVersion: input.readModelVersion,
8109
9380
  userOpHash: input.userOpHash,
8110
9381
  txHash: input.txHash
8111
- })),
9382
+ })), normalizePaymentTiming$1),
8112
9383
  status: (draftId, options) => runIfActive(options?.signal, "workbench.status", () => deps.convexCall.query(fns.getDraft, { draftId })),
8113
9384
  cancel: (draftId, options) => runIfActive(options?.signal, "workbench.cancel", () => deps.convexCall.mutation(fns.cancelApproval, { draftId }))
8114
9385
  }
8115
9386
  };
8116
9387
  }
9388
+ function refToRecipientString(ref) {
9389
+ if (typeof ref === "string") throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
9390
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput("to", "recipient must be a typed Ref variant");
9391
+ switch (ref.kind) {
9392
+ case "handle": return handleRefValue(ref.handle, "handle");
9393
+ case "email": return nonEmptyRefValue(ref.email, "email");
9394
+ case "orgHandle": return nonEmptyRefValue(ref.orgHandle, "orgHandle");
9395
+ case "capxulUserId": return nonEmptyRefValue(ref.capxulUserId, "capxulUserId");
9396
+ case "payeeId": return nonEmptyRefValue(ref.payeeId, "payeeId");
9397
+ default: throw Errors.invalidInput("to", "recipient must be a known Ref variant");
9398
+ }
9399
+ }
9400
+ function nonEmptyRefValue(value, field) {
9401
+ const trimmed = value.trim();
9402
+ if (trimmed.length === 0) throw Errors.invalidInput(field, "Ref value must be non-empty");
9403
+ if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) throw Errors.invalidInput(field, "raw 0x addresses are not valid Ref values");
9404
+ return trimmed;
9405
+ }
9406
+ function handleRefValue(value, field) {
9407
+ const trimmed = nonEmptyRefValue(value, field);
9408
+ return trimmed.startsWith("@") ? trimmed.slice(1) : trimmed;
9409
+ }
9410
+ function normalizeRefForBackend(ref, field) {
9411
+ try {
9412
+ if (typeof ref === "string") throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
9413
+ if (typeof ref !== "object" || ref === null || !("kind" in ref)) throw Errors.invalidInput(field, "recipient must be a typed Ref variant");
9414
+ switch (ref.kind) {
9415
+ case "handle": return {
9416
+ ok: true,
9417
+ value: {
9418
+ kind: "handle",
9419
+ handle: handleRefValue(ref.handle, "handle")
9420
+ }
9421
+ };
9422
+ case "email": return {
9423
+ ok: true,
9424
+ value: {
9425
+ kind: "email",
9426
+ email: nonEmptyRefValue(ref.email, "email")
9427
+ }
9428
+ };
9429
+ case "orgHandle": return {
9430
+ ok: true,
9431
+ value: {
9432
+ kind: "orgHandle",
9433
+ orgHandle: nonEmptyRefValue(ref.orgHandle, "orgHandle")
9434
+ }
9435
+ };
9436
+ case "capxulUserId": return {
9437
+ ok: true,
9438
+ value: {
9439
+ kind: "capxulUserId",
9440
+ capxulUserId: nonEmptyRefValue(ref.capxulUserId, "capxulUserId")
9441
+ }
9442
+ };
9443
+ case "payeeId": return {
9444
+ ok: true,
9445
+ value: {
9446
+ kind: "payeeId",
9447
+ payeeId: nonEmptyRefValue(ref.payeeId, "payeeId")
9448
+ }
9449
+ };
9450
+ default: throw Errors.invalidInput(field, "recipient must be a known Ref variant");
9451
+ }
9452
+ } catch (cause) {
9453
+ if (cause instanceof Error && "code" in cause) return {
9454
+ ok: false,
9455
+ error: cause
9456
+ };
9457
+ return {
9458
+ ok: false,
9459
+ error: Errors.invalidInput(field, "recipient must be a typed Ref variant")
9460
+ };
9461
+ }
9462
+ }
9463
+ function normalizePaymentTiming$1(payment) {
9464
+ const { release: _release, ...rest } = payment;
9465
+ return {
9466
+ ...rest,
9467
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
9468
+ };
9469
+ }
9470
+ function mapOk$1(result, f) {
9471
+ if (!result.ok) return result;
9472
+ return {
9473
+ ok: true,
9474
+ value: f(result.value)
9475
+ };
9476
+ }
8117
9477
  async function runIfActive(signal, operation, effect) {
8118
9478
  if (signal?.aborted === true) return {
8119
9479
  ok: false,
@@ -8556,6 +9916,41 @@ function readTreasuryProgram(orgId) {
8556
9916
  return zeroTreasury(orgId);
8557
9917
  });
8558
9918
  }
9919
+ function findOrgById(orgs, orgId) {
9920
+ return orgs.find((org) => String(org.id) === String(orgId));
9921
+ }
9922
+ function orgNotFound(orgId) {
9923
+ return Errors.invalidInput("orgId", `org ${String(orgId)} was not found for this session`);
9924
+ }
9925
+ function readOrgProfileProgram(orgId) {
9926
+ return Effect.gen(function* () {
9927
+ const org = findOrgById(yield* listOrgsProgram(), orgId);
9928
+ if (org === void 0) return yield* Effect.fail(orgNotFound(orgId));
9929
+ return {
9930
+ actor: {
9931
+ kind: "org",
9932
+ orgId: String(orgId)
9933
+ },
9934
+ displayName: org.name,
9935
+ handle: org.handle
9936
+ };
9937
+ });
9938
+ }
9939
+ function readOrgDepositInstructionsProgram(orgId) {
9940
+ return Effect.gen(function* () {
9941
+ const deps = yield* OrgDepsTag;
9942
+ const org = findOrgById(yield* listOrgsProgram(), orgId);
9943
+ if (org === void 0) return yield* Effect.fail(orgNotFound(orgId));
9944
+ return {
9945
+ accountKind: "orgTreasury",
9946
+ chainId: Number(deps.chainId ?? 84532),
9947
+ network: "base-sepolia",
9948
+ currency: "USD",
9949
+ address: String(org.safeAddress).toLowerCase(),
9950
+ label: "Capxul org treasury"
9951
+ };
9952
+ });
9953
+ }
8559
9954
  function listRolesProgram(orgId) {
8560
9955
  return Effect.gen(function* () {
8561
9956
  const deps = yield* OrgDepsTag;
@@ -8599,6 +9994,30 @@ function inviteMemberProgram(orgId, input) {
8599
9994
  return member;
8600
9995
  });
8601
9996
  }
9997
+ function pendingMembersProgram(orgId) {
9998
+ return Effect.gen(function* () {
9999
+ const deps = yield* OrgDepsTag;
10000
+ if (deps.orgPort?.pendingMembers !== void 0) return yield* deps.orgPort.pendingMembers({ orgId }).pipe(Effect.mapError((error) => error.publicError));
10001
+ if (deps.orgPort !== void 0) return (yield* deps.orgPort.listMembers({ orgId }).pipe(Effect.mapError((error) => error.publicError))).filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant");
10002
+ return [];
10003
+ });
10004
+ }
10005
+ function resendInviteTokenProgram(orgId, email) {
10006
+ return Effect.gen(function* () {
10007
+ const deps = yield* OrgDepsTag;
10008
+ if (deps.orgPort?.resendInviteToken !== void 0) return yield* deps.orgPort.resendInviteToken({
10009
+ orgId,
10010
+ email
10011
+ }).pipe(Effect.mapError((error) => error.publicError));
10012
+ if (!isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgPort.resendInviteToken"));
10013
+ return hermeticMember({
10014
+ orgId,
10015
+ email,
10016
+ role: "Member",
10017
+ status: "pending"
10018
+ });
10019
+ });
10020
+ }
8602
10021
  function detectAndAcceptPendingInvitationsProgram() {
8603
10022
  return Effect.gen(function* () {
8604
10023
  const deps = yield* OrgDepsTag;
@@ -8660,7 +10079,7 @@ function leakSafeOrgPayment(input) {
8660
10079
  documentHash: input.documentHash,
8661
10080
  kind: input.paymentType === "payroll" ? "payslip" : "memo"
8662
10081
  }],
8663
- release: { kind: "instant" },
10082
+ timing: { kind: "instant" },
8664
10083
  released: money,
8665
10084
  availableToClaim: {
8666
10085
  ...money,
@@ -8720,11 +10139,15 @@ function spendViaPaymentsProgram(orgId, input) {
8720
10139
  return Effect.gen(function* () {
8721
10140
  const deps = yield* OrgDepsTag;
8722
10141
  if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
10142
+ const to = yield* Effect.try({
10143
+ try: () => refToRecipientString(input.to),
10144
+ catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
10145
+ });
8723
10146
  const gated = yield* gateOneRun({
8724
10147
  deps,
8725
10148
  orgId,
8726
10149
  from: input.from,
8727
- to: input.to,
10150
+ to,
8728
10151
  amount: input.amount
8729
10152
  });
8730
10153
  const paymentType = input.paymentType ?? "unspecified";
@@ -8736,7 +10159,7 @@ function spendViaPaymentsProgram(orgId, input) {
8736
10159
  }).pipe(Effect.mapError((error) => error.publicError));
8737
10160
  return leakSafeOrgPayment({
8738
10161
  orgId,
8739
- to: input.to,
10162
+ to,
8740
10163
  amount: input.amount,
8741
10164
  paymentType,
8742
10165
  index: 0
@@ -8749,13 +10172,17 @@ function batchPayrollProgram(orgId, input) {
8749
10172
  if (deps.orgSpendPort === void 0 && !isHermeticOrgDeps(deps)) return yield* Effect.fail(missingLiveOrgDep("orgSpendPort"));
8750
10173
  if (input.runs.length === 0) return yield* Effect.fail(Errors.invalidInput("runs", "payroll batch must include at least one run"));
8751
10174
  const gated = [];
10175
+ const recipients = yield* Effect.try({
10176
+ try: () => input.runs.map((run) => refToRecipientString(run.to)),
10177
+ catch: (cause) => isCapxulError(cause) ? cause : Errors.invalidInput("to", "invalid Ref")
10178
+ });
8752
10179
  let accumulatedRaw = 0n;
8753
- for (const run of input.runs) {
10180
+ for (const [index, run] of input.runs.entries()) {
8754
10181
  const result = yield* gateOneRun({
8755
10182
  deps,
8756
10183
  orgId,
8757
10184
  from: input.from,
8758
- to: run.to,
10185
+ to: recipients[index],
8759
10186
  amount: run.amount,
8760
10187
  accumulatedRaw: accumulatedRaw.toString(10)
8761
10188
  });
@@ -8773,7 +10200,7 @@ function batchPayrollProgram(orgId, input) {
8773
10200
  }).pipe(Effect.mapError((error) => error.publicError));
8774
10201
  return input.runs.map((run, index) => leakSafeOrgPayment({
8775
10202
  orgId,
8776
- to: run.to,
10203
+ to: recipients[index],
8777
10204
  amount: run.amount,
8778
10205
  paymentType: "payroll",
8779
10206
  index
@@ -8827,7 +10254,31 @@ function makeOrgMethods(deps) {
8827
10254
  return toCapxulResult(detectAndAcceptPendingInvitationsProgram(), layer);
8828
10255
  } }),
8829
10256
  org(orgId) {
10257
+ const convexCall = deps.convexCall;
8830
10258
  return {
10259
+ ...makeActorRelationshipMethods({
10260
+ actor: {
10261
+ kind: "org",
10262
+ orgId: String(orgId)
10263
+ },
10264
+ ...convexCall === void 0 ? {} : { convexCall }
10265
+ }),
10266
+ profile: {
10267
+ get(_options) {
10268
+ if (_options?.signal?.aborted) return Promise.resolve({
10269
+ ok: false,
10270
+ error: Errors.cancelled({ operation: "org.profile.get" })
10271
+ });
10272
+ return toCapxulResult(readOrgProfileProgram(orgId), layer);
10273
+ },
10274
+ depositInstructions(_options) {
10275
+ if (_options?.signal?.aborted) return Promise.resolve({
10276
+ ok: false,
10277
+ error: Errors.cancelled({ operation: "org.profile.depositInstructions" })
10278
+ });
10279
+ return toCapxulResult(readOrgDepositInstructionsProgram(orgId), layer);
10280
+ }
10281
+ },
8831
10282
  treasury(options) {
8832
10283
  if (options?.signal?.aborted) return Promise.resolve({
8833
10284
  ok: false,
@@ -8863,6 +10314,20 @@ function makeOrgMethods(deps) {
8863
10314
  });
8864
10315
  return toCapxulResult(inviteMemberProgram(orgId, _input), layer);
8865
10316
  },
10317
+ pendingMembers(_options) {
10318
+ if (_options?.signal?.aborted) return Promise.resolve({
10319
+ ok: false,
10320
+ error: Errors.cancelled({ operation: "org.pendingMembers" })
10321
+ });
10322
+ return toCapxulResult(pendingMembersProgram(orgId), layer);
10323
+ },
10324
+ inviteToken: { resend(_input, _options) {
10325
+ if (_options?.signal?.aborted) return Promise.resolve({
10326
+ ok: false,
10327
+ error: Errors.cancelled({ operation: "org.inviteToken.resend" })
10328
+ });
10329
+ return toCapxulResult(resendInviteTokenProgram(orgId, String(_input.email)), layer);
10330
+ } },
8866
10331
  removeMember(_input, _options) {
8867
10332
  if (_options?.signal?.aborted) return Promise.resolve({
8868
10333
  ok: false,
@@ -8890,11 +10355,281 @@ function makeOrgMethods(deps) {
8890
10355
  error: Errors.cancelled({ operation: "org.batchPayroll" })
8891
10356
  });
8892
10357
  return toCapxulResult(batchPayrollProgram(orgId, _input), layer);
8893
- }
10358
+ },
10359
+ payroll: convexCall === void 0 ? makeNotImplementedPayrollMethods() : makePayrollMethods({
10360
+ orgId: String(orgId),
10361
+ convexCall
10362
+ })
8894
10363
  };
8895
10364
  }
8896
10365
  };
8897
10366
  }
10367
+ const PAYROLL_FUNCTIONS = {
10368
+ add: makeFunctionReference("financialOps/payrollRoster:add"),
10369
+ list: makeFunctionReference("financialOps/payrollRoster:list"),
10370
+ update: makeFunctionReference("financialOps/payrollRoster:update"),
10371
+ remove: makeFunctionReference("financialOps/payrollRoster:remove"),
10372
+ run: makeFunctionReference("financialOps/payrollRoster:run")
10373
+ };
10374
+ function makePayrollMethods(deps) {
10375
+ const fns = PAYROLL_FUNCTIONS;
10376
+ return {
10377
+ roster: {
10378
+ add: async (input, options) => {
10379
+ const employee = normalizeRefForBackend$1(input.employee, "employee");
10380
+ if (!employee.ok) return employee;
10381
+ return mapOk(runConvexIfActive(options?.signal, "payroll.roster.add", () => deps.convexCall.mutation(fns.add, {
10382
+ orgId: deps.orgId,
10383
+ employee: employee.value,
10384
+ amount: input.amount,
10385
+ timing: input.timing,
10386
+ payslipTemplate: toPayrollTemplate(input.payslipTemplate)
10387
+ })), mapPayrollRosterLine);
10388
+ },
10389
+ list: (options) => mapOk(runConvexIfActive(options?.signal, "payroll.roster.list", () => deps.convexCall.query(fns.list, { orgId: deps.orgId })), (lines) => lines.map(mapPayrollRosterLine)),
10390
+ update: async (rosterLineId, input, options) => {
10391
+ const employee = input.employee === void 0 ? void 0 : normalizeRefForBackend$1(input.employee, "employee");
10392
+ if (employee !== void 0 && !employee.ok) return employee;
10393
+ return mapOk(runConvexIfActive(options?.signal, "payroll.roster.update", () => deps.convexCall.mutation(fns.update, {
10394
+ orgId: deps.orgId,
10395
+ rosterLineId,
10396
+ ...employee === void 0 ? {} : { employee: employee.value },
10397
+ ...input.amount === void 0 ? {} : { amount: input.amount },
10398
+ ...input.timing === void 0 ? {} : { timing: input.timing },
10399
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: toPayrollTemplate(input.payslipTemplate) }
10400
+ })), mapPayrollRosterLine);
10401
+ },
10402
+ remove: (rosterLineId, options) => mapOk(runConvexIfActive(options?.signal, "payroll.roster.remove", () => deps.convexCall.mutation(fns.remove, {
10403
+ orgId: deps.orgId,
10404
+ rosterLineId
10405
+ })), mapPayrollRosterLine)
10406
+ },
10407
+ run: (input, options) => mapOk(runConvexIfActive(options?.signal, "payroll.run", () => deps.convexCall.mutation(fns.run, {
10408
+ orgId: deps.orgId,
10409
+ period: input.period,
10410
+ from: String(input.from)
10411
+ })), (run) => run.payments.map(normalizePaymentTiming))
10412
+ };
10413
+ }
10414
+ function makeNotImplementedPayrollMethods() {
10415
+ return {
10416
+ roster: {
10417
+ add: () => missingConvexCall("payroll.roster.add"),
10418
+ list: () => missingConvexCall("payroll.roster.list"),
10419
+ update: () => missingConvexCall("payroll.roster.update"),
10420
+ remove: () => missingConvexCall("payroll.roster.remove")
10421
+ },
10422
+ run: () => missingConvexCall("payroll.run")
10423
+ };
10424
+ }
10425
+ function missingConvexCall(operation) {
10426
+ return Promise.resolve({
10427
+ ok: false,
10428
+ error: Errors.providerError("convex", operation, "ConvexCallPort is required")
10429
+ });
10430
+ }
10431
+ async function mapOk(resultOrPromise, f) {
10432
+ const result = await resultOrPromise;
10433
+ if (!result.ok) return result;
10434
+ return {
10435
+ ok: true,
10436
+ value: f(result.value)
10437
+ };
10438
+ }
10439
+ function mapPayrollRosterLine(line) {
10440
+ return {
10441
+ id: line.id,
10442
+ employee: line.employee,
10443
+ amount: line.amount,
10444
+ timing: line.timing,
10445
+ status: line.status === "removed" ? "ended" : line.status
10446
+ };
10447
+ }
10448
+ function toPayrollTemplate(document) {
10449
+ if (document === void 0) return { title: "Payroll" };
10450
+ if ("title" in document) return {
10451
+ title: document.title,
10452
+ ...typeof document.memo === "string" ? { memo: document.memo } : {}
10453
+ };
10454
+ if (document.primaryType === "Payslip") return { title: `Payslip ${document.message.period}` };
10455
+ if ("reference" in document.message) return {
10456
+ title: document.primaryType,
10457
+ memo: document.message.reference
10458
+ };
10459
+ return { title: document.primaryType };
10460
+ }
10461
+ function normalizePaymentTiming(payment) {
10462
+ const { release: _release, ...rest } = payment;
10463
+ return {
10464
+ ...rest,
10465
+ timing: payment.timing ?? payment.release ?? { kind: "instant" }
10466
+ };
10467
+ }
10468
+ //#endregion
10469
+ //#region ../../packages/sdk/src/flows/onboarding.ts
10470
+ const DEFAULT_ORG_TEMPLATE = "Startup";
10471
+ async function runCompletePersonalOnboarding(ops, input) {
10472
+ const validated = validatePersonalInput(input);
10473
+ if (!validated.ok) return validated;
10474
+ const session = await ops.currentSession();
10475
+ if (session === null) return fail(Errors.notAuthenticated());
10476
+ const written = await ops.completeIdentityOnboarding({
10477
+ authUserId: session.authUserId,
10478
+ email: session.email,
10479
+ displayName: validated.value.displayName,
10480
+ country: validated.value.country,
10481
+ ...validated.value.withdrawalAddress === void 0 ? {} : { withdrawalAddress: validated.value.withdrawalAddress }
10482
+ });
10483
+ if (!written.ok) return fail(written.error);
10484
+ const provisioned = await ops.triggerProvisioning();
10485
+ if (!provisioned.ok) return fail(provisioned.error);
10486
+ ops.kickProvisioning();
10487
+ const lifecycle = await ops.readLifecycle();
10488
+ if (!lifecycle.ok) return fail(lifecycle.error);
10489
+ return {
10490
+ ok: true,
10491
+ value: { lifecycle: lifecycle.value }
10492
+ };
10493
+ }
10494
+ async function runCompleteOrganizationOnboarding(ops, input) {
10495
+ const validated = validateOrganizationInput(input);
10496
+ if (!validated.ok) return validated;
10497
+ const session = await ops.currentSession();
10498
+ if (session === null) return fail(Errors.notAuthenticated());
10499
+ const written = await ops.completeIdentityOnboarding({
10500
+ authUserId: session.authUserId,
10501
+ email: session.email,
10502
+ displayName: validated.value.ownerDisplayName,
10503
+ country: validated.value.country
10504
+ });
10505
+ if (!written.ok) return fail(written.error);
10506
+ const provisioned = await ops.triggerProvisioning();
10507
+ if (!provisioned.ok) return fail(provisioned.error);
10508
+ const org = await ops.createOrg({
10509
+ name: validated.value.organizationName,
10510
+ handle: validated.value.handle,
10511
+ template: DEFAULT_ORG_TEMPLATE,
10512
+ country: validated.value.country
10513
+ });
10514
+ if (!org.ok) return fail(org.error);
10515
+ ops.kickProvisioning();
10516
+ const lifecycle = await ops.readLifecycle();
10517
+ if (!lifecycle.ok) return fail(lifecycle.error);
10518
+ return {
10519
+ ok: true,
10520
+ value: {
10521
+ org: org.value,
10522
+ lifecycle: lifecycle.value
10523
+ }
10524
+ };
10525
+ }
10526
+ function validatePersonalInput(input) {
10527
+ const displayName = requireNonEmpty(input.displayName, "displayName");
10528
+ if (!displayName.ok) return displayName;
10529
+ const country = parseCountry(input.country);
10530
+ if (!country.ok) return country;
10531
+ if (input.withdrawalAddress === void 0) return {
10532
+ ok: true,
10533
+ value: {
10534
+ displayName: displayName.value,
10535
+ country: country.value
10536
+ }
10537
+ };
10538
+ const withdrawalAddress = parseAddress(input.withdrawalAddress, "withdrawalAddress");
10539
+ if (!withdrawalAddress.ok) return withdrawalAddress;
10540
+ return {
10541
+ ok: true,
10542
+ value: {
10543
+ displayName: displayName.value,
10544
+ country: country.value,
10545
+ withdrawalAddress: withdrawalAddress.value
10546
+ }
10547
+ };
10548
+ }
10549
+ function validateOrganizationInput(input) {
10550
+ const organizationName = requireNonEmpty(input.organizationName, "organizationName");
10551
+ if (!organizationName.ok) return organizationName;
10552
+ const handle = requireNonEmpty(input.handle, "handle");
10553
+ if (!handle.ok) return handle;
10554
+ const ownerDisplayName = requireNonEmpty(input.ownerDisplayName, "ownerDisplayName");
10555
+ if (!ownerDisplayName.ok) return ownerDisplayName;
10556
+ const country = parseCountry(input.country);
10557
+ if (!country.ok) return country;
10558
+ return {
10559
+ ok: true,
10560
+ value: {
10561
+ organizationName: organizationName.value,
10562
+ handle: handle.value,
10563
+ country: country.value,
10564
+ ownerDisplayName: ownerDisplayName.value
10565
+ }
10566
+ };
10567
+ }
10568
+ function requireNonEmpty(value, field) {
10569
+ const trimmed = typeof value === "string" ? value.trim() : "";
10570
+ if (trimmed.length === 0) return fail(Errors.invalidInput(field, "must be a non-empty string"));
10571
+ return {
10572
+ ok: true,
10573
+ value: trimmed
10574
+ };
10575
+ }
10576
+ function parseCountry(value) {
10577
+ try {
10578
+ return {
10579
+ ok: true,
10580
+ value: toCountryCode(value)
10581
+ };
10582
+ } catch (cause) {
10583
+ return fail(invalidFrom("country", cause, "must be an ISO-3166 alpha-2 code"));
10584
+ }
10585
+ }
10586
+ function parseAddress(value, field) {
10587
+ try {
10588
+ return {
10589
+ ok: true,
10590
+ value: toAddress(value)
10591
+ };
10592
+ } catch (cause) {
10593
+ return fail(invalidFrom(field, cause, "must be a 0x-prefixed 20-byte address"));
10594
+ }
10595
+ }
10596
+ function invalidFrom(field, cause, fallback) {
10597
+ const message = cause instanceof Error && cause.message.length > 0 ? cause.message : fallback;
10598
+ return Errors.invalidInput(field, message);
10599
+ }
10600
+ function fail(error) {
10601
+ return {
10602
+ ok: false,
10603
+ error: error instanceof CapxulError ? error : Errors.unknown(error)
10604
+ };
10605
+ }
10606
+ //#endregion
10607
+ //#region ../../packages/sdk/src/client/onboarding.ts
10608
+ /**
10609
+ * Onboarding method surface. The thin namespace over the `flows/onboarding.ts`
10610
+ * choreography: it adds the `signal`-abort pre-check and delegates to the run
10611
+ * functions. The `OnboardingOps` seam is supplied by `assembleCapxulClient`
10612
+ * (real ops over the account lane + createOrg + IdentityPort) or by tests
10613
+ * (in-memory double).
10614
+ */
10615
+ function makeOnboardingMethods(ops) {
10616
+ return {
10617
+ completePersonal(input, options) {
10618
+ if (options?.signal?.aborted) return Promise.resolve({
10619
+ ok: false,
10620
+ error: Errors.cancelled({ operation: "onboarding.completePersonal" })
10621
+ });
10622
+ return runCompletePersonalOnboarding(ops, input);
10623
+ },
10624
+ completeOrganization(input, options) {
10625
+ if (options?.signal?.aborted) return Promise.resolve({
10626
+ ok: false,
10627
+ error: Errors.cancelled({ operation: "onboarding.completeOrganization" })
10628
+ });
10629
+ return runCompleteOrganizationOnboarding(ops, input);
10630
+ }
10631
+ };
10632
+ }
8898
10633
  //#endregion
8899
10634
  //#region ../../packages/sdk/src/ports/auth-cache.ts
8900
10635
  var AuthCacheError = class extends Data.TaggedError("AuthCacheError") {};
@@ -9021,6 +10756,7 @@ function assembleCapxulClient(input) {
9021
10756
  const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
9022
10757
  let detectPendingOrgInvitations;
9023
10758
  let kickProvisioning;
10759
+ const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
9024
10760
  const accountBundle = makeAccountMethods({
9025
10761
  actor,
9026
10762
  authCache,
@@ -9030,6 +10766,8 @@ function assembleCapxulClient(input) {
9030
10766
  chainId: input.bootstrap.chainId,
9031
10767
  requirement: input.requirement,
9032
10768
  accountReadPort: input.ports.accountRead,
10769
+ profileMethods: financialOps.me,
10770
+ convexCall: input.ports.convexCall,
9033
10771
  ...input.signer === void 0 ? {} : { signer: input.signer }
9034
10772
  });
9035
10773
  kickProvisioning = accountBundle.kickProvisioning;
@@ -9065,7 +10803,6 @@ function assembleCapxulClient(input) {
9065
10803
  chainId: input.bootstrap.chainId,
9066
10804
  telemetry: input.ports.telemetry
9067
10805
  });
9068
- const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });
9069
10806
  const subAccounts = makeSubAccountsMethods({
9070
10807
  subAccountPort: input.ports.subAccount,
9071
10808
  telemetry: input.ports.telemetry
@@ -9075,11 +10812,26 @@ function assembleCapxulClient(input) {
9075
10812
  telemetry: input.ports.telemetry,
9076
10813
  ...selectedOrgPort === void 0 ? {} : { orgPort: selectedOrgPort },
9077
10814
  ...input.orgRolesDeploymentPort === void 0 ? {} : { orgRolesDeploymentPort: input.orgRolesDeploymentPort },
9078
- ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort }
10815
+ ...input.orgSpendPort === void 0 ? {} : { orgSpendPort: input.orgSpendPort },
10816
+ convexCall: input.ports.convexCall
9079
10817
  });
9080
10818
  if (selectedOrgPort !== void 0) detectPendingOrgInvitations = async () => {
9081
10819
  await orgMethods.orgs.detectAndAcceptPendingInvitations();
9082
10820
  };
10821
+ const onboarding = makeOnboardingMethods({
10822
+ currentSession: async () => {
10823
+ const session = await currentSession(actor, authCache);
10824
+ return session === null ? null : {
10825
+ authUserId: session.authUserId,
10826
+ email: session.email
10827
+ };
10828
+ },
10829
+ completeIdentityOnboarding: (write) => runPortEffect(input.ports.identity.completeOnboarding(write)),
10830
+ triggerProvisioning: () => account._internal.provision(),
10831
+ kickProvisioning: () => kickProvisioning?.(),
10832
+ readLifecycle: () => account.getLifecycle(),
10833
+ createOrg: (createOrgInput) => orgMethods.createOrg(createOrgInput)
10834
+ });
9083
10835
  return {
9084
10836
  auth,
9085
10837
  smartAccount,
@@ -9089,6 +10841,7 @@ function assembleCapxulClient(input) {
9089
10841
  me: financialOps.me,
9090
10842
  handles: financialOps.handles,
9091
10843
  payees: financialOps.payees,
10844
+ destinations: financialOps.destinations,
9092
10845
  payments: financialOps.payments,
9093
10846
  paymentDocuments: financialOps.paymentDocuments,
9094
10847
  paymentRequests: financialOps.paymentRequests,
@@ -9097,6 +10850,7 @@ function assembleCapxulClient(input) {
9097
10850
  createOrg: orgMethods.createOrg,
9098
10851
  orgs: orgMethods.orgs,
9099
10852
  org: orgMethods.org,
10853
+ onboarding,
9100
10854
  _internal: {
9101
10855
  authActor: {
9102
10856
  input: actor.input,
@@ -9616,7 +11370,7 @@ function toPublicError(cause, operation) {
9616
11370
  return Errors.providerError("sdk-org-deployment-client", operation, cause);
9617
11371
  }
9618
11372
  //#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
11373
+ //#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
11374
  /**
9621
11375
  * Returns the nonce of the account with the entry point.
9622
11376
  *
@@ -9668,7 +11422,7 @@ const getAccountNonce = async (client, args) => {
9668
11422
  });
9669
11423
  };
9670
11424
  //#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
11425
+ //#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
11426
  async function toOwner({ owner, address }) {
9673
11427
  if ("type" in owner && owner.type === "local") return owner;
9674
11428
  let walletClient = void 0;
@@ -9699,7 +11453,7 @@ async function toOwner({ owner, address }) {
9699
11453
  });
9700
11454
  }
9701
11455
  //#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
11456
+ //#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
11457
  function decode7579Calls(callData) {
9704
11458
  const decoded = decodeFunctionData({
9705
11459
  abi: [{
@@ -9782,7 +11536,7 @@ function decode7579Calls(callData) {
9782
11536
  };
9783
11537
  }
9784
11538
  //#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
11539
+ //#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
11540
  function getCallType(callType) {
9787
11541
  switch (callType) {
9788
11542
  case "call": return "0x00";
@@ -9806,7 +11560,7 @@ function encodeExecutionMode({ type, revertOnError, selector, context }) {
9806
11560
  ]);
9807
11561
  }
9808
11562
  //#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
11563
+ //#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
11564
  function encode7579Calls({ mode, callData }) {
9811
11565
  if (callData.length > 1 && mode?.type !== "batchcall") throw new Error(`mode ${JSON.stringify(mode)} does not supported for batchcall calldata`);
9812
11566
  const executeAbi = [{
@@ -9865,20 +11619,20 @@ function encode7579Calls({ mode, callData }) {
9865
11619
  });
9866
11620
  }
9867
11621
  //#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
11622
+ //#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
11623
  const isSmartAccountDeployed = async (client, address) => {
9870
11624
  const contractCode = await getCode(client, { address });
9871
11625
  return Boolean(contractCode);
9872
11626
  };
9873
11627
  //#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
11628
+ //#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
11629
  /**
9876
11630
  * Utility module for handling optional ox imports
9877
11631
  * This allows the library to work without ox being installed
9878
11632
  */
9879
11633
  let oxModule = null;
9880
11634
  try {
9881
- oxModule = { importPromise: import("./_esm-CA4cvybV.mjs") };
11635
+ oxModule = { importPromise: import("./_esm-DUwdnl5L.mjs") };
9882
11636
  } catch (error) {}
9883
11637
  async function getOxModule() {
9884
11638
  if (!oxModule) throw new Error("The 'ox' package is required for WebAuthn functionality. Please install it: npm install ox");
@@ -9899,7 +11653,7 @@ async function getOxExports() {
9899
11653
  };
9900
11654
  }
9901
11655
  //#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
11656
+ //#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
11657
  const concatSignatures = (signatures) => {
9904
11658
  signatures.sort((left, right) => left.signer.toLowerCase().localeCompare(right.signer.toLowerCase()));
9905
11659
  const SIGNATURE_LENGTH_BYTES = 65;
@@ -10064,7 +11818,7 @@ async function signUserOperation(parameters) {
10064
11818
  ]);
10065
11819
  }
10066
11820
  //#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
11821
+ //#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
11822
  const multiSendAbi$1 = [{
10069
11823
  inputs: [{
10070
11824
  internalType: "bytes",
@@ -11430,6 +13184,7 @@ function toViemHexAddress(value) {
11430
13184
  const orgCreateMutation = makeFunctionReference("org/mutations:createOrg");
11431
13185
  const orgDeployRolesAction = makeFunctionReference("org/actions:deployOrgRoles");
11432
13186
  const orgInviteMemberAction = makeFunctionReference("org/actions:inviteMember");
13187
+ const orgResendInviteTokenMutation = makeFunctionReference("org/mutations:resendInviteToken");
11433
13188
  const orgDetectAndAcceptPendingInvitationsAction = makeFunctionReference("org/actions:detectAndAcceptPendingInvitations");
11434
13189
  const orgAssignRoleAction = makeFunctionReference("org/actions:assignRole");
11435
13190
  const orgRemoveMemberAction = makeFunctionReference("org/actions:removeMember");
@@ -11647,6 +13402,9 @@ var LiveOrgDeploymentAdapter = class {
11647
13402
  listMembers(input) {
11648
13403
  return this.#convex.query(orgListMembersByOrgIdQuery, { orgId: input.orgId }).pipe(Effect.mapError((error) => orgErrorFromCapxul("listMembers", error.publicError, error)), Effect.map((members) => members.map(brandOrgMember)));
11649
13404
  }
13405
+ pendingMembers(input) {
13406
+ return this.listMembers(input).pipe(Effect.map((members) => members.filter((member) => member.status === "pending" || member.status === "pending_safe" || member.status === "pending_grant")));
13407
+ }
11650
13408
  inviteMember(input) {
11651
13409
  return this.#convex.action(orgInviteMemberAction, {
11652
13410
  orgId: input.orgId,
@@ -11655,6 +13413,12 @@ var LiveOrgDeploymentAdapter = class {
11655
13413
  ...process.env.CAPXUL_E2E_RUN_ID === void 0 ? {} : { telemetryRunId: process.env.CAPXUL_E2E_RUN_ID }
11656
13414
  }).pipe(Effect.mapError((error) => orgErrorFromCapxul("inviteMember", error.publicError, error)), Effect.map(brandOrgMember));
11657
13415
  }
13416
+ resendInviteToken(input) {
13417
+ return this.#convex.mutation(orgResendInviteTokenMutation, {
13418
+ orgId: input.orgId,
13419
+ email: input.email
13420
+ }).pipe(Effect.mapError((error) => orgErrorFromCapxul("resendInviteToken", error.publicError, error)), Effect.map(brandOrgMember));
13421
+ }
11658
13422
  detectAndAcceptPendingInvitations(_input) {
11659
13423
  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
13424
  }
@@ -12147,6 +13911,102 @@ function toOrgError(operation, cause) {
12147
13911
  return orgErrorFromCapxul(operation, cause instanceof CapxulError ? cause : Errors.providerError("permissionless-org-deployment", operation, cause), cause);
12148
13912
  }
12149
13913
  //#endregion
13914
+ //#region ../../packages/backend/convex/financialOps/settlementBuild.ts
13915
+ const ADDRESS_RE$2 = /^0x[0-9a-fA-F]{40}$/;
13916
+ const BYTES32_RE$1 = /^0x[0-9a-fA-F]{64}$/;
13917
+ const DECIMAL_RE$1 = /^([0-9]+)(?:\.([0-9]+))?$/;
13918
+ const ZERO_BYTES32$1 = `0x${"0".repeat(64)}`;
13919
+ const PAYMENT_TYPE_PAYROLL = 2;
13920
+ function requireAllowlistedToken() {
13921
+ const tokenAddress = DIRECT_BASE_ROUTE.token.address;
13922
+ if (!isExactTransferTokenAllowed(tokenAddress)) throw Errors.invalidInput("token", "token is not on the exact-transfer allowlist");
13923
+ return tokenAddress;
13924
+ }
13925
+ function settlementMoneyToRawUnits(amount) {
13926
+ const decimals = DIRECT_BASE_ROUTE.token.decimals;
13927
+ if (amount.decimals !== decimals) throw Errors.invalidInput("amount", `USDX payments require ${decimals} decimals`);
13928
+ if (amount.currency !== "USD" && amount.currency !== "USDX") throw Errors.invalidInput("amount", "currency must be USD or USDX");
13929
+ const match = DECIMAL_RE$1.exec(amount.value);
13930
+ if (match === null) throw Errors.invalidInput("amount", "value must be a decimal string");
13931
+ const whole = match[1] ?? "0";
13932
+ const fraction = match[2] ?? "";
13933
+ if (fraction.length > decimals) throw Errors.invalidInput("amount", `USDX supports at most ${decimals} decimals`);
13934
+ const rawUnits = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fraction.padEnd(decimals, "0"));
13935
+ if (rawUnits <= 0n) throw Errors.invalidInput("amount", "must be greater than zero");
13936
+ return rawUnits;
13937
+ }
13938
+ function normalizeSettlementRecipient(value, field = "recipient") {
13939
+ if (!ADDRESS_RE$2.test(value)) throw Errors.invalidInput(field, "must be 0x + 40 hex chars");
13940
+ return value.toLowerCase();
13941
+ }
13942
+ function normalizeSettlementBytes32(value, field = "documentHash") {
13943
+ if (value === void 0) return ZERO_BYTES32$1;
13944
+ if (!BYTES32_RE$1.test(value)) throw Errors.invalidInput(field, "must be a 32-byte 0x hex string");
13945
+ return value.toLowerCase();
13946
+ }
13947
+ function commitmentTimes$1(timing) {
13948
+ if (timing.kind === "scheduled") return {
13949
+ startTime: timing.at,
13950
+ cliffTime: timing.at,
13951
+ endTime: timing.at
13952
+ };
13953
+ return {
13954
+ startTime: timing.startsAt,
13955
+ cliffTime: timing.cliffAt ?? timing.startsAt,
13956
+ endTime: timing.endsAt
13957
+ };
13958
+ }
13959
+ function buildPaymentSettlementCallData(input) {
13960
+ const tokenAddress = requireAllowlistedToken();
13961
+ const recipientAddress = normalizeSettlementRecipient(input.recipient);
13962
+ const rawAmount = settlementMoneyToRawUnits(input.amount);
13963
+ const documentHash = normalizeSettlementBytes32(input.documentHash);
13964
+ const paymentType = input.paymentType ?? 0;
13965
+ const timing = input.timing ?? { kind: "instant" };
13966
+ if (timing.kind === "instant") return buildCapxulPaymentsPersonalSendCallData({
13967
+ tokenAddress,
13968
+ recipientAddress,
13969
+ amount: rawAmount,
13970
+ documentHash,
13971
+ paymentType
13972
+ });
13973
+ const times = commitmentTimes$1(timing);
13974
+ return buildCapxulCreateCommitmentPersonalCallData({
13975
+ tokenAddress,
13976
+ recipientAddress,
13977
+ totalAmount: rawAmount,
13978
+ startTime: times.startTime,
13979
+ cliffTime: times.cliffTime,
13980
+ endTime: times.endTime,
13981
+ documentHash,
13982
+ paymentType
13983
+ });
13984
+ }
13985
+ function buildRolePayrollSettlementCallData(input) {
13986
+ if (input.runs.length === 0) throw Errors.invalidInput("runs", "payroll batch must include at least one run");
13987
+ const tokenAddress = requireAllowlistedToken();
13988
+ return buildOrgRoleSpendPersonalCallData(buildCapxulPaymentsRoleBatchSpendCall({
13989
+ rolesModuleAddress: normalizeSettlementRecipient(input.rolesModule, "rolesModule"),
13990
+ roleKey: normalizeSettlementBytes32(input.roleKey, "roleKey"),
13991
+ tokenAddress,
13992
+ paymentType: PAYMENT_TYPE_PAYROLL,
13993
+ runs: input.runs.map((run) => ({
13994
+ recipientAddress: normalizeSettlementRecipient(run.recipient, "recipient"),
13995
+ amount: settlementMoneyToRawUnits(run.amount),
13996
+ ...run.timing === void 0 || run.timing.kind === "instant" ? {} : { timing: commitmentTimes$1(run.timing) },
13997
+ ...run.documentHash === void 0 ? {} : { documentHash: normalizeSettlementBytes32(run.documentHash, "documentHash") }
13998
+ }))
13999
+ }));
14000
+ }
14001
+ function buildCommitmentLifecycleSettlementCallData(input) {
14002
+ const commitmentId = BigInt(input.onchainCommitmentId);
14003
+ switch (input.kind) {
14004
+ case "claim": return buildCapxulCommitmentClaimCallData(commitmentId);
14005
+ case "cancel": return buildCapxulCommitmentCancelCallData(commitmentId, normalizeSettlementBytes32(input.documentHash));
14006
+ case "redirect": return buildCapxulCommitmentRedirectCallData(commitmentId, normalizeSettlementRecipient(input.newRecipient, "newRecipient"), normalizeSettlementBytes32(input.newDocumentHash, "newDocumentHash"));
14007
+ }
14008
+ }
14009
+ //#endregion
12150
14010
  //#region ../../packages/backend/convex/smartAccount/deploy.ts
12151
14011
  /** Merge only the paymaster fields a `pm_*` result actually returned (viem-style override). */
12152
14012
  function definedPaymasterFields(r) {
@@ -12433,7 +14293,6 @@ function directBaseSettlementPort() {
12433
14293
  }
12434
14294
  //#endregion
12435
14295
  //#region src/org-sender.ts
12436
- const PAYMENT_TYPE_PAYROLL = 2;
12437
14296
  /**
12438
14297
  * Execute an org payroll batch (or a single org spend, runs.length === 1) as one
12439
14298
  * sponsored UserOp through the member's role on the Org Roles modifier. The
@@ -12448,24 +14307,21 @@ const PAYMENT_TYPE_PAYROLL = 2;
12448
14307
  async function executeOrgPayrollBatch(input) {
12449
14308
  return guard$1("org.batchPayroll", async () => {
12450
14309
  const port = input.port ?? directBaseSettlementPort();
12451
- const tokenAddress = port.requireAllowlistedToken();
12452
14310
  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,
14311
+ const callData = buildRolePayrollSettlementCallData({
14312
+ rolesModule: input.rolesModuleAddress,
14313
+ roleKey: input.roleKey,
12458
14314
  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") }
14315
+ recipient: run.recipientAddress,
14316
+ amount: run.amount,
14317
+ ...run.documentHash === void 0 ? {} : { documentHash: run.documentHash }
12462
14318
  }))
12463
14319
  });
12464
14320
  const submitted = await port.submitAndConfirm({
12465
14321
  signer: input.signer,
12466
14322
  payerEmail: input.memberEmail,
12467
14323
  policyId: input.policyId,
12468
- callData: buildOrgRoleSpendPersonalCallData(call),
14324
+ callData,
12469
14325
  method: "org.batchPayroll",
12470
14326
  mapReverts: true,
12471
14327
  ...input.waitReceiptMs === void 0 ? {} : { waitReceiptMs: input.waitReceiptMs },
@@ -12495,6 +14351,40 @@ function guard$1(method, fn) {
12495
14351
  }
12496
14352
  //#endregion
12497
14353
  //#region src/org-spend-port.ts
14354
+ function refToMcpRecipient(ref) {
14355
+ switch (ref.kind) {
14356
+ case "handle": return ref.handle;
14357
+ case "email": return ref.email;
14358
+ case "orgHandle": return ref.orgHandle;
14359
+ case "capxulUserId": return ref.capxulUserId;
14360
+ case "payeeId": return ref.payeeId;
14361
+ }
14362
+ }
14363
+ function recipientIdentityFromRef(ref) {
14364
+ switch (ref.kind) {
14365
+ case "handle": return {
14366
+ recipientKind: "handle",
14367
+ recipientRef: ref.handle
14368
+ };
14369
+ case "email": return {
14370
+ recipientKind: "email",
14371
+ recipientRef: ref.email
14372
+ };
14373
+ case "orgHandle": return {
14374
+ recipientKind: "org",
14375
+ recipientRef: ref.orgHandle
14376
+ };
14377
+ case "capxulUserId": return {
14378
+ recipientKind: "capxulUserId",
14379
+ recipientRef: ref.capxulUserId
14380
+ };
14381
+ case "payeeId": return {
14382
+ recipientKind: "payee",
14383
+ recipientRef: ref.payeeId,
14384
+ recipientPayeeId: ref.payeeId
14385
+ };
14386
+ }
14387
+ }
12498
14388
  /**
12499
14389
  * A leak-safe authority that defers the per-tx / per-day cap to the ON-CHAIN
12500
14390
  * Roles modifier. The off-chain gate must pass everything EXCEPT a genuinely
@@ -12593,6 +14483,7 @@ function makeDevOrgSpendPort(deps) {
12593
14483
  const recorded = await recordOrgPayment({
12594
14484
  orgId,
12595
14485
  recipientLabel: run.to,
14486
+ ...run.identity,
12596
14487
  recipientSafeAddress,
12597
14488
  amount,
12598
14489
  paymentType,
@@ -12617,12 +14508,14 @@ function makeDevOrgSpendPort(deps) {
12617
14508
  catch: (cause) => orgErrorFromCapxul("readSpendAuthority", Errors.providerError("capxul-mcp", "readSpendAuthority", cause))
12618
14509
  }),
12619
14510
  submitSpendViaPayments: (input) => submitRuns(String(input.orgId), [{
12620
- to: input.input.to,
14511
+ to: refToMcpRecipient(input.input.to),
14512
+ identity: recipientIdentityFromRef(input.input.to),
12621
14513
  amount: money(input.input.amount),
12622
14514
  ...input.input.document === void 0 ? {} : { document: input.input.document }
12623
14515
  }], "org.spendViaPayments").pipe(Effect.map((payments) => payments[0])),
12624
14516
  submitBatchPayroll: (input) => submitRuns(String(input.orgId), input.runs.map(({ run }) => ({
12625
- to: run.to,
14517
+ to: refToMcpRecipient(run.to),
14518
+ identity: recipientIdentityFromRef(run.to),
12626
14519
  amount: money(run.amount),
12627
14520
  ...run.payslip === void 0 ? {} : { document: run.payslip }
12628
14521
  })), "org.batchPayroll")
@@ -12729,6 +14622,7 @@ async function submitFromMemberSafe(input) {
12729
14622
  policyId: input.deps.policyId,
12730
14623
  callData: input.callData,
12731
14624
  method: input.operation,
14625
+ mapReverts: true,
12732
14626
  waitReceiptMs: input.deps.waitReceiptMs ?? 18e4,
12733
14627
  ...input.deps.pollIntervalMs === void 0 ? {} : { pollIntervalMs: input.deps.pollIntervalMs },
12734
14628
  ...input.onUserOpHash === void 0 ? {} : { onUserOpHash: input.onUserOpHash }
@@ -12753,19 +14647,18 @@ async function sendCapxulPayment(input) {
12753
14647
  const tokenAddress = port.requireAllowlistedToken();
12754
14648
  const deps = input.deps ?? {};
12755
14649
  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);
14650
+ const rawAmount = settlementMoneyToRawUnits(input.amount);
14651
+ const recipient = normalizeSettlementRecipient(input.recipientAddress);
12759
14652
  const recipientBefore = (await readBalance({
12760
14653
  chainId,
12761
14654
  tokenAddress,
12762
14655
  holderAddress: recipient
12763
14656
  })).rawBalance;
12764
- const callData = buildCapxulPaymentsPersonalSendCallData({
12765
- tokenAddress,
12766
- recipientAddress: recipient,
12767
- amount: rawAmount,
12768
- documentHash,
14657
+ const callData = buildPaymentSettlementCallData({
14658
+ recipient,
14659
+ amount: input.amount,
14660
+ timing: { kind: "instant" },
14661
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash },
12769
14662
  paymentType: input.paymentType
12770
14663
  });
12771
14664
  const confirmed = await port.submitAndConfirm({
@@ -12845,19 +14738,17 @@ function submitCommitment(port, args) {
12845
14738
  async function executeCommitmentCreate(input) {
12846
14739
  const result = await guard("payments.pay", async () => {
12847
14740
  const port = input.port ?? directBaseSettlementPort();
12848
- const tokenAddress = port.requireAllowlistedToken();
12849
14741
  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,
14742
+ const callData = buildPaymentSettlementCallData({
14743
+ recipient: input.recipientAddress,
14744
+ amount: input.amount,
14745
+ timing: {
14746
+ kind: "stream",
14747
+ startsAt: input.startTime,
14748
+ cliffAt: input.cliffTime,
14749
+ endsAt: input.endTime
14750
+ },
14751
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash },
12861
14752
  paymentType: input.paymentType
12862
14753
  });
12863
14754
  const submitted = await submitCommitment(port, {
@@ -12891,7 +14782,10 @@ async function executeCommitmentCreate(input) {
12891
14782
  async function executeCommitmentClaim(input) {
12892
14783
  return guard("payments.claim", async () => {
12893
14784
  const port = input.port ?? directBaseSettlementPort();
12894
- const callData = buildCapxulCommitmentClaimCallData(BigInt(input.onchainCommitmentId));
14785
+ const callData = buildCommitmentLifecycleSettlementCallData({
14786
+ kind: "claim",
14787
+ onchainCommitmentId: input.onchainCommitmentId
14788
+ });
12895
14789
  const submitted = await submitCommitment(port, {
12896
14790
  signer: input.signer,
12897
14791
  payerEmail: input.recipientEmail,
@@ -12913,7 +14807,11 @@ async function executeCommitmentClaim(input) {
12913
14807
  async function executeCommitmentCancel(input) {
12914
14808
  return guard("payments.cancel", async () => {
12915
14809
  const port = input.port ?? directBaseSettlementPort();
12916
- const callData = buildCapxulCommitmentCancelCallData(BigInt(input.onchainCommitmentId), port.normalizeDocumentHash(input.documentHash));
14810
+ const callData = buildCommitmentLifecycleSettlementCallData({
14811
+ kind: "cancel",
14812
+ onchainCommitmentId: input.onchainCommitmentId,
14813
+ ...input.documentHash === void 0 ? {} : { documentHash: input.documentHash }
14814
+ });
12917
14815
  const submitted = await submitCommitment(port, {
12918
14816
  signer: input.signer,
12919
14817
  payerEmail: input.creatorEmail,
@@ -12935,7 +14833,12 @@ async function executeCommitmentCancel(input) {
12935
14833
  async function executeCommitmentRedirect(input) {
12936
14834
  return guard("payments.redirect", async () => {
12937
14835
  const port = input.port ?? directBaseSettlementPort();
12938
- const callData = buildCapxulCommitmentRedirectCallData(BigInt(input.onchainCommitmentId), port.normalizeRecipient(input.newRecipientAddress), port.normalizeDocumentHash(input.newDocumentHash));
14836
+ const callData = buildCommitmentLifecycleSettlementCallData({
14837
+ kind: "redirect",
14838
+ onchainCommitmentId: input.onchainCommitmentId,
14839
+ newRecipient: input.newRecipientAddress,
14840
+ ...input.newDocumentHash === void 0 ? {} : { newDocumentHash: input.newDocumentHash }
14841
+ });
12939
14842
  const submitted = await submitCommitment(port, {
12940
14843
  signer: input.signer,
12941
14844
  payerEmail: input.creatorEmail,
@@ -12960,8 +14863,8 @@ async function executeCommitmentRedirect(input) {
12960
14863
  */
12961
14864
  async function fetchCommitmentCreatedIdFromLogs(input) {
12962
14865
  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");
14866
+ const { fetchCommitmentCreatedLog } = await import("./alchemy-rpc-DxVP2GsG.mjs");
14867
+ const { CAPXUL_PAYMENTS_ADDRESS } = await import("./src-BmSYoMhj.mjs");
12965
14868
  const topic0 = keccak256(toBytes("CommitmentCreated(uint256,address,address,address,uint256,uint48,uint48,uint48,bytes32,uint8)"));
12966
14869
  const idTopic = (await fetchCommitmentCreatedLog({
12967
14870
  chainId: input.chainId,
@@ -12975,6 +14878,29 @@ async function fetchCommitmentCreatedIdFromLogs(input) {
12975
14878
  }
12976
14879
  //#endregion
12977
14880
  //#region src/sdk.ts
14881
+ function refFromMcpRecipient(recipient) {
14882
+ const trimmed = recipient.trim();
14883
+ if (/^payee_[0-9A-Za-z]+$/.test(trimmed)) return {
14884
+ kind: "payeeId",
14885
+ payeeId: trimmed
14886
+ };
14887
+ if (/^user_[0-9A-Za-z]+$/.test(trimmed)) return {
14888
+ kind: "capxulUserId",
14889
+ capxulUserId: trimmed
14890
+ };
14891
+ if (trimmed.startsWith("@")) return {
14892
+ kind: "handle",
14893
+ handle: trimmed.slice(1)
14894
+ };
14895
+ if (trimmed.includes("@")) return {
14896
+ kind: "email",
14897
+ email: trimmed
14898
+ };
14899
+ return {
14900
+ kind: "orgHandle",
14901
+ orgHandle: trimmed
14902
+ };
14903
+ }
12978
14904
  function toMcpOrgView(view) {
12979
14905
  return {
12980
14906
  orgId: String(view.id),
@@ -13035,6 +14961,26 @@ function toMcpRoleView(view) {
13035
14961
  canManageRoles: view.definition.canManageRoles ?? false
13036
14962
  };
13037
14963
  }
14964
+ function actorBundle(client, actor) {
14965
+ return actor.kind === "account" ? client.account : client.org(toOrgId(actor.orgId));
14966
+ }
14967
+ function actorForSdk(actor) {
14968
+ if (actor === void 0) return void 0;
14969
+ return actor.kind === "account" ? { kind: "account" } : {
14970
+ kind: "org",
14971
+ orgId: actor.orgId
14972
+ };
14973
+ }
14974
+ function moneyForSdk(amount) {
14975
+ return {
14976
+ currency: toCurrencyCode(amount.currency),
14977
+ value: amount.value,
14978
+ decimals: amount.decimals
14979
+ };
14980
+ }
14981
+ function transferEndpoint(value) {
14982
+ return value === "main" ? "main" : toSubAccountId(value);
14983
+ }
13038
14984
  const PAYMENT_TYPE_UINT8 = {
13039
14985
  unspecified: 0,
13040
14986
  invoice: 1,
@@ -13217,13 +15163,9 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13217
15163
  getMe: async () => {
13218
15164
  const result = await client.me.get();
13219
15165
  if (!result.ok) return result;
13220
- const withChain = result.value;
13221
15166
  return {
13222
15167
  ok: true,
13223
- value: {
13224
- ...result.value,
13225
- chainId: withChain.chainId ?? 84532
13226
- }
15168
+ value: result.value
13227
15169
  };
13228
15170
  },
13229
15171
  getDepositInstructions: () => client.me.depositInstructions(),
@@ -13269,11 +15211,92 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13269
15211
  value: res.value.map(toMcpRoleView)
13270
15212
  } : res;
13271
15213
  },
15214
+ orgPendingMembers: async (orgId) => {
15215
+ const res = await client.org(toOrgId(orgId)).pendingMembers();
15216
+ return res.ok ? {
15217
+ ok: true,
15218
+ value: res.value.map(toMcpMemberView)
15219
+ } : res;
15220
+ },
15221
+ addressBookList: (actor) => actorBundle(client, actor).addressBook.list(),
15222
+ addressBookGet: (actor, entryId) => actorBundle(client, actor).addressBook.get(entryId),
15223
+ addressBookAdd: (input) => actorBundle(client, input.actor).addressBook.add({
15224
+ ref: input.ref,
15225
+ ...input.label === void 0 ? {} : { label: input.label }
15226
+ }),
15227
+ addressBookHide: (actor, entryId) => actorBundle(client, actor).addressBook.hide(entryId),
15228
+ addressBookUnhide: (actor, entryId) => actorBundle(client, actor).addressBook.unhide(entryId),
15229
+ addressBookLabel: (input) => actorBundle(client, input.actor).addressBook.label({
15230
+ entryId: input.entryId,
15231
+ label: input.label
15232
+ }),
15233
+ actorRequestIssue: (input) => actorBundle(client, input.actor).requests.issue({
15234
+ payer: input.payer,
15235
+ amount: input.amount,
15236
+ reference: input.reference,
15237
+ ...input.memo === void 0 ? {} : { memo: input.memo },
15238
+ ...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt }
15239
+ }),
15240
+ actorRequestsList: (actor) => actorBundle(client, actor).requests.list(),
15241
+ actorRequestsGet: (actor, requestId) => actorBundle(client, actor).requests.get(requestId),
15242
+ actorRequestsCancel: (actor, requestId) => actorBundle(client, actor).requests.cancel(requestId),
15243
+ actorRequestsReconcile: (actor) => actorBundle(client, actor).requests.reconcile(),
15244
+ inboxList: (actor) => actorBundle(client, actor).inbox.list(),
15245
+ inboxApprove: (actor, requestId, timing) => actorBundle(client, actor).inbox.approve({
15246
+ requestId,
15247
+ ...timing === void 0 ? {} : { timing }
15248
+ }),
15249
+ inboxDecline: (actor, requestId) => actorBundle(client, actor).inbox.decline(requestId),
15250
+ insightsSummary: (actor) => actorBundle(client, actor).insights.summary(),
15251
+ insightsHistory: (actor) => actorBundle(client, actor).insights.history(),
15252
+ addDestination: (input) => client.destinations.add({
15253
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15254
+ ref: input.ref,
15255
+ kind: input.kind,
15256
+ ...input.label === void 0 ? {} : { label: input.label },
15257
+ payload: input.payload
15258
+ }),
15259
+ listDestinations: (input) => client.destinations.list({
15260
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15261
+ ref: input.ref
15262
+ }),
15263
+ removeDestination: (input) => client.destinations.remove({
15264
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15265
+ destinationId: input.destinationId
15266
+ }),
15267
+ payout: (input) => client.payments.payout({
15268
+ ...actorForSdk(input.actor) === void 0 ? {} : { actor: actorForSdk(input.actor) },
15269
+ destinationId: input.destinationId,
15270
+ amount: moneyForSdk(input.amount)
15271
+ }),
15272
+ transfer: (input) => client.subAccounts.transfer({
15273
+ from: transferEndpoint(input.from),
15274
+ to: transferEndpoint(input.to),
15275
+ amount: moneyForSdk(input.amount)
15276
+ }),
15277
+ payrollRosterAdd: (input) => client.org(toOrgId(input.orgId)).payroll.roster.add({
15278
+ employee: input.employee,
15279
+ amount: moneyForSdk(input.amount),
15280
+ timing: input.timing,
15281
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: input.payslipTemplate }
15282
+ }),
15283
+ payrollRosterList: (orgId) => client.org(toOrgId(orgId)).payroll.roster.list(),
15284
+ payrollRosterUpdate: (input) => client.org(toOrgId(input.orgId)).payroll.roster.update(input.rosterLineId, {
15285
+ ...input.employee === void 0 ? {} : { employee: input.employee },
15286
+ ...input.amount === void 0 ? {} : { amount: moneyForSdk(input.amount) },
15287
+ ...input.timing === void 0 ? {} : { timing: input.timing },
15288
+ ...input.payslipTemplate === void 0 ? {} : { payslipTemplate: input.payslipTemplate }
15289
+ }),
15290
+ payrollRosterRemove: (orgId, rosterLineId) => client.org(toOrgId(orgId)).payroll.roster.remove(rosterLineId),
15291
+ payrollRun: (input) => client.org(toOrgId(input.orgId)).payroll.run({
15292
+ period: input.period,
15293
+ from: toSubAccountId(input.from)
15294
+ }),
13272
15295
  draftPayment: (input) => client.workbench.draft({
13273
15296
  clientId: input.clientId,
13274
15297
  audience: input.audience,
13275
15298
  scopes: input.scopes,
13276
- to: input.to,
15299
+ to: refFromMcpRecipient(input.to),
13277
15300
  amount: input.amount,
13278
15301
  idempotencyKey: input.idempotencyKey,
13279
15302
  ...input.document === void 0 ? {} : { document: input.document },
@@ -13294,10 +15317,10 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13294
15317
  error: Errors.notAuthenticated("no active session")
13295
15318
  };
13296
15319
  const recorded = await client.payments.pay({
13297
- to: input.to,
15320
+ to: refFromMcpRecipient(input.to),
13298
15321
  amount: input.amount,
13299
15322
  ...input.document === void 0 ? {} : { document: input.document },
13300
- ...input.release === void 0 ? {} : { release: input.release },
15323
+ ...input.release === void 0 ? {} : { timing: input.release },
13301
15324
  ...input.lineItems === void 0 ? {} : { lineItems: input.lineItems }
13302
15325
  });
13303
15326
  if (!recorded.ok) return recorded;
@@ -13442,7 +15465,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13442
15465
  if (!executed.ok) return executed;
13443
15466
  return client.payments._internal.redirect({
13444
15467
  paymentId,
13445
- to,
15468
+ to: refFromMcpRecipient(to),
13446
15469
  evidence: makeOnchainEvidence({
13447
15470
  userOpHash: executed.value.userOpHash,
13448
15471
  txHash: executed.value.txHash
@@ -13499,7 +15522,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13499
15522
  const amount = input.amount;
13500
15523
  return client.org(toOrgId(input.orgId)).spendViaPayments({
13501
15524
  from: toSubAccountId(input.from),
13502
- to: input.to,
15525
+ to: refFromMcpRecipient(input.to),
13503
15526
  amount: {
13504
15527
  currency: toCurrencyCode(amount.currency),
13505
15528
  value: amount.value,
@@ -13512,7 +15535,7 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13512
15535
  orgBatchPayroll: async (input) => client.org(toOrgId(input.orgId)).batchPayroll({
13513
15536
  from: toSubAccountId(input.from),
13514
15537
  runs: input.runs.map((run) => ({
13515
- to: run.to,
15538
+ to: refFromMcpRecipient(run.to),
13516
15539
  amount: {
13517
15540
  currency: toCurrencyCode(run.amount.currency),
13518
15541
  value: run.amount.value,
@@ -13543,6 +15566,13 @@ function makeSdkClientFactory(config, options = { mode: { mode: "live" } }) {
13543
15566
  value: toMcpMemberView(res.value)
13544
15567
  } : res;
13545
15568
  },
15569
+ orgInviteTokenResend: async (input) => {
15570
+ const res = await client.org(toOrgId(input.orgId)).inviteToken.resend({ email: input.email });
15571
+ return res.ok ? {
15572
+ ok: true,
15573
+ value: toMcpMemberView(res.value)
15574
+ } : res;
15575
+ },
13546
15576
  orgAssignRole: async (input) => {
13547
15577
  const resolved = await resolveMemberSafeAddress(client, input.orgId, input.email, "org.assignRole");
13548
15578
  if (!resolved.ok) return resolved;
@@ -13652,7 +15682,9 @@ function buildDevOrgPort(input) {
13652
15682
  listOrgs: deploymentAdapter.listOrgs.bind(deploymentAdapter),
13653
15683
  listRoles: deploymentAdapter.listRoles.bind(deploymentAdapter),
13654
15684
  listMembers: deploymentAdapter.listMembers.bind(deploymentAdapter),
15685
+ pendingMembers: deploymentAdapter.pendingMembers.bind(deploymentAdapter),
13655
15686
  inviteMember: deploymentAdapter.inviteMember.bind(deploymentAdapter),
15687
+ resendInviteToken: deploymentAdapter.resendInviteToken.bind(deploymentAdapter),
13656
15688
  detectAndAcceptPendingInvitations: deploymentAdapter.detectAndAcceptPendingInvitations.bind(deploymentAdapter),
13657
15689
  deployRoles: deploymentAdapter.deployRoles.bind(deploymentAdapter),
13658
15690
  grantRole: deploymentAdapter.grantRole.bind(deploymentAdapter),