@capxul/mcp 4.20.0-beta.10 → 4.20.0-beta.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.
Files changed (2) hide show
  1. package/dist/main.mjs +711 -1016
  2. package/package.json +2 -2
package/dist/main.mjs CHANGED
@@ -825,6 +825,38 @@ function validateHandle(raw) {
825
825
  return handle;
826
826
  }
827
827
  //#endregion
828
+ //#region ../../packages/types/src/organization-setup.ts
829
+ /** Backend-owned Organization setup states shared by wire and telemetry. */
830
+ const ORGANIZATION_SETUP_STATUSES = [
831
+ "awaitingAuthorization",
832
+ "processing",
833
+ "needsAttention",
834
+ "ready",
835
+ "rechecking",
836
+ "failed"
837
+ ];
838
+ /** Closed reasons for a stored Organization setup issue. */
839
+ const ORGANIZATION_SETUP_REASONS = [
840
+ "submission_unknown",
841
+ "receipt_unresolved",
842
+ "provider_unavailable",
843
+ "receipt_reverted",
844
+ "deterministic_address_mismatch",
845
+ "receipt_mismatch",
846
+ "block_identity_changed",
847
+ "authority_event_mismatch",
848
+ "allowance_timestamp_mismatch",
849
+ "receipt_identity_unavailable",
850
+ "receipt_identity_mismatch",
851
+ "contract_code_unavailable",
852
+ "contract_state_mismatch",
853
+ "permission_projection_mismatch",
854
+ "bootstrap_reorg",
855
+ "dependent_authority_unresolved",
856
+ "historical_evidence_missing",
857
+ "worker_failed"
858
+ ];
859
+ //#endregion
828
860
  //#region ../../packages/types/src/index.ts
829
861
  const ASSET_ID_RE = /^eip155:([1-9][0-9]*)\/erc20:(0x[0-9a-f]{40})$/;
830
862
  const EVM_ADDRESS_RE$1 = /^0x[0-9a-f]{40}$/i;
@@ -3227,9 +3259,6 @@ function normalizeBindingEmail(email) {
3227
3259
  return normalizeSafeSaltEmail(email);
3228
3260
  }
3229
3261
  //#endregion
3230
- //#region ../../packages/config/src/role-dsl.ts
3231
- const ADMIN_ROLE_LABEL = "Admin";
3232
- //#endregion
3233
3262
  //#region ../../packages/config/src/capxul-payments-v2.ts
3234
3263
  /** The exact compiled CapxulPaymentsV2 ABI. */
3235
3264
  const CAPXUL_PAYMENTS_V2_ABI = [
@@ -4066,8 +4095,7 @@ const RESTORING = { phase: "restoring" };
4066
4095
  const label = (state) => {
4067
4096
  if (state.phase !== "authenticated") return state.phase;
4068
4097
  if (state.account.at !== "claimed") return `authenticated:${state.account.at}`;
4069
- const org = state.account.org;
4070
- return org === null ? "authenticated:claimed" : `authenticated:claimed:${org.at}`;
4098
+ return state.account.org === null ? "authenticated:claimed" : "authenticated:claimed:organization";
4071
4099
  };
4072
4100
  const EVENT_TAGS = [
4073
4101
  "RequestOtp",
@@ -4085,8 +4113,8 @@ const EVENT_TAGS = [
4085
4113
  "RetryAccount",
4086
4114
  "CreateOrganization",
4087
4115
  "AttachOrganization",
4088
- "RetryOrganization",
4089
- "LeaveOrganization"
4116
+ "LeaveOrganization",
4117
+ "ObserveOrganization"
4090
4118
  ];
4091
4119
  const PRIVATE_EVENT_TAGS = [
4092
4120
  "OtpSent",
@@ -4102,9 +4130,8 @@ const PRIVATE_EVENT_TAGS = [
4102
4130
  "AccountClaiming",
4103
4131
  "AccountClaimed",
4104
4132
  "AccountFailed",
4105
- "OrgAt",
4106
- "OrgReady",
4107
- "OrgFailed"
4133
+ "OrgSelected",
4134
+ "OrgSelectionFailed"
4108
4135
  ];
4109
4136
  const IDENTITY_EVENT_TAGS = [...EVENT_TAGS, ...PRIVATE_EVENT_TAGS];
4110
4137
  /** Valid in every `authenticated:*` position — the pre-S1 auth machine's row. */
@@ -4154,18 +4181,11 @@ const TRANSITION_TABLE = {
4154
4181
  "CreateOrganization",
4155
4182
  "AttachOrganization"
4156
4183
  ],
4157
- "authenticated:claimed:creating": [...SESSION_EVENTS],
4158
- "authenticated:claimed:loading": [...SESSION_EVENTS],
4159
- "authenticated:claimed:settingUp": [...SESSION_EVENTS],
4160
- "authenticated:claimed:ready": [
4184
+ "authenticated:claimed:organization": [
4161
4185
  ...SESSION_EVENTS,
4162
4186
  "AttachOrganization",
4163
- "LeaveOrganization"
4164
- ],
4165
- "authenticated:claimed:failed": [
4166
- ...SESSION_EVENTS,
4167
- "RetryOrganization",
4168
- "LeaveOrganization"
4187
+ "LeaveOrganization",
4188
+ "ObserveOrganization"
4169
4189
  ]
4170
4190
  };
4171
4191
  const DEFAULT_CONFIG = {
@@ -4245,36 +4265,24 @@ const privateTransition = (state, event) => {
4245
4265
  failure: event.failure,
4246
4266
  retryable: isRetryable(event.failure)
4247
4267
  }) } : WRONG;
4248
- case "OrgAt": {
4268
+ case "OrgSelected": {
4249
4269
  const held = claimedOrg(state);
4250
- if (held === null || held.claimed.org === null) return WRONG;
4251
- const org = held.claimed.org;
4252
- return org.at === "creating" || org.at === "loading" || org.at === "settingUp" ? { next: withOrg(held.state, held.claimed, {
4253
- at: "settingUp",
4254
- orgId: event.orgId,
4255
- step: event.step
4256
- }) } : WRONG;
4257
- }
4258
- case "OrgReady": {
4259
- const held = claimedOrg(state);
4260
- if (held === null || held.claimed.org === null) return WRONG;
4261
- const org = held.claimed.org;
4262
- return org.at === "creating" || org.at === "settingUp" || org.at === "loading" ? { next: withOrg(held.state, held.claimed, {
4263
- at: "ready",
4264
- orgId: event.orgId
4265
- }) } : WRONG;
4270
+ if (held === null || held.claimed.org === null || held.claimed.org.orgId !== null) return WRONG;
4271
+ return { next: withOrg(held.state, held.claimed, {
4272
+ orgId: event.setup.orgId,
4273
+ setup: event.setup,
4274
+ observation: "connected"
4275
+ }) };
4266
4276
  }
4267
- case "OrgFailed": {
4277
+ case "OrgSelectionFailed": {
4268
4278
  const held = claimedOrg(state);
4269
- if (held === null || held.claimed.org === null) return WRONG;
4270
- const org = held.claimed.org;
4271
- return org.at === "creating" || org.at === "loading" || org.at === "settingUp" ? { next: withOrg(held.state, held.claimed, {
4272
- at: "failed",
4273
- orgId: event.orgId,
4274
- step: event.step,
4275
- failure: event.failure,
4276
- retryable: event.retryable ?? isRetryable(event.failure)
4277
- }) } : WRONG;
4279
+ if (held === null || held.claimed.org === null || held.claimed.org.orgId !== null) return WRONG;
4280
+ return { next: withOrg(held.state, held.claimed, {
4281
+ orgId: null,
4282
+ setup: null,
4283
+ observation: "error",
4284
+ failure: event.failure
4285
+ }) };
4278
4286
  }
4279
4287
  }
4280
4288
  };
@@ -4343,35 +4351,43 @@ const transition = (state, event, config = DEFAULT_CONFIG) => {
4343
4351
  case "CreateOrganization": {
4344
4352
  const held = claimedOrg(state);
4345
4353
  if (held === null || held.claimed.org !== null) return WRONG;
4346
- const draft = {
4347
- name: event.draft.name,
4348
- handle: event.draft.handle,
4349
- country: event.draft.country
4350
- };
4351
4354
  return { next: withOrg(held.state, held.claimed, {
4352
- at: "creating",
4353
- draft
4355
+ orgId: null,
4356
+ setup: null,
4357
+ observation: "loading"
4354
4358
  }) };
4355
4359
  }
4356
4360
  case "AttachOrganization": {
4357
4361
  const held = claimedOrg(state);
4358
4362
  if (held === null) return WRONG;
4359
- if (held.claimed.org?.at === "ready" && held.claimed.org.orgId === event.orgId) return { next: state };
4360
- if (held.claimed.org !== null && held.claimed.org.at !== "ready") return WRONG;
4363
+ if (held.claimed.org?.orgId === event.orgId) return { next: state };
4361
4364
  return { next: withOrg(held.state, held.claimed, {
4362
- at: "loading",
4363
- orgId: event.orgId
4365
+ orgId: event.orgId,
4366
+ setup: null,
4367
+ observation: "loading"
4364
4368
  }) };
4365
4369
  }
4366
- case "RetryOrganization": {
4370
+ case "ObserveOrganization": {
4367
4371
  const held = claimedOrg(state);
4368
- if (held === null || held.claimed.org === null) return WRONG;
4369
- const org = held.claimed.org;
4370
- if (org.at !== "failed" || !org.retryable || org.orgId === null) return WRONG;
4372
+ if (held === null || held.claimed.org?.orgId !== event.orgId) return WRONG;
4373
+ const snapshot = event.snapshot;
4374
+ if (snapshot.status === "value") {
4375
+ if (String(snapshot.value.orgId) !== event.orgId) return { refused: "INVALID_INPUT" };
4376
+ return { next: withOrg(held.state, held.claimed, {
4377
+ orgId: event.orgId,
4378
+ setup: snapshot.value,
4379
+ observation: "connected"
4380
+ }) };
4381
+ }
4371
4382
  return { next: withOrg(held.state, held.claimed, {
4372
- at: "settingUp",
4373
- orgId: org.orgId,
4374
- step: org.step
4383
+ ...held.claimed.org,
4384
+ observation: snapshot.status === "loading" ? "loading" : "error",
4385
+ ...snapshot.status === "error" ? { failure: {
4386
+ code: snapshot.error.code,
4387
+ message: snapshot.error.message,
4388
+ ...snapshot.error.mode === void 0 ? {} : { mode: snapshot.error.mode },
4389
+ error: snapshot.error
4390
+ } } : {}
4375
4391
  }) };
4376
4392
  }
4377
4393
  case "LeaveOrganization": {
@@ -7585,8 +7601,8 @@ const TelemetryEnvelopeProps = {
7585
7601
  * failure came from the chain path. Spread into every failure event and posted
7586
7602
  * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
7587
7603
  */
7588
- const FailureModeSchema = Schema.Literals(FAILURE_MODES$1);
7589
- const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
7604
+ const FailureModeSchema$1 = Schema.Literals(FAILURE_MODES$1);
7605
+ const ChainUpstreamSchema$1 = Schema.Literals(CHAIN_UPSTREAMS);
7590
7606
  /**
7591
7607
  * The refusing upstream's response headers (#1818): exactly the names in
7592
7608
  * `RESPONSE_HEADER_ALLOWLIST`, each optional, so the catalog itself refuses a
@@ -7604,15 +7620,15 @@ const ResponseHeadersSchema = Schema.Struct({
7604
7620
  });
7605
7621
  /** One upstream tried, flat (#1818): the `chain_attempts` entry on every producer's row. */
7606
7622
  const ChainAttemptSchema = Schema.Struct({
7607
- upstream: ChainUpstreamSchema,
7608
- failure_mode: FailureModeSchema,
7623
+ upstream: ChainUpstreamSchema$1,
7624
+ failure_mode: FailureModeSchema$1,
7609
7625
  http_status: Schema.optional(Schema.Number),
7610
7626
  rpc_code: Schema.optional(Schema.Number),
7611
7627
  duration_ms: Schema.Number
7612
7628
  });
7613
7629
  const ChainCauseTelemetryProps = {
7614
- failure_mode: Schema.optional(FailureModeSchema),
7615
- chain_upstream: Schema.optional(ChainUpstreamSchema),
7630
+ failure_mode: Schema.optional(FailureModeSchema$1),
7631
+ chain_upstream: Schema.optional(ChainUpstreamSchema$1),
7616
7632
  chain_method: OptionalString,
7617
7633
  chain_retryable: Schema.optional(Schema.Boolean),
7618
7634
  chain_http_status: Schema.optional(Schema.Number),
@@ -7796,9 +7812,9 @@ const ChainUpstreamFallbackProps = Schema.Struct({
7796
7812
  ...TelemetryEnvelopeProps,
7797
7813
  service: ChainServiceSchema,
7798
7814
  method: Schema.String,
7799
- from_upstream: ChainUpstreamSchema,
7800
- to_upstream: Schema.optional(ChainUpstreamSchema),
7801
- failure_mode: FailureModeSchema,
7815
+ from_upstream: ChainUpstreamSchema$1,
7816
+ to_upstream: Schema.optional(ChainUpstreamSchema$1),
7817
+ failure_mode: FailureModeSchema$1,
7802
7818
  exhausted: Schema.Boolean,
7803
7819
  http_status: Schema.optional(Schema.Number),
7804
7820
  rpc_code: Schema.optional(Schema.Number),
@@ -7807,8 +7823,8 @@ const ChainUpstreamFallbackProps = Schema.Struct({
7807
7823
  const BundlerErrorProps = Schema.Struct({
7808
7824
  ...TelemetryEnvelopeProps,
7809
7825
  method: Schema.String,
7810
- failure_mode: FailureModeSchema,
7811
- chain_upstream: ChainUpstreamSchema,
7826
+ failure_mode: FailureModeSchema$1,
7827
+ chain_upstream: ChainUpstreamSchema$1,
7812
7828
  chain_retryable: Schema.Boolean,
7813
7829
  http_status: Schema.optional(Schema.Number),
7814
7830
  rpc_code: Schema.optional(Schema.Number),
@@ -7819,13 +7835,13 @@ const ReceiptPendingProps = Schema.Struct({
7819
7835
  ...TelemetryEnvelopeProps,
7820
7836
  service: ChainServiceSchema,
7821
7837
  method: Schema.String,
7822
- chain_upstream: ChainUpstreamSchema,
7838
+ chain_upstream: ChainUpstreamSchema$1,
7823
7839
  reason: Schema.Literals(["zero_block_hash", "no_receipt"])
7824
7840
  });
7825
7841
  const OperationRetriedProps = Schema.Struct({
7826
7842
  ...TelemetryEnvelopeProps,
7827
7843
  operation: Schema.String,
7828
- failure_mode: FailureModeSchema,
7844
+ failure_mode: FailureModeSchema$1,
7829
7845
  reason: Schema.optional(Schema.Literal("connection-lost-in-flight")),
7830
7846
  connection_id: OptionalString,
7831
7847
  connection_count: Schema.optional(Schema.Number),
@@ -7866,14 +7882,16 @@ const OrganizationCreationStartedProps = Schema.Struct({
7866
7882
  ...TelemetryEnvelopeProps,
7867
7883
  $insert_id: Schema.String,
7868
7884
  organization_id: OrgIdTelemetrySchema,
7869
- attempt_number: AttemptNumberSchema
7885
+ attempt_number: AttemptNumberSchema,
7886
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
7870
7887
  });
7871
7888
  const OrganizationCreationReadyProps = Schema.Struct({
7872
7889
  ...TelemetryEnvelopeProps,
7873
7890
  $insert_id: Schema.String,
7874
7891
  organization_id: OrgIdTelemetrySchema,
7875
7892
  attempt_number: AttemptNumberSchema,
7876
- duration_ms: DurationMsSchema$1
7893
+ duration_ms: DurationMsSchema$1,
7894
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)))
7877
7895
  });
7878
7896
  const OrganizationCreationFailedProps = Schema.Struct({
7879
7897
  ...TelemetryEnvelopeProps,
@@ -7884,20 +7902,13 @@ const OrganizationCreationFailedProps = Schema.Struct({
7884
7902
  stage: OnboardingStageSchema,
7885
7903
  error_code: Schema.String,
7886
7904
  retryable: Schema.Boolean,
7905
+ release: Schema.optional(Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u))),
7887
7906
  /** #1655: the SDK's backoff before this attempt. Absent on the first attempt. */
7888
7907
  backoff_ms: Schema.optional(DurationMsSchema$1),
7889
7908
  failure_reason: Schema.optional(Schema.Literals([
7890
- "deterministic_address_mismatch",
7891
7909
  "receipt_provider_unavailable",
7892
- "receipt_mismatch",
7893
7910
  "block_provider_unavailable",
7894
- "authority_event_mismatch",
7895
- "allowance_timestamp_mismatch",
7896
- "receipt_identity_unavailable",
7897
- "receipt_identity_mismatch",
7898
- "contract_code_unavailable",
7899
- "contract_state_mismatch",
7900
- "permission_projection_mismatch"
7911
+ ...ORGANIZATION_SETUP_REASONS
7901
7912
  ]))
7902
7913
  });
7903
7914
  const OnboardingIntentSchema = Schema.Literals(["personal", "organization"]);
@@ -8654,12 +8665,17 @@ Schema.Struct({
8654
8665
  "cancelled"
8655
8666
  ]),
8656
8667
  duration_ms: Schema.Number,
8668
+ organization_id: Schema.optional(OrgIdTelemetrySchema),
8669
+ setup_status: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_STATUSES)),
8670
+ setup_reason: Schema.optional(Schema.Literals(ORGANIZATION_SETUP_REASONS)),
8671
+ $groups: Schema.optional(Schema.Struct({ organization: OrgIdTelemetrySchema })),
8657
8672
  error_code: Schema.optional(Schema.Literals([
8658
8673
  ...CAPXUL_ERROR_CODES,
8659
8674
  "CLI_USAGE",
8660
8675
  "CLI_CONFIG",
8661
8676
  "CLI_STORAGE",
8662
- "CLI_DEFECT"
8677
+ "CLI_DEFECT",
8678
+ "CLI_DEADLINE"
8663
8679
  ]))
8664
8680
  })
8665
8681
  });
@@ -9412,14 +9428,7 @@ const CAPXUL_FUNCTIONS = {
9412
9428
  setOrgLogo: "media:setOrgLogo",
9413
9429
  setProfileImage: "media:setProfileImage"
9414
9430
  },
9415
- "org/actions": {
9416
- confirmBootstrap: "org/actions:confirmBootstrap",
9417
- prepareBootstrap: "org/actions:prepareBootstrap",
9418
- prepareFounderAccount: "org/actions:prepareFounderAccount",
9419
- readTreasury: "org/actions:readTreasury",
9420
- resumeBootstrapSubmission: "org/actions:resumeBootstrapSubmission",
9421
- submitBootstrap: "org/actions:submitBootstrap"
9422
- },
9431
+ "org/actions": { readTreasury: "org/actions:readTreasury" },
9423
9432
  "payroll/actions": { authorizeRun: "payroll/actions:authorizeRun" },
9424
9433
  "payroll/mutations": {
9425
9434
  removeGroup: "payroll/mutations:removeGroup",
@@ -9436,17 +9445,18 @@ const CAPXUL_FUNCTIONS = {
9436
9445
  authorize: "permission/queries:authorize",
9437
9446
  read: "permission/queries:read"
9438
9447
  },
9439
- "org/lifecycle": {
9440
- getProofReceipt: "org/lifecycle:getProofReceipt",
9441
- load: "org/lifecycle:load",
9442
- recordFailure: "org/lifecycle:recordFailure",
9443
- retry: "org/lifecycle:retry",
9444
- startOrResume: "org/lifecycle:startOrResume"
9448
+ "org/setup": {
9449
+ begin: "org/setup:begin",
9450
+ get: "org/setup:get",
9451
+ getProofReceipt: "org/setup:getProofReceipt",
9452
+ listMine: "org/setup:listMine",
9453
+ prepareAuthorization: "org/setup:prepareAuthorization",
9454
+ resume: "org/setup:resume",
9455
+ submitAuthorization: "org/setup:submitAuthorization"
9445
9456
  },
9446
9457
  "org/mutations": {
9447
9458
  accept: "org/mutations:accept",
9448
9459
  cancel: "org/mutations:cancel",
9449
- createOrg: "org/mutations:createOrg",
9450
9460
  decline: "org/mutations:decline",
9451
9461
  invite: "org/mutations:invite",
9452
9462
  resend: "org/mutations:resend",
@@ -9567,6 +9577,60 @@ const CLIENT_AUTHORIZATION_REFUSALS = [
9567
9577
  "revoke_unconfirmed"
9568
9578
  ];
9569
9579
  //#endregion
9580
+ //#region ../../packages/wire/src/organization-setup.ts
9581
+ const FailureModeSchema = Schema.Literals(FAILURE_MODES$1);
9582
+ const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
9583
+ const ChainCauseSchema = Schema.Struct({
9584
+ mode: FailureModeSchema,
9585
+ upstream: ChainUpstreamSchema,
9586
+ method: Schema.String,
9587
+ retryable: Schema.Boolean,
9588
+ httpStatus: Schema.optional(Schema.Number),
9589
+ rpcCode: Schema.optional(Schema.Number),
9590
+ revert: Schema.optional(Schema.Struct({
9591
+ name: Schema.NullOr(Schema.String),
9592
+ selector: Schema.String,
9593
+ args: Schema.Record(Schema.String, Schema.String)
9594
+ })),
9595
+ providerMessage: Schema.optional(Schema.String),
9596
+ attempts: Schema.optional(Schema.Array(Schema.Struct({
9597
+ upstream: ChainUpstreamSchema,
9598
+ mode: FailureModeSchema,
9599
+ httpStatus: Schema.optional(Schema.Number),
9600
+ rpcCode: Schema.optional(Schema.Number),
9601
+ durationMs: Schema.Number
9602
+ }))),
9603
+ responseHeaders: Schema.optional(Schema.Record(Schema.String, Schema.String))
9604
+ });
9605
+ const ErrorSchema = Schema.Struct({
9606
+ code: Schema.Literals(CAPXUL_ERROR_CODES),
9607
+ message: Schema.String,
9608
+ details: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
9609
+ correlationId: Schema.optional(Schema.String),
9610
+ layer: Schema.optional(Schema.String),
9611
+ mode: Schema.optional(FailureModeSchema),
9612
+ chain: Schema.optional(ChainCauseSchema)
9613
+ });
9614
+ const OrganizationSetupIssueSchema = Schema.Struct({
9615
+ reason: Schema.Literals(ORGANIZATION_SETUP_REASONS),
9616
+ error: Schema.optional(ErrorSchema)
9617
+ });
9618
+ const OrganizationSetupSchema = Schema.Struct({
9619
+ orgId: Schema.String,
9620
+ status: Schema.Literals(ORGANIZATION_SETUP_STATUSES),
9621
+ completedAt: Schema.NullOr(Schema.Number),
9622
+ lastCheckedAt: Schema.NullOr(Schema.Number),
9623
+ nextCheckAt: Schema.NullOr(Schema.Number),
9624
+ issue: Schema.NullOr(OrganizationSetupIssueSchema),
9625
+ lastSendIssue: Schema.NullOr(OrganizationSetupIssueSchema),
9626
+ recovery: Schema.Literals([
9627
+ "authorize",
9628
+ "checkAgain",
9629
+ "none"
9630
+ ]),
9631
+ phase: Schema.optional(Schema.Literals(["resolvingSubmission", "confirmingBootstrap"]))
9632
+ });
9633
+ //#endregion
9570
9634
  //#region ../../packages/wire/src/payment-document.ts
9571
9635
  const UINT256_MAX = 2n ** 256n - 1n;
9572
9636
  const INT256_MIN = -(2n ** 255n);
@@ -12357,7 +12421,7 @@ function signerFailure(source, operation, cause) {
12357
12421
  }
12358
12422
  //#endregion
12359
12423
  //#region ../../packages/sdk/package.json
12360
- var version$2 = "4.20.0-beta.10";
12424
+ var version$2 = "4.20.0-beta.11";
12361
12425
  //#endregion
12362
12426
  //#region ../../packages/sdk/src/telemetry/exception-projection.ts
12363
12427
  /** Fixed fallback for failures that have no safe message. */
@@ -15569,7 +15633,7 @@ function mismatch(field, message) {
15569
15633
  error: Errors.invalidInput(field, message)
15570
15634
  };
15571
15635
  }
15572
- function cancelled(operation) {
15636
+ function cancelled$1(operation) {
15573
15637
  return {
15574
15638
  ok: false,
15575
15639
  error: Errors.cancelled({ operation })
@@ -15601,7 +15665,7 @@ async function abandonPrepared(deps, executionId, reason, result, onPreparedClos
15601
15665
  return result;
15602
15666
  }
15603
15667
  async function executePersonalPayment(deps, payment, signal, requestKey, onPreparedClosed) {
15604
- if (isAborted$2(signal)) return cancelled(CAPXUL_OPERATIONS.payments.pay);
15668
+ if (isAborted$2(signal)) return cancelled$1(CAPXUL_OPERATIONS.payments.pay);
15605
15669
  if (deps.signer === void 0) return mismatch("signer", "payments.pay requires a configured CapxulSigner");
15606
15670
  const session = deps.actor.authSession();
15607
15671
  if (session === null) return {
@@ -15629,10 +15693,10 @@ async function executePersonalPayment(deps, payment, signal, requestKey, onPrepa
15629
15693
  executionId: prepared.value.executionId,
15630
15694
  recipient: prepared.value.recipientObservation
15631
15695
  }, deps.runPromise);
15632
- if (isAborted$2(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
15696
+ if (isAborted$2(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled$1(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
15633
15697
  const signature = await signerCall(deps.signer.source, "signUserOpHash", () => deps.signer.signUserOpHash(prepared.value.digest));
15634
15698
  if (!signature.ok) return abandonPrepared(deps, prepared.value.executionId, "signer_rejected", signature, onPreparedClosed);
15635
- if (isAborted$2(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
15699
+ if (isAborted$2(signal)) return abandonPrepared(deps, prepared.value.executionId, "cancelled", cancelled$1(CAPXUL_OPERATIONS.payments.pay), onPreparedClosed);
15636
15700
  return runIfActive(void 0, CAPXUL_OPERATIONS.payments.submitExecution, () => deps.convexCall.action(deps.functions.submitPaymentExecution, { input: {
15637
15701
  executionId: prepared.value.executionId,
15638
15702
  signature: signature.value
@@ -40834,6 +40898,7 @@ const MINIMAL_LOG_NAMES = /* @__PURE__ */ new Set([
40834
40898
  "convex.action.connection_lost",
40835
40899
  "cli.command.completed",
40836
40900
  "cli.sdk.operation.failed",
40901
+ "cli.signer.wait",
40837
40902
  "cli.wallet.step"
40838
40903
  ]);
40839
40904
  const MINIMAL_ERROR_CODES = /* @__PURE__ */ new Set([
@@ -40841,7 +40906,8 @@ const MINIMAL_ERROR_CODES = /* @__PURE__ */ new Set([
40841
40906
  "CLI_USAGE",
40842
40907
  "CLI_CONFIG",
40843
40908
  "CLI_STORAGE",
40844
- "CLI_DEFECT"
40909
+ "CLI_DEFECT",
40910
+ "CLI_DEADLINE"
40845
40911
  ]);
40846
40912
  const MINIMAL_NUMBERS = /* @__PURE__ */ new Set([
40847
40913
  "schema_version",
@@ -40921,6 +40987,13 @@ const MINIMAL_ENUM_VALUES = /* @__PURE__ */ new Map([
40921
40987
  ["provider", ["better-auth", "oidc"]],
40922
40988
  ["cli_identity_kind", ["anonymous", "identified"]],
40923
40989
  ["output_mode", ["human", "json"]],
40990
+ ["setup_status", ORGANIZATION_SETUP_STATUSES],
40991
+ ["setup_reason", ORGANIZATION_SETUP_REASONS],
40992
+ ["signer_stage", [
40993
+ "address",
40994
+ "readiness",
40995
+ "sign"
40996
+ ]],
40924
40997
  ["unit", [
40925
40998
  "1",
40926
40999
  "s",
@@ -40941,6 +41014,7 @@ const MINIMAL_VERSION_KEYS = /* @__PURE__ */ new Set([
40941
41014
  ]);
40942
41015
  function minimalStringValue(key, text) {
40943
41016
  if (key === "operation") return isCapxulOperation(text);
41017
+ if (key === "organization_id") return /^org_[0-9A-Za-z]+$/u.test(text);
40944
41018
  if (MINIMAL_CODE_KEYS.has(key)) return MINIMAL_ERROR_CODES.has(text);
40945
41019
  if (MINIMAL_VERSION_KEYS.has(key)) return /^[A-Za-z0-9][A-Za-z0-9._+@-]{0,127}$/u.test(text);
40946
41020
  if (key === "trace_id") return traceId(text);
@@ -45500,11 +45574,8 @@ const OBSERVED_CONVEX_ACTIONS = /* @__PURE__ */ new Set([
45500
45574
  "account/actions:readBalance",
45501
45575
  "holdings/actions:current",
45502
45576
  "smartAccount/actions:claim",
45503
- "org/actions:prepareFounderAccount",
45504
- "org/actions:prepareBootstrap",
45505
- "org/actions:submitBootstrap",
45506
- "org/actions:resumeBootstrapSubmission",
45507
- "org/actions:confirmBootstrap",
45577
+ "org/setup:prepareAuthorization",
45578
+ "org/setup:submitAuthorization",
45508
45579
  "org/actions:readTreasury",
45509
45580
  "moneyExecution/actions:preparePermissionExecution",
45510
45581
  "moneyExecution/actions:submitPermissionExecution",
@@ -45540,8 +45611,7 @@ const OBSERVED_CONVEX_QUERIES = /* @__PURE__ */ new Set([
45540
45611
  "permission/queries:read",
45541
45612
  "permission/queries:authorize",
45542
45613
  "identity/queries:loadByAuthUserId",
45543
- "smartAccount/queries:loadByAuthUserId",
45544
- "org/lifecycle:load"
45614
+ "smartAccount/queries:loadByAuthUserId"
45545
45615
  ]);
45546
45616
  const OBSERVED_CONVEX_MUTATIONS = /* @__PURE__ */ new Set([
45547
45617
  "movement/activity:annotate",
@@ -45562,9 +45632,8 @@ const OBSERVED_CONVEX_MUTATIONS = /* @__PURE__ */ new Set([
45562
45632
  "identity/mutations:update",
45563
45633
  "identity/mutations:completeOnboarding",
45564
45634
  "smartAccount/mutations:provision",
45565
- "org/lifecycle:startOrResume",
45566
- "org/lifecycle:recordFailure",
45567
- "org/lifecycle:retry",
45635
+ "org/setup:begin",
45636
+ "org/setup:resume",
45568
45637
  "org/mutations:invite",
45569
45638
  "org/mutations:accept"
45570
45639
  ]);
@@ -46107,6 +46176,43 @@ function orgErrorFromCapxul(operation, error, cause = error) {
46107
46176
  }
46108
46177
  var OrgPortTag = class extends Context.Service()("@capxul/sdk/ports/OrgPort") {};
46109
46178
  //#endregion
46179
+ //#region ../../packages/sdk/src/surface/org-lifecycle.ts
46180
+ function validateOrganizationSetupScope(orgId, setup) {
46181
+ return String(setup.orgId) === String(orgId) ? {
46182
+ ok: true,
46183
+ value: setup
46184
+ } : {
46185
+ ok: false,
46186
+ error: Errors.invalidInput("orgId", "Organization setup scope does not match")
46187
+ };
46188
+ }
46189
+ function rehydrateSetupIssue(item) {
46190
+ return item === null ? null : {
46191
+ reason: item.reason,
46192
+ ...item.error === void 0 ? {} : { error: deserializeCapxulError(item.error) }
46193
+ };
46194
+ }
46195
+ /** Validate the wire projection and restore its structured error causes. */
46196
+ function parseOrganizationSetup(value) {
46197
+ try {
46198
+ const wire = Schema.decodeUnknownSync(OrganizationSetupSchema)(value);
46199
+ return {
46200
+ ok: true,
46201
+ value: {
46202
+ ...wire,
46203
+ orgId: toOrgId(wire.orgId),
46204
+ issue: rehydrateSetupIssue(wire.issue),
46205
+ lastSendIssue: rehydrateSetupIssue(wire.lastSendIssue)
46206
+ }
46207
+ };
46208
+ } catch (cause) {
46209
+ return {
46210
+ ok: false,
46211
+ error: Errors.invalidInput("organizationSetup", String(cause))
46212
+ };
46213
+ }
46214
+ }
46215
+ //#endregion
46110
46216
  //#region ../../packages/sdk/src/adapters/org/parse.ts
46111
46217
  /** Brand the backend access projection without adding authority or profile fields. */
46112
46218
  function brandOrganizationAccess(wire) {
@@ -46119,37 +46225,17 @@ function brandOrganizationAccess(wire) {
46119
46225
  address: toAddress(wire.account.address),
46120
46226
  ready: wire.account.ready
46121
46227
  },
46122
- setup: brandOrgLifecycle(wire.setup),
46228
+ setup: brandOrgSetup(wire.setup),
46123
46229
  member: wire.member === null ? null : brandMemberIdentity(wire.member),
46124
46230
  capabilities: wire.capabilities,
46125
46231
  custody: wire.custody,
46126
46232
  observedAt: wire.observedAt
46127
46233
  };
46128
46234
  }
46129
- function brandOrgLifecycle(wire) {
46130
- const orgId = toOrgId(wire.orgId);
46131
- if (wire.status === "ready") return {
46132
- ...wire,
46133
- orgId
46134
- };
46135
- if (wire.status === "settingUp") {
46136
- if (!isSetupStep$1(wire.step)) throw Errors.invalidInput("lifecycle.step", "Unknown setup step");
46137
- return {
46138
- ...wire,
46139
- orgId,
46140
- step: wire.step
46141
- };
46142
- }
46143
- if (!isSetupStep$1(wire.at)) throw Errors.invalidInput("lifecycle.at", "Unknown setup step");
46144
- return {
46145
- ...wire,
46146
- orgId,
46147
- at: wire.at,
46148
- error: new CapxulError(CAPXUL_ERROR_CODES.find((candidate) => candidate === wire.error.code) ?? "UNKNOWN", wire.error.message)
46149
- };
46150
- }
46151
- function isSetupStep$1(value) {
46152
- return value === "preparingFounderAccount" || value === "awaitingFounderAuthorization" || value === "submittingBootstrap" || value === "confirmingBootstrap";
46235
+ function brandOrgSetup(wire) {
46236
+ const parsed = parseOrganizationSetup(wire);
46237
+ if (!parsed.ok) throw parsed.error;
46238
+ return parsed.value;
46153
46239
  }
46154
46240
  function brandMemberIdentity(wire) {
46155
46241
  return {
@@ -46257,9 +46343,6 @@ var ConvexOrganizationAdapter = class {
46257
46343
  this.#telemetry = input.telemetry;
46258
46344
  this.#rates = input.rates ?? MONEY_READ_RATES;
46259
46345
  }
46260
- createOrg(_input) {
46261
- return Effect.fail(orgErrorFromCapxul("createOrg", Errors.notImplemented("organizationSetup", "use onboarding.completeOrganization")));
46262
- }
46263
46346
  listOrgs(input) {
46264
46347
  return this.#convex.query(this.#fns.listAll, copyInvocationObservation(input, {})).pipe(Effect.mapError((error) => orgErrorFromCapxul("listOrgs", error.publicError, error)), Effect.map((wires) => wires.map(brandOrganizationAccess)), Effect.catchDefect((cause) => Effect.fail(toOrgError("listOrgs", cause))));
46265
46348
  }
@@ -46301,267 +46384,234 @@ function partialOrgTruth(operation, currentState) {
46301
46384
  //#endregion
46302
46385
  //#region ../../packages/sdk/src/adapters/org/ConvexOrganizationSetupAdapter.ts
46303
46386
  const DEFAULT_FUNCTIONS = {
46304
- startOrResume: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].startOrResume),
46305
- prepareFounderAccount: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareFounderAccount),
46306
- prepareBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].prepareBootstrap),
46307
- submitBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].submitBootstrap),
46308
- resumeBootstrapSubmission: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].resumeBootstrapSubmission),
46309
- confirmBootstrap: makeFunctionReference(CAPXUL_FUNCTIONS["org/actions"].confirmBootstrap),
46310
- recordFailure: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].recordFailure),
46311
- load: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].load),
46312
- retry: makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].retry)
46313
- };
46314
- /** Durable Organization setup capability composed by the standard client. */
46387
+ begin: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].begin),
46388
+ get: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].get),
46389
+ listMine: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].listMine),
46390
+ resume: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].resume),
46391
+ prepare: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].prepareAuthorization),
46392
+ submit: makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].submitAuthorization)
46393
+ };
46394
+ /** Convex transport for one backend-owned Organization setup. */
46315
46395
  var ConvexOrganizationSetupAdapter = class {
46316
46396
  #convex;
46317
46397
  #signer;
46318
46398
  #chainId;
46319
- #fns;
46399
+ #functions;
46400
+ #runPromise;
46401
+ #subscriptions = /* @__PURE__ */ new Set();
46402
+ #generation = 0;
46320
46403
  constructor(input) {
46321
46404
  this.#convex = input.convex;
46322
46405
  this.#signer = input.signer ?? null;
46323
46406
  this.#chainId = input.chainId;
46324
- this.#fns = input.functions ?? DEFAULT_FUNCTIONS;
46407
+ this.#functions = input.functions ?? DEFAULT_FUNCTIONS;
46408
+ this.#runPromise = input.runPromise ?? Effect.runPromise;
46325
46409
  }
46326
- async startOrResume(input) {
46327
- if (this.#signer === null) return fail$1(Errors.capabilityUnavailable("signer", "startOrResume"));
46328
- const result = await runCall("startOrResume", this.#convex.mutation(this.#fns.startOrResume, copyInvocationObservation(input, {
46410
+ async begin(input) {
46411
+ const result = await this.#call("begin", this.#convex.mutation(this.#functions.begin, copyInvocationObservation(input, {
46329
46412
  ...input,
46330
46413
  chainId: this.#chainId
46331
46414
  })));
46332
46415
  if (!result.ok) return result;
46333
- const lifecycle = parseLifecycle("startOrResume", result.value.lifecycle);
46334
- if (!lifecycle.ok) return lifecycle;
46335
- const orgId = parseOrgId("startOrResume", result.value.orgId);
46336
- if (!orgId.ok) return orgId;
46337
- if (String(orgId.value) !== String(lifecycle.value.orgId)) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle scope does not match"));
46416
+ const setup = parseOrganizationSetup(result.value.setup);
46417
+ if (!setup.ok) return setup;
46418
+ try {
46419
+ const orgId = toOrgId(result.value.orgId);
46420
+ const scoped = validateOrganizationSetupScope(orgId, setup.value);
46421
+ return scoped.ok ? {
46422
+ ok: true,
46423
+ value: {
46424
+ orgId,
46425
+ setup: scoped.value
46426
+ }
46427
+ } : scoped;
46428
+ } catch (cause) {
46429
+ return fail(Errors.invalidInput("orgId", String(cause)));
46430
+ }
46431
+ }
46432
+ async get(orgId, options) {
46433
+ if (options?.signal?.aborted) return cancelled();
46434
+ const result = await this.#call("get", this.#convex.query(this.#functions.get, { orgId }));
46435
+ if (!result.ok) return result;
46436
+ if (result.value === null) return fail(Errors.invalidInput("orgId", "Organization setup was not found"));
46437
+ const parsed = parseOrganizationSetup(result.value);
46438
+ return parsed.ok ? validateOrganizationSetupScope(orgId, parsed.value) : parsed;
46439
+ }
46440
+ async listMine(input = {}, options) {
46441
+ if (options?.signal?.aborted) return cancelled();
46442
+ if (input.cursor !== void 0 && typeof input.cursor !== "string" || input.limit !== void 0 && (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 50)) return fail(Errors.invalidInput("organizationSetupPage", "Invalid cursor or limit"));
46443
+ const generation = this.#generation;
46444
+ const result = await abortable(this.#call("listMine", this.#convex.query(this.#functions.listMine, input)), options?.signal);
46445
+ if (generation !== this.#generation || options?.signal?.aborted) return cancelled();
46446
+ if (!result.ok) return result;
46447
+ const value = result.value;
46448
+ if (typeof value !== "object" || value === null || !Array.isArray(value.page) || !(value.cursor === null || typeof value.cursor === "string") || typeof value.isDone !== "boolean") return fail(Errors.invalidInput("organizationSetupPage", "Invalid page envelope"));
46449
+ const page = [];
46450
+ for (const item of value.page) {
46451
+ const parsed = parseOrganizationSetup(item);
46452
+ if (!parsed.ok) return parsed;
46453
+ page.push(parsed.value);
46454
+ }
46338
46455
  return {
46339
46456
  ok: true,
46340
46457
  value: {
46341
- orgId: orgId.value,
46342
- lifecycle: lifecycle.value
46458
+ page,
46459
+ cursor: value.cursor,
46460
+ isDone: value.isDone
46343
46461
  }
46344
46462
  };
46345
46463
  }
46346
- prepareFounderAccount(input) {
46347
- return this.#lifecycleAction("prepareFounderAccount", input, () => this.#convex.action(this.#fns.prepareFounderAccount, copyInvocationObservation(input, {
46348
- orgId: input.orgId,
46349
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46350
- })));
46351
- }
46352
- async authorizeAndSubmitBootstrap(input) {
46353
- const cancelled = cancellation(input.signal);
46354
- if (cancelled !== void 0) return cancelled;
46464
+ async resume(orgId, options) {
46465
+ if (options?.signal?.aborted) return cancelled();
46466
+ const result = await this.#call("resume", this.#convex.mutation(this.#functions.resume, { orgId }));
46467
+ if (!result.ok) return result;
46468
+ const parsed = parseOrganizationSetup(result.value);
46469
+ return parsed.ok ? validateOrganizationSetupScope(orgId, parsed.value) : parsed;
46470
+ }
46471
+ async authorize(orgId, options) {
46472
+ if (options?.signal?.aborted) return cancelled();
46473
+ const current = await this.get(orgId, options);
46474
+ if (options?.signal?.aborted) return cancelled();
46475
+ if (!current.ok || current.value.status !== "awaitingAuthorization") return current;
46355
46476
  const signer = this.#signer;
46356
- if (signer === null) return fail$1(Errors.capabilityUnavailable("signer", "authorizeAndSubmitBootstrap"));
46357
- const signerAddress = await signerResult(signer.source, "getAddress", () => signer.getAddress());
46358
- if (!signerAddress.ok) return signerAddress;
46359
- const prepared = await runCall("prepareBootstrap", this.#convex.action(this.#fns.prepareBootstrap, copyInvocationObservation(input, {
46360
- orgId: input.orgId,
46361
- signerAddress: signerAddress.value,
46362
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46363
- })));
46477
+ if (signer === null) return fail(Errors.capabilityUnavailable("signer", "authorize"));
46478
+ const address = await signerResult(signer, "getAddress", () => signer.getAddress());
46479
+ if (!address.ok) return address;
46480
+ const prepared = await this.#call("prepareAuthorization", this.#convex.action(this.#functions.prepare, { orgId }));
46364
46481
  if (!prepared.ok) return prepared;
46365
- const authority = validatePreparedAuthorities(prepared.value, signerAddress.value);
46482
+ const authority = validatePrepared(prepared.value, orgId, address.value);
46366
46483
  if (!authority.ok) return authority;
46367
- const cancelledAfterPrepare = cancellation(input.signal);
46368
- if (cancelledAfterPrepare !== void 0) return cancelledAfterPrepare;
46369
- const signature = await signerResult(signer.source, "signUserOpHash", () => signer.signUserOpHash(prepared.value.digest));
46484
+ if (options?.signal?.aborted) return cancelled();
46485
+ const signature = await signerResult(signer, "signUserOpHash", () => signer.signUserOpHash(prepared.value.digest));
46370
46486
  if (!signature.ok) return signature;
46371
- const cancelledAfterSign = cancellation(input.signal);
46372
- if (cancelledAfterSign !== void 0) return cancelledAfterSign;
46373
- const submitted = await runCall("submitBootstrap", this.#convex.action(this.#fns.submitBootstrap, copyInvocationObservation(input, {
46374
- orgId: input.orgId,
46375
- signerAddress: signerAddress.value,
46376
- signature: signature.value,
46487
+ if (options?.signal?.aborted) return cancelled();
46488
+ const submitted = await this.#call("submitAuthorization", this.#convex.action(this.#functions.submit, {
46489
+ orgId,
46490
+ preparationId: prepared.value.preparationId,
46377
46491
  userOp: prepared.value.userOp,
46378
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46379
- })));
46380
- if (!submitted.ok) return submitted;
46381
- return parseLifecycle("submitBootstrap", submitted.value);
46382
- }
46383
- resumeSubmittedBootstrap(input) {
46384
- return this.#lifecycleAction("resumeBootstrapSubmission", input, () => this.#convex.action(this.#fns.resumeBootstrapSubmission, copyInvocationObservation(input, {
46385
- orgId: input.orgId,
46386
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46387
- })));
46388
- }
46389
- confirmSubmittedBootstrap(input) {
46390
- return this.#lifecycleAction("confirmBootstrap", input, () => this.#convex.action(this.#fns.confirmBootstrap, copyInvocationObservation(input, {
46391
- orgId: input.orgId,
46392
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext },
46393
- ...input.retryDelayMs === void 0 ? {} : { retryDelayMs: input.retryDelayMs }
46394
- })));
46395
- }
46396
- async recordFailure(input) {
46397
- const errorProvider = input.error.details?.provider;
46398
- const errorOperation = input.error.details?.operation;
46399
- const result = await runCall("recordFailure", this.#convex.mutation(this.#fns.recordFailure, copyInvocationObservation(input, {
46400
- orgId: input.orgId,
46401
- errorCode: input.error.code,
46402
- ...typeof errorProvider === "string" && typeof errorOperation === "string" ? {
46403
- errorProvider,
46404
- errorOperation
46405
- } : {},
46406
- retryable: input.retryable,
46407
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46408
- })));
46409
- return result.ok ? parseLifecycle("recordFailure", result.value) : result;
46410
- }
46411
- async loadLifecycle(input) {
46412
- const result = await runCall("loadLifecycle", this.#convex.query(this.#fns.load, input));
46413
- if (!result.ok) return result;
46414
- if (result.value === null) return fail$1(Errors.invalidInput("orgId", "Organization lifecycle was not found"));
46415
- return parseLifecycle("loadLifecycle", result.value);
46416
- }
46417
- async retry(input) {
46418
- const cancelled = cancellation(input.signal);
46419
- if (cancelled !== void 0) return cancelled;
46420
- const current = await this.loadLifecycle({
46421
- orgId: input.orgId,
46422
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46423
- });
46424
- if (!current.ok) return current;
46425
- if (current.value.status === "failed" && current.value.retryable && current.value.at === "awaitingFounderAuthorization") {
46426
- if (this.#signer === null) return fail$1(Errors.capabilityUnavailable("signer", "retry"));
46427
- const reset = resetSignerSession(this.#signer);
46428
- if (!reset.ok) return reset;
46492
+ signature: signature.value
46493
+ }));
46494
+ if (!submitted.ok) {
46495
+ const acceptedSetup = await this.get(orgId);
46496
+ return acceptedSetup.ok && acceptedSetup.value.status !== "awaitingAuthorization" ? acceptedSetup : submitted;
46497
+ }
46498
+ const parsed = parseOrganizationSetup(submitted.value);
46499
+ return parsed.ok ? validateOrganizationSetupScope(orgId, parsed.value) : parsed;
46500
+ }
46501
+ async subscribe(orgId, listener, options) {
46502
+ if (options?.signal?.aborted) return cancelled();
46503
+ let active = true;
46504
+ let remoteStop;
46505
+ const stop = () => {
46506
+ if (!active) return;
46507
+ active = false;
46508
+ options?.signal?.removeEventListener("abort", stop);
46509
+ this.#subscriptions.delete(stop);
46510
+ remoteStop?.();
46511
+ };
46512
+ const notify = (snapshot) => {
46513
+ try {
46514
+ Promise.resolve(listener(snapshot)).catch(() => void 0);
46515
+ } catch {}
46516
+ };
46517
+ options?.signal?.addEventListener("abort", stop, { once: true });
46518
+ this.#subscriptions.add(stop);
46519
+ const result = await this.#call("subscribe", this.#convex.subscribe(this.#functions.get, { orgId }, (snapshot) => {
46520
+ if (!active) return;
46521
+ if (snapshot.status === "loading") return notify({ status: "loading" });
46522
+ if (snapshot.status === "error") return notify({
46523
+ status: "error",
46524
+ error: snapshot.error
46525
+ });
46526
+ const parsed = snapshot.value === null ? fail(Errors.invalidInput("orgId", "Organization setup was not found")) : parseOrganizationSetup(snapshot.value);
46527
+ const scoped = parsed.ok ? validateOrganizationSetupScope(orgId, parsed.value) : parsed;
46528
+ notify(scoped.ok ? {
46529
+ status: "value",
46530
+ value: scoped.value
46531
+ } : {
46532
+ status: "error",
46533
+ error: scoped.error
46534
+ });
46535
+ }));
46536
+ if (!result.ok) {
46537
+ stop();
46538
+ return result;
46539
+ }
46540
+ remoteStop = result.value;
46541
+ if (!active) {
46542
+ remoteStop();
46543
+ return cancelled();
46429
46544
  }
46430
- const result = await runCall("retry", this.#convex.mutation(this.#fns.retry, copyInvocationObservation(input, {
46431
- orgId: input.orgId,
46432
- ...input.observationContext === void 0 ? {} : { observationContext: input.observationContext }
46433
- })));
46434
- if (!result.ok) return result;
46435
- return parseLifecycle("retry", result.value);
46436
- }
46437
- async #lifecycleAction(operation, input, call) {
46438
- const cancelled = cancellation(input.signal);
46439
- if (cancelled !== void 0) return cancelled;
46440
- const result = await runCall(operation, call());
46441
- if (!result.ok) return result;
46442
- const cancelledAfter = cancellation(input.signal);
46443
- if (cancelledAfter !== void 0) return cancelledAfter;
46444
- return parseLifecycle(operation, result.value);
46445
- }
46446
- };
46447
- function resetSignerSession(signer) {
46448
- const resetSession = signer.resetSession;
46449
- if (typeof resetSession !== "function") return {
46450
- ok: true,
46451
- value: void 0
46452
- };
46453
- try {
46454
- resetSession.call(signer);
46455
46545
  return {
46456
46546
  ok: true,
46457
- value: void 0
46547
+ value: stop
46458
46548
  };
46459
- } catch (cause) {
46460
- return fail$1(signerFailure(signer.source, "resetSession", cause));
46461
46549
  }
46462
- }
46463
- async function runCall(operation, effect) {
46464
- try {
46465
- const result = await Effect.runPromise(Effect.result(effect));
46466
- return Result.isSuccess(result) ? {
46467
- ok: true,
46468
- value: result.success
46469
- } : fail$1(publicError(operation, result.failure));
46470
- } catch (cause) {
46471
- return fail$1(publicError(operation, cause));
46472
- }
46473
- }
46474
- function publicError(operation, cause) {
46475
- if (cause instanceof CapxulError) return cause;
46476
- if (typeof cause === "object" && cause !== null) {
46477
- const carried = cause.publicError;
46478
- if (carried instanceof CapxulError) return carried;
46550
+ invalidateSubscriptions() {
46551
+ this.#generation += 1;
46552
+ for (const stop of this.#subscriptions) stop();
46479
46553
  }
46480
- return Errors.providerError("convex-organization", operation, cause);
46481
- }
46482
- async function signerResult(source, operation, run) {
46483
- try {
46484
- return {
46485
- ok: true,
46486
- value: await run()
46487
- };
46488
- } catch (cause) {
46489
- return fail$1(signerFailure(source, operation, cause));
46554
+ async #call(operation, effect) {
46555
+ try {
46556
+ const result = await this.#runPromise(Effect.result(effect));
46557
+ return Result.isSuccess(result) ? {
46558
+ ok: true,
46559
+ value: result.success
46560
+ } : fail(publicError(result.failure));
46561
+ } catch (cause) {
46562
+ return fail(publicError(cause));
46563
+ }
46490
46564
  }
46491
- }
46492
- function validatePreparedAuthorities(prepared, signerAddress) {
46565
+ };
46566
+ function validatePrepared(prepared, orgId, signerAddress) {
46493
46567
  const signer = signerAddress.toLowerCase();
46494
- const preparedSigner = prepared.signerAddress.toLowerCase();
46568
+ if (prepared.orgId !== orgId || prepared.expectedSigner.toLowerCase() !== signer) return fail(Errors.invalidInput("authorization", "Prepared signer or Organization does not match"));
46495
46569
  const founder = prepared.founderPersonalAccount.toLowerCase();
46496
46570
  const organization = prepared.organizationAccountAddress.toLowerCase();
46497
- const sender = prepared.userOp.sender.toLowerCase();
46498
- if (preparedSigner !== signer) return fail$1(Errors.invalidInput("signerAddress", "Prepared signer does not match configured signer"));
46499
- if (founder === signer || organization === signer || organization === founder) return fail$1(Errors.invalidInput("organizationAuthority", "Signer EOA, founder Account, and Organization Account must be distinct"));
46500
- if (sender !== founder) return fail$1(Errors.invalidInput("userOp.sender", "Bootstrap sender must be the founder Account"));
46501
- if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) return fail$1(Errors.invalidInput("digest", "Prepared bootstrap digest must be 32-byte hex"));
46571
+ if (founder === signer || organization === signer || organization === founder || prepared.userOp.sender.toLowerCase() !== founder) return fail(Errors.invalidInput("organizationAuthority", "Prepared authorities do not match"));
46572
+ if (!/^0x[0-9a-fA-F]{64}$/u.test(prepared.digest)) return fail(Errors.invalidInput("digest", "Prepared digest must be 32-byte hex"));
46502
46573
  return {
46503
46574
  ok: true,
46504
46575
  value: void 0
46505
46576
  };
46506
46577
  }
46507
- function parseLifecycle(operation, wire) {
46508
- const orgId = parseOrgId(operation, wire.orgId);
46509
- if (!orgId.ok) return orgId;
46510
- if (wire.status === "loading") return {
46511
- ok: true,
46512
- value: {
46513
- status: "loading",
46514
- orgId: orgId.value
46515
- }
46516
- };
46517
- if (wire.status === "ready") return {
46518
- ok: true,
46519
- value: {
46520
- status: "ready",
46521
- orgId: orgId.value,
46522
- canTransact: true
46523
- }
46524
- };
46525
- if (wire.status === "failed") {
46526
- if (!isSetupStep(wire.at)) return fail$1(Errors.invalidInput("lifecycle.at", "Unknown setup step"));
46527
- return {
46528
- ok: true,
46529
- value: {
46530
- status: "failed",
46531
- orgId: orgId.value,
46532
- at: wire.at,
46533
- error: new CapxulError(wire.error.code, wire.error.message),
46534
- retryable: wire.retryable
46535
- }
46536
- };
46537
- }
46538
- if (!isSetupStep(wire.step)) return fail$1(Errors.invalidInput("lifecycle.step", `Unknown setup step from ${operation}`));
46539
- return {
46540
- ok: true,
46541
- value: {
46542
- status: "settingUp",
46543
- orgId: orgId.value,
46544
- step: wire.step
46545
- }
46546
- };
46547
- }
46548
- function parseOrgId(operation, value) {
46578
+ async function signerResult(signer, operation, run) {
46549
46579
  try {
46550
46580
  return {
46551
46581
  ok: true,
46552
- value: toOrgId(value)
46582
+ value: await run()
46553
46583
  };
46554
46584
  } catch (cause) {
46555
- return fail$1(Errors.providerError("convex-organization", operation, cause));
46585
+ return fail(signerFailure(signer.source, operation, cause));
46586
+ }
46587
+ }
46588
+ function publicError(cause) {
46589
+ if (cause instanceof CapxulError) return cause;
46590
+ if (typeof cause === "object" && cause !== null && "publicError" in cause) {
46591
+ const carried = cause.publicError;
46592
+ if (carried instanceof CapxulError) return carried;
46556
46593
  }
46594
+ return Errors.unknown(cause);
46557
46595
  }
46558
- function isSetupStep(value) {
46559
- return value === "preparingFounderAccount" || value === "awaitingFounderAuthorization" || value === "submittingBootstrap" || value === "confirmingBootstrap";
46596
+ function cancelled() {
46597
+ return fail(Errors.cancelled({ operation: CAPXUL_OPERATIONS.organization.setup }));
46560
46598
  }
46561
- function cancellation(signal) {
46562
- return signal?.aborted ? fail$1(Errors.cancelled({ operation: CAPXUL_OPERATIONS.organization.setup })) : void 0;
46599
+ async function abortable(pending, signal) {
46600
+ if (signal === void 0) return pending;
46601
+ if (signal.aborted) return cancelled();
46602
+ let onAbort;
46603
+ const interrupted = new Promise((resolve) => {
46604
+ onAbort = () => resolve(cancelled());
46605
+ signal.addEventListener("abort", onAbort, { once: true });
46606
+ if (signal.aborted) onAbort();
46607
+ });
46608
+ try {
46609
+ return await Promise.race([pending, interrupted]);
46610
+ } finally {
46611
+ signal.removeEventListener("abort", onAbort);
46612
+ }
46563
46613
  }
46564
- function fail$1(error) {
46614
+ function fail(error) {
46565
46615
  return {
46566
46616
  ok: false,
46567
46617
  error
@@ -46726,22 +46776,27 @@ const IDENTITY_SLOT_BY_EVENT = {
46726
46776
  AccountFailed: IDENTITY_SLOT.account,
46727
46777
  CreateOrganization: IDENTITY_SLOT.org,
46728
46778
  AttachOrganization: IDENTITY_SLOT.org,
46729
- RetryOrganization: IDENTITY_SLOT.org,
46730
46779
  LeaveOrganization: IDENTITY_SLOT.org,
46731
- OrgAt: IDENTITY_SLOT.org,
46732
- OrgReady: IDENTITY_SLOT.org,
46733
- OrgFailed: IDENTITY_SLOT.org
46780
+ ObserveOrganization: IDENTITY_SLOT.org,
46781
+ OrgSelected: IDENTITY_SLOT.org,
46782
+ OrgSelectionFailed: IDENTITY_SLOT.org
46734
46783
  };
46735
46784
  const identitySlot = (event) => IDENTITY_SLOT_BY_EVENT[event._tag];
46736
46785
  const initialIdentityState = () => RESTORING;
46737
- function createIdentityAuthorityTracker(sessionStore) {
46786
+ function createIdentityAuthorityTracker(sessionStore, onGenerationChange = () => void 0) {
46738
46787
  let generation = 0;
46739
46788
  let authUserId = null;
46740
46789
  let stopped = false;
46741
46790
  let readState = initialIdentityState;
46791
+ const advanceGeneration = () => {
46792
+ generation += 1;
46793
+ try {
46794
+ onGenerationChange();
46795
+ } catch {}
46796
+ };
46742
46797
  const revoke = () => {
46743
46798
  if (stopped) return;
46744
- generation += 1;
46799
+ advanceGeneration();
46745
46800
  authUserId = null;
46746
46801
  };
46747
46802
  return {
@@ -46759,13 +46814,13 @@ function createIdentityAuthorityTracker(sessionStore) {
46759
46814
  observe: (state) => {
46760
46815
  if (stopped) return;
46761
46816
  const next = state.phase === "authenticated" ? state.session.authUserId : null;
46762
- if (authUserId !== null && next !== authUserId) generation += 1;
46817
+ if (authUserId !== null && next !== authUserId) advanceGeneration();
46763
46818
  authUserId = next;
46764
46819
  },
46765
46820
  invalidate: () => {
46766
46821
  if (stopped) return;
46767
46822
  stopped = true;
46768
- generation += 1;
46823
+ advanceGeneration();
46769
46824
  authUserId = null;
46770
46825
  },
46771
46826
  matches: (captured, expectedAuthUserId) => {
@@ -46776,29 +46831,6 @@ function createIdentityAuthorityTracker(sessionStore) {
46776
46831
  }
46777
46832
  };
46778
46833
  }
46779
- /** 2 s, 4 s, 8 s, 16 s, 32 s, 60 s, 60 s: about three minutes, then the user decides. */
46780
- const DEFAULT_CONFIRMATION_BACKOFF = {
46781
- initialDelayMs: 2e3,
46782
- maxDelayMs: 6e4,
46783
- maxRetries: 7
46784
- };
46785
- /**
46786
- * A public partial override must not bring the tight loop back: a zero,
46787
- * negative, or non-finite delay, or a non-integer or infinite retry count,
46788
- * falls back to the default for that field. `maxDelayMs` is never below
46789
- * `initialDelayMs`.
46790
- */
46791
- const positiveMs = (value, fallback) => value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
46792
- function normalizeConfirmationBackoff(override) {
46793
- const initialDelayMs = positiveMs(override?.initialDelayMs, DEFAULT_CONFIRMATION_BACKOFF.initialDelayMs);
46794
- const maxDelayMs = Math.max(initialDelayMs, positiveMs(override?.maxDelayMs, DEFAULT_CONFIRMATION_BACKOFF.maxDelayMs));
46795
- const retries = override?.maxRetries;
46796
- return {
46797
- initialDelayMs,
46798
- maxDelayMs,
46799
- maxRetries: retries !== void 0 && Number.isSafeInteger(retries) && retries >= 0 ? retries : DEFAULT_CONFIRMATION_BACKOFF.maxRetries
46800
- };
46801
- }
46802
46834
  const failureOf = (error) => {
46803
46835
  if (error instanceof CapxulError) {
46804
46836
  const mode = error.mode ?? error.details?.failure_mode;
@@ -46922,12 +46954,6 @@ const accountLane = (input, config, session, send, isCurrent) => Effect.gen(func
46922
46954
  address: String(claimed.success.smartAccountAddress)
46923
46955
  });
46924
46956
  });
46925
- const orgStep = (lifecycle) => {
46926
- if (lifecycle.status === "ready") return "ready";
46927
- if (lifecycle.status === "settingUp") return lifecycle.step;
46928
- if (lifecycle.status === "failed") return lifecycle.at;
46929
- return "preparingFounderAccount";
46930
- };
46931
46957
  const orgEngineeringContext = (controls, parent) => {
46932
46958
  const correlationId = safeEngineeringIdentifier(controls.correlation_id);
46933
46959
  const journeyId = safeEngineeringIdentifier(controls.journey_id);
@@ -46938,165 +46964,22 @@ const orgEngineeringContext = (controls, parent) => {
46938
46964
  ...traceparent === void 0 ? {} : { traceparent }
46939
46965
  };
46940
46966
  };
46941
- const runOrgStep = (setup, orgId, step, controls, retryDelayMs) => {
46942
- const [name, invoke] = step === "preparingFounderAccount" ? ["organization-setup.prepare-founder-account", (parent) => setup.prepareFounderAccount({
46943
- orgId,
46944
- observationContext: orgEngineeringContext(controls, parent)
46945
- })] : step === "awaitingFounderAuthorization" ? ["organization-setup.authorize-and-submit-bootstrap", (parent) => setup.authorizeAndSubmitBootstrap({
46946
- orgId,
46967
+ const beginOrganization$1 = (setup, draft, send, controls) => Effect.gen(function* () {
46968
+ const opened = yield* Effect.result(resultEffect("organization-setup.begin", (parent) => setup.begin({
46969
+ ...draft,
46947
46970
  observationContext: orgEngineeringContext(controls, parent)
46948
- })] : step === "submittingBootstrap" ? ["organization-setup.resume-submitted-bootstrap", (parent) => setup.resumeSubmittedBootstrap({
46949
- orgId,
46950
- observationContext: orgEngineeringContext(controls, parent)
46951
- })] : ["organization-setup.confirm-submitted-bootstrap", (parent) => setup.confirmSubmittedBootstrap({
46952
- orgId,
46953
- observationContext: orgEngineeringContext(controls, parent),
46954
- ...retryDelayMs === void 0 ? {} : { retryDelayMs }
46955
- })];
46956
- return resultEffect(name, invoke);
46957
- };
46958
- const orgLane = (setup, start, send, controls, backoff, telemetry) => Effect.gen(function* () {
46959
- let orgId;
46960
- let lifecycle;
46961
- if (start.kind === "create") {
46962
- const opened = yield* Effect.result(resultEffect("organization-setup.start-or-resume", (parent) => setup.startOrResume({
46963
- ...start.draft,
46964
- observationContext: orgEngineeringContext(controls, parent)
46965
- })));
46966
- if (Result.isFailure(opened)) {
46967
- yield* send({
46968
- _tag: "OrgFailed",
46969
- orgId: null,
46970
- step: "preparingFounderAccount",
46971
- failure: opened.failure
46972
- });
46973
- return yield* Effect.fail(opened.failure);
46974
- }
46975
- orgId = String(opened.success.orgId);
46976
- lifecycle = opened.success.lifecycle;
46977
- } else {
46978
- const opened = yield* Effect.result(start.kind === "retry" ? resultEffect("organization-setup.retry", (parent) => setup.retry({
46979
- orgId: start.orgId,
46980
- observationContext: orgEngineeringContext(controls, parent)
46981
- })) : resultEffect("organization-setup.load-lifecycle", (parent) => setup.loadLifecycle({
46982
- orgId: start.orgId,
46983
- observationContext: orgEngineeringContext(controls, parent)
46984
- })));
46985
- if (Result.isFailure(opened)) {
46986
- yield* send({
46987
- _tag: "OrgFailed",
46988
- orgId: start.orgId,
46989
- step: "preparingFounderAccount",
46990
- failure: opened.failure
46991
- });
46992
- return yield* Effect.fail(opened.failure);
46993
- }
46994
- orgId = start.orgId;
46995
- lifecycle = opened.success;
46996
- }
46997
- if (lifecycle.status === "failed") {
46998
- const failure = failureOf(lifecycle.error);
46999
- yield* send({
47000
- _tag: "OrgFailed",
47001
- orgId,
47002
- step: lifecycle.at,
47003
- failure,
47004
- retryable: lifecycle.retryable
47005
- });
47006
- return yield* Effect.fail(failure);
47007
- }
47008
- let step = orgStep(lifecycle);
47009
- if (step === "ready") {
46971
+ })));
46972
+ if (Result.isFailure(opened)) {
47010
46973
  yield* send({
47011
- _tag: "OrgReady",
47012
- orgId
46974
+ _tag: "OrgSelectionFailed",
46975
+ failure: opened.failure
47013
46976
  });
47014
- return;
46977
+ return yield* Effect.fail(opened.failure);
47015
46978
  }
47016
46979
  yield* send({
47017
- _tag: "OrgAt",
47018
- orgId,
47019
- step
46980
+ _tag: "OrgSelected",
46981
+ setup: opened.success.setup
47020
46982
  });
47021
- let retries = 0;
47022
- let retryDelayMs;
47023
- while (step !== "ready") {
47024
- const current = step;
47025
- const advanced = yield* Effect.result(runOrgStep(setup, orgId, current, controls, retryDelayMs));
47026
- retryDelayMs = void 0;
47027
- if (Result.isFailure(advanced)) {
47028
- yield* send({
47029
- _tag: "OrgFailed",
47030
- orgId,
47031
- step: current,
47032
- failure: advanced.failure
47033
- });
47034
- return yield* Effect.fail(advanced.failure);
47035
- }
47036
- lifecycle = advanced.success;
47037
- if (lifecycle.status === "failed") {
47038
- if (lifecycle.at === "confirmingBootstrap" && lifecycle.retryable && retries < backoff.maxRetries) {
47039
- const delayMs = Math.min(backoff.initialDelayMs * 2 ** retries, backoff.maxDelayMs);
47040
- retries += 1;
47041
- if (telemetry !== void 0) yield* telemetry.emit({
47042
- name: "operation_retried",
47043
- props: {
47044
- operation: CAPXUL_OPERATIONS.org.confirmBootstrap,
47045
- failure_mode: failureOf(lifecycle.error).mode ?? "unknown",
47046
- attempt: retries,
47047
- delay_ms: delayMs
47048
- }
47049
- }).pipe(Effect.catchDefect(() => Effect.void));
47050
- yield* Effect.sleep(Duration.millis(delayMs));
47051
- const reset = yield* Effect.result(resultEffect("organization-setup.retry", (parent) => setup.retry({
47052
- orgId,
47053
- observationContext: orgEngineeringContext(controls, parent)
47054
- })));
47055
- if (Result.isFailure(reset)) {
47056
- yield* send({
47057
- _tag: "OrgFailed",
47058
- orgId,
47059
- step: current,
47060
- failure: reset.failure
47061
- });
47062
- return yield* Effect.fail(reset.failure);
47063
- }
47064
- lifecycle = reset.success;
47065
- if (lifecycle.status !== "failed") {
47066
- retryDelayMs = delayMs;
47067
- step = orgStep(lifecycle);
47068
- yield* step === "ready" ? send({
47069
- _tag: "OrgReady",
47070
- orgId
47071
- }) : send({
47072
- _tag: "OrgAt",
47073
- orgId,
47074
- step
47075
- });
47076
- continue;
47077
- }
47078
- }
47079
- const failure = failureOf(lifecycle.error);
47080
- yield* send({
47081
- _tag: "OrgFailed",
47082
- orgId,
47083
- step: lifecycle.at,
47084
- failure,
47085
- retryable: lifecycle.retryable
47086
- });
47087
- return yield* Effect.fail(failure);
47088
- }
47089
- step = orgStep(lifecycle);
47090
- yield* step === "ready" ? send({
47091
- _tag: "OrgReady",
47092
- orgId
47093
- }) : send({
47094
- _tag: "OrgAt",
47095
- orgId,
47096
- step
47097
- });
47098
- if (step === current) yield* Effect.sleep("1 second");
47099
- }
47100
46983
  });
47101
46984
  const recoverIdentityFailure = (state, event, failure) => {
47102
46985
  if (event === "ReadSession") return {
@@ -47127,23 +47010,8 @@ const recoverIdentityFailure = (state, event, failure) => {
47127
47010
  failure
47128
47011
  };
47129
47012
  if (state.account.at !== "claimed" || state.account.org === null) return void 0;
47130
- const org = state.account.org;
47131
- if (org.at === "creating") return {
47132
- _tag: "OrgFailed",
47133
- orgId: null,
47134
- step: "preparingFounderAccount",
47135
- failure
47136
- };
47137
- if (org.at === "loading") return {
47138
- _tag: "OrgFailed",
47139
- orgId: org.orgId,
47140
- step: "preparingFounderAccount",
47141
- failure
47142
- };
47143
- return org.at === "settingUp" ? {
47144
- _tag: "OrgFailed",
47145
- orgId: org.orgId,
47146
- step: org.step,
47013
+ return state.account.org.orgId === null ? {
47014
+ _tag: "OrgSelectionFailed",
47147
47015
  failure
47148
47016
  } : void 0;
47149
47017
  };
@@ -47154,7 +47022,6 @@ const identitySpec = (input, sessionStore, authority) => {
47154
47022
  hasSigner: input.signer !== void 0,
47155
47023
  ...input.otpTtlMs === void 0 ? {} : { otpTtlMs: input.otpTtlMs }
47156
47024
  };
47157
- const backoff = normalizeConfirmationBackoff(input.confirmationBackoff);
47158
47025
  return {
47159
47026
  machine: "identity",
47160
47027
  initial: RESTORING,
@@ -47171,7 +47038,7 @@ const identitySpec = (input, sessionStore, authority) => {
47171
47038
  IDENTITY_SLOT.session,
47172
47039
  IDENTITY_SLOT.account,
47173
47040
  IDENTITY_SLOT.org
47174
- ] : [],
47041
+ ] : event._tag === "LeaveOrganization" || event._tag === "AttachOrganization" ? [IDENTITY_SLOT.org] : [],
47175
47042
  work: ({ state, event }) => {
47176
47043
  const activeSession = state.phase === "authenticated" ? state.session : null;
47177
47044
  const org = state.phase === "authenticated" && state.account.at === "claimed" ? state.account.org : null;
@@ -47265,29 +47132,10 @@ const identitySpec = (input, sessionStore, authority) => {
47265
47132
  }
47266
47133
  };
47267
47134
  }
47268
- case "CreateOrganization": return input.organizationSetup === void 0 || org?.at !== "creating" ? void 0 : {
47269
- slot: IDENTITY_SLOT.org,
47270
- port: "organization-setup",
47271
- run: (send, controls) => orgLane(input.organizationSetup, {
47272
- kind: "create",
47273
- draft: event.draft
47274
- }, send, controls, backoff, input.telemetry)
47275
- };
47276
- case "AttachOrganization": return input.organizationSetup === void 0 || org?.at !== "loading" ? void 0 : {
47277
- slot: IDENTITY_SLOT.org,
47278
- port: "organization-setup",
47279
- run: (send, controls) => orgLane(input.organizationSetup, {
47280
- kind: "attach",
47281
- orgId: org.orgId
47282
- }, send, controls, backoff, input.telemetry)
47283
- };
47284
- case "RetryOrganization": return input.organizationSetup === void 0 || org?.at !== "settingUp" ? void 0 : {
47135
+ case "CreateOrganization": return input.organizationSetup === void 0 || org === null || org.orgId !== null ? void 0 : {
47285
47136
  slot: IDENTITY_SLOT.org,
47286
47137
  port: "organization-setup",
47287
- run: (send, controls) => orgLane(input.organizationSetup, {
47288
- kind: "retry",
47289
- orgId: org.orgId
47290
- }, send, controls, backoff, input.telemetry)
47138
+ run: (send, controls) => beginOrganization$1(input.organizationSetup, event.draft, send, controls)
47291
47139
  };
47292
47140
  default: return;
47293
47141
  }
@@ -47296,10 +47144,69 @@ const identitySpec = (input, sessionStore, authority) => {
47296
47144
  };
47297
47145
  const bootIdentityFlow = (input, options = {}) => Effect.gen(function* () {
47298
47146
  const sessionStore = { current: null };
47299
- const authority = createIdentityAuthorityTracker(sessionStore);
47147
+ let invalidateOrganizationSubscriptions = () => input.organizationSetup?.invalidateSubscriptions?.();
47148
+ const authority = createIdentityAuthorityTracker(sessionStore, () => invalidateOrganizationSubscriptions());
47300
47149
  const actor = yield* boot(identitySpec(input, sessionStore, authority), options);
47301
47150
  authority.bindState(actor.snapshot);
47302
- const unsubscribeAuthority = actor.subscribe(authority.observe);
47151
+ const runPromise = input.runPromise ?? Effect.runPromise;
47152
+ let selectedOrgId = null;
47153
+ let stopRemote = null;
47154
+ let selectionEpoch = 0;
47155
+ invalidateOrganizationSubscriptions = () => {
47156
+ selectionEpoch += 1;
47157
+ const stop = stopRemote;
47158
+ stopRemote = null;
47159
+ try {
47160
+ stop?.();
47161
+ } finally {
47162
+ input.organizationSetup?.invalidateSubscriptions?.();
47163
+ }
47164
+ };
47165
+ const observe = (state) => {
47166
+ authority.observe(state);
47167
+ const nextOrgId = state.phase === "authenticated" && state.account.at === "claimed" ? state.account.org?.orgId ?? null : null;
47168
+ if (nextOrgId === selectedOrgId) return;
47169
+ selectedOrgId = nextOrgId;
47170
+ selectionEpoch += 1;
47171
+ const epoch = selectionEpoch;
47172
+ stopRemote?.();
47173
+ stopRemote = null;
47174
+ if (nextOrgId === null || input.organizationSetup === void 0) return;
47175
+ const capturedLifetime = authority.snapshot();
47176
+ const expectedAuthUserId = state.phase === "authenticated" ? state.session.authUserId : null;
47177
+ const emit = (snapshot) => {
47178
+ if (epoch !== selectionEpoch || !authority.matches(capturedLifetime, expectedAuthUserId)) return;
47179
+ runPromise(actor.tell({
47180
+ _tag: "ObserveOrganization",
47181
+ orgId: nextOrgId,
47182
+ snapshot
47183
+ })).catch(() => void 0);
47184
+ };
47185
+ try {
47186
+ const orgId = toOrgId(nextOrgId);
47187
+ input.organizationSetup.subscribe(orgId, emit).then((result) => {
47188
+ if (epoch !== selectionEpoch) {
47189
+ if (result.ok) result.value();
47190
+ return;
47191
+ }
47192
+ if (result.ok) stopRemote = result.value;
47193
+ else emit({
47194
+ status: "error",
47195
+ error: result.error
47196
+ });
47197
+ }).catch((cause) => emit({
47198
+ status: "error",
47199
+ error: Errors.unknown(cause)
47200
+ }));
47201
+ } catch (cause) {
47202
+ emit({
47203
+ status: "error",
47204
+ error: Errors.unknown(cause)
47205
+ });
47206
+ }
47207
+ };
47208
+ const unsubscribeAuthority = actor.subscribe(observe);
47209
+ observe(actor.snapshot());
47303
47210
  yield* Effect.addFinalizer(() => Effect.sync(() => {
47304
47211
  authority.invalidate();
47305
47212
  unsubscribeAuthority();
@@ -47324,7 +47231,7 @@ const bootIdentityFlow = (input, options = {}) => Effect.gen(function* () {
47324
47231
  });
47325
47232
  //#endregion
47326
47233
  //#region ../../packages/sdk/src/contract/org-lifecycle.ts
47327
- const organizationSetupProofReceiptQuery = makeFunctionReference(CAPXUL_FUNCTIONS["org/lifecycle"].getProofReceipt);
47234
+ const organizationSetupProofReceiptQuery = makeFunctionReference(CAPXUL_FUNCTIONS["org/setup"].getProofReceipt);
47328
47235
  //#endregion
47329
47236
  //#region ../../packages/sdk/src/surface/capxul-deps.ts
47330
47237
  /** The single Context tag the atoms + public methods both resolve. */
@@ -48007,6 +47914,10 @@ function normalizeOrganization(input) {
48007
47914
  ok: false,
48008
47915
  error: Errors.invalidInput("size", "must be text")
48009
47916
  };
47917
+ if (input.logoStorageId !== void 0 && typeof input.logoStorageId !== "string") return {
47918
+ ok: false,
47919
+ error: Errors.invalidInput("logoStorageId", "must be a storage ID")
47920
+ };
48010
47921
  let country;
48011
47922
  try {
48012
47923
  country = toCountryCode(input.country);
@@ -48025,7 +47936,8 @@ function normalizeOrganization(input) {
48025
47936
  handle: handle.value,
48026
47937
  country,
48027
47938
  ...bio.length === 0 ? {} : { bio },
48028
- ...size.length === 0 ? {} : { size }
47939
+ ...size.length === 0 ? {} : { size },
47940
+ ...input.logoStorageId === void 0 ? {} : { logoStorageId: input.logoStorageId }
48029
47941
  }
48030
47942
  };
48031
47943
  }
@@ -48117,93 +48029,137 @@ async function reachClaimedAccount(deps, options) {
48117
48029
  value: state
48118
48030
  } : organizationWrongState(state.phase === "authenticated" ? state.account.at : state.phase, ["claimed"]);
48119
48031
  }
48120
- async function createOrResumeOrganization(deps, state, draft, options) {
48121
- const selected = await selectOrganizationLane(deps, state, options);
48122
- if (!selected.ok) return selected;
48123
- state = selected.value;
48124
- const active = state.account.org;
48125
- if (active?.at === "ready") return {
48126
- ok: true,
48127
- value: { organizationId: active.orgId }
48128
- };
48129
- if (active?.at === "failed" && !active.retryable) return {
48032
+ async function beginOrganization(deps, input, options) {
48033
+ const normalized = normalizeOrganization(input);
48034
+ if (!normalized.ok) return normalized;
48035
+ const setup = deps.organizationSetup;
48036
+ if (setup === void 0) return {
48130
48037
  ok: false,
48131
- error: publicIdentityFailure(active.failure)
48038
+ error: Errors.notImplemented("organizationSetup", "begin")
48132
48039
  };
48133
- if (active?.at === "failed" && active.orgId === null) {
48134
- const cleared = await deps.sendIdentity({ _tag: "LeaveOrganization" }, options);
48135
- if (!cleared.ok) return cleared;
48040
+ const captured = deps.authLifetime();
48041
+ try {
48042
+ const session = await deps.restoreSession(options);
48043
+ if (!session.ok) return session;
48044
+ if (session.value === null) return {
48045
+ ok: false,
48046
+ error: Errors.notAuthenticated()
48047
+ };
48048
+ const authUserId = String(session.value.authUserId);
48049
+ const current = () => deps.matchesAuthLifetime(captured, authUserId) && !requestCancelled(options);
48050
+ if (!current()) return cancelledOrganization();
48051
+ const profile = await deps.loadProfile(options);
48052
+ if (!current()) return cancelledOrganization();
48053
+ if (!profile.ok) return profile;
48054
+ if (profile.value?.displayName === null || profile.value?.handle === null || profile.value === null) return organizationWrongState("profile-incomplete", ["profile-complete"]);
48055
+ const refreshed = await deps.refreshIdentity(options);
48056
+ if (!current()) return cancelledOrganization();
48057
+ if (!refreshed.ok) return refreshed;
48058
+ const claimed = await reachClaimedAccount(deps, options);
48059
+ if (!current()) return cancelledOrganization();
48060
+ if (!claimed.ok) return claimed;
48061
+ const begun = await setup.begin(normalized.value);
48062
+ if (!current()) return cancelledOrganization();
48063
+ if (begun.ok) {
48064
+ await deps.sendIdentity({
48065
+ _tag: "AttachOrganization",
48066
+ orgId: String(begun.value.orgId)
48067
+ }, options);
48068
+ if (!current()) return cancelledOrganization();
48069
+ }
48070
+ return begun;
48071
+ } catch (cause) {
48072
+ return {
48073
+ ok: false,
48074
+ error: Errors.unknown(cause)
48075
+ };
48136
48076
  }
48137
- const event = active?.at === "failed" && active.orgId !== null ? { _tag: "RetryOrganization" } : {
48138
- _tag: "CreateOrganization",
48139
- draft
48140
- };
48141
- const created = await deps.sendIdentity(event, options);
48142
- if (!created.ok) return created;
48143
- const final = created.value;
48144
- const organization = isClaimedIdentityState(final) ? final.account.org : null;
48145
- return organization?.at === "ready" ? {
48146
- ok: true,
48147
- value: { organizationId: organization.orgId }
48148
- } : organizationWrongState(organization?.at ?? "organization-missing", ["ready"], organization !== null && "orgId" in organization ? organization.orgId ?? void 0 : void 0);
48149
48077
  }
48150
- async function selectOrganizationLane(deps, state, options) {
48151
- if (options?.intent !== "create") return {
48152
- ok: true,
48153
- value: state
48078
+ function setupFailure(setup) {
48079
+ const issue = setup.issue;
48080
+ const details = {
48081
+ ...issue?.error?.details,
48082
+ organizationId: String(setup.orgId),
48083
+ ...issue !== null && { setupReason: issue.reason }
48154
48084
  };
48155
- const active = state.account.org;
48156
- if (active?.at === "ready") {
48157
- const left = await deps.sendIdentity({ _tag: "LeaveOrganization" }, options);
48158
- if (!left.ok) return left;
48159
- return isClaimedIdentityState(left.value) ? {
48160
- ok: true,
48161
- value: left.value
48162
- } : organizationWrongState("organization-leave-incomplete", ["claimed"]);
48085
+ if (issue?.error !== void 0) {
48086
+ const error = issue.error;
48087
+ return new CapxulError(error.code, error.message, {
48088
+ details,
48089
+ ...error.mode === void 0 ? {} : { mode: error.mode },
48090
+ ...error.chain === void 0 ? {} : { chain: error.chain },
48091
+ ...error.layer === void 0 ? {} : { layer: error.layer },
48092
+ ...error.correlationId === void 0 ? {} : { correlationId: error.correlationId }
48093
+ });
48163
48094
  }
48164
- if (active === null || active === void 0) return {
48165
- ok: true,
48166
- value: state
48167
- };
48168
- const organizationId = "orgId" in active ? active.orgId ?? void 0 : void 0;
48169
- return organizationWrongState(active.at, ["no-active-organization"], organizationId);
48095
+ const fallback = Errors.wrongState({
48096
+ method: CAPXUL_OPERATIONS.onboarding.completeOrganization,
48097
+ currentState: setup.status,
48098
+ validStates: ["ready"],
48099
+ organizationId: String(setup.orgId)
48100
+ });
48101
+ return new CapxulError(fallback.code, fallback.message, { details: {
48102
+ ...fallback.details,
48103
+ ...details
48104
+ } });
48170
48105
  }
48171
- function projectOrganizationState(state) {
48172
- if (state.phase !== "authenticated" || state.account.at !== "claimed") return {
48173
- organizationId: null,
48174
- lifecycle: null
48175
- };
48176
- const org = state.account.org;
48177
- if (org === null || org.at === "creating") return {
48178
- organizationId: null,
48179
- lifecycle: null
48180
- };
48181
- if (org.at === "failed" && org.orgId === null) return {
48182
- organizationId: null,
48183
- lifecycle: null
48184
- };
48185
- const organizationId = toOrgId(org.orgId);
48186
- return {
48187
- organizationId,
48188
- lifecycle: org.at === "loading" ? {
48189
- status: "loading",
48190
- orgId: organizationId
48191
- } : org.at === "settingUp" ? {
48192
- status: "settingUp",
48193
- orgId: organizationId,
48194
- step: org.step
48195
- } : org.at === "ready" ? {
48196
- status: "ready",
48197
- orgId: organizationId,
48198
- canTransact: true
48199
- } : {
48200
- status: "failed",
48201
- orgId: organizationId,
48202
- at: org.step,
48203
- error: publicIdentityFailure(org.failure),
48204
- retryable: org.retryable
48205
- }
48206
- };
48106
+ const cancelledOrganization = () => ({
48107
+ ok: false,
48108
+ error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.onboarding.completeOrganization })
48109
+ });
48110
+ function awaitReady(deps, orgId, options) {
48111
+ const setup = deps.organizationSetup;
48112
+ if (setup === void 0) return Promise.resolve({
48113
+ ok: false,
48114
+ error: Errors.notImplemented("organizationSetup", "subscribe")
48115
+ });
48116
+ const lifetime = deps.authLifetime();
48117
+ const isCurrent = () => deps.matchesAuthLifetime(lifetime, lifetime.authUserId);
48118
+ return new Promise((resolve) => {
48119
+ let done = false;
48120
+ let stopRemote = null;
48121
+ let stopIdentity = null;
48122
+ const finish = (result) => {
48123
+ if (done) return;
48124
+ done = true;
48125
+ stopRemote?.();
48126
+ stopIdentity?.();
48127
+ options?.signal?.removeEventListener("abort", onAbort);
48128
+ resolve(result);
48129
+ };
48130
+ const onAbort = () => finish(cancelledOrganization());
48131
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
48132
+ const releaseIdentity = deps.subscribeIdentity((state) => {
48133
+ if (state.phase !== "authenticated" || !deps.matchesAuthLifetime(lifetime, state.session.authUserId)) finish(cancelledOrganization());
48134
+ });
48135
+ if (done) releaseIdentity();
48136
+ else stopIdentity = releaseIdentity;
48137
+ if (options?.signal?.aborted || !isCurrent()) return onAbort();
48138
+ setup.subscribe(orgId, (snapshot) => {
48139
+ if (done) return;
48140
+ if (!isCurrent()) return finish(cancelledOrganization());
48141
+ if (snapshot.status === "loading") return;
48142
+ if (snapshot.status === "error") return finish({
48143
+ ok: false,
48144
+ error: snapshot.error
48145
+ });
48146
+ if (snapshot.value.status === "ready") return finish({
48147
+ ok: true,
48148
+ value: { organizationId: orgId }
48149
+ });
48150
+ if (snapshot.value.status === "needsAttention" || snapshot.value.status === "failed") finish({
48151
+ ok: false,
48152
+ error: setupFailure(snapshot.value)
48153
+ });
48154
+ }, options).then((result) => {
48155
+ if (!result.ok) return finish(result);
48156
+ if (done) result.value();
48157
+ else stopRemote = result.value;
48158
+ }).catch((cause) => finish({
48159
+ ok: false,
48160
+ error: Errors.unknown(cause)
48161
+ }));
48162
+ });
48207
48163
  }
48208
48164
  const cancelledPerson = () => ({
48209
48165
  ok: false,
@@ -48257,8 +48213,22 @@ const samePersonInput = (left, right) => {
48257
48213
  function makeOnboardingMethods(deps) {
48258
48214
  let personFlight = null;
48259
48215
  return {
48260
- subscribeOrganization(observer) {
48261
- return deps.subscribeIdentity((state) => observer(projectOrganizationState(state)));
48216
+ async listOrganizationSetups(input, options) {
48217
+ if (requestCancelled(options)) return cancelledOrganization();
48218
+ if (deps.organizationSetup === void 0) return {
48219
+ ok: false,
48220
+ error: Errors.notImplemented("organizationSetup", "listMine")
48221
+ };
48222
+ const lifetime = deps.authLifetime();
48223
+ const session = await deps.restoreSession(options);
48224
+ if (!session.ok) return session;
48225
+ if (session.value === null) return {
48226
+ ok: false,
48227
+ error: Errors.notAuthenticated()
48228
+ };
48229
+ if (!deps.matchesAuthLifetime(lifetime, String(session.value.authUserId)) || requestCancelled(options)) return cancelledOrganization();
48230
+ const listed = await deps.organizationSetup.listMine(input, options);
48231
+ return deps.matchesAuthLifetime(lifetime, String(session.value.authUserId)) && !requestCancelled(options) ? listed : cancelledOrganization();
48262
48232
  },
48263
48233
  async completePerson(input, options) {
48264
48234
  if (options?.signal?.aborted) return cancelledPerson();
@@ -48404,39 +48374,40 @@ function makeOnboardingMethods(deps) {
48404
48374
  if (personFlight?.pending === pending) personFlight = null;
48405
48375
  }
48406
48376
  },
48377
+ beginOrganization(input, options) {
48378
+ return beginOrganization(deps, input, options);
48379
+ },
48407
48380
  async completeOrganization(input, options) {
48408
- const operation = CAPXUL_OPERATIONS.onboarding.completeOrganization;
48409
- const normalized = normalizeOrganization(input);
48410
- if (!normalized.ok) return normalized;
48411
- const session = await deps.restoreSession(options);
48412
- if (!session.ok) return session;
48413
- if (session.value === null) return {
48414
- ok: false,
48415
- error: Errors.notAuthenticated()
48416
- };
48417
- const profile = await deps.loadProfile(options);
48418
- if (!profile.ok) return profile;
48419
- if (profile.value === null || profile.value.displayName === null || profile.value.handle === null) return {
48420
- ok: false,
48421
- error: Errors.wrongState({
48422
- method: operation,
48423
- currentState: "profile-incomplete",
48424
- validStates: ["profile-complete"]
48425
- })
48426
- };
48427
- const refreshed = await deps.refreshIdentity(options);
48428
- if (!refreshed.ok) return refreshed;
48429
- if (requestCancelled(options)) return {
48430
- ok: false,
48431
- error: Errors.cancelled({ operation })
48432
- };
48433
- const claimed = await reachClaimedAccount(deps, options);
48434
- if (!claimed.ok) return claimed;
48435
- if (requestCancelled(options)) return {
48436
- ok: false,
48437
- error: Errors.cancelled({ operation })
48438
- };
48439
- return createOrResumeOrganization(deps, claimed.value, normalized.value, options);
48381
+ try {
48382
+ const begun = await beginOrganization(deps, input, options);
48383
+ if (!begun.ok) return begun;
48384
+ const lifetime = deps.authLifetime();
48385
+ const isCurrent = () => deps.matchesAuthLifetime(lifetime, lifetime.authUserId);
48386
+ if (!isCurrent()) return cancelledOrganization();
48387
+ const { orgId } = begun.value;
48388
+ let setup = begun.value.setup;
48389
+ if (setup.status === "awaitingAuthorization") {
48390
+ const authorized = await deps.organizationSetup.authorize(orgId, options);
48391
+ if (!isCurrent()) return cancelledOrganization();
48392
+ if (!authorized.ok) return authorized;
48393
+ setup = authorized.value;
48394
+ }
48395
+ if (requestCancelled(options) || !isCurrent()) return cancelledOrganization();
48396
+ if (setup.status === "ready") return {
48397
+ ok: true,
48398
+ value: { organizationId: orgId }
48399
+ };
48400
+ if (setup.status === "needsAttention" || setup.status === "failed") return {
48401
+ ok: false,
48402
+ error: setupFailure(setup)
48403
+ };
48404
+ return awaitReady(deps, orgId, options);
48405
+ } catch (cause) {
48406
+ return {
48407
+ ok: false,
48408
+ error: Errors.unknown(cause)
48409
+ };
48410
+ }
48440
48411
  }
48441
48412
  };
48442
48413
  }
@@ -49489,92 +49460,6 @@ function makeUnavailablePayrollMethods() {
49489
49460
  };
49490
49461
  }
49491
49462
  //#endregion
49492
- //#region ../../packages/sdk/src/surface/_shared/org-telemetry.ts
49493
- /** Extract the domain from an email for telemetry (never the local part / PII). */
49494
- function emailDomain$1(email) {
49495
- const at = email.lastIndexOf("@");
49496
- if (at < 0 || at === email.length - 1) return void 0;
49497
- return email.slice(at + 1).toLowerCase();
49498
- }
49499
- /** Fire-and-forget emit through an optional port; never throws. */
49500
- async function emitOrgTelemetry(telemetry, event, runPromise) {
49501
- if (telemetry === void 0) return;
49502
- await Promise.resolve().then(() => runPromise(Effect.suspend(() => telemetry.emit(event)).pipe(Effect.catch((cause) => reportOrgTelemetryFailure("error", event.name, cause)), Effect.catchDefect((cause) => reportOrgTelemetryFailure("defect", event.name, cause))))).catch(() => void 0);
49503
- }
49504
- function emitOrgCreateStarted(telemetry, input, runPromise) {
49505
- const domain = input.email === void 0 ? void 0 : emailDomain$1(input.email);
49506
- return emitOrgTelemetry(telemetry, {
49507
- name: "org_create_started",
49508
- props: {
49509
- template: input.template,
49510
- ...domain === void 0 ? {} : { email_domain: domain }
49511
- }
49512
- }, runPromise);
49513
- }
49514
- /** Spread the `chainId` prop only when known — never emit a misleading `0`. */
49515
- function chainIdProp(chainId) {
49516
- return chainId === void 0 ? {} : { chainId };
49517
- }
49518
- function emitOrgSafeCreated(telemetry, input, runPromise) {
49519
- return emitOrgTelemetry(telemetry, {
49520
- name: "org_safe_created",
49521
- props: {
49522
- org_id: input.orgId,
49523
- safe_address: input.safeAddress,
49524
- ...chainIdProp(input.chainId)
49525
- }
49526
- }, runPromise);
49527
- }
49528
- function emitOrgSafeConfirmed(telemetry, input, runPromise) {
49529
- return emitOrgTelemetry(telemetry, {
49530
- name: "org_safe_confirmed",
49531
- props: {
49532
- org_id: input.orgId,
49533
- safe_address: input.safeAddress,
49534
- ...chainIdProp(input.chainId)
49535
- }
49536
- }, runPromise);
49537
- }
49538
- function emitOrgRolesSeeded(telemetry, input, runPromise) {
49539
- return emitOrgTelemetry(telemetry, {
49540
- name: "org_roles_seeded",
49541
- props: {
49542
- org_id: input.orgId,
49543
- role: input.role
49544
- }
49545
- }, runPromise);
49546
- }
49547
- function emitOrgCreated(telemetry, input, runPromise) {
49548
- return emitOrgTelemetry(telemetry, {
49549
- name: "org_created",
49550
- props: {
49551
- org_id: input.orgId,
49552
- safe_address: input.safeAddress,
49553
- ...chainIdProp(input.chainId)
49554
- }
49555
- }, runPromise);
49556
- }
49557
- function emitOrgCreateFailed(telemetry, error, runPromise) {
49558
- return emitOrgTelemetry(telemetry, {
49559
- name: "org_create_failed",
49560
- props: {
49561
- ...failureDetail(error),
49562
- reason: error.code
49563
- }
49564
- }, runPromise);
49565
- }
49566
- function reportOrgTelemetryFailure(kind, name, cause) {
49567
- if (!isOrgTelemetryDebugEnabled()) return Effect.void;
49568
- return Effect.logWarning("org.telemetry.dropped").pipe(Effect.annotateLogs({
49569
- kind,
49570
- event_name: name,
49571
- ...failureDetail(cause)
49572
- }));
49573
- }
49574
- function isOrgTelemetryDebugEnabled() {
49575
- return globalThis.process?.env?.CAPXUL_DEBUG_TELEMETRY === "1";
49576
- }
49577
- //#endregion
49578
49463
  //#region ../../packages/sdk/src/surface/org-deps.ts
49579
49464
  var OrgDepsTag = class extends Context.Service()("@capxul/sdk/OrgDeps") {};
49580
49465
  function orgDepsLayer(deps) {
@@ -49596,91 +49481,6 @@ function stripPrefix(value) {
49596
49481
  const cleaned = (underscore < 0 ? value : value.slice(underscore + 1)).replace(/[^0-9A-Za-z]/g, "");
49597
49482
  return cleaned.length > 0 ? cleaned : "0";
49598
49483
  }
49599
- /** Map an arbitrary string deterministically into lowercase hex chars. */
49600
- function toHexSeed(value) {
49601
- let out = "";
49602
- for (const ch of value) out += (ch.codePointAt(0) ?? 0).toString(16).padStart(2, "0");
49603
- return out.length > 0 ? out : "0";
49604
- }
49605
- /**
49606
- * Build the hermetic `OrgView` for the no-port L1 path: a deterministic
49607
- * counterfactual-shaped placeholder Org Safe + a `$0` treasury (D3). The live
49608
- * path replaces this with the real deployed address + RPC balance.
49609
- */
49610
- function hermeticOrgView(input) {
49611
- const orgId = toOrgId(`org_${stripPrefix(`x_${input.handle}`)}`);
49612
- const placeholder = `0x${toHexSeed(input.handle).padEnd(40, "0").slice(0, 40)}`;
49613
- return {
49614
- id: orgId,
49615
- name: input.name,
49616
- handle: input.handle,
49617
- safeAddress: toAddress(placeholder),
49618
- role: ADMIN_ROLE_LABEL,
49619
- treasury: zeroTreasury(orgId),
49620
- bio: null,
49621
- size: null,
49622
- logoUrl: null,
49623
- account: {
49624
- id: null,
49625
- address: toAddress(placeholder),
49626
- ready: null
49627
- },
49628
- setup: {
49629
- status: "settingUp",
49630
- orgId,
49631
- step: "preparingFounderAccount"
49632
- },
49633
- member: null,
49634
- capabilities: {
49635
- canManagePeople: false,
49636
- canSpend: false
49637
- },
49638
- custody: { status: "unknown" },
49639
- observedAt: 0
49640
- };
49641
- }
49642
- function createOrgProgram(input) {
49643
- return Effect.gen(function* () {
49644
- const deps = yield* OrgDepsTag;
49645
- const chainId = deps.chainId;
49646
- yield* Effect.promise(() => emitOrgCreateStarted(deps.telemetry, { template: input.template }, deps.runPromise));
49647
- return yield* Effect.gen(function* () {
49648
- if (deps.orgPort !== void 0) {
49649
- const org = yield* deps.orgPort.createOrg({ input }).pipe(Effect.mapError((error) => error.publicError));
49650
- yield* emitCreationFunnelTail(deps.telemetry, org, chainId, deps.runPromise);
49651
- return org;
49652
- }
49653
- const org = hermeticOrgView(input);
49654
- yield* emitCreationFunnelTail(deps.telemetry, org, chainId, deps.runPromise);
49655
- return org;
49656
- }).pipe(Effect.tapError((error) => Effect.promise(() => emitOrgCreateFailed(deps.telemetry, error, deps.runPromise))));
49657
- });
49658
- }
49659
- /** Emit the remaining `org_creation` funnel steps once the org is built. */
49660
- function emitCreationFunnelTail(telemetry, org, chainId, runPromise) {
49661
- return Effect.promise(async () => {
49662
- const chain = chainId === void 0 ? {} : { chainId };
49663
- await emitOrgSafeCreated(telemetry, {
49664
- orgId: org.id,
49665
- safeAddress: org.safeAddress,
49666
- ...chain
49667
- }, runPromise);
49668
- await emitOrgSafeConfirmed(telemetry, {
49669
- orgId: org.id,
49670
- safeAddress: org.safeAddress,
49671
- ...chain
49672
- }, runPromise);
49673
- if (org.role !== null) await emitOrgRolesSeeded(telemetry, {
49674
- orgId: org.id,
49675
- role: org.role
49676
- }, runPromise);
49677
- await emitOrgCreated(telemetry, {
49678
- orgId: org.id,
49679
- safeAddress: org.safeAddress,
49680
- ...chain
49681
- }, runPromise);
49682
- });
49683
- }
49684
49484
  function readTreasuryProgram(orgId) {
49685
49485
  return Effect.gen(function* () {
49686
49486
  const deps = yield* OrgDepsTag;
@@ -49747,90 +49547,6 @@ function listOrgsProgram() {
49747
49547
  });
49748
49548
  }
49749
49549
  //#endregion
49750
- //#region ../../packages/sdk/src/surface/org-lifecycle.ts
49751
- function fail(error) {
49752
- return {
49753
- ok: false,
49754
- error
49755
- };
49756
- }
49757
- function validateOrganizationLifecycleScope(orgId, lifecycle) {
49758
- if (String(lifecycle.orgId) !== String(orgId)) return fail(Errors.invalidInput("orgId", "Organization lifecycle scope does not match"));
49759
- return {
49760
- ok: true,
49761
- value: lifecycle
49762
- };
49763
- }
49764
- /** Advance only the steps still required by one durable Organization lane. */
49765
- async function advanceOrganizationSetup(setup, orgId, initial, context) {
49766
- const { signal, observationSource } = context ?? {};
49767
- const scopedInitial = validateOrganizationLifecycleScope(orgId, initial);
49768
- if (!scopedInitial.ok) return scopedInitial;
49769
- let lifecycle = scopedInitial.value;
49770
- for (let transition = 0; transition < 3; transition += 1) {
49771
- if (lifecycle.status !== "settingUp") return {
49772
- ok: true,
49773
- value: lifecycle
49774
- };
49775
- const currentStep = lifecycle.step;
49776
- if (signal?.aborted) return recordSetupFailure(setup, orgId, Errors.cancelled({ operation: CAPXUL_OPERATIONS.organization.setup }), true, observationSource);
49777
- const stepInput = copyInvocationObservation(observationSource, {
49778
- orgId,
49779
- ...signal === void 0 ? {} : { signal }
49780
- });
49781
- 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);
49782
- if (!next.ok) return recordSetupFailure(setup, orgId, next.error, isRetryableOrganizationSetupFailure(next.error), observationSource);
49783
- const scopedNext = validateOrganizationLifecycleScope(orgId, next.value);
49784
- if (!scopedNext.ok) return recordSetupFailure(setup, orgId, scopedNext.error, false, observationSource);
49785
- lifecycle = scopedNext.value;
49786
- if (currentStep === "confirmingBootstrap") return {
49787
- ok: true,
49788
- value: lifecycle
49789
- };
49790
- }
49791
- if (lifecycle.status !== "settingUp" || lifecycle.step === "confirmingBootstrap") return {
49792
- ok: true,
49793
- value: lifecycle
49794
- };
49795
- return recordSetupFailure(setup, orgId, Errors.wrongState({
49796
- method: CAPXUL_OPERATIONS.organization.setup,
49797
- currentState: lifecycle.step,
49798
- validStates: [
49799
- "confirmingBootstrap",
49800
- "ready",
49801
- "failed"
49802
- ]
49803
- }), false, observationSource);
49804
- }
49805
- async function recordSetupFailure(setup, orgId, error, retryable, observationSource) {
49806
- const recorded = await setup.recordFailure(copyInvocationObservation(observationSource, {
49807
- orgId,
49808
- error,
49809
- retryable
49810
- }));
49811
- if (!recorded.ok) return recorded;
49812
- const scopedRecorded = validateOrganizationLifecycleScope(orgId, recorded.value);
49813
- if (!scopedRecorded.ok) return scopedRecorded;
49814
- return scopedRecorded;
49815
- }
49816
- /**
49817
- * ADR-0023 R7: the layer that saw the chain failure says whether the same
49818
- * request can succeed later; its word wins over the mode table. The table is
49819
- * the one `identity/model.ts` uses, so the two gates read one list
49820
- * (`org.account.get` retried a `transient: false` 403 in 1.5 s, 2026-09-03).
49821
- */
49822
- function isRetryableProviderFailure(error) {
49823
- if (error.chain !== void 0) return error.chain.retryable;
49824
- const mode = error.mode ?? error.details?.failure_mode;
49825
- return !DEFINITIVE_PROVIDER_MODES.has(isFailureMode(mode) ? mode : void 0);
49826
- }
49827
- /** @internal Exported for the retry-gate test; the surface calls it from the setup loop. */
49828
- function isRetryableOrganizationSetupFailure(error) {
49829
- if (error.code === "CANCELLED" || error.code === "SIGNER_REJECTED") return true;
49830
- if (error.code === "PROVIDER_ERROR") return isRetryableProviderFailure(error);
49831
- return error.code === "NETWORK_ERROR" || error.code === "UNKNOWN";
49832
- }
49833
- //#endregion
49834
49550
  //#region ../../packages/sdk/src/surface/org.ts
49835
49551
  /**
49836
49552
  * Org method surface (canon §C2/§C3, D13). The entity-scoped bundle is
@@ -49858,6 +49574,20 @@ function invitationMethodsDeps(deps, convexCall) {
49858
49574
  ...deps.signer === void 0 ? {} : { signer: deps.signer }
49859
49575
  };
49860
49576
  }
49577
+ async function invokeSetup(setup, method, call) {
49578
+ if (setup === void 0) return {
49579
+ ok: false,
49580
+ error: Errors.notImplemented("organizationSetup", method)
49581
+ };
49582
+ try {
49583
+ return await call();
49584
+ } catch (cause) {
49585
+ return {
49586
+ ok: false,
49587
+ error: Errors.unknown(cause)
49588
+ };
49589
+ }
49590
+ }
49861
49591
  function makeOrgMethods(deps) {
49862
49592
  const orgDeps = {
49863
49593
  runPromise: deps.runPromise,
@@ -49883,13 +49613,6 @@ function makeOrgMethods(deps) {
49883
49613
  }))), controls, CAPXUL_OPERATIONS.org.orgs, deps.runPromise);
49884
49614
  };
49885
49615
  return {
49886
- createOrg(input, options) {
49887
- if (options?.signal?.aborted) return Promise.resolve({
49888
- ok: false,
49889
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.org.createOrg })
49890
- });
49891
- return toCapxulResult(createOrgProgram(input), layer, deps.runPromise);
49892
- },
49893
49616
  orgs: Object.assign((options) => listOrganizations(deps.invocationControls?.(options) ?? options), { invitations: deps.convexCall === void 0 ? () => Promise.resolve({
49894
49617
  ok: false,
49895
49618
  error: Errors.notImplemented("invitations", "listOwn")
@@ -49910,38 +49633,11 @@ function makeOrgMethods(deps) {
49910
49633
  convexCall,
49911
49634
  ...observedRunnerDeps(deps)
49912
49635
  }, String(orgId)),
49913
- async getLifecycle(options) {
49914
- if (options?.signal?.aborted) return {
49915
- ok: false,
49916
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.org.getLifecycle })
49917
- };
49918
- if (deps.organizationSetup === void 0) return {
49919
- ok: false,
49920
- error: Errors.notImplemented("organizationSetup", "getLifecycle")
49921
- };
49922
- const loaded = await deps.organizationSetup.loadLifecycle({ orgId });
49923
- if (!loaded.ok) return loaded;
49924
- return validateOrganizationLifecycleScope(orgId, loaded.value);
49925
- },
49926
- async retrySetup(options) {
49927
- if (options?.signal?.aborted) return {
49928
- ok: false,
49929
- error: Errors.cancelled({ operation: CAPXUL_OPERATIONS.org.retrySetup })
49930
- };
49931
- const setup = deps.organizationSetup;
49932
- if (setup === void 0) return {
49933
- ok: false,
49934
- error: Errors.notImplemented("organizationSetup", "retrySetup")
49935
- };
49936
- const retried = await setup.retry(copyInvocationObservation(options, {
49937
- orgId,
49938
- ...options?.signal === void 0 ? {} : { signal: options.signal }
49939
- }));
49940
- if (!retried.ok) return retried;
49941
- return advanceOrganizationSetup(setup, orgId, retried.value, {
49942
- signal: options?.signal,
49943
- observationSource: options
49944
- });
49636
+ setup: {
49637
+ get: (options) => invokeSetup(deps.organizationSetup, "get", () => deps.organizationSetup.get(orgId, options)),
49638
+ subscribe: (listener, options) => invokeSetup(deps.organizationSetup, "subscribe", () => deps.organizationSetup.subscribe(orgId, listener, options)),
49639
+ resume: (options) => invokeSetup(deps.organizationSetup, "resume", () => deps.organizationSetup.resume(orgId, options)),
49640
+ authorize: (options) => invokeSetup(deps.organizationSetup, "authorize", () => deps.organizationSetup.authorize(orgId, options))
49945
49641
  },
49946
49642
  profile: {
49947
49643
  get(_options) {
@@ -50297,8 +49993,8 @@ const APPLIED_ACTION_BY_EVENT = {
50297
49993
  RetryAccount: "none",
50298
49994
  CreateOrganization: "none",
50299
49995
  AttachOrganization: "none",
50300
- RetryOrganization: "none",
50301
49996
  LeaveOrganization: "none",
49997
+ ObserveOrganization: "none",
50302
49998
  OtpSent: "otp-requested",
50303
49999
  OtpFailed: "failed",
50304
50000
  Verified: "verified",
@@ -50312,9 +50008,8 @@ const APPLIED_ACTION_BY_EVENT = {
50312
50008
  AccountClaiming: "none",
50313
50009
  AccountClaimed: "none",
50314
50010
  AccountFailed: "none",
50315
- OrgAt: "none",
50316
- OrgReady: "none",
50317
- OrgFailed: "none"
50011
+ OrgSelected: "none",
50012
+ OrgSelectionFailed: "none"
50318
50013
  };
50319
50014
  const linkage = (record) => ({
50320
50015
  ...record.correlation_id === void 0 ? {} : { correlation_id: record.correlation_id },
@@ -50377,8 +50072,7 @@ const REFUSAL_EVENTS = /* @__PURE__ */ new Set([
50377
50072
  "ClaimAccount",
50378
50073
  "RetryAccount",
50379
50074
  "CreateOrganization",
50380
- "AttachOrganization",
50381
- "RetryOrganization"
50075
+ "AttachOrganization"
50382
50076
  ]);
50383
50077
  function mapIdentityProductObservation(record, state) {
50384
50078
  if (record.machine !== "identity" || !IDENTITY_EVENT_TAG_SET.has(record.event)) return NONE;
@@ -50557,7 +50251,7 @@ function assembleCapxulClient(input) {
50557
50251
  ...input.signer === void 0 ? {} : { signer: input.signer },
50558
50252
  ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup },
50559
50253
  ...input.otpTtlMs === void 0 ? {} : { otpTtlMs: input.otpTtlMs },
50560
- ...input.ports.telemetry === void 0 ? {} : { telemetry: input.ports.telemetry }
50254
+ runPromise: effectRunner.runPromise
50561
50255
  }), scope)), observation.hostObservationSnapshot);
50562
50256
  const unsubscribeProductTelemetry = actor.subscribeTransitions((record) => {
50563
50257
  effectRunner.runPromise(executeIdentityProductObservation(input.ports.telemetry, record, actor.snapshot())).catch(() => {});
@@ -50585,7 +50279,7 @@ function assembleCapxulClient(input) {
50585
50279
  return stopPromise;
50586
50280
  };
50587
50281
  if (input.signal !== void 0) input.signal.addEventListener("abort", () => void stopActor(), { once: true });
50588
- const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;
50282
+ const selectedOrgPort = input.orgPort;
50589
50283
  let kickProvisioning;
50590
50284
  const financialOps = makeFinancialOpsMethods({
50591
50285
  runPromise: effectRunner.runPromise,
@@ -50672,7 +50366,8 @@ function assembleCapxulClient(input) {
50672
50366
  getLifecycle: account.getLifecycle,
50673
50367
  snapshotIdentity: actor.snapshot,
50674
50368
  subscribeIdentity: actor.subscribe,
50675
- sendIdentity: (event, options) => runCapxulEffect(askIdentity(actor, event, options), options, CAPXUL_OPERATIONS._internal.identity.send, effectRunner.runPromise)
50369
+ sendIdentity: (event, options) => runCapxulEffect(askIdentity(actor, event, options), options, CAPXUL_OPERATIONS._internal.identity.send, effectRunner.runPromise),
50370
+ ...input.organizationSetup === void 0 ? {} : { organizationSetup: input.organizationSetup }
50676
50371
  });
50677
50372
  const system = makeSystemMethods({
50678
50373
  convexCall: input.ports.convexCall,
@@ -50802,7 +50497,6 @@ function assembleCapxulClient(input) {
50802
50497
  offramp: financialOps.offramp,
50803
50498
  paymentDocuments: financialOps.paymentDocuments,
50804
50499
  media,
50805
- createOrg: orgMethods.createOrg,
50806
50500
  orgs: orgMethods.orgs,
50807
50501
  org: orgMethods.org,
50808
50502
  signer: input.signer?.statusStore ?? UNOBSERVABLE_SIGNER_STATUS,
@@ -51978,7 +51672,8 @@ async function createCapxulClientWithSignerControls(input, controls) {
51978
51672
  organizationSetup: new ConvexOrganizationSetupAdapter({
51979
51673
  convex: adapters.value.ports.convexCall,
51980
51674
  ...signer === void 0 ? {} : { signer },
51981
- chainId: adapters.value.bootstrap.chainId
51675
+ chainId: adapters.value.bootstrap.chainId,
51676
+ runPromise: effectRunner.runPromise
51982
51677
  }),
51983
51678
  ...input.signal === void 0 ? {} : { signal: input.signal },
51984
51679
  ...input.otpTtlMs === void 0 ? {} : { otpTtlMs: input.otpTtlMs },
@@ -52722,7 +52417,7 @@ function stdioIdentity(env = process.env, options = {}) {
52722
52417
  }
52723
52418
  //#endregion
52724
52419
  //#region package.json
52725
- var version = "4.20.0-beta.10";
52420
+ var version = "4.20.0-beta.11";
52726
52421
  //#endregion
52727
52422
  //#region src/deps.ts
52728
52423
  const NO_IDENTITY = async () => void 0;