@capxul/mcp 1.0.0-alpha.20 → 1.0.0-alpha.21

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.
Files changed (2) hide show
  1. package/dist/main.mjs +240 -114
  2. package/package.json +2 -2
package/dist/main.mjs CHANGED
@@ -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.20";
235
+ var version$1 = "1.0.0-alpha.21";
236
236
  //#endregion
237
237
  //#region src/tool-result.ts
238
238
  function okResult(structured) {
@@ -1649,6 +1649,10 @@ const FIELD_RULES = {
1649
1649
  maxLength: 128,
1650
1650
  pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
1651
1651
  },
1652
+ journeyId: {
1653
+ maxLength: 128,
1654
+ pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
1655
+ },
1652
1656
  correlationId: {
1653
1657
  maxLength: 128,
1654
1658
  pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u
@@ -4162,6 +4166,41 @@ function captureExceptionSync(telemetry, error, context) {
4162
4166
  } catch {}
4163
4167
  }
4164
4168
  //#endregion
4169
+ //#region ../../packages/sdk/src/internal/invocation-observation.ts
4170
+ const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
4171
+ const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
4172
+ /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
4173
+ function attachInvocationObservation(target, context) {
4174
+ const snapshot = Object.freeze(context === void 0 ? {} : { context: Object.freeze({ ...context }) });
4175
+ Object.defineProperty(target, INVOCATION_OBSERVATION, {
4176
+ configurable: false,
4177
+ enumerable: false,
4178
+ value: snapshot,
4179
+ writable: false
4180
+ });
4181
+ return target;
4182
+ }
4183
+ /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
4184
+ function readInvocationObservation(source) {
4185
+ if (typeof source !== "object" || source === null) return void 0;
4186
+ return source[INVOCATION_OBSERVATION];
4187
+ }
4188
+ /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
4189
+ function copyInvocationObservation(source, target) {
4190
+ const snapshot = readInvocationObservation(source);
4191
+ return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot.context);
4192
+ }
4193
+ /** @internal Mark a failure envelope as already resolved at the public invocation boundary. */
4194
+ function markFailureInvocationSnapshot(failure) {
4195
+ Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
4196
+ configurable: false,
4197
+ enumerable: false,
4198
+ value: true,
4199
+ writable: false
4200
+ });
4201
+ return failure;
4202
+ }
4203
+ //#endregion
4165
4204
  //#region ../../packages/sdk/src/client/_shared/effect-actor-bridge.ts
4166
4205
  /**
4167
4206
  * Bridge an Effect whose typed failure carries `{ publicError: CapxulError }`
@@ -5004,7 +5043,7 @@ function makeAccountMethods(deps) {
5004
5043
  };
5005
5044
  };
5006
5045
  const deployMutex = /* @__PURE__ */ new Map();
5007
- const deploySafeImpl = async () => {
5046
+ const deploySafeImpl = async (observationSource) => {
5008
5047
  const session = await currentSession(deps.actor, deps.authCache);
5009
5048
  if (session === null) return {
5010
5049
  ok: false,
@@ -5032,7 +5071,8 @@ function makeAccountMethods(deps) {
5032
5071
  authUserId: session.authUserId,
5033
5072
  chainId: deps.chainId,
5034
5073
  signer,
5035
- smartAccountPort: deps.smartAccountPort
5074
+ smartAccountPort: deps.smartAccountPort,
5075
+ observationSource
5036
5076
  }).finally(() => {
5037
5077
  deployMutex.delete(mutexKey);
5038
5078
  });
@@ -5156,11 +5196,11 @@ async function runBackendClaim(input) {
5156
5196
  error: Errors.providerError("signer", "getAddress", cause)
5157
5197
  };
5158
5198
  }
5159
- const claimed = await runPortEffect(input.smartAccountPort.claim({
5199
+ const claimed = await runPortEffect(input.smartAccountPort.claim(copyInvocationObservation(input.observationSource, {
5160
5200
  authUserId: input.authUserId,
5161
5201
  chainId,
5162
5202
  signerAddress
5163
- }));
5203
+ })));
5164
5204
  if (!claimed.ok) return claimed;
5165
5205
  return {
5166
5206
  ok: true,
@@ -5302,7 +5342,7 @@ async function recoverRawDigestSigner(input) {
5302
5342
  }
5303
5343
  //#endregion
5304
5344
  //#region ../../packages/sdk/package.json
5305
- var version = "1.0.0-alpha.20";
5345
+ var version = "1.0.0-alpha.21";
5306
5346
  //#endregion
5307
5347
  //#region ../../packages/sdk/src/ports/auth-client.ts
5308
5348
  var AuthClientError = class extends Data.TaggedError("AuthClientError") {};
@@ -6214,44 +6254,10 @@ function convexCallErrorFromCapxul(operation, error) {
6214
6254
  }
6215
6255
  var ConvexCallPortTag = class extends Context.Tag("@capxul/sdk/ports/ConvexCallPort")() {};
6216
6256
  //#endregion
6217
- //#region ../../packages/sdk/src/internal/invocation-observation.ts
6218
- const INVOCATION_OBSERVATION = Symbol("capxul.invocation-observation");
6219
- const FAILURE_INVOCATION_SNAPSHOT = Symbol("capxul.failure-invocation-snapshot");
6220
- /** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */
6221
- function attachInvocationObservation(target, context) {
6222
- const snapshot = Object.freeze(context === void 0 ? {} : { context: Object.freeze({ ...context }) });
6223
- Object.defineProperty(target, INVOCATION_OBSERVATION, {
6224
- configurable: false,
6225
- enumerable: false,
6226
- value: snapshot,
6227
- writable: false
6228
- });
6229
- return target;
6230
- }
6231
- /** @internal Read the snapshot without exposing its symbol or adding a wire field. */
6232
- function readInvocationObservation(source) {
6233
- if (typeof source !== "object" || source === null) return void 0;
6234
- return source[INVOCATION_OBSERVATION];
6235
- }
6236
- /** @internal Carry a snapshot across an SDK adapter projection without resolving again. */
6237
- function copyInvocationObservation(source, target) {
6238
- const snapshot = readInvocationObservation(source);
6239
- return snapshot === void 0 ? target : attachInvocationObservation(target, snapshot.context);
6240
- }
6241
- /** @internal Mark a failure envelope as already resolved at the public invocation boundary. */
6242
- function markFailureInvocationSnapshot(failure) {
6243
- Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {
6244
- configurable: false,
6245
- enumerable: false,
6246
- value: true,
6247
- writable: false
6248
- });
6249
- return failure;
6250
- }
6251
- //#endregion
6252
6257
  //#region ../../packages/sdk/src/adapters/convex-call/ConvexCallAdapter.ts
6253
6258
  /** Exact floor-first allowlist; every additional handler must migrate its validator first. */
6254
- const OBSERVED_CONVEX_ACTIONS = new Set(["subAccount/actions:transfer"]);
6259
+ const OBSERVED_CONVEX_ACTIONS = new Set(["subAccount/actions:transfer", "smartAccount/actions:claim"]);
6260
+ const OBSERVED_CONVEX_MUTATIONS = new Set(["org/lifecycle:startOrResume", "org/lifecycle:retry"]);
6255
6261
  var ConvexCallAdapter = class {
6256
6262
  #client;
6257
6263
  #tokenProvider;
@@ -6274,20 +6280,21 @@ var ConvexCallAdapter = class {
6274
6280
  });
6275
6281
  }
6276
6282
  mutation(fn, args) {
6283
+ const path = getFunctionName(fn);
6277
6284
  return Effect.tryPromise({
6278
- try: () => this.#client.mutation(fn, args),
6279
- catch: (cause) => mapToConvexCallError(getFunctionName(fn), cause)
6285
+ try: () => this.#client.mutation(fn, this.#observedArgs(OBSERVED_CONVEX_MUTATIONS, path, args)),
6286
+ catch: (cause) => mapToConvexCallError(path, cause)
6280
6287
  });
6281
6288
  }
6282
6289
  action(fn, args) {
6283
6290
  const path = getFunctionName(fn);
6284
6291
  return Effect.tryPromise({
6285
- try: () => this.#client.action(fn, this.#observedActionArgs(path, args)),
6292
+ try: () => this.#client.action(fn, this.#observedArgs(OBSERVED_CONVEX_ACTIONS, path, args)),
6286
6293
  catch: (cause) => mapToConvexCallError(path, cause)
6287
6294
  });
6288
6295
  }
6289
- #observedActionArgs(path, args) {
6290
- if (!OBSERVED_CONVEX_ACTIONS.has(path)) return args;
6296
+ #observedArgs(allowlist, path, args) {
6297
+ if (!allowlist.has(path)) return args;
6291
6298
  let hostContext;
6292
6299
  const invocationSnapshot = readInvocationObservation(args);
6293
6300
  if (invocationSnapshot !== void 0) hostContext = invocationSnapshot.context;
@@ -6877,6 +6884,8 @@ function brandProfile(raw) {
6877
6884
  email: toEmail(raw.email),
6878
6885
  displayName: raw.displayName,
6879
6886
  country: raw.country === null ? null : toCountryCode(raw.country),
6887
+ onboarded: raw.onboarded ?? false,
6888
+ withdrawalAddress: raw.withdrawalAddress === null || raw.withdrawalAddress === void 0 ? null : toAddress(raw.withdrawalAddress),
6880
6889
  kycTier: toKycTier(raw.kycTier),
6881
6890
  createdAt: toEpochMs(raw.createdAt),
6882
6891
  updatedAt: toEpochMs(raw.updatedAt)
@@ -7136,11 +7145,11 @@ var ConvexSmartAccountAdapter = class {
7136
7145
  })), Effect.catchAllDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("confirmDeployment", cause))));
7137
7146
  }
7138
7147
  claim(input) {
7139
- return this.#convex.action(this.#fns.claim, {
7148
+ return this.#convex.action(this.#fns.claim, copyInvocationObservation(input, {
7140
7149
  chainId: wireChainId(input.chainId),
7141
7150
  signerAddress: input.signerAddress,
7142
7151
  ...input.telemetryRunId === void 0 ? {} : { telemetryRunId: input.telemetryRunId }
7143
- }).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("claim", error.publicError, error)), Effect.flatMap((row) => Effect.try({
7152
+ })).pipe(Effect.mapError((error) => smartAccountErrorFromCapxul("claim", error.publicError, error)), Effect.flatMap((row) => Effect.try({
7144
7153
  try: () => brandProvisionedSmartAccount(input.authUserId, row),
7145
7154
  catch: (cause) => smartAccountErrorFromUnknown("claim", cause)
7146
7155
  })), Effect.catchAllDefect((cause) => Effect.fail(smartAccountErrorFromUnknown("claim", cause))));
@@ -7402,14 +7411,19 @@ const DEFAULT_FUNCTIONS$1 = {
7402
7411
  var ConvexOrganizationSetupAdapter = class {
7403
7412
  #convex;
7404
7413
  #signer;
7414
+ #chainId;
7405
7415
  #fns;
7406
7416
  constructor(input) {
7407
7417
  this.#convex = input.convex;
7408
7418
  this.#signer = input.signer;
7419
+ this.#chainId = input.chainId;
7409
7420
  this.#fns = input.functions ?? DEFAULT_FUNCTIONS$1;
7410
7421
  }
7411
7422
  async startOrResume(input) {
7412
- const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, input));
7423
+ const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, copyInvocationObservation(input, {
7424
+ ...input,
7425
+ chainId: this.#chainId
7426
+ })));
7413
7427
  if (!result.ok) return result;
7414
7428
  const lifecycle = parseLifecycle("startOrResume", result.value.lifecycle);
7415
7429
  if (!lifecycle.ok) return lifecycle;
@@ -7425,17 +7439,17 @@ var ConvexOrganizationSetupAdapter = class {
7425
7439
  };
7426
7440
  }
7427
7441
  prepareFounderAccount(input) {
7428
- return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, { orgId: input.orgId }));
7442
+ return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, copyInvocationObservation(input, { orgId: input.orgId })));
7429
7443
  }
7430
7444
  async authorizeAndSubmitBootstrap(input) {
7431
7445
  const cancelled = cancellation(input.signal);
7432
7446
  if (cancelled !== void 0) return cancelled;
7433
7447
  const signerAddress = await signerResult("getAddress", () => this.#signer.getAddress());
7434
7448
  if (!signerAddress.ok) return signerAddress;
7435
- const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, {
7449
+ const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, copyInvocationObservation(input, {
7436
7450
  orgId: input.orgId,
7437
7451
  signerAddress: signerAddress.value
7438
- }));
7452
+ })));
7439
7453
  if (!prepared.ok) return prepared;
7440
7454
  const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);
7441
7455
  if (!authority.ok) return authority;
@@ -7445,25 +7459,25 @@ var ConvexOrganizationSetupAdapter = class {
7445
7459
  if (!signature.ok) return signature;
7446
7460
  const cancelledAfterSign = cancellation(input.signal);
7447
7461
  if (cancelledAfterSign !== void 0) return cancelledAfterSign;
7448
- const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, {
7462
+ const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, copyInvocationObservation(input, {
7449
7463
  orgId: input.orgId,
7450
7464
  signerAddress: signerAddress.value,
7451
7465
  signature: signature.value,
7452
7466
  userOp: prepared.value.userOp
7453
- }));
7467
+ })));
7454
7468
  if (!submitted.ok) return submitted;
7455
7469
  return parseLifecycle("submitBootstrap", submitted.value);
7456
7470
  }
7457
7471
  resumeSubmittedBootstrap(input) {
7458
- return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, { orgId: input.orgId }));
7472
+ return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, copyInvocationObservation(input, { orgId: input.orgId })));
7459
7473
  }
7460
7474
  confirmSubmittedBootstrap(input) {
7461
- return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, { orgId: input.orgId }));
7475
+ return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, copyInvocationObservation(input, { orgId: input.orgId })));
7462
7476
  }
7463
7477
  async recordFailure(input) {
7464
7478
  const errorProvider = input.error.details?.provider;
7465
7479
  const errorOperation = input.error.details?.operation;
7466
- const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, {
7480
+ const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, copyInvocationObservation(input, {
7467
7481
  orgId: input.orgId,
7468
7482
  errorCode: input.error.code,
7469
7483
  ...typeof errorProvider === "string" && typeof errorOperation === "string" ? {
@@ -7471,7 +7485,7 @@ var ConvexOrganizationSetupAdapter = class {
7471
7485
  errorOperation
7472
7486
  } : {},
7473
7487
  retryable: input.retryable
7474
- }));
7488
+ })));
7475
7489
  return result.ok ? parseLifecycle("recordFailure", result.value) : result;
7476
7490
  }
7477
7491
  async loadLifecycle(input) {
@@ -7489,7 +7503,7 @@ var ConvexOrganizationSetupAdapter = class {
7489
7503
  const reset = resetSignerSession(this.#signer);
7490
7504
  if (!reset.ok) return reset;
7491
7505
  }
7492
- const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, { orgId: input.orgId }));
7506
+ const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, copyInvocationObservation(input, { orgId: input.orgId })));
7493
7507
  if (!result.ok) return result;
7494
7508
  return parseLifecycle("retry", result.value);
7495
7509
  }
@@ -7674,6 +7688,7 @@ const PayeeIdTelemetrySchema = Schema.String.pipe(Schema.filter((value) => PAYEE
7674
7688
  const DocumentHashSchema = Schema.String.pipe(Schema.filter((value) => BYTES32_RE$2.test(value), { message: () => "must be 0x + 64 hex chars" }));
7675
7689
  const TelemetryEnvelopeProps = {
7676
7690
  capxul_e2e_run_id: OptionalString,
7691
+ journeyId: OptionalString,
7677
7692
  correlationId: OptionalString,
7678
7693
  capxulEnv: OptionalString,
7679
7694
  sdkVersion: OptionalString,
@@ -7805,6 +7820,46 @@ const TransferFailedProps = Schema.Struct({
7805
7820
  const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
7806
7821
  const OrgIdTelemetrySchema = Schema.String.pipe(Schema.filter((value) => ORG_ID_TELEMETRY_RE.test(value), { message: () => "must be org_ plus an alphanumeric id" }));
7807
7822
  const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
7823
+ const AttemptNumberSchema = Schema.Number.pipe(Schema.filter((value) => Number.isSafeInteger(value) && value > 0, { message: () => "must be a positive safe integer" }));
7824
+ const OnboardingStageSchema = Schema.Literal("profile", "accountProvisioning", "accountClaim", "preparingFounderAccount", "awaitingFounderAuthorization", "submittingBootstrap", "confirmingBootstrap");
7825
+ const MemberActivationStartedProps = Schema.Struct({
7826
+ $insert_id: Schema.String,
7827
+ producer: Schema.Literal("server")
7828
+ });
7829
+ const MemberActivationReadyProps = Schema.Struct({
7830
+ $insert_id: Schema.String,
7831
+ duration_ms: DurationMsSchema,
7832
+ producer: Schema.Literal("server")
7833
+ });
7834
+ const MemberActivationFailedProps = Schema.Struct({
7835
+ $insert_id: Schema.String,
7836
+ stage: OnboardingStageSchema,
7837
+ error_code: Schema.String,
7838
+ retryable: Schema.Boolean,
7839
+ producer: Schema.Literal("server")
7840
+ });
7841
+ const OrganizationCreationStartedProps = Schema.Struct({
7842
+ $insert_id: Schema.String,
7843
+ organization_id: OrgIdTelemetrySchema,
7844
+ attempt_number: AttemptNumberSchema,
7845
+ producer: Schema.Literal("server")
7846
+ });
7847
+ const OrganizationCreationReadyProps = Schema.Struct({
7848
+ $insert_id: Schema.String,
7849
+ organization_id: OrgIdTelemetrySchema,
7850
+ attempt_number: AttemptNumberSchema,
7851
+ duration_ms: DurationMsSchema,
7852
+ producer: Schema.Literal("server")
7853
+ });
7854
+ const OrganizationCreationFailedProps = Schema.Struct({
7855
+ $insert_id: Schema.String,
7856
+ organization_id: OrgIdTelemetrySchema,
7857
+ attempt_number: AttemptNumberSchema,
7858
+ stage: OnboardingStageSchema,
7859
+ error_code: Schema.String,
7860
+ retryable: Schema.Boolean,
7861
+ producer: Schema.Literal("server")
7862
+ });
7808
7863
  const OrgCreateStartedProps = Schema.Struct({
7809
7864
  ...TelemetryEnvelopeProps,
7810
7865
  org_id: OptionalOrgId,
@@ -7966,6 +8021,30 @@ Schema.Struct({
7966
8021
  name: Schema.Literal("bootstrap_failed"),
7967
8022
  props: Schema.optional(BootstrapFailedProps)
7968
8023
  });
8024
+ Schema.Struct({
8025
+ name: Schema.Literal("member_activation_started"),
8026
+ props: MemberActivationStartedProps
8027
+ });
8028
+ Schema.Struct({
8029
+ name: Schema.Literal("member_activation_ready"),
8030
+ props: MemberActivationReadyProps
8031
+ });
8032
+ Schema.Struct({
8033
+ name: Schema.Literal("member_activation_failed"),
8034
+ props: MemberActivationFailedProps
8035
+ });
8036
+ Schema.Struct({
8037
+ name: Schema.Literal("organization_creation_started"),
8038
+ props: OrganizationCreationStartedProps
8039
+ });
8040
+ Schema.Struct({
8041
+ name: Schema.Literal("organization_creation_ready"),
8042
+ props: OrganizationCreationReadyProps
8043
+ });
8044
+ Schema.Struct({
8045
+ name: Schema.Literal("organization_creation_failed"),
8046
+ props: OrganizationCreationFailedProps
8047
+ });
7969
8048
  Schema.Struct({
7970
8049
  name: Schema.Literal("account_balance_read"),
7971
8050
  props: Schema.optional(AccountBalanceReadProps)
@@ -11209,7 +11288,7 @@ function validateOrganizationLifecycleScope(orgId, lifecycle) {
11209
11288
  };
11210
11289
  }
11211
11290
  /** Advance only the steps still required by one durable Organization lane. */
11212
- async function advanceOrganizationSetup(setup, orgId, initial, signal) {
11291
+ async function advanceOrganizationSetup(setup, orgId, initial, signal, observationSource) {
11213
11292
  const scopedInitial = validateOrganizationLifecycleScope(orgId, initial);
11214
11293
  if (!scopedInitial.ok) return scopedInitial;
11215
11294
  let lifecycle = scopedInitial.value;
@@ -11219,19 +11298,15 @@ async function advanceOrganizationSetup(setup, orgId, initial, signal) {
11219
11298
  value: lifecycle
11220
11299
  };
11221
11300
  const currentStep = lifecycle.step;
11222
- if (signal?.aborted) return recordSetupFailure(setup, orgId, Errors.cancelled({ operation: "organization.setup" }), true);
11223
- const stepInput = {
11301
+ if (signal?.aborted) return recordSetupFailure(setup, orgId, Errors.cancelled({ operation: "organization.setup" }), true, observationSource);
11302
+ const stepInput = copyInvocationObservation(observationSource, {
11224
11303
  orgId,
11225
11304
  ...signal === void 0 ? {} : { signal }
11226
- };
11305
+ });
11227
11306
  const next = lifecycle.step === "preparingFounderAccount" ? await setup.prepareFounderAccount(stepInput) : lifecycle.step === "awaitingFounderAuthorization" ? await setup.authorizeAndSubmitBootstrap(stepInput) : lifecycle.step === "submittingBootstrap" ? await setup.resumeSubmittedBootstrap(stepInput) : await setup.confirmSubmittedBootstrap(stepInput);
11228
- if (!next.ok) {
11229
- if (next.error.code === "CANCELLED") return recordSetupFailure(setup, orgId, next.error, true);
11230
- if (next.error.code === "PROVIDER_ERROR") return recordSetupFailure(setup, orgId, next.error, isRetryableProviderFailure(next.error));
11231
- return next;
11232
- }
11307
+ if (!next.ok) return recordSetupFailure(setup, orgId, next.error, isRetryableOrganizationSetupFailure(next.error), observationSource);
11233
11308
  const scopedNext = validateOrganizationLifecycleScope(orgId, next.value);
11234
- if (!scopedNext.ok) return scopedNext;
11309
+ if (!scopedNext.ok) return recordSetupFailure(setup, orgId, scopedNext.error, false, observationSource);
11235
11310
  lifecycle = scopedNext.value;
11236
11311
  if (currentStep === "confirmingBootstrap") return {
11237
11312
  ok: true,
@@ -11242,7 +11317,7 @@ async function advanceOrganizationSetup(setup, orgId, initial, signal) {
11242
11317
  ok: true,
11243
11318
  value: lifecycle
11244
11319
  };
11245
- return fail$1(Errors.wrongState({
11320
+ return recordSetupFailure(setup, orgId, Errors.wrongState({
11246
11321
  method: "organization.setup",
11247
11322
  currentState: lifecycle.step,
11248
11323
  validStates: [
@@ -11250,23 +11325,28 @@ async function advanceOrganizationSetup(setup, orgId, initial, signal) {
11250
11325
  "ready",
11251
11326
  "failed"
11252
11327
  ]
11253
- }));
11328
+ }), false, observationSource);
11254
11329
  }
11255
- async function recordSetupFailure(setup, orgId, error, retryable) {
11256
- const recorded = await setup.recordFailure({
11330
+ async function recordSetupFailure(setup, orgId, error, retryable, observationSource) {
11331
+ const recorded = await setup.recordFailure(copyInvocationObservation(observationSource, {
11257
11332
  orgId,
11258
11333
  error,
11259
11334
  retryable
11260
- });
11335
+ }));
11261
11336
  if (!recorded.ok) return recorded;
11262
11337
  const scopedRecorded = validateOrganizationLifecycleScope(orgId, recorded.value);
11263
11338
  if (!scopedRecorded.ok) return scopedRecorded;
11264
- return fail$1(error);
11339
+ return scopedRecorded;
11265
11340
  }
11266
11341
  function isRetryableProviderFailure(error) {
11267
11342
  const mode = error.details?.failure_mode;
11268
11343
  return mode !== "auth-origin-mismatch" && mode !== "app-env-allowlist" && mode !== "no-secure-context";
11269
11344
  }
11345
+ function isRetryableOrganizationSetupFailure(error) {
11346
+ if (error.code === "CANCELLED" || error.code === "SIGNER_REJECTED") return true;
11347
+ if (error.code === "PROVIDER_ERROR") return isRetryableProviderFailure(error);
11348
+ return error.code === "NETWORK_ERROR" || error.code === "UNKNOWN";
11349
+ }
11270
11350
  //#endregion
11271
11351
  //#region ../../packages/sdk/src/client/org.ts
11272
11352
  /**
@@ -11339,12 +11419,12 @@ function makeOrgMethods(deps) {
11339
11419
  ok: false,
11340
11420
  error: Errors.notImplemented("organizationSetup", "retrySetup")
11341
11421
  };
11342
- const retried = await setup.retry({
11422
+ const retried = await setup.retry(copyInvocationObservation(options, {
11343
11423
  orgId,
11344
11424
  ...options?.signal === void 0 ? {} : { signal: options.signal }
11345
- });
11425
+ }));
11346
11426
  if (!retried.ok) return retried;
11347
- return advanceOrganizationSetup(setup, orgId, retried.value, options?.signal);
11427
+ return advanceOrganizationSetup(setup, orgId, retried.value, options?.signal, options);
11348
11428
  },
11349
11429
  profile: {
11350
11430
  get(_options) {
@@ -11605,17 +11685,21 @@ async function runCompleteOrganizationOnboarding(ops, input, options) {
11605
11685
  const written = await ops.completeIdentityOnboarding({
11606
11686
  authUserId: session.authUserId,
11607
11687
  email: session.email,
11608
- displayName: validated.value.ownerDisplayName,
11609
- country: validated.value.country
11688
+ displayName: validated.value.profile.displayName,
11689
+ country: validated.value.profile.country,
11690
+ ...validated.value.profile.withdrawalAddress === void 0 ? {} : { withdrawalAddress: validated.value.profile.withdrawalAddress }
11610
11691
  });
11611
11692
  if (!written.ok) return fail(written.error);
11612
- const started = await setup.startOrResume({
11613
- name: validated.value.organizationName,
11614
- handle: validated.value.handle,
11615
- country: validated.value.country
11616
- });
11693
+ const founderAccount = await ops.ensureFounderAccountReady(input);
11694
+ if (!founderAccount.ok) return fail(founderAccount.error);
11695
+ if (options?.signal?.aborted === true) return fail(Errors.cancelled({ operation: "onboarding.completeOrganization" }));
11696
+ const started = await setup.startOrResume(copyInvocationObservation(input, {
11697
+ name: validated.value.organization.name,
11698
+ handle: validated.value.organization.handle,
11699
+ country: validated.value.organization.country
11700
+ }));
11617
11701
  if (!started.ok) return fail(started.error);
11618
- const lifecycle = await advanceOrganizationSetup(setup, started.value.orgId, started.value.lifecycle, options?.signal);
11702
+ const lifecycle = await advanceOrganizationSetup(setup, started.value.orgId, started.value.lifecycle, options?.signal, input);
11619
11703
  if (!lifecycle.ok) {
11620
11704
  const error = lifecycle.error;
11621
11705
  return fail(new CapxulError(error.code, error.message, {
@@ -11637,9 +11721,36 @@ async function runCompleteOrganizationOnboarding(ops, input, options) {
11637
11721
  };
11638
11722
  }
11639
11723
  function validatePersonalInput(input) {
11640
- const displayName = requireNonEmpty(input.displayName, "displayName");
11724
+ if (!isRecord(input) || !isRecord(input.profile)) return fail(Errors.invalidInput("profile", "must be an object"));
11725
+ return validateProfileInput(input.profile);
11726
+ }
11727
+ function validateOrganizationInput(input) {
11728
+ if (!isRecord(input) || !isRecord(input.profile)) return fail(Errors.invalidInput("profile", "must be an object"));
11729
+ if (!isRecord(input.organization)) return fail(Errors.invalidInput("organization", "must be an object"));
11730
+ const profile = validateProfileInput(input.profile);
11731
+ if (!profile.ok) return profile;
11732
+ const name = requireNonEmpty(input.organization.name, "organization.name");
11733
+ if (!name.ok) return name;
11734
+ const handle = requireNonEmpty(input.organization.handle, "organization.handle");
11735
+ if (!handle.ok) return handle;
11736
+ const country = parseCountry(input.organization.country, "organization.country");
11737
+ if (!country.ok) return country;
11738
+ return {
11739
+ ok: true,
11740
+ value: {
11741
+ profile: profile.value,
11742
+ organization: {
11743
+ name: name.value,
11744
+ handle: handle.value,
11745
+ country: country.value
11746
+ }
11747
+ }
11748
+ };
11749
+ }
11750
+ function validateProfileInput(input) {
11751
+ const displayName = requireNonEmpty(input.displayName, "profile.displayName");
11641
11752
  if (!displayName.ok) return displayName;
11642
- const country = parseCountry(input.country);
11753
+ const country = parseCountry(input.country, "profile.country");
11643
11754
  if (!country.ok) return country;
11644
11755
  if (input.withdrawalAddress === void 0) return {
11645
11756
  ok: true,
@@ -11648,7 +11759,7 @@ function validatePersonalInput(input) {
11648
11759
  country: country.value
11649
11760
  }
11650
11761
  };
11651
- const withdrawalAddress = parseAddress(input.withdrawalAddress, "withdrawalAddress");
11762
+ const withdrawalAddress = parseAddress(input.withdrawalAddress, "profile.withdrawalAddress");
11652
11763
  if (!withdrawalAddress.ok) return withdrawalAddress;
11653
11764
  return {
11654
11765
  ok: true,
@@ -11659,25 +11770,6 @@ function validatePersonalInput(input) {
11659
11770
  }
11660
11771
  };
11661
11772
  }
11662
- function validateOrganizationInput(input) {
11663
- const organizationName = requireNonEmpty(input.organizationName, "organizationName");
11664
- if (!organizationName.ok) return organizationName;
11665
- const handle = requireNonEmpty(input.handle, "handle");
11666
- if (!handle.ok) return handle;
11667
- const ownerDisplayName = requireNonEmpty(input.ownerDisplayName, "ownerDisplayName");
11668
- if (!ownerDisplayName.ok) return ownerDisplayName;
11669
- const country = parseCountry(input.country);
11670
- if (!country.ok) return country;
11671
- return {
11672
- ok: true,
11673
- value: {
11674
- organizationName: organizationName.value,
11675
- handle: handle.value,
11676
- country: country.value,
11677
- ownerDisplayName: ownerDisplayName.value
11678
- }
11679
- };
11680
- }
11681
11773
  function requireNonEmpty(value, field) {
11682
11774
  const trimmed = typeof value === "string" ? value.trim() : "";
11683
11775
  if (trimmed.length === 0) return fail(Errors.invalidInput(field, "must be a non-empty string"));
@@ -11686,14 +11778,14 @@ function requireNonEmpty(value, field) {
11686
11778
  value: trimmed
11687
11779
  };
11688
11780
  }
11689
- function parseCountry(value) {
11781
+ function parseCountry(value, field = "country") {
11690
11782
  try {
11691
11783
  return {
11692
11784
  ok: true,
11693
11785
  value: toCountryCode(value)
11694
11786
  };
11695
11787
  } catch (cause) {
11696
- return fail(invalidFrom("country", cause, "must be an ISO-3166 alpha-2 code"));
11788
+ return fail(invalidFrom(field, cause, "must be an ISO-3166 alpha-2 code"));
11697
11789
  }
11698
11790
  }
11699
11791
  function parseAddress(value, field) {
@@ -11710,6 +11802,9 @@ function invalidFrom(field, cause, fallback) {
11710
11802
  const message = cause instanceof Error && cause.message.length > 0 ? cause.message : fallback;
11711
11803
  return Errors.invalidInput(field, message);
11712
11804
  }
11805
+ function isRecord(value) {
11806
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11807
+ }
11713
11808
  function fail(error) {
11714
11809
  return {
11715
11810
  ok: false,
@@ -11947,6 +12042,22 @@ function assembleCapxulClient(input) {
11947
12042
  };
11948
12043
  },
11949
12044
  completeIdentityOnboarding: (write) => runPortEffect(input.ports.identity.completeOnboarding(write)),
12045
+ ensureFounderAccountReady: async (observationSource) => {
12046
+ const deployed = await account._internal.deploySafe(observationSource);
12047
+ if (!deployed.ok) return deployed;
12048
+ if (deployed.value.deployedAt === null || deployed.value.claimedAt === null) return {
12049
+ ok: false,
12050
+ error: Errors.wrongState({
12051
+ method: "onboarding.completeOrganization",
12052
+ currentState: "founderAccountClaimPending",
12053
+ validStates: ["founderAccountDeployedAndClaimed"]
12054
+ })
12055
+ };
12056
+ return {
12057
+ ok: true,
12058
+ value: void 0
12059
+ };
12060
+ },
11950
12061
  triggerProvisioning: () => account._internal.provision(),
11951
12062
  kickProvisioning: () => kickProvisioning?.(),
11952
12063
  readLifecycle: () => account.getLifecycle(),
@@ -12057,7 +12168,7 @@ function observeSdkClient(client, adapter) {
12057
12168
  if (cached !== void 0) return cached;
12058
12169
  const wrapped = new Proxy(callable, {
12059
12170
  apply(currentTarget, _thisArg, args) {
12060
- const invocationContext = resolveAdapterContext(adapter);
12171
+ const invocationContext = invocationObservationContext(resolveAdapterContext(adapter));
12061
12172
  const invocationArgs = carryInvocationContext(operation, args, invocationContext);
12062
12173
  let output;
12063
12174
  try {
@@ -12094,9 +12205,23 @@ function observeSdkClient(client, adapter) {
12094
12205
  return wrapObject(client, []);
12095
12206
  }
12096
12207
  function carryInvocationContext(operation, args, context) {
12097
- if (operation !== "subAccounts.transfer" || !isPlainObject(args[0])) return args;
12208
+ if (!isPlainObject(args[0])) return args.length === 0 && operation === "org.retrySetup" ? [attachInvocationObservation({}, context)] : args;
12098
12209
  return [attachInvocationObservation({ ...args[0] }, context), ...args.slice(1)];
12099
12210
  }
12211
+ /** One stable correlation id per public call; the next call is an explicit retry. */
12212
+ function invocationObservationContext(context) {
12213
+ return {
12214
+ ...context,
12215
+ correlationId: createInvocationCorrelationId()
12216
+ };
12217
+ }
12218
+ function createInvocationCorrelationId() {
12219
+ if (typeof globalThis.crypto?.randomUUID === "function") return `sdk_${globalThis.crypto.randomUUID()}`;
12220
+ const bytes = new Uint8Array(16);
12221
+ if (typeof globalThis.crypto?.getRandomValues === "function") globalThis.crypto.getRandomValues(bytes);
12222
+ else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256);
12223
+ return `sdk_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
12224
+ }
12100
12225
  /** @internal Reports a factory-level typed failure without changing its identity. */
12101
12226
  function observeFailedResult(result, adapter, operation) {
12102
12227
  if (adapter !== void 0 && isFailedResult(result)) report(adapter, "operation", operation, result.error, resolveAdapterContext(adapter));
@@ -12508,7 +12633,8 @@ async function createCapxulClient(input) {
12508
12633
  orgPort: new ConvexOrganizationAdapter({ convex: adapters.value.ports.convexCall }),
12509
12634
  ...signer === void 0 ? {} : { organizationSetup: new ConvexOrganizationSetupAdapter({
12510
12635
  convex: adapters.value.ports.convexCall,
12511
- signer
12636
+ signer,
12637
+ chainId: adapters.value.bootstrap.chainId
12512
12638
  }) },
12513
12639
  ...input.signal === void 0 ? {} : { signal: input.signal },
12514
12640
  ...input.otpTtlMs === void 0 ? {} : { otpTtlMs: input.otpTtlMs },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/mcp",
3
- "version": "1.0.0-alpha.20",
3
+ "version": "1.0.0-alpha.21",
4
4
  "private": false,
5
5
  "description": "Capxul MCP server — agent-facing financial-ops tools (auth, account readiness, balances, testnet faucet, payments) exposed over Streamable HTTP with OAuth bearer auth and a dev-mode custody gate.",
6
6
  "keywords": [
@@ -56,7 +56,7 @@
56
56
  "@capxul/config": "0.1.0-alpha.3",
57
57
  "@capxul/errors": "0.0.1-alpha.0",
58
58
  "@capxul/observability": "0.1.0-alpha.1",
59
- "@capxul/sdk": "1.0.0-alpha.20",
59
+ "@capxul/sdk": "1.0.0-alpha.21",
60
60
  "@capxul/types": "0.1.0-alpha.1",
61
61
  "@capxul/wire": "0.1.0-alpha.3"
62
62
  },