@capxul/mcp 4.20.0-beta.41 → 4.20.0-beta.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { i as __exportAll, o as __require, r as __commonJSMin, s as __toESM } from "./lib-DnmstTkB.mjs";
3
- import { $ as withCapturedAttemptContext, $n as isEvmAddress, $t as CLI_CAPABILITIES, A as convexCallErrorFromCapxul, An as sha256, At as SystemClockLayer, B as withheld, Bn as keccak256$1, Bt as AuthClientPortTag, C as PonderIndexerAdapter, Cn as toOrgId, Ct as runPortEffect, D as TelemetryPortTag, Dn as images, Dt as formatTraceparent, E as AccountReadPortTag, En as toPublishableKey, Et as toCapxulResult, F as makePaymentsMethods, Fn as slice, Ft as attachInvocationObservation, G as asCapxulError, Gn as toHex, Gt as maskedMessage, H as normalizeSafeSaltEmail, Hn as bytesToHex, Ht as globalLocalStorage, I as makeDestinationsMethods, In as concat, It as copyInvocationObservation, J as failureEvidenceProps, Jn as trim$1, Jt as BootstrapEnvelope, K as toPublicError, Kn as hexToBigInt, Kt as maskedResponseBody, L as makeCheckoutMethods, Ln as concatHex, Lt as readInvocationObservation, M as registerProductTelemetryInvocation, Mn as publicKeyToAddress, Mt as BetterAuthNodeLayer, N as makeApprovalsMethods, Nn as formatGwei$1, Nt as BetterAuthBrowserLayer, O as ConvexCallError, On as isBytes32, Ot as ActorFailure, P as makeAccountMethods, Pn as createCursor, Pt as observationRequestHeaders, Q as observationContextProps, Qn as toEpochMs, Qt as redactTelemetryProps, R as makeTargetsMethods, Rn as isAddress, Rt as sanitizeObservationContext, S as makeHoldingsMethods, Sn as isExpectedOutcome, St as runIdentityFacade, T as ConvexAccountLayer, Tn as toAllowedOrigin, Tt as runCapxulEffect, U as BASE_SEPOLIA_CHAIN_ID, Un as numberToHex$1, Ut as AuthCachePortTag, Vn as hexToBytes, Vt as detectAuthCacheAdapter, W as callOperation, Wn as stringToHex, Wt as deserializeCapxulError, X as observeFailedResult, Xn as size, Xt as toAuthUserId, Y as postHogFailureObservation, Yn as BaseError, Yt as EngineeringTelemetryBootstrapPolicy, Z as observeSdkClient, Zn as isHex, Zt as toEmail, _ as makeActivityMethods, _n as readField, _t as validateHandle, an as stampTelemetryEnvelope, ar as httpStatusMode, at as isEcdsaSignatureHex, b as ConvexSmartAccountLayer, bn as isCredentialField, bt as noSessionError, c as OrgPortTag, cn as normalizeCapxulOperation, cr as isCapxulError, ct as recoverRawDigestSigner, dn as onboardings, dr as getFunctionName, dt as makeCurrentUserMethods, en as CLI_COMMAND_NAMES, er as toAddress, et as failureProperties, fn as setups, ft as makeClientRequestMethods, g as makeMeMethods, gn as isRecord, gt as toHandle, h as bootIdentityFlow, hn as decodeChainCause, ht as toTesterKind, in as MCP_EXPECTED_OUTCOME_EVENT_NAME, ir as PROVIDER_PROBLEMS, it as httpStatusOf, j as bindProductTelemetryInvocation, jn as toRlp, jt as ClockPortTag, k as ConvexCallPortTag, kn as hashTypedData, kt as oauthBearerAuthClient, ln as OPERATIONS, lr as FAILURE_MODES, lt as signerFailure, m as executeIdentityProductObservation, mn as ORGANIZATION_SETUP_STATUSES, mt as toKycTier, n as makeOrgMethods, nn as FAILURE_CLASSES, nr as providerStatusFailure, nt as UNOBSERVABLE_SIGNER_STATUS, on as CAPXUL_OPERATIONS, or as absurd, ot as isSignerNotReadySignal, pn as ORGANIZATION_SETUP_REASONS, pt as toCountryCode, q as failureDetail$1, qn as hexToNumber, qt as serializeCapxulError, r as makeBankingMethods, rn as EXCEPTION_EVENT_NAME, rr as PROVIDERS, rt as causeChain, s as ConvexOrganizationAdapter, sn as isCapxulOperation, sr as CapxulError, st as openfortSignerNotReadyCode, t as ConvexOrganizationSetupAdapter, tn as CLI_INVOCATION_KINDS, tr as Errors, tt as version$2, un as details, ur as isFailureMode, ut as signerPathFailure, v as makePaymentDocumentsMethods, vn as redactSecrets, vt as makeAuthMethods, w as makeAccountsMethods, wn as diagnostics, wt as sessionFromActor, x as SmartAccountPortTag, xn as CAPXUL_ERROR_CODES, xt as publicIdentityFailure, y as makeSmartAccountMethods, yn as redactUrlSecrets, yt as askIdentity, z as makeVerificationMethods, zn as InvalidAddressError, zt as AuthClientError } from "./organizations-D3Z6n79m.mjs";
3
+ import { $ as withCapturedAttemptContext, $n as isEvmAddress, $t as CLI_CAPABILITIES, A as convexCallErrorFromCapxul, An as sha256, At as SystemClockLayer, B as withheld, Bn as keccak256$1, Bt as AuthClientPortTag, C as PonderIndexerAdapter, Cn as toOrgId, Ct as runPortEffect, D as TelemetryPortTag, Dn as images, Dt as formatTraceparent, E as AccountReadPortTag, En as toPublishableKey, Et as toCapxulResult, F as makePaymentsMethods, Fn as slice, Ft as attachInvocationObservation, G as asCapxulError, Gn as toHex, Gt as maskedMessage, H as normalizeSafeSaltEmail, Hn as bytesToHex, Ht as globalLocalStorage, I as makeDestinationsMethods, In as concat, It as copyInvocationObservation, J as failureEvidenceProps, Jn as trim$1, Jt as BootstrapEnvelope, K as toPublicError, Kn as hexToBigInt, Kt as maskedResponseBody, L as makeCheckoutMethods, Ln as concatHex, Lt as readInvocationObservation, M as registerProductTelemetryInvocation, Mn as publicKeyToAddress, Mt as BetterAuthNodeLayer, N as makeApprovalsMethods, Nn as formatGwei$1, Nt as BetterAuthBrowserLayer, O as ConvexCallError, On as isBytes32, Ot as ActorFailure, P as makeAccountMethods, Pn as createCursor, Pt as observationRequestHeaders, Q as observationContextProps, Qn as toEpochMs, Qt as redactTelemetryProps, R as makeTargetsMethods, Rn as isAddress, Rt as sanitizeObservationContext, S as makeHoldingsMethods, Sn as isExpectedOutcome, St as runIdentityFacade, T as ConvexAccountLayer, Tn as toAllowedOrigin, Tt as runCapxulEffect, U as BASE_SEPOLIA_CHAIN_ID, Un as numberToHex$1, Ut as AuthCachePortTag, Vn as hexToBytes, Vt as detectAuthCacheAdapter, W as callOperation, Wn as stringToHex, Wt as deserializeCapxulError, X as observeFailedResult, Xn as size, Xt as toAuthUserId, Y as postHogFailureObservation, Yn as BaseError, Yt as EngineeringTelemetryBootstrapPolicy, Z as observeSdkClient, Zn as isHex, Zt as toEmail, _ as makeActivityMethods, _n as readField, _t as validateHandle, an as stampTelemetryEnvelope, ar as httpStatusMode, at as isEcdsaSignatureHex, b as ConvexSmartAccountLayer, bn as isCredentialField, bt as noSessionError, c as OrgPortTag, cn as normalizeCapxulOperation, cr as isCapxulError, ct as recoverRawDigestSigner, dn as onboardings, dr as getFunctionName, dt as makeCurrentUserMethods, en as CLI_COMMAND_NAMES, er as toAddress, et as failureProperties, fn as setups, ft as makeClientRequestMethods, g as makeMeMethods, gn as isRecord, gt as toHandle, h as bootIdentityFlow, hn as decodeChainCause, ht as toTesterKind, in as MCP_EXPECTED_OUTCOME_EVENT_NAME, ir as PROVIDER_PROBLEMS, it as httpStatusOf, j as bindProductTelemetryInvocation, jn as toRlp, jt as ClockPortTag, k as ConvexCallPortTag, kn as hashTypedData, kt as oauthBearerAuthClient, ln as OPERATIONS, lr as FAILURE_MODES, lt as signerFailure, m as executeIdentityProductObservation, mn as ORGANIZATION_SETUP_STATUSES, mt as toKycTier, n as makeOrgMethods, nn as FAILURE_CLASSES, nr as providerStatusFailure, nt as UNOBSERVABLE_SIGNER_STATUS, on as CAPXUL_OPERATIONS, or as absurd, ot as isSignerNotReadySignal, pn as ORGANIZATION_SETUP_REASONS, pt as toCountryCode, q as failureDetail$1, qn as hexToNumber, qt as serializeCapxulError, r as makeBankingMethods, rn as EXCEPTION_EVENT_NAME, rr as PROVIDERS, rt as causeChain, s as ConvexOrganizationAdapter, sn as isCapxulOperation, sr as CapxulError, st as openfortSignerNotReadyCode, t as ConvexOrganizationSetupAdapter, tn as CLI_INVOCATION_KINDS, tr as Errors, tt as version$2, un as details, ur as isFailureMode, ut as signerPathFailure, v as makePaymentDocumentsMethods, vn as redactSecrets, vt as makeAuthMethods, w as makeAccountsMethods, wn as diagnostics, wt as sessionFromActor, x as SmartAccountPortTag, xn as CAPXUL_ERROR_CODES, xt as publicIdentityFailure, y as makeSmartAccountMethods, yn as redactUrlSecrets, yt as askIdentity, z as makeVerificationMethods, zn as InvalidAddressError, zt as AuthClientError } from "./organizations-CeOxH4kV.mjs";
4
4
  import { t as secp256k1 } from "./secp256k1-vkvPWdOZ.mjs";
5
5
  import { t as require_lib } from "./lib-CoGPQsbr.mjs";
6
6
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
@@ -26,7 +26,7 @@ import { z } from "zod";
26
26
  import { McpServer, createMcpHandler } from "@modelcontextprotocol/server";
27
27
  import { instrument } from "@posthog/mcp";
28
28
  //#region package.json
29
- var version$1 = "4.20.0-beta.41";
29
+ var version$1 = "4.20.0-beta.42";
30
30
  //#endregion
31
31
  //#region ../../node_modules/.pnpm/convex@1.39.1_react@19.2.7/node_modules/convex/dist/esm/values/base64.js
32
32
  var lookup = [];
@@ -1278,7 +1278,8 @@ const CLI_ENGINEERING_LIMITS = Object.freeze({
1278
1278
  ordinaryRequests: 2,
1279
1279
  requestBytes: 1572864,
1280
1280
  metricSeries: 16,
1281
- requestTimeoutMs: 1e3
1281
+ requestTimeoutMs: 1e3,
1282
+ responseBytes: 65536
1282
1283
  });
1283
1284
  //#endregion
1284
1285
  //#region ../../packages/observability/src/delivery/admission.ts
@@ -1292,6 +1293,7 @@ function newDeliveryState(budget, ownsMetrics) {
1292
1293
  logs: [],
1293
1294
  spans: /* @__PURE__ */ new Map(),
1294
1295
  terminalBodies: /* @__PURE__ */ new WeakSet(),
1296
+ packets: /* @__PURE__ */ new WeakMap(),
1295
1297
  bodyLeases: /* @__PURE__ */ new WeakMap(),
1296
1298
  pendingBodies: /* @__PURE__ */ new Set()
1297
1299
  };
@@ -1586,6 +1588,14 @@ function boundedSpan(state, span) {
1586
1588
  }
1587
1589
  //#endregion
1588
1590
  //#region ../../packages/observability/src/delivery/requests.ts
1591
+ const rememberPacket = (state, body, lane) => {
1592
+ if (state.budget.journal === void 0 || body._tag !== "Uint8Array" || body.body.byteLength > CLI_ENGINEERING_LIMITS.requestBytes) return;
1593
+ state.packets.set(body, {
1594
+ lane,
1595
+ body: new TextDecoder().decode(body.body),
1596
+ terminal: state.terminalBodies.has(body)
1597
+ });
1598
+ };
1589
1599
  function admittedSerialization(state, delegate) {
1590
1600
  return {
1591
1601
  logs(data) {
@@ -1594,6 +1604,7 @@ function admittedSerialization(state, delegate) {
1594
1604
  const body = delegate.logs(data);
1595
1605
  if (data.resourceLogs.some((r) => r.scopeLogs.some((s) => s.logRecords?.some((l) => terminalName(l.body?.stringValue ?? ""))))) state.terminalBodies.add(body);
1596
1606
  holdBody(state, body, releases);
1607
+ rememberPacket(state, body, "logs");
1597
1608
  return body;
1598
1609
  } catch (error) {
1599
1610
  for (const release of releases) release();
@@ -1611,6 +1622,7 @@ function admittedSerialization(state, delegate) {
1611
1622
  const body = delegate.traces(data);
1612
1623
  if (data.resourceSpans.some((r) => r.scopeSpans.some((s) => s.spans.some((span) => terminalName(span.name))))) state.terminalBodies.add(body);
1613
1624
  holdBody(state, body, releases);
1625
+ rememberPacket(state, body, "traces");
1614
1626
  return body;
1615
1627
  } catch (error) {
1616
1628
  for (const release of releases) release();
@@ -1620,6 +1632,7 @@ function admittedSerialization(state, delegate) {
1620
1632
  metrics(data) {
1621
1633
  const body = delegate.metrics(data);
1622
1634
  state.terminalBodies.add(body);
1635
+ rememberPacket(state, body, "metrics");
1623
1636
  return body;
1624
1637
  }
1625
1638
  };
@@ -1642,7 +1655,7 @@ function admittedTransport(state, client, enabled = () => true) {
1642
1655
  let received = 0;
1643
1656
  return Stream.runForEach(result.stream, (chunk) => Effect.sync(() => {
1644
1657
  received += chunk.byteLength;
1645
- if (received > 65536) throw new Error("Engineering response limit exceeded");
1658
+ if (received > CLI_ENGINEERING_LIMITS.responseBytes) throw new Error("Engineering response limit exceeded");
1646
1659
  })).pipe(Effect.catchReason("HttpClientError", "EmptyBodyError", () => Effect.void));
1647
1660
  }))).pipe(HttpClient.filterStatusOk, HttpClient.retryTransient({
1648
1661
  times: 1,
@@ -1666,7 +1679,15 @@ function admittedTransport(state, client, enabled = () => true) {
1666
1679
  }
1667
1680
  const lease = state.bodyLeases.get(request.body);
1668
1681
  if (lease !== void 0) lease.started = true;
1669
- return response.pipe(Effect.asVoid, Effect.timeoutOption(CLI_ENGINEERING_LIMITS.requestTimeoutMs), Effect.raceFirst(Deferred.await(state.closed).pipe(Effect.andThen(Effect.interrupt))), Effect.tap((result) => Effect.sync(() => {
1682
+ return (budget.journal === void 0 ? response : Effect.suspend(() => {
1683
+ const packet = state.packets.get(request.body);
1684
+ state.packets.delete(request.body);
1685
+ if (packet === void 0 || !enabled()) {
1686
+ budget.drop();
1687
+ return Effect.void;
1688
+ }
1689
+ return budget.journal?.(packet) ?? Effect.void;
1690
+ })).pipe(Effect.asVoid, Effect.timeoutOption(CLI_ENGINEERING_LIMITS.requestTimeoutMs), Effect.raceFirst(Deferred.await(state.closed).pipe(Effect.andThen(Effect.interrupt))), Effect.tap((result) => Effect.sync(() => {
1670
1691
  if (Option.isNone(result)) budget.drop();
1671
1692
  })), Effect.catchCause(() => Effect.sync(() => {
1672
1693
  budget.drop();
@@ -2152,9 +2173,11 @@ const logEngineeringInfo = (message, attributes) => {
2152
2173
  /** Shared browser/server OTLP layer. OtlpLogger merges with incumbent loggers once. */
2153
2174
  const makeEngineeringTelemetryLayer = (config) => {
2154
2175
  const validated = validateEngineeringTelemetryConfig(config);
2176
+ if (validated.deliveryBudget?.journal !== void 0 && validated.privacy !== "minimal") throw new TypeError("CLI journal delivery requires minimal engineering privacy");
2155
2177
  return Layer.suspend(() => {
2156
2178
  const bounded = validated.deliveryBudget === void 0 ? void 0 : cliEngineeringDelivery(validated.deliveryBudget, validated.serviceName === "capxul-cli");
2157
2179
  const endpoints = postHogOtlpEndpoints(validated.host);
2180
+ const headers = validated.deliveryBudget?.journal === void 0 ? validated.headers : void 0;
2158
2181
  let disabled = false;
2159
2182
  const enabled = () => {
2160
2183
  if (disabled) return false;
@@ -2185,13 +2208,13 @@ const makeEngineeringTelemetryLayer = (config) => {
2185
2208
  };
2186
2209
  const tracing = Layer.effect(Tracer.Tracer, OtlpTracer.make({
2187
2210
  url: endpoints.traces,
2188
- headers: validated.headers,
2211
+ headers,
2189
2212
  resource,
2190
2213
  ...delivery
2191
2214
  }).pipe(Effect.map((tracer) => makeLeakSafeEngineeringTracer(bounded?.tracer(tracer) ?? tracer, enabled)))).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));
2192
2215
  const ownedLogging = Layer.effect(EngineeringLog, OtlpLogger.make({
2193
2216
  url: endpoints.logs,
2194
- headers: validated.headers,
2217
+ headers,
2195
2218
  resource,
2196
2219
  ...delivery,
2197
2220
  ...bounded === void 0 ? {} : { excludeLogSpans: true }
@@ -2204,7 +2227,7 @@ const makeEngineeringTelemetryLayer = (config) => {
2204
2227
  const logging = Logger.layer([EngineeringLog], { mergeWithExisting: true }).pipe(Layer.provideMerge(ownedLogging));
2205
2228
  const metricConfig = {
2206
2229
  url: endpoints.metrics,
2207
- headers: validated.headers,
2230
+ headers,
2208
2231
  resource,
2209
2232
  temporality: "delta",
2210
2233
  ...delivery
@@ -1,39 +1,6 @@
1
1
  import { r as __commonJSMin } from "./lib-DnmstTkB.mjs";
2
2
  import { c as clean, f as swap32IfBE, i as aexists, m as u32$1, n as Hash$1, o as anumber, p as toBytes$2, r as abytes, s as aoutput, t as sha256$2, u as createHasher } from "./sha2-D5rBHwg7.mjs";
3
3
  import { Cause, Clock, Context, Data, Deferred, Effect, Exit, Fiber, Layer, Option, Predicate, Queue, Ref, Result, Schema, SchemaAST, SchemaGetter, SchemaIssue, SchemaParser, Tracer } from "effect";
4
- //#region ../../packages/observability/src/catalog/infrastructure.ts
5
- /** Find consecutive qualifying minutes across the hourly evaluator's gap. */
6
- function sustainedCpu(key, state, minutes, threshold) {
7
- return {
8
- key,
9
- dashboard: false,
10
- display: "BoldNumber",
11
- query: [
12
- "select if(count() > 0, 1, 0) as alert_value from (",
13
- " select host from (",
14
- " select host, minute,",
15
- " toUnixTimestamp(minute) / 60 - row_number() over (partition by host order by minute) as interval_id",
16
- " from (",
17
- " select s.resource_attributes['host.name'] as host,",
18
- ` toStartOfMinute(m.timestamp) as minute, ${state === "idle" ? "1 - avg(m.value)" : "avg(m.value)"} as utilization`,
19
- " from posthog.metrics m",
20
- " inner join posthog.metric_series s on m.series_fingerprint = s.series_fingerprint",
21
- " where m.timestamp > now() - interval 2 hour",
22
- " and m.timestamp < toStartOfMinute(now())",
23
- " and m.service_name = 'capxul-worker-host'",
24
- " and m.metric_name = 'system.cpu.utilization'",
25
- " and s.resource_attributes.capxul_env = '<env>'",
26
- ` and s.attributes.state = '${state}'`,
27
- " group by host, minute",
28
- ` ) where utilization > ${threshold}`,
29
- " ) group by host, interval_id",
30
- ` having count() >= ${minutes}`,
31
- ")"
32
- ]
33
- };
34
- }
35
- sustainedCpu("worker_cpu_steal_15m", "steal", 15, .2), sustainedCpu("worker_cpu_busy_30m", "idle", 30, .8);
36
- //#endregion
37
4
  //#region ../../node_modules/.pnpm/convex@1.39.1_react@19.2.7/node_modules/convex/dist/esm/server/functionName.js
38
5
  const functionName = Symbol.for("functionName");
39
6
  //#endregion
@@ -1446,6 +1413,16 @@ const PAYMENT_STATUSES = [
1446
1413
  "cancelled",
1447
1414
  "failed"
1448
1415
  ];
1416
+ const ATTEMPT_STATES = [
1417
+ "prepared",
1418
+ "sending",
1419
+ "sent",
1420
+ "succeeded",
1421
+ "reverted",
1422
+ "expired",
1423
+ "displaced",
1424
+ "unknown"
1425
+ ];
1449
1426
  /** The lifecycle of one signed Payment execution attempt. */
1450
1427
  const PAYMENT_EXECUTION_STATUS = {
1451
1428
  PENDING: "pending",
@@ -5851,6 +5828,30 @@ Schema.Union([
5851
5828
  retryable: Schema.Literal(true)
5852
5829
  })
5853
5830
  ]);
5831
+ /**
5832
+ * One indexed `PaymentSent` fact, as the indexer decoded it (D2): the Payment's
5833
+ * settlement proof, read by settlement id. `position` is the PaymentSent log;
5834
+ * `transfer` is the ERC-20 `Transfer` that log settled, bound in the same
5835
+ * transaction, so the ledger keys the settlement on the same block-global
5836
+ * Transfer index the receipt path keys on (`payments.by_settlement_log`).
5837
+ */
5838
+ const IndexedSettlementFactSchema = Schema.Struct({
5839
+ chainId: BaseSepoliaChainIdSchema,
5840
+ txHash: TxHashSchema$1,
5841
+ blockNumber: BlockNumberSchema$1,
5842
+ blockHash: Bytes32Schema,
5843
+ blockTimestamp: Uint48Schema,
5844
+ position: EvidenceLogPositionSchema,
5845
+ contract: AddressSchema$1,
5846
+ settlementId: SettlementIdSchema,
5847
+ sender: AddressSchema$1,
5848
+ recipient: AddressSchema$1,
5849
+ token: AddressSchema$1,
5850
+ amount: Uint256StringSchema,
5851
+ kind: Uint16Schema,
5852
+ documentHash: Bytes32Schema,
5853
+ transfer: EvidenceLogPositionSchema
5854
+ }).pipe(strict);
5854
5855
  Schema.Literals([
5855
5856
  "Payment",
5856
5857
  "Payout",
@@ -5987,6 +5988,11 @@ Schema.Union([
5987
5988
  userOpHash: Bytes32Schema
5988
5989
  }),
5989
5990
  ApplyVerifiedEvidenceCommandSchema,
5991
+ Schema.Struct({
5992
+ kind: Schema.Literal("chain_settled"),
5993
+ paymentId: PaymentIdSchema,
5994
+ fact: IndexedSettlementFactSchema
5995
+ }),
5990
5996
  Schema.Struct({
5991
5997
  kind: Schema.Literal("apply_rail_delivery"),
5992
5998
  paymentId: PaymentIdSchema
@@ -9787,7 +9793,7 @@ const ANSWER$1 = ["PROVIDER_RESPONSE_INVALID"];
9787
9793
  /** The sender's balance, or the paymaster, cannot cover the UserOperation. */
9788
9794
  const FUNDING$1 = ["INSUFFICIENT_BALANCE"];
9789
9795
  /** This deployment has money writes switched off. */
9790
- const DISABLED$1 = ["NOT_IMPLEMENTED"];
9796
+ const DISABLED$2 = ["NOT_IMPLEMENTED"];
9791
9797
  /** Another submission of the same execution won, or its nonce moved on. */
9792
9798
  const RACE = ["SUPERSEDED"];
9793
9799
  /** Preparing any Payment: plan it, then build the sponsored UserOperation. */
@@ -9799,7 +9805,7 @@ const PREPARE = [
9799
9805
  ...CHAIN$2,
9800
9806
  ...ANSWER$1,
9801
9807
  ...FUNDING$1,
9802
- ...DISABLED$1
9808
+ ...DISABLED$2
9803
9809
  ];
9804
9810
  /** Sending a signed execution once, then recording what the bundler accepted. */
9805
9811
  const SUBMIT$1 = [
@@ -9811,7 +9817,7 @@ const SUBMIT$1 = [
9811
9817
  ...CHAIN$2,
9812
9818
  ...ANSWER$1,
9813
9819
  ...RACE,
9814
- ...DISABLED$1
9820
+ ...DISABLED$2
9815
9821
  ];
9816
9822
  /** The Payments a caller can see: its own Account's, or an Organization's it takes part in. */
9817
9823
  const records = {
@@ -10453,23 +10459,10 @@ const PermissionVerificationOutcomeSchema = Schema.Struct({
10453
10459
  });
10454
10460
  //#endregion
10455
10461
  //#region ../../packages/protocol/src/permissions/command-view-schema.ts
10462
+ /** One execution of a Permission command: its Attempt state (D3) and the operation it carries. */
10456
10463
  const PermissionCommandExecutionSchema = Schema.Struct({
10457
10464
  executionId: MoneyExecutionIdSchema,
10458
- state: Schema.Literals([
10459
- "prepared",
10460
- "submitting",
10461
- "submitted",
10462
- "pending",
10463
- "included",
10464
- "dropped",
10465
- "replaced",
10466
- "expired",
10467
- "unresolved",
10468
- "failed",
10469
- "settled",
10470
- "rejected",
10471
- "superseded"
10472
- ]),
10465
+ state: Schema.Literals(ATTEMPT_STATES),
10473
10466
  expectedUserOpHash: Schema.optional(Bytes32Schema),
10474
10467
  userOpHash: Schema.optional(Bytes32Schema),
10475
10468
  submittedAt: Schema.optional(nonNegativeInteger("submittedAt")),
@@ -10651,6 +10644,8 @@ const ANSWER = ["PROVIDER_RESPONSE_INVALID"];
10651
10644
  const SPONSOR = ["INSUFFICIENT_BALANCE"];
10652
10645
  /** Another submission of the same execution won the race. */
10653
10646
  const SUBMIT = ["SUPERSEDED"];
10647
+ /** The one Attempt writer (D3) refuses every write when this deployment has money writes off. */
10648
+ const DISABLED$1 = ["NOT_IMPLEMENTED"];
10654
10649
  const commands = {
10655
10650
  /** Plan one Permission command and save it, or return the saved one for the same request. */
10656
10651
  prepare: Operation.mutation("permissions.commands.prepare", {
@@ -10751,7 +10746,8 @@ verify: Operation.action("permissions.verifications.verify", {
10751
10746
  ...DEFECTS,
10752
10747
  ...ACCOUNT,
10753
10748
  ...STATE$1,
10754
- ...CHAIN$1
10749
+ ...CHAIN$1,
10750
+ ...DISABLED$1
10755
10751
  ]
10756
10752
  }) };
10757
10753
  const authorities = {
@@ -11364,21 +11360,13 @@ const checkouts = {
11364
11360
  request: Operation.query("requests.checkouts.request", {
11365
11361
  input: Link,
11366
11362
  output: Schema.NullOr(RequestCheckoutSummarySchema),
11367
- errors: [
11368
- ...PUBLIC,
11369
- ...DEFECTS,
11370
- ...DISABLED
11371
- ]
11363
+ errors: [...PUBLIC, ...DEFECTS]
11372
11364
  }),
11373
11365
  /** Freeze an unaddressed request for this wallet, then its unsigned transactions. */
11374
11366
  prepareRequest: Operation.mutation("requests.checkouts.prepareRequest", {
11375
11367
  input: LinkFunding,
11376
11368
  output: RequestCheckoutPreparationSchema,
11377
- errors: [
11378
- ...PUBLIC,
11379
- ...DEFECTS,
11380
- ...DISABLED
11381
- ]
11369
+ errors: [...PUBLIC, ...DEFECTS]
11382
11370
  }),
11383
11371
  /** A request link's saved receipt, checked against the chain now; null when there is none. */
11384
11372
  requestState: Operation.action("requests.checkouts.requestState", {
@@ -11419,21 +11407,13 @@ const checkouts = {
11419
11407
  invoice: Operation.query("requests.checkouts.invoice", {
11420
11408
  input: Link,
11421
11409
  output: Schema.NullOr(InvoiceCheckoutSummarySchema),
11422
- errors: [
11423
- ...PUBLIC,
11424
- ...DEFECTS,
11425
- ...DISABLED
11426
- ]
11410
+ errors: [...PUBLIC, ...DEFECTS]
11427
11411
  }),
11428
11412
  /** The unsigned allowance and payment transactions for an open Invoice. */
11429
11413
  prepareInvoice: Operation.query("requests.checkouts.prepareInvoice", {
11430
11414
  input: LinkFunding,
11431
11415
  output: InvoiceCheckoutPreparationSchema,
11432
- errors: [
11433
- ...PUBLIC,
11434
- ...DEFECTS,
11435
- ...DISABLED
11436
- ]
11416
+ errors: [...PUBLIC, ...DEFECTS]
11437
11417
  }),
11438
11418
  /** An Invoice link's saved receipt, checked against the chain now; null when it names no Invoice. */
11439
11419
  invoiceState: Operation.action("requests.checkouts.invoiceState", {
@@ -11518,9 +11498,13 @@ const OPERATIONS = [
11518
11498
  const PEOPLE_OPERATIONS = {
11519
11499
  /** Access's internal functions and HTTP pages; its public rows join from `OPERATIONS`. */
11520
11500
  access: {
11501
+ /** One request to a route BetterAuth mounts (`/api/auth/*`), with its route and status. */
11502
+ auth: { request: "access.auth.request" },
11521
11503
  /** The OAuth pages the agent authorization server sends a browser to. */
11522
11504
  agents: {
11523
11505
  consentPage: "access.agents.consentPage",
11506
+ /** `GET /.well-known/oauth-authorization-server` and `/.well-known/openid-configuration`. */
11507
+ discovery: "access.agents.discovery",
11524
11508
  loginPage: "access.agents.loginPage"
11525
11509
  },
11526
11510
  /** AUTH A2 (#2072): one name per durable transition the native endpoints run. */
@@ -11876,6 +11860,8 @@ load: "organizations.treasuries.load" }
11876
11860
  recordSnapshot: "parties.verifications.recordSnapshot",
11877
11861
  recordPrefill: "parties.verifications.recordPrefill",
11878
11862
  upload: "parties.verifications.upload",
11863
+ /** `OPTIONS /parties/verifications/documents`: the CORS preflight. */
11864
+ uploadPreflight: "parties.verifications.uploadPreflight",
11879
11865
  recordDocument: "parties.verifications.recordDocument",
11880
11866
  loadDocument: "parties.verifications.loadDocument",
11881
11867
  deleteDocument: "parties.verifications.deleteDocument"
@@ -11949,18 +11935,20 @@ emitSaved: "activity.annotations.emitSaved" },
11949
11935
  executions: {
11950
11936
  store: "payments.executions.store",
11951
11937
  loadActive: "payments.executions.loadActive",
11938
+ /** The command's stored operations at one nonce of its own lane, read before a build on a lane that moved (CAP-701). */
11939
+ loadLaneHolders: "payments.executions.loadLaneHolders",
11952
11940
  load: "payments.executions.load",
11953
11941
  claim: "payments.executions.claim",
11942
+ /** One Attempt classified from chain proof (D3), outside the verification lease. */
11943
+ classify: "payments.executions.classify",
11944
+ /** A Payment send's own-lane diagnostic, recorded on its prepared Attempt. */
11954
11945
  resetClaim: "payments.executions.resetClaim",
11955
- releaseClaim: "payments.executions.releaseClaim",
11956
- supersedeClaim: "payments.executions.supersedeClaim",
11957
11946
  complete: "payments.executions.complete",
11958
11947
  fail: "payments.executions.fail",
11959
11948
  recordSendAttempt: "payments.executions.recordSendAttempt",
11960
11949
  /** The cron's sweep of submissions whose claim lapsed. */
11961
11950
  recoverClaims: "payments.executions.recoverClaims",
11962
- listExpiredClaims: "payments.executions.listExpiredClaims",
11963
- retireExpired: "payments.executions.retireExpired"
11951
+ listExpiredClaims: "payments.executions.listExpiredClaims"
11964
11952
  },
11965
11953
  records: {
11966
11954
  /** The one guarded writer of the Payment ledger. */
@@ -11980,7 +11968,17 @@ emitSaved: "activity.annotations.emitSaved" },
11980
11968
  recover: "payments.verifications.recover",
11981
11969
  recoverJob: "payments.verifications.recoverJob",
11982
11970
  retryMismatch: "payments.verifications.retryMismatch",
11983
- retryUnresolved: "payments.verifications.retryUnresolved"
11971
+ retryUnresolved: "payments.verifications.retryUnresolved",
11972
+ /** D2: settle the named open Payments from their indexed `PaymentSent` facts. */
11973
+ settle: "payments.verifications.settle",
11974
+ /** The minute cron: the open Payments the settle action missed, oldest first. */
11975
+ sweepSettlements: "payments.verifications.sweepSettlements",
11976
+ /** The settle action's read: which of its Payments are still open, and their terms. */
11977
+ loadOpenSettlements: "payments.verifications.loadOpenSettlements",
11978
+ /** The sweep's read: the oldest open Payment ids, 50 or fewer. */
11979
+ listOpenSettlements: "payments.verifications.listOpenSettlements",
11980
+ /** The settle action's transaction: one indexed fact through the Payment writer. */
11981
+ applySettlement: "payments.verifications.applySettlement"
11984
11982
  },
11985
11983
  movements: {
11986
11984
  migrateInclusion: "payments.movements.migrateInclusion",
@@ -12104,6 +12102,8 @@ const PLATFORM_OPERATIONS = {
12104
12102
  applications: {
12105
12103
  bootstraps: {
12106
12104
  admitKey: "applications.bootstraps.admitKey",
12105
+ /** `OPTIONS /v1/client/bootstrap`: the CORS preflight. */
12106
+ preflight: "applications.bootstraps.preflight",
12107
12107
  recordUse: "applications.bootstraps.recordUse",
12108
12108
  resolve: "applications.bootstraps.resolve"
12109
12109
  },
@@ -12114,7 +12114,9 @@ const PLATFORM_OPERATIONS = {
12114
12114
  },
12115
12115
  quickstarts: {
12116
12116
  claim: "applications.quickstarts.claim",
12117
- mint: "applications.quickstarts.mint"
12117
+ mint: "applications.quickstarts.mint",
12118
+ /** `OPTIONS /v1/client/mint-quickstart-key`: the CORS preflight. */
12119
+ preflight: "applications.quickstarts.preflight"
12118
12120
  },
12119
12121
  registrations: { register: "applications.registrations.register" },
12120
12122
  repairs: {
@@ -12207,6 +12209,13 @@ const PLATFORM_OPERATIONS = {
12207
12209
  * by the tool.
12208
12210
  */
12209
12211
  mcp: { request: "mcp.request" },
12212
+ /** The SDK failure relay's HTTP door; a relayed failure is named by its own operation. */
12213
+ telemetry: { relay: {
12214
+ /** `POST /v1/client/observe`: one relay request, beside the failure it relays. */
12215
+ observe: "telemetry.relay.observe",
12216
+ /** `OPTIONS /v1/client/observe`: the CORS preflight. */
12217
+ preflight: "telemetry.relay.preflight"
12218
+ } },
12210
12219
  _internal: {
12211
12220
  accounts: { fund: "_internal.accounts.fund" },
12212
12221
  close: "_internal.close",
@@ -18348,7 +18357,7 @@ function mapAccountLifecycle(input) {
18348
18357
  }
18349
18358
  //#endregion
18350
18359
  //#region ../../packages/sdk/package.json
18351
- var version$1 = "4.20.0-beta.41";
18360
+ var version$1 = "4.20.0-beta.42";
18352
18361
  //#endregion
18353
18362
  //#region ../../packages/sdk/src/observability/telemetry/exception-projection.ts
18354
18363
  /** Fixed fallback for failures that have no safe message. */
@@ -20944,7 +20953,7 @@ function sourcePurpose(source) {
20944
20953
  return purpose === "unspecified" ? "quick_pay" : purpose;
20945
20954
  }
20946
20955
  function isBirthItem(item) {
20947
- return item?.operation === "send" || item?.operation === "create_commitment";
20956
+ return item?.operation === "send";
20948
20957
  }
20949
20958
  /** Retry keeps the original request instruction. Ordinary Payment retries keep actor context. */
20950
20959
  function requestRetryInstruction(input) {
@@ -21222,29 +21231,22 @@ function recipientMatches$1(source, observation, target) {
21222
21231
  return (observation.recipient_locator_kind === to.kind || payrollEmailResolution) && observation.recipient_address.toLowerCase() === target && observation.external_address_acknowledged === (source.externalAddressAcknowledged === true) && (to.kind !== "address" || to.address.toLowerCase() === target) && (to.kind !== "party" || observation.recipient_party_id === to.partyId) && (to.kind !== "handle" || observation.recipient_handle?.toLowerCase() === to.handle.toLowerCase());
21223
21232
  }
21224
21233
  /**
21225
- * The later release the caller asked for, or null for one paid at once. A
21226
- * stored birth item names its operation; an Organization request item names
21227
- * only its `timing` (#2439).
21234
+ * The caller asked for a Payment paid at once. A stored birth item names its
21235
+ * operation; an Organization request item names only its `timing` (#2439).
21236
+ * Held releases retired in the V3 cut (D6), so a source that asks for one
21237
+ * matches nothing.
21228
21238
  */
21229
- function heldRelease(source) {
21230
- if ("operation" in source) return source.operation === "create_commitment" ? source.release : null;
21231
- return source.timing?.kind === "instant" ? null : source.timing ?? null;
21239
+ function paysAtOnce$1(source) {
21240
+ if ("operation" in source) return source.operation === "send";
21241
+ return (source.timing?.kind ?? "instant") === "instant";
21232
21242
  }
21233
21243
  function operationMatches(source, item) {
21234
- if (item.operation !== "send" && item.operation !== "create_commitment") return false;
21235
- if (!Object.entries(PAYMENT_PURPOSE_KIND_CODES).some(([purpose, code]) => purpose === sourcePurpose(source) && code === item.kind)) return false;
21236
- const release = heldRelease(source);
21237
- if (release === null) return item.operation === "send";
21238
- if (item.operation !== "create_commitment") return false;
21239
- const start = Math.floor((release.kind === "scheduled" ? release.at : release.startsAt) / 1e3);
21240
- const cliff = Math.floor((release.kind === "scheduled" ? release.at : release.cliffAt ?? release.startsAt) / 1e3);
21241
- const end = Math.floor((release.kind === "scheduled" ? release.at : release.endsAt) / 1e3);
21242
- return item.startTime === start && item.cliffTime === cliff && item.endTime === end;
21244
+ return paysAtOnce$1(source) && Object.entries(PAYMENT_PURPOSE_KIND_CODES).some(([purpose, code]) => purpose === sourcePurpose(source) && code === item.kind);
21243
21245
  }
21244
21246
  function itemFactsMatch(source, item, observation) {
21245
21247
  const exact = toExactAssetAmount(source.amount, CONFIGURED_MONEY_ASSETS);
21246
21248
  const asset = CONFIGURED_MONEY_ASSETS.find((row) => row.assetId === exact.asset);
21247
- if (item.tokenAddress.toLowerCase() !== asset?.tokenAddress.toLowerCase() || (item.operation === "send" ? item.rawAmount : item.totalAmount) !== exact.minorUnits || !operationMatches(source, item) || observation !== void 0 && "to" in source && !recipientMatches$1(source, observation, item.recipientSafe.toLowerCase())) return null;
21249
+ if (item.tokenAddress.toLowerCase() !== asset?.tokenAddress.toLowerCase() || item.rawAmount !== exact.minorUnits || !operationMatches(source, item) || observation !== void 0 && "to" in source && !recipientMatches$1(source, observation, item.recipientSafe.toLowerCase())) return null;
21248
21250
  return exact;
21249
21251
  }
21250
21252
  async function oneBirthMatches(input) {
@@ -21265,23 +21267,7 @@ function confirmedRequestFactsMatch(confirmation, source, item, instruction) {
21265
21267
  if (confirmation.payer.kind === "account") {
21266
21268
  if (source.actor.kind !== "account") return false;
21267
21269
  } else if (source.actor.kind !== "organization" || source.actor.orgId !== confirmation.payer.orgId) return false;
21268
- return confirmation.release.kind === "instant" ? original.operation === "send" : original.operation === "create_commitment" && documentJson(original.release) === documentJson(confirmation.release);
21269
- }
21270
- function redirectMatches(evidence, item) {
21271
- const request = evidence.request;
21272
- if ("items" in request || request.kind !== "redirect" || item.operation !== "redirect_commitment") return false;
21273
- const observation = evidence.recipientObservations[0];
21274
- const recipient = request.recipient;
21275
- return evidence.recipientObservations.length === 1 && observation !== void 0 && observation.recipient_locator_kind === recipient.kind && observation.recipient_address.toLowerCase() === item.recipientSafe.toLowerCase() && (recipient.kind !== "address" || recipient.address.toLowerCase() === item.recipientSafe.toLowerCase()) && (recipient.kind !== "party" || observation.recipient_party_id === recipient.partyId) && (recipient.kind !== "handle" || observation.recipient_handle?.toLowerCase() === recipient.handle.toLowerCase());
21276
- }
21277
- function lifecycleMatches(evidence) {
21278
- const request = evidence.request;
21279
- if ("items" in request || request.kind === "retry" || request.kind === "offer_checkout" || request.kind === "invoice_checkout") return false;
21280
- const command = evidence.preparedCommand;
21281
- const item = command?.items[0];
21282
- const persisted = evidence.lifecycleSource;
21283
- if (command?.items.length !== 1 || persisted === void 0 || item?.operation !== "claim_commitment" && item?.operation !== "cancel_commitment" && item?.operation !== "redirect_commitment") return false;
21284
- return item.paymentId === request.paymentId && persisted.paymentId === request.paymentId && item.operation === `${request.kind}_commitment` && item.commitmentId === persisted.commitmentId && (item.operation === "claim_commitment" || item.documentHash === persisted.documentHash) && (request.kind === "redirect" ? redirectMatches(evidence, item) : evidence.recipientObservations.length === 0);
21270
+ return confirmation.release.kind === "instant" && original.operation === "send";
21285
21271
  }
21286
21272
  //#endregion
21287
21273
  //#region ../../packages/sdk/src/documents/evidence.ts
@@ -21290,12 +21276,12 @@ function documentJson(value) {
21290
21276
  if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${documentJson(value[key])}`).join(",")}}`;
21291
21277
  return JSON.stringify(value) ?? "null";
21292
21278
  }
21293
- /** Verify every birth item and exact instruction/Receipt commitment before signing. */
21279
+ /** Verify every birth item and the exact instruction and Receipt hashes it binds before signing. */
21294
21280
  async function verifiesMoneyBirthEvidence(evidence) {
21295
21281
  try {
21296
21282
  const command = evidence.preparedCommand;
21297
21283
  if (command === void 0) return false;
21298
- if (!("items" in evidence.request) && evidence.request.kind !== "retry") return lifecycleMatches(evidence);
21284
+ if (!("items" in evidence.request) && evidence.request.kind !== "retry") return false;
21299
21285
  const context = "kind" in evidence.request && evidence.request.kind === "payment_request" ? requestBirthContext(evidence) : "items" in evidence.request ? {
21300
21286
  source: evidence.request.items,
21301
21287
  actorKind: "organization",
@@ -22487,15 +22473,20 @@ function paymentsV2Signature(name) {
22487
22473
  if (item === void 0) throw new Error(`CapxulPaymentsV2 ABI has no ${name} function`);
22488
22474
  return toSignature(item);
22489
22475
  }
22490
- const SEND_SIGNATURE = paymentsV2Signature("send");
22491
- const SEND_BATCH_SIGNATURE = paymentsV2Signature("sendBatch");
22492
- const CREATE_COMMITMENT_SIGNATURE = paymentsV2Signature("createCommitment");
22476
+ function paymentsV3Signature(name) {
22477
+ const item = CAPXUL_PAYMENTS_V3_ABI.find((candidate) => candidate.type === "function" && candidate.name === name);
22478
+ if (item === void 0) throw new Error(`CapxulPaymentsV3 ABI has no ${name} function`);
22479
+ return toSignature(item);
22480
+ }
22481
+ const V3_SEND_SIGNATURE = paymentsV3Signature("send");
22482
+ const V3_SEND_BATCH_SIGNATURE = paymentsV3Signature("sendBatch");
22483
+ const V2_CREATE_COMMITMENT_SIGNATURE = paymentsV2Signature("createCommitment");
22493
22484
  /**
22494
22485
  * #2299 ruling C: only an Owner cancels or redirects an Organization-funded
22495
22486
  * commitment, so these two sit in the Owner role's scope, never a Budget's.
22496
22487
  * The contract admits only the commitment's creator, the Organization Safe.
22497
22488
  */
22498
- const OWNER_COMMITMENT_SIGNATURES = [paymentsV2Signature("cancel"), paymentsV2Signature("redirect")];
22489
+ const V2_OWNER_COMMITMENT_SIGNATURES = [paymentsV2Signature("cancel"), paymentsV2Signature("redirect")];
22499
22490
  //#endregion
22500
22491
  //#region ../../packages/protocol/src/evm/organization-payments.ts
22501
22492
  /** Zodiac ModuleProxyFactory on Base Sepolia. */
@@ -22774,16 +22765,6 @@ function moneySafeOpDigest(operation, chainId) {
22774
22765
  userOp: safe4337UserOperation(operation)
22775
22766
  });
22776
22767
  }
22777
- /**
22778
- * An Organization-funded cancel or redirect runs through the Owner role
22779
- * (#2299), which no Budget names. Its role key cannot widen what the signer
22780
- * may do: the Roles module admits only a role the signer's Safe holds, and the
22781
- * contract admits only the commitment's creator.
22782
- */
22783
- function isOwnerLifecycle(command) {
22784
- const [item] = command.items;
22785
- return command.items.length === 1 && (item?.operation === "cancel_commitment" || item?.operation === "redirect_commitment");
22786
- }
22787
22768
  /** Verify every actual Money signing target against configured trust anchors. */
22788
22769
  function verifiesMoneyOperation(evidence, expectedSafe, chainId, permissionId) {
22789
22770
  try {
@@ -22795,7 +22776,7 @@ function verifiesMoneyOperation(evidence, expectedSafe, chainId, permissionId) {
22795
22776
  const route = command.executionRoute;
22796
22777
  if (route.kind === "direct") {
22797
22778
  if (permissionId !== void 0 || command.senderSafe.toLowerCase() !== expectedSafe.toLowerCase()) return false;
22798
- } else if ((permissionId === void 0 ? !isOwnerLifecycle(command) : route.roleKey.toLowerCase() !== roleKeyForPermission(permissionId).toLowerCase()) || command.senderSafe.toLowerCase() !== route.organizationSafe.toLowerCase()) return false;
22779
+ } else if (permissionId === void 0 || route.roleKey.toLowerCase() !== roleKeyForPermission(permissionId).toLowerCase() || command.senderSafe.toLowerCase() !== route.organizationSafe.toLowerCase()) return false;
22799
22780
  if (operation.callData.toLowerCase() !== encodePreparedPaymentCallData(command).toLowerCase()) return false;
22800
22781
  const digest = moneySafeOpDigest(operation, chainId);
22801
22782
  return evidence.digest.toLowerCase() === digest.toLowerCase() && matchesMoneyExecutionId(evidence.executionId, digest, evidence.commandId);
@@ -23147,15 +23128,9 @@ function mismatch$1(field, message) {
23147
23128
  error: Errors.invalidInput(field, message)
23148
23129
  };
23149
23130
  }
23150
- function plannedCommitmentMatches(prepared) {
23151
- const { item } = prepared;
23152
- const timing = prepared.payment.timing ?? { kind: "instant" };
23153
- if (timing.kind === "instant") return item.operation === "send";
23154
- if (item.operation !== "create_commitment") return false;
23155
- const start = Math.floor((timing.kind === "scheduled" ? timing.at : timing.startsAt) / 1e3);
23156
- const cliff = Math.floor((timing.kind === "scheduled" ? timing.at : timing.cliffAt ?? timing.startsAt) / 1e3);
23157
- const end = Math.floor((timing.kind === "scheduled" ? timing.at : timing.endsAt) / 1e3);
23158
- return item.startTime === start && item.cliffTime === cliff && item.endTime === end;
23131
+ /** A personal Payment pays at once: held timing retired in the V3 cut (D6). */
23132
+ function paysAtOnce(prepared) {
23133
+ return (prepared.payment.timing?.kind ?? "instant") === "instant";
23159
23134
  }
23160
23135
  function recipientMatches(prepared, target) {
23161
23136
  const { to, externalAddressAcknowledged } = prepared.payment;
@@ -23164,37 +23139,27 @@ function recipientMatches(prepared, target) {
23164
23139
  }
23165
23140
  function itemMatches(prepared, amount) {
23166
23141
  const { item, payment } = prepared;
23167
- if (item.operation !== "send" && item.operation !== "create_commitment") return false;
23142
+ if (item.operation !== "send") return false;
23168
23143
  const documentKind = payment.document?.kind === "invoice" ? "invoice" : payment.document?.kind === "envelope" ? decodeSupportedPaymentDocumentEnvelope(decodeCanonicalBase64V3(payment.document.bytesBase64)).primaryType.toLowerCase() : "memo";
23169
23144
  const purpose = payment.paymentType ?? (documentKind === "invoice" ? "invoice" : (payment.supportingReceipts?.length ?? 0) > 0 ? "reimbursement" : "unspecified");
23170
23145
  const expectedPurpose = purpose === "unspecified" ? "quick_pay" : purpose;
23171
23146
  const asset = CONFIGURED_MONEY_ASSETS.find((row) => row.assetId === amount.asset);
23172
- return item.paymentId === prepared.paymentId && Object.entries(PAYMENT_PURPOSE_KIND_CODES).some(([name, code]) => name === prepared.purposeKind && code === item.kind) && expectedPurpose === prepared.purposeKind && documentKind === "invoice" === (purpose === "invoice") && purpose !== "payroll" && item.tokenAddress.toLowerCase() === asset?.tokenAddress.toLowerCase() && (item.operation === "send" ? item.rawAmount : item.totalAmount) === amount.minorUnits && plannedCommitmentMatches(prepared) && recipientMatches(prepared, item.recipientSafe.toLowerCase());
23147
+ return item.paymentId === prepared.paymentId && Object.entries(PAYMENT_PURPOSE_KIND_CODES).some(([name, code]) => name === prepared.purposeKind && code === item.kind) && expectedPurpose === prepared.purposeKind && documentKind === "invoice" === (purpose === "invoice") && purpose !== "payroll" && item.tokenAddress.toLowerCase() === asset?.tokenAddress.toLowerCase() && item.rawAmount === amount.minorUnits && paysAtOnce(prepared) && recipientMatches(prepared, item.recipientSafe.toLowerCase());
23173
23148
  }
23174
- /** The callData a personal Payment birth item must carry: approve, then send or commit. */
23149
+ /** The callData a personal Payment birth item must carry: approve, then send. */
23175
23150
  function expectedPersonalCallData(prepared, expectedSafe, chainId) {
23176
23151
  const item = prepared.item;
23177
- if (item.operation !== "send" && item.operation !== "create_commitment") throw new Error("Expected personal Payment birth item");
23152
+ if (item.operation !== "send") throw new Error("Expected personal Payment send");
23178
23153
  const contract = toAddress(CAPXUL_PAYMENTS_V2_ADDRESS);
23179
23154
  const { settlementId, recipientSafe, tokenAddress, documentHash } = item;
23180
- const amount = BigInt(item.operation === "send" ? item.rawAmount : item.totalAmount);
23181
- const paymentData = item.operation === "send" ? encodeCapxulPaymentsV2Send({
23155
+ const amount = BigInt(item.rawAmount);
23156
+ const paymentData = encodeCapxulPaymentsV2Send({
23182
23157
  settlementId,
23183
23158
  recipient: recipientSafe,
23184
23159
  token: tokenAddress,
23185
23160
  amount,
23186
23161
  kind: item.kind,
23187
23162
  documentHash
23188
- }) : encodeCapxulPaymentsV2CreateCommitment({
23189
- settlementId,
23190
- recipient: recipientSafe,
23191
- token: tokenAddress,
23192
- totalAmount: amount,
23193
- startTime: item.startTime,
23194
- cliffTime: item.cliffTime,
23195
- endTime: item.endTime,
23196
- kind: item.kind,
23197
- documentHash
23198
23163
  });
23199
23164
  const calls = (router, encodedPaymentData) => safe4337MultiSendUserOpCallData({ calls: [{
23200
23165
  to: tokenAddress,
@@ -23210,7 +23175,6 @@ function expectedPersonalCallData(prepared, expectedSafe, chainId) {
23210
23175
  data: encodedPaymentData
23211
23176
  }] });
23212
23177
  const v2 = calls(contract, paymentData);
23213
- if (item.operation !== "send") return [v2];
23214
23178
  const terms = {
23215
23179
  recipient: item.recipientSafe,
23216
23180
  token: item.tokenAddress,
@@ -23261,7 +23225,7 @@ async function documentReferenceMatches(prepared, amount) {
23261
23225
  const { item, documentBundle: bundle, instructionDocument: ref } = prepared;
23262
23226
  const envelope = bundle.envelope;
23263
23227
  if (envelope.version === 5) return false;
23264
- if (item.operation !== "send" && item.operation !== "create_commitment") return false;
23228
+ if (item.operation !== "send") return false;
23265
23229
  return bundle.originId === hashDocumentOriginIdV3({
23266
23230
  chainId: prepared.chainId,
23267
23231
  actorKind: "account",
@@ -23611,12 +23575,10 @@ function subscribeFreshQuery(deps, args, listener, operation, projection, option
23611
23575
  //#endregion
23612
23576
  //#region ../../packages/sdk/src/payments/lifecycle-execution.ts
23613
23577
  /**
23614
- * The prepared command is this lifecycle intent; a retry also names the
23615
- * original birth command of the scope it was asked for. A claim, and an
23616
- * Account's own cancel or redirect, runs directly from the signer's Safe; an
23617
- * Organization's cancel or redirect runs through its Owner role (#2299).
23578
+ * The prepared command is this retry, and it names the original birth command
23579
+ * of the scope it was asked for.
23618
23580
  */
23619
- const lifecycleCommandCheck = (intent, expectedOrganizationId) => async (request, evidence) => await matchesIntent(intent)(request, evidence) && (intent.kind === "retry" ? expectedOrganizationId === void 0 ? evidence.sourceCommand?.kind === "birth" && evidence.sourceCommand.actor.kind === "account" : evidence.sourceCommand?.kind === "birth" && evidence.sourceCommand.actor.kind === "organization" && evidence.sourceCommand.actor.orgId === expectedOrganizationId : evidence.preparedCommand?.executionRoute.kind === (intent.kind === "claim" || expectedOrganizationId === void 0 ? "direct" : "zodiac_role"));
23581
+ const lifecycleCommandCheck = (intent, expectedOrganizationId) => async (request, evidence) => await matchesIntent(intent)(request, evidence) && evidence.sourceCommand?.kind === "birth" && (expectedOrganizationId === void 0 ? evidence.sourceCommand.actor.kind === "account" : evidence.sourceCommand.actor.kind === "organization" && evidence.sourceCommand.actor.orgId === expectedOrganizationId);
23620
23582
  /** The prepared command pays exactly the request the payer confirmed. */
23621
23583
  const requestPaymentCheck = (confirmation) => async (request) => "kind" in request && request.kind === "payment_request" && canonicalJson(request.confirmation) === canonicalJson(confirmation);
23622
23584
  function executePaymentLifecycle(deps, intent, signal, controls, expectedOrganizationId, onPrepared) {
@@ -24260,7 +24222,7 @@ async function readApprovedInboxPayment(calls, command, controls, current) {
24260
24222
  ok: false,
24261
24223
  error: Errors.cancelled({ operation: inboxes.approve.name })
24262
24224
  };
24263
- if (command.items.length !== 1 || item === void 0 || item.operation !== "send" && item.operation !== "create_commitment") return refused();
24225
+ if (command.items.length !== 1 || item === void 0 || item.operation !== "send") return refused();
24264
24226
  if (!current()) return cancelled;
24265
24227
  const check = (payment) => {
24266
24228
  if (!current()) return cancelled;
@@ -24270,7 +24232,7 @@ async function readApprovedInboxPayment(calls, command, controls, current) {
24270
24232
  const asset = CONFIGURED_MONEY_ASSETS.find((row) => row.assetId === amount.asset);
24271
24233
  const instruction = payment.documents.find((document) => document.role === "instruction");
24272
24234
  const expected = command.instructionDocuments?.[0];
24273
- if (asset?.tokenAddress.toLowerCase() !== item.tokenAddress.toLowerCase() || amount.minorUnits !== (item.operation === "send" ? item.rawAmount : item.totalAmount) || instruction?.documentHash !== item.documentHash || expected !== void 0 && (instruction.contentHash !== expected.contentHash || instruction.format !== expected.format) || payment.status === "settled" && payment.receipt?.chainId !== command.chainId) return refused();
24235
+ if (asset?.tokenAddress.toLowerCase() !== item.tokenAddress.toLowerCase() || amount.minorUnits !== item.rawAmount || instruction?.documentHash !== item.documentHash || expected !== void 0 && (instruction.contentHash !== expected.contentHash || instruction.format !== expected.format) || payment.status === "settled" && payment.receipt?.chainId !== command.chainId) return refused();
24274
24236
  return {
24275
24237
  ok: true,
24276
24238
  value: normalizePaymentTiming(payment)
@@ -24301,6 +24263,11 @@ function makeInboxMethods(calls) {
24301
24263
  list: (options) => book(inboxes.listCurrent, { actor }, options, (items) => mapPage(items, mapInboxItem)),
24302
24264
  approve: async (providedInput, options) => {
24303
24265
  const input = structuredClone(providedInput);
24266
+ const heldTiming = heldTimingRefusal(passedTiming(input));
24267
+ if (heldTiming !== null) return {
24268
+ ok: false,
24269
+ error: heldTiming
24270
+ };
24304
24271
  const identity = deps.identityActor;
24305
24272
  const lifetime = identity?.authLifetime();
24306
24273
  const current = () => identity === void 0 || lifetime !== void 0 && identity.matchesAuthLifetime(lifetime, lifetime.authUserId);
@@ -24315,7 +24282,6 @@ function makeInboxMethods(calls) {
24315
24282
  actor,
24316
24283
  paymentRequestId: input.requestId,
24317
24284
  ...requestKey === void 0 ? {} : { requestKey },
24318
- ...input.timing === void 0 ? {} : { timing: input.timing },
24319
24285
  ...input.permissionId === void 0 ? {} : { permissionId: input.permissionId }
24320
24286
  }, controls, (value) => value);
24321
24287
  if (!current()) return cancelled;
@@ -24336,7 +24302,7 @@ function makeInboxMethods(calls) {
24336
24302
  orgId: actor.orgId
24337
24303
  },
24338
24304
  permissionId: input.permissionId,
24339
- release: input.timing ?? { kind: "instant" }
24305
+ release: { kind: "instant" }
24340
24306
  }, input.requestKey, (key) => approve(key));
24341
24307
  },
24342
24308
  fulfill: (input, options) => {
@@ -24346,6 +24312,8 @@ function makeInboxMethods(calls) {
24346
24312
  const decoded = Schema.decodeResult(RequestPaymentConfirmationSchema, { onExcessProperty: "error" })(input);
24347
24313
  if (decoded._tag === "Failure") return refuse(Errors.invalidInput("confirmation", "invalid request confirmation"));
24348
24314
  const confirmation = structuredClone(decoded.success);
24315
+ const heldRelease = heldTimingRefusal(confirmation.release, "release");
24316
+ if (heldRelease !== null) return refuse(heldRelease);
24349
24317
  if (actor.kind === "account" && confirmation.payer.kind !== "account" || actor.kind === "org" && (confirmation.payer.kind !== "organization" || confirmation.payer.orgId !== actor.orgId)) return refuse(Errors.invalidInput("payer", "request payer does not match the method scope"));
24350
24318
  const identityActor = deps.identityActor;
24351
24319
  const chainId = deps.chainId;
@@ -24803,11 +24771,26 @@ function normalizeDestinationInputScope(input, field) {
24803
24771
  }
24804
24772
  //#endregion
24805
24773
  //#region ../../packages/sdk/src/payments/records.ts
24774
+ /**
24775
+ * A Payment pays at once. Held timing (`scheduled` or `stream`) retired in the
24776
+ * V3 cut (D6), so an untyped caller that still passes one is refused here,
24777
+ * before the backend could hold the money. Absent timing means instant.
24778
+ */
24779
+ function heldTimingRefusal(timing, field = "timing") {
24780
+ return timing === void 0 || typeof timing === "object" && timing !== null && "kind" in timing && timing.kind === "instant" ? null : Errors.invalidInput(field, "a Payment pays at once; held timing is no longer supported");
24781
+ }
24782
+ /** The `timing` an untyped caller may still pass on an input object. */
24783
+ const passedTiming = (input) => "timing" in input ? input.timing : void 0;
24806
24784
  function paymentExecutionIntent(input) {
24807
24785
  if ("lineItems" in input) return {
24808
24786
  ok: false,
24809
24787
  error: Errors.invalidInput("lineItems", "place items inside an Invoice draft or envelope")
24810
24788
  };
24789
+ const heldTiming = heldTimingRefusal(passedTiming(input));
24790
+ if (heldTiming !== null) return {
24791
+ ok: false,
24792
+ error: heldTiming
24793
+ };
24811
24794
  if (actorReferenceToBackend(input.actor)?.kind === "org") return {
24812
24795
  ok: false,
24813
24796
  error: Errors.notImplemented("payments", "pay.organizationActor")
@@ -24825,8 +24808,7 @@ function paymentExecutionIntent(input) {
24825
24808
  ...input.externalAddressAcknowledged === void 0 ? {} : { externalAddressAcknowledged: input.externalAddressAcknowledged },
24826
24809
  ...input.paymentType === void 0 ? {} : { paymentType: input.paymentType },
24827
24810
  ...input.document === void 0 ? {} : { document: input.document },
24828
- ...input.supportingReceipts === void 0 ? {} : { supportingReceipts: input.supportingReceipts },
24829
- ...input.timing === void 0 ? {} : { timing: input.timing }
24811
+ ...input.supportingReceipts === void 0 ? {} : { supportingReceipts: input.supportingReceipts }
24830
24812
  });
24831
24813
  return Result.isSuccess(decoded) ? {
24832
24814
  ok: true,
@@ -25320,8 +25302,8 @@ function makePersonalPay(deps) {
25320
25302
  }
25321
25303
  //#endregion
25322
25304
  //#region ../../packages/sdk/src/payments/lifecycle-methods.ts
25323
- /** Claim, cancel, redirect and retry: one signed lifecycle command over an existing Payment. */
25324
- function makeLifecycleRunners(deps) {
25305
+ /** Retry: one signed command over an existing Payment that answers its whole original cohort. */
25306
+ function makePaymentRetry(deps) {
25325
25307
  const lifecycleDependencies = () => deps.actor === void 0 || deps.chainId === void 0 || deps.signer === void 0 ? {
25326
25308
  ok: false,
25327
25309
  error: Errors.notImplemented("payments", "executionComposition")
@@ -25335,48 +25317,31 @@ function makeLifecycleRunners(deps) {
25335
25317
  runPromise: deps.runPromise
25336
25318
  }
25337
25319
  };
25338
- const run = (intent, controls, operation, project) => runCapxulEffect(Effect.gen(function* () {
25320
+ return (paymentId, controls) => runCapxulEffect(Effect.gen(function* () {
25339
25321
  const captured = carryInvocationParentSpan(controls, yield* Effect.currentSpan.pipe(Effect.orDie));
25340
25322
  const result = yield* Effect.tryPromise({
25341
25323
  try: async () => {
25342
25324
  const execution = lifecycleDependencies();
25343
25325
  if (!execution.ok) return execution;
25344
- const submitted = await executePaymentLifecycle(execution.value, intent, controls?.signal, captured);
25345
- return submitted.ok ? project(submitted.value.payments) : submitted;
25326
+ const submitted = await executePaymentLifecycle(execution.value, {
25327
+ kind: "retry",
25328
+ paymentId
25329
+ }, controls?.signal, captured);
25330
+ return submitted.ok ? {
25331
+ ok: true,
25332
+ value: submitted.value.payments.map((payment) => normalizePaymentTiming(payment))
25333
+ } : submitted;
25346
25334
  },
25347
25335
  catch: (cause) => asCapxulError(cause)
25348
25336
  });
25349
25337
  return yield* result.ok ? Effect.succeed(result.value) : Effect.fail(result.error);
25350
- }), observationOnlyControls(controls), operation, deps.runPromise);
25351
- /** Claim, cancel or redirect answers exactly the one Payment it acted on. */
25352
- const runLifecycle = (intent, controls, operation) => run(intent, controls, operation, (payments) => {
25353
- const payment = payments[0];
25354
- return payment === void 0 || payments.length !== 1 ? {
25355
- ok: false,
25356
- error: Errors.unknown()
25357
- } : {
25358
- ok: true,
25359
- value: normalizePaymentTiming(payment)
25360
- };
25361
- });
25362
- /** Retry answers the whole original cohort. */
25363
- const retryPayment = (paymentId, controls) => run({
25364
- kind: "retry",
25365
- paymentId
25366
- }, controls, CAPXUL_OPERATIONS.payments.retry, (payments) => ({
25367
- ok: true,
25368
- value: payments.map((payment) => normalizePaymentTiming(payment))
25369
- }));
25370
- return {
25371
- runLifecycle,
25372
- retryPayment
25373
- };
25338
+ }), observationOnlyControls(controls), CAPXUL_OPERATIONS.payments.retry, deps.runPromise);
25374
25339
  }
25375
25340
  //#endregion
25376
25341
  //#region ../../packages/sdk/src/payments/methods.ts
25377
25342
  function makePaymentsMethods(deps) {
25378
25343
  const pay = makePersonalPay(deps);
25379
- const { runLifecycle, retryPayment } = makeLifecycleRunners(deps);
25344
+ const retryPayment = makePaymentRetry(deps);
25380
25345
  return {
25381
25346
  quote: makePaymentQuote(deps),
25382
25347
  payoutStage: makePayoutStage(deps),
@@ -25389,12 +25354,6 @@ function makePaymentsMethods(deps) {
25389
25354
  }, paymentId, listener, options),
25390
25355
  pay,
25391
25356
  retry: (paymentId, options) => retryPayment(paymentId, deps.invocationControls?.(options) ?? options),
25392
- createCommitment: (input, options) => pay(input, options),
25393
- claim: (paymentId, options) => runLifecycle({
25394
- kind: "claim",
25395
- requestKey: options?.requestKey ?? `pay_${crypto.randomUUID()}`,
25396
- paymentId
25397
- }, deps.invocationControls?.(options) ?? options, CAPXUL_OPERATIONS.payments.claim),
25398
25357
  list: (options) => {
25399
25358
  const controls = deps.invocationControls?.(options) ?? options;
25400
25359
  return runPortEffect(projectReply(callOperation(deps.convexCall, records.list, copyInvocationObservation(controls, {})).pipe(Effect.mapError((publicError) => ({ publicError }))), (payments) => mapPage(payments, normalizePaymentTiming)), controls, records.list.name, deps.runPromise);
@@ -25402,22 +25361,6 @@ function makePaymentsMethods(deps) {
25402
25361
  get: (paymentId, options) => {
25403
25362
  const controls = deps.invocationControls?.(options) ?? options;
25404
25363
  return runPortEffect(projectReply(callOperation(deps.convexCall, records.get, copyInvocationObservation(controls, { paymentId })).pipe(Effect.mapError((publicError) => ({ publicError }))), (payment) => payment === null ? null : normalizePaymentTiming(payment)), controls, records.get.name, deps.runPromise);
25405
- },
25406
- cancel: (paymentId, options) => runLifecycle({
25407
- kind: "cancel",
25408
- requestKey: options?.requestKey ?? `pay_${crypto.randomUUID()}`,
25409
- paymentId
25410
- }, deps.invocationControls?.(options) ?? options, CAPXUL_OPERATIONS.payments.cancel),
25411
- redirect: async (input, options) => {
25412
- const controls = deps.invocationControls?.(options) ?? options;
25413
- const recipient = normalizeTargetForBackend(input.to, "to");
25414
- if (!recipient.ok) return runCapxulEffect(Effect.fail(recipient.error), observationOnlyControls(controls), CAPXUL_OPERATIONS.payments.redirect, deps.runPromise);
25415
- return runLifecycle({
25416
- kind: "redirect",
25417
- requestKey: options?.requestKey ?? `pay_${crypto.randomUUID()}`,
25418
- paymentId: input.paymentId,
25419
- recipient: recipient.value
25420
- }, controls, CAPXUL_OPERATIONS.payments.redirect);
25421
25364
  }
25422
25365
  };
25423
25366
  }
@@ -25432,16 +25375,37 @@ const organizationPaymentIntentSchema = Schema.Struct({
25432
25375
  /** One Payment's decoded `items.0.amount.value` is the caller's `amount.value`. */
25433
25376
  const singleItemPath = (path) => path[0] === "items" && path[1] === "0" ? path.slice(2) : path;
25434
25377
  /**
25378
+ * An untyped caller's null or non-object input is a caller mistake, refused
25379
+ * before any of its fields is read (CAP-648).
25380
+ */
25381
+ function organizationPaymentInputRefusal(input) {
25382
+ return typeof input !== "object" || input === null ? {
25383
+ ok: false,
25384
+ error: Errors.invalidInput("input", "must be an object")
25385
+ } : null;
25386
+ }
25387
+ /**
25435
25388
  * Decode a batch. `single` says the caller passed one Payment that its call
25436
25389
  * site wrapped as `items: [item]`, so a refusal names the caller's own field.
25437
25390
  */
25438
25391
  function organizationPaymentIntent(orgId, input, single = false) {
25392
+ const notObject = organizationPaymentInputRefusal(input);
25393
+ if (notObject !== null) return notObject;
25439
25394
  if (input.requestKey !== void 0) {
25440
25395
  if (Schema.decodeResult(PrepareOrganizationPaymentExecutionInputSchema.fields.requestKey)(input.requestKey)._tag === "Failure") return {
25441
25396
  ok: false,
25442
25397
  error: Errors.invalidInput("requestKey", "invalid Payment request key")
25443
25398
  };
25444
25399
  }
25400
+ const items = input.items;
25401
+ for (const [index, item] of (Array.isArray(items) ? items : []).entries()) {
25402
+ if (typeof item !== "object" || item === null) continue;
25403
+ const refused = heldTimingRefusal(passedTiming(item), single ? "timing" : `items.${index}.timing`);
25404
+ if (refused !== null) return {
25405
+ ok: false,
25406
+ error: refused
25407
+ };
25408
+ }
25445
25409
  const decoded = Schema.decodeResult(organizationPaymentIntentSchema, { onExcessProperty: "error" })({
25446
25410
  orgId,
25447
25411
  permissionId: input.permissionId,
@@ -25684,27 +25648,6 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
25684
25648
  flights: /* @__PURE__ */ new Map()
25685
25649
  };
25686
25650
  const execute = (input, signal, operation = "organization-pay-batch", controls, onPrepared, single = false) => executeOrganizationBatch(scope, input, signal, operation, controls, onPrepared, single);
25687
- /** One Owner-signed cancel or redirect, answering the one Payment it acted on (#2299). */
25688
- const ownerLifecycle = (intent, controls, operation) => runCapxulEffect(Effect.gen(function* () {
25689
- const captured = carryInvocationParentSpan(controls, yield* Effect.currentSpan.pipe(Effect.orDie));
25690
- return yield* awaitCapxulResult(async () => {
25691
- const execution = executionDependencies$1(deps);
25692
- if (execution === null) return {
25693
- ok: false,
25694
- error: Errors.notImplemented("organizationPayments", "executionComposition")
25695
- };
25696
- const result = await executePaymentLifecycle(execution, intent, controls?.signal, captured, orgId);
25697
- if (!result.ok) return result;
25698
- const [payment, ...rest] = result.value.payments;
25699
- return payment === void 0 || rest.length !== 0 ? {
25700
- ok: false,
25701
- error: Errors.unknown()
25702
- } : {
25703
- ok: true,
25704
- value: normalizePaymentTiming(payment)
25705
- };
25706
- });
25707
- }), observationOnlyControls(controls), operation, deps.runPromise);
25708
25651
  return {
25709
25652
  ...makeOrganizationPaymentReadMethods(deps, orgId),
25710
25653
  quote: makePaymentQuote(deps, {
@@ -25752,6 +25695,8 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
25752
25695
  const parent = yield* Effect.currentSpan.pipe(Effect.orDie);
25753
25696
  const captured = carryInvocationParentSpan(controls, parent);
25754
25697
  return yield* awaitCapxulResult(async () => {
25698
+ const refused = organizationPaymentInputRefusal(input);
25699
+ if (refused !== null) return refused;
25755
25700
  const { permissionId, requestKey: providedRequestKey, lineage, ...item } = input;
25756
25701
  const result = await execute({
25757
25702
  permissionId,
@@ -25771,21 +25716,6 @@ function makeOrganizationPaymentsMethods(deps, orgId) {
25771
25716
  });
25772
25717
  }), observationOnlyControls(controls), CAPXUL_OPERATIONS.organizationPayments.pay, deps.runPromise);
25773
25718
  },
25774
- cancel: (paymentId, options) => ownerLifecycle({
25775
- kind: "cancel",
25776
- paymentId,
25777
- requestKey: options?.requestKey ?? `pay_${crypto.randomUUID()}`
25778
- }, deps.invocationControls?.(options) ?? options, CAPXUL_OPERATIONS.organizationPayments.cancel),
25779
- redirect: (input, options) => {
25780
- const controls = deps.invocationControls?.(options) ?? options;
25781
- const recipient = normalizeTargetForBackend(input.to, "to");
25782
- return recipient.ok ? ownerLifecycle({
25783
- kind: "redirect",
25784
- paymentId: input.paymentId,
25785
- recipient: recipient.value,
25786
- requestKey: options?.requestKey ?? `pay_${crypto.randomUUID()}`
25787
- }, controls, CAPXUL_OPERATIONS.organizationPayments.redirect) : runCapxulEffect(Effect.fail(recipient.error), observationOnlyControls(controls), CAPXUL_OPERATIONS.organizationPayments.redirect, deps.runPromise);
25788
- },
25789
25719
  payBatch: (input, options) => {
25790
25720
  const controls = deps.invocationControls?.(options) ?? options;
25791
25721
  return runCapxulEffect(Effect.gen(function* () {
@@ -26553,7 +26483,7 @@ function isRunItem(prepared, item, evidence, index, runId, period) {
26553
26483
  const preparedItem = evidence.preparedCommand?.items[index];
26554
26484
  const payslip = bundle?.envelope;
26555
26485
  if (bundle === void 0 || payslip?.primaryType !== "Payslip") return false;
26556
- return canonicalJson(prepared.to) === canonicalJson(item.to) && prepared.paymentType === "payroll" && canonicalJson(prepared.amount) === canonicalJson(item.amount) && bundle.adjustments !== void 0 && canonicalJson(bundle.adjustments) === canonicalJson(item.adjustments) && payslipIdentityMatches(payslip.message, item, index, runId, period) && payslipAmountMatches(payslip.message, item) && (preparedItem?.operation === "send" || preparedItem?.operation === "create_commitment") && preparedItem.documentHash === evidence.preparedCommand?.instructionDocuments?.[index]?.documentHash;
26486
+ return canonicalJson(prepared.to) === canonicalJson(item.to) && prepared.paymentType === "payroll" && canonicalJson(prepared.amount) === canonicalJson(item.amount) && bundle.adjustments !== void 0 && canonicalJson(bundle.adjustments) === canonicalJson(item.adjustments) && payslipIdentityMatches(payslip.message, item, index, runId, period) && payslipAmountMatches(payslip.message, item) && preparedItem?.operation === "send" && preparedItem.documentHash === evidence.preparedCommand?.instructionDocuments?.[index]?.documentHash;
26557
26487
  }
26558
26488
  /**
26559
26489
  * The batch the backend derived from a payroll intent must be the batch this
@@ -26976,47 +26906,20 @@ async function checked(deps, signerAddress, prepared, expected, close) {
26976
26906
  };
26977
26907
  return close ? abandonPrepared(deps, evidence.executionId, "prepared_mismatch", refused) : refused;
26978
26908
  }
26979
- /** A retry, cancel or redirect, a request payment or a payroll run, rather than a new Payment. */
26980
- const isCommandApproval = (input) => "retry" in input || "cancel" in input || "redirect" in input || "request" in input || "payrollRun" in input;
26981
- /** The next step of an existing Payment the input names; a recipient that cannot be one is refused. */
26982
- function lifecycleIntent(input) {
26983
- if ("retry" in input) return {
26984
- ok: true,
26985
- value: {
26986
- kind: "retry",
26987
- paymentId: input.retry
26988
- }
26989
- };
26990
- if ("cancel" in input) return {
26991
- ok: true,
26992
- value: {
26993
- kind: "cancel",
26994
- paymentId: input.cancel,
26995
- requestKey: input.requestKey ?? `pay_${crypto.randomUUID()}`
26996
- }
26997
- };
26998
- const recipient = normalizeTargetForBackend(input.to, "to");
26999
- return recipient.ok ? {
27000
- ok: true,
27001
- value: {
27002
- kind: "redirect",
27003
- paymentId: input.redirect,
27004
- recipient: recipient.value,
27005
- requestKey: input.requestKey ?? `pay_${crypto.randomUUID()}`
27006
- }
27007
- } : recipient;
27008
- }
27009
- /** Prepare a retry, cancel, redirect, request payment or payroll run for `signerAddress`, checked. */
26909
+ /** A retry, a request payment or a payroll run, rather than a new Payment. */
26910
+ const isCommandApproval = (input) => "retry" in input || "request" in input || "payrollRun" in input;
26911
+ /** Prepare a retry, request payment or payroll run for `signerAddress`, checked. */
27010
26912
  function prepareVerifiedCommand(deps, input, signerAddress, signal) {
27011
26913
  if ("request" in input) return prepareVerifiedRequestPayment(deps, input, signerAddress, signal);
27012
26914
  if ("payrollRun" in input) return prepareVerifiedPayrollRun(deps, input, signerAddress, signal);
27013
26915
  return prepareVerifiedLifecycle(deps, input, signerAddress, signal);
27014
26916
  }
27015
- /** The next step of one Payment, prepared in the scope that paid it. */
26917
+ /** A retry of one Payment, prepared in the scope that paid it. */
27016
26918
  async function prepareVerifiedLifecycle(deps, input, signerAddress, signal) {
27017
- const named = lifecycleIntent(input);
27018
- if (!named.ok) return named;
27019
- const intent = named.value;
26919
+ const intent = {
26920
+ kind: "retry",
26921
+ paymentId: input.retry
26922
+ };
27020
26923
  return checked(deps, signerAddress, await runIfActive(signal, CAPXUL_OPERATIONS.payments.prepareLifecycleExecution, () => callOperation(deps.convexCall, lifecycles.prepareScoped, {
27021
26924
  signerAddress,
27022
26925
  intent,
@@ -27034,6 +26937,11 @@ async function prepareVerifiedRequestPayment(deps, input, signerAddress, signal)
27034
26937
  error: Errors.invalidInput("confirmation", "invalid request confirmation")
27035
26938
  };
27036
26939
  const confirmation = decoded.success;
26940
+ const heldRelease = heldTimingRefusal(confirmation.release, "release");
26941
+ if (heldRelease !== null) return {
26942
+ ok: false,
26943
+ error: heldRelease
26944
+ };
27037
26945
  const run = async (named, prepared) => {
27038
26946
  const result = await runIfActive(signal, commands$1.prepareRequest.name, () => callOperation(deps.convexCall, commands$1.prepareRequest, {
27039
26947
  confirmation: named,
@@ -27141,7 +27049,7 @@ function makeApprovalsMethods(deps) {
27141
27049
  const signal = options?.signal;
27142
27050
  if (isCommandApproval(input)) return openApproval(signal, (signerAddress) => prepareVerifiedCommand(deps, input, signerAddress, signal));
27143
27051
  if (isPermissionChange(input)) return openApproval(signal, async (signerAddress) => {
27144
- const { prepareVerifiedPermissionChange } = await import("./permission-approvals-DJ08uQHm.mjs");
27052
+ const { prepareVerifiedPermissionChange } = await import("./permission-approvals-C3gzC62m.mjs");
27145
27053
  return prepareVerifiedPermissionChange(deps, input, signerAddress, signal);
27146
27054
  });
27147
27055
  if ("organizationId" in input) return checkedBankApproval(deps, input, await openApproval(signal, (signerAddress) => prepareVerifiedOrganizationPayment(deps, input, signerAddress, signal)));
@@ -30371,6 +30279,9 @@ function and$1(...children) {
30371
30279
  children
30372
30280
  };
30373
30281
  }
30282
+ function or(...children) {
30283
+ return orMatch(children);
30284
+ }
30374
30285
  function calldataMatches$1(children) {
30375
30286
  return {
30376
30287
  paramType: PARAMETER_TYPE.calldata,
@@ -39858,45 +39769,48 @@ function normalizeOrgBudgetPolicy(policy) {
39858
39769
  refillPeriod: policy.refill === "monthly" ? MONTHLY_REFILL_PERIOD_SECONDS : 0n
39859
39770
  };
39860
39771
  }
39861
- function resolvedBudgetApprovalPermission(tokenAddress) {
39772
+ /**
39773
+ * The Budget may approve only the routers its actions call: V3 for sends (D6),
39774
+ * V2 for commitments until T4.12 retires them.
39775
+ */
39776
+ function resolvedBudgetApprovalPermission(tokenAddress, spenderAddresses) {
39777
+ const [first, ...rest] = spenderAddresses.map((spender) => equalAddress(spender));
39778
+ if (first === void 0) throw Errors.invalidInput("policy.actions", "must include an action that spends a token");
39862
39779
  return {
39863
39780
  targetAddress: tokenAddress,
39864
39781
  signature: "approve(address,uint256)",
39865
- condition: calldataMatches$1([equalAddress(CAPXUL_PAYMENTS_V2_ADDRESS), passStatic()])
39782
+ condition: calldataMatches$1([rest.length === 0 ? first : or(first, ...rest), passStatic()])
39866
39783
  };
39867
39784
  }
39868
39785
  function resolvedBudgetPermissions(input) {
39869
39786
  const recipient = recipientCondition(input.policy.recipients);
39870
39787
  const amount = input.policy.limit.kind === "finite" && input.allowanceKey !== null ? and$1(lteUint256(input.policy.limit.rawUnits), withinAllowance(input.allowanceKey)) : passStatic();
39871
- const itemConditions = [
39788
+ const sendItemConditions = [
39872
39789
  passStatic(),
39873
39790
  recipient,
39874
39791
  equalAddress(input.policy.tokenAddress),
39875
39792
  amount,
39876
39793
  passStatic(),
39794
+ passStatic(),
39795
+ passStatic(),
39877
39796
  passStatic()
39878
39797
  ];
39879
- const permissions = [];
39880
- if (input.policy.actions.some((action) => action === "send" || action === "sendBatch" || action === "createCommitment")) permissions.push(resolvedBudgetApprovalPermission(input.policy.tokenAddress));
39881
- for (const action of input.policy.actions) switch (action) {
39882
- case "send":
39883
- permissions.push({
39884
- targetAddress: CAPXUL_PAYMENTS_V2_ADDRESS,
39885
- signature: SEND_SIGNATURE,
39886
- condition: calldataMatches$1([tupleMatches(itemConditions)])
39887
- });
39888
- break;
39889
- case "sendBatch":
39890
- permissions.push({
39891
- targetAddress: CAPXUL_PAYMENTS_V2_ADDRESS,
39892
- signature: SEND_BATCH_SIGNATURE,
39893
- condition: calldataMatches$1([everyTupleMatches(itemConditions)])
39894
- });
39895
- break;
39896
- case "createCommitment":
39897
- permissions.push({
39798
+ const approvalSpenders = [...input.policy.actions.some((action) => action === "send" || action === "sendBatch") ? [CAPXUL_PAYMENTS_V3_ADDRESS] : [], ...input.policy.actions.includes("createCommitment") ? [CAPXUL_PAYMENTS_V2_ADDRESS] : []];
39799
+ const actionPermissions = input.policy.actions.map((action) => {
39800
+ switch (action) {
39801
+ case "send": return {
39802
+ targetAddress: CAPXUL_PAYMENTS_V3_ADDRESS,
39803
+ signature: V3_SEND_SIGNATURE,
39804
+ condition: calldataMatches$1([tupleMatches(sendItemConditions)])
39805
+ };
39806
+ case "sendBatch": return {
39807
+ targetAddress: CAPXUL_PAYMENTS_V3_ADDRESS,
39808
+ signature: V3_SEND_BATCH_SIGNATURE,
39809
+ condition: calldataMatches$1([everyTupleMatches(sendItemConditions)])
39810
+ };
39811
+ case "createCommitment": return {
39898
39812
  targetAddress: CAPXUL_PAYMENTS_V2_ADDRESS,
39899
- signature: CREATE_COMMITMENT_SIGNATURE,
39813
+ signature: V2_CREATE_COMMITMENT_SIGNATURE,
39900
39814
  condition: calldataMatches$1([tupleMatches([
39901
39815
  passStatic(),
39902
39816
  recipient,
@@ -39908,11 +39822,11 @@ function resolvedBudgetPermissions(input) {
39908
39822
  passStatic(),
39909
39823
  passStatic()
39910
39824
  ])])
39911
- });
39912
- break;
39913
- default: return absurd(action);
39914
- }
39915
- return permissions;
39825
+ };
39826
+ default: return absurd(action);
39827
+ }
39828
+ });
39829
+ return [resolvedBudgetApprovalPermission(input.policy.tokenAddress, approvalSpenders), ...actionPermissions];
39916
39830
  }
39917
39831
  /** Compile one resolved Budget to direct calls on an existing Roles module. */
39918
39832
  function buildOrgBudgetCallsWithEncoder(input, encodeRoles) {
@@ -40134,7 +40048,7 @@ function buildExplicitBootstrapRoleCalls(input, encodeRoles) {
40134
40048
  targetAddress: input.rolesModuleAddress,
40135
40049
  signature
40136
40050
  })),
40137
- ...OWNER_COMMITMENT_SIGNATURES.map((signature) => ({
40051
+ ...V2_OWNER_COMMITMENT_SIGNATURES.map((signature) => ({
40138
40052
  targetAddress: CAPXUL_PAYMENTS_V2_ADDRESS,
40139
40053
  signature
40140
40054
  }))
@@ -42563,9 +42477,7 @@ function makeNotImplementedOrganizationPaymentsMethods() {
42563
42477
  subscribe: organizationPaymentExecutionUnavailable,
42564
42478
  pay: organizationPaymentExecutionUnavailable,
42565
42479
  payBatch: organizationPaymentExecutionUnavailable,
42566
- retry: organizationPaymentExecutionUnavailable,
42567
- cancel: organizationPaymentExecutionUnavailable,
42568
- redirect: organizationPaymentExecutionUnavailable
42480
+ retry: organizationPaymentExecutionUnavailable
42569
42481
  };
42570
42482
  }
42571
42483
  const orgMeUnavailable = () => Promise.resolve({
@@ -1,4 +1,4 @@
1
- import { G as asCapxulError, V as abandonPrepared, a as prepareConfiguration, bt as noSessionError, d as verifiedPreparation, f as buildCommand, i as authorInvitation, l as preparePermission, o as verifiedConfiguration, on as CAPXUL_OPERATIONS, or as absurd, p as validateReplacementInput, sr as CapxulError, u as preparedIdentity } from "./organizations-D3Z6n79m.mjs";
1
+ import { G as asCapxulError, V as abandonPrepared, a as prepareConfiguration, bt as noSessionError, d as verifiedPreparation, f as buildCommand, i as authorInvitation, l as preparePermission, o as verifiedConfiguration, on as CAPXUL_OPERATIONS, or as absurd, p as validateReplacementInput, sr as CapxulError, u as preparedIdentity } from "./organizations-CeOxH4kV.mjs";
2
2
  //#region ../../packages/sdk/src/accounts/permission-approvals.ts
3
3
  /** Prepare a Permission write or an invitation's configuration for `signerAddress`, checked. */
4
4
  function prepareVerifiedPermissionChange(deps, input, signerAddress, signal) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capxul/mcp",
3
- "version": "4.20.0-beta.41",
3
+ "version": "4.20.0-beta.42",
4
4
  "private": false,
5
5
  "description": "Capxul MCP server for auth, Account readiness, identity, Organizations, relationships, requests, destinations, and testnet funding over Streamable HTTP.",
6
6
  "keywords": [
@@ -54,10 +54,10 @@
54
54
  "typescript": "npm:@typescript/typescript6@6.0.2",
55
55
  "vite": "npm:@voidzero-dev/vite-plus-core@1.0.0",
56
56
  "vite-plus": "1.0.0",
57
- "@capxul/observability": "4.20.0-beta.41",
58
- "@capxul/protocol": "4.20.0-beta.41",
59
- "@capxul/typescript-config": "0.0.0",
60
- "@capxul/sdk": "4.20.0-beta.41"
57
+ "@capxul/observability": "4.20.0-beta.42",
58
+ "@capxul/protocol": "4.20.0-beta.42",
59
+ "@capxul/sdk": "4.20.0-beta.42",
60
+ "@capxul/typescript-config": "0.0.0"
61
61
  },
62
62
  "scripts": {
63
63
  "dev": "vp exec tsx src/main.ts serve",