@manifest-network/manifest-agent-core 0.17.0 → 0.19.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"manage-domain.d.ts","names":[],"sources":["../src/manage-domain.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsHsB,YAAA,CACpB,IAAA,EAAM,gBAAA,EACN,SAAA,EAAW,qBAAA,EACX,IAAA,EAAM,mBAAA,GACL,OAAA,CAAQ,kBAAA"}
1
+ {"version":3,"file":"manage-domain.d.ts","names":[],"sources":["../src/manage-domain.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqGsB,YAAA,CACpB,IAAA,EAAM,gBAAA,EACN,SAAA,EAAW,qBAAA,EACX,IAAA,EAAM,mBAAA,GACL,OAAA,CAAQ,kBAAA"}
@@ -1,7 +1,7 @@
1
1
  import { makeCancellationScope } from "./internals/cancellation.js";
2
2
  import { verifyAndRecover } from "./internals/verify-recover.js";
3
3
  import { verifyDomainState } from "./internals/verify-domain-state.js";
4
- import { ManifestMCPError, ManifestMCPErrorCode, noopLogger, parseFqdn, parseLeaseUuid, setItemCustomDomain } from "@manifest-network/manifest-mcp-core";
4
+ import { ManifestMCPError, ManifestMCPErrorCode, isNotFoundError, noopLogger, parseFqdn, parseLeaseUuid, setItemCustomDomain } from "@manifest-network/manifest-mcp-core";
5
5
  //#region src/manage-domain.ts
6
6
  /**
7
7
  * Public entry point: orchestrate setting, clearing, or looking up a
@@ -29,23 +29,6 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
29
29
  const FQDN_RE = /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
30
30
  const SCHEME_PREFIX_RE = /^https?:\/\//i;
31
31
  /**
32
- * Cosmos SDK / gRPC NotFound message patterns. Match against
33
- * `Error.message` to distinguish chain-keeper NotFound (treated as
34
- * "unclaimed FQDN" → typed `null` result) from real failures (treated
35
- * as `QUERY_FAILED` throws). Anchored loose patterns to tolerate
36
- * different keeper / transport formatting ("not found", "NotFound",
37
- * "no such record", "does not exist").
38
- *
39
- * Per CLAUDE.md: use `String.prototype.match()` over `RegExp.test()`
40
- * to avoid the CI security hook's false-positive on shell-execution
41
- * tokens.
42
- */
43
- const NOT_FOUND_RES = [
44
- /not.?found/i,
45
- /no.?such/i,
46
- /does.?not.?exist/i
47
- ];
48
- /**
49
32
  * Set / clear / look up a lease item's custom domain.
50
33
  *
51
34
  * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation.
@@ -234,12 +217,6 @@ async function lookupDomain(fqdn, callbacks, opts) {
234
217
  callbacks.onComplete?.(lookupResult);
235
218
  return lookupResult;
236
219
  }
237
- function isNotFoundError(err) {
238
- if (err instanceof ManifestMCPError) return false;
239
- if (!(err instanceof Error)) return false;
240
- const msg = err.message;
241
- return NOT_FOUND_RES.some((re) => msg.match(re) !== null);
242
- }
243
220
  function readLeaseUuid(lease) {
244
221
  if (lease === null || typeof lease !== "object") return void 0;
245
222
  const r = lease;
@@ -1 +1 @@
1
- {"version":3,"file":"manage-domain.js","names":[],"sources":["../src/manage-domain.ts"],"sourcesContent":["/**\n * Public entry point: orchestrate setting, clearing, or looking up a\n * lease item's custom domain.\n *\n * Composition (mirrors `deploy-app.ts`'s shape):\n *\n * - `set` / `clear` render a confirmation block, optionally call\n * `onConfirm`, broadcast `setItemCustomDomain` against the agent's\n * bound chain client, then verify the post-broadcast on-chain state\n * via `verifyAndRecover` driving `verify-domain-state` over a direct\n * `billing.v1.lease({ leaseUuid })` single-lease query (tenant-\n * agnostic, no pagination edge cases). Branches are inline closures\n * bound to the per-action context; recovery options are intentionally\n * empty so the verifier surfaces failures via the simple-form\n * `onFailure({ reason })` adapter rather than the rich-form\n * `RecoveryOption[]` prompt (manage-domain has no recovery primitives\n * the orchestrator can dispatch; the user re-runs after a real fix).\n *\n * - `lookup` skips broadcast/verify and resolves the FQDN via the\n * `lease_by_custom_domain` chain query; returns `null` lease when\n * the FQDN isn't claimed.\n */\n\nimport {\n ManifestMCPError,\n ManifestMCPErrorCode,\n noopLogger,\n parseFqdn,\n parseLeaseUuid,\n setItemCustomDomain,\n} from '@manifest-network/manifest-mcp-core';\nimport { makeCancellationScope } from './internals/cancellation.js';\nimport {\n type VerifyDomainOutcome,\n type VerifyDomainResult,\n verifyDomainState,\n} from './internals/verify-domain-state.js';\nimport {\n type VerificationSpec,\n verifyAndRecover,\n} from './internals/verify-recover.js';\nimport type {\n DeploymentPlanBlock,\n ManageDomainArgs,\n ManageDomainCallbacks,\n ManageDomainOptions,\n ManageDomainResult,\n} from './types.js';\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// RFC 1123 hostname: each label 1-63 chars, alphanumeric + hyphens, no leading/\n// trailing hyphen; total ≤253 chars; ≥2 labels (FQDN, not single-label host).\n// Rejects scheme prefixes ('http://'), whitespace, trailing dots, and raw\n// unicode (ASCII punycode `xn--...` is accepted — it matches the regex's\n// `[A-Za-z0-9-]` label character class, which is the standard wire form\n// for IDN labels).\n//\n// Client-side typo gate only. The chain's `MsgSetItemCustomDomain` keeper is\n// the authoritative validator (canonical lowercase, reserved-suffix rules,\n// FQDN format). This anchored regex catches the obvious-malformed-input\n// cases pre-broadcast so we don't waste a tx on `\"\"`, `\" \"`, `\"http://x.y\"`,\n// or `\"not a domain\"`. Anything that passes here still goes through the\n// chain's own validation.\nconst FQDN_RE =\n /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;\n\nconst SCHEME_PREFIX_RE = /^https?:\\/\\//i;\n\n/**\n * Cosmos SDK / gRPC NotFound message patterns. Match against\n * `Error.message` to distinguish chain-keeper NotFound (treated as\n * \"unclaimed FQDN\" → typed `null` result) from real failures (treated\n * as `QUERY_FAILED` throws). Anchored loose patterns to tolerate\n * different keeper / transport formatting (\"not found\", \"NotFound\",\n * \"no such record\", \"does not exist\").\n *\n * Per CLAUDE.md: use `String.prototype.match()` over `RegExp.test()`\n * to avoid the CI security hook's false-positive on shell-execution\n * tokens.\n */\nconst NOT_FOUND_RES: readonly RegExp[] = [\n /not.?found/i,\n /no.?such/i,\n /does.?not.?exist/i,\n];\n\n/**\n * Set / clear / look up a lease item's custom domain.\n *\n * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation.\n * @throws `ManifestMCPError(OPERATION_CANCELLED)` when `onConfirm` returns\n * `'no'` (deliberate user cancellation — ENG-272).\n * @throws `ManifestMCPError` (typically `TX_FAILED`) propagated as-is\n * from the `setItemCustomDomain()` broadcast step in `set` / `clear`\n * paths. Broadcast errors do NOT invoke `onFailure` — that callback\n * is reserved for post-broadcast verification failures.\n * `setItemCustomDomain` already raises a structured `ManifestMCPError`\n * from the core package; wrapping it again at this layer would be\n * redundant. Callers wanting to react to broadcast errors should\n * catch them at the call site.\n * @throws `ManifestMCPError(TX_FAILED)` when post-broadcast verification\n * reaches a `not_found` / `mismatch` outcome (after `onFailure` has\n * been invoked so the caller can react).\n * @throws `ManifestMCPError(QUERY_FAILED)` when a chain query raises a\n * non-NotFound error (RPC / transport / decoding failure). Two paths\n * surface this:\n * - the `lookup` chain query (`lease_by_custom_domain`); the keeper's\n * `NotFound` on an unclaimed FQDN is surfaced as a typed\n * `{ lease: null }` result, not a throw.\n * - the post-broadcast verify chain query (`billing.v1.lease`) in\n * the `set` / `clear` paths (wrapped inside the verifier closure\n * so the failure flows through `onFailure({ reason })` before the\n * throw).\n * Structured `ManifestMCPError`s raised by the chain client are\n * re-thrown as-is (with `onFailure` invoked first).\n */\nexport async function manageDomain(\n args: ManageDomainArgs,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n validateArgs(args);\n\n if (args.action === 'lookup') {\n return await lookupDomain(args.fqdn, callbacks, opts);\n }\n\n const serviceName = args.serviceName;\n // Normalize the FQDN once for `set`: trim surrounding whitespace\n // (Copilot review PR #60, comment 3276519081) AND lowercase (RFC 4343),\n // matching what `parseFqdn` does to the broadcast value below. Both the\n // broadcast (`parseFqdn(fqdn)`) and the post-broadcast verification\n // (`expected: fqdn`) must compare the SAME normalized value — otherwise a\n // mixed-case input broadcasts lowercased but verifies against the raw\n // casing, producing a spurious mismatch (code-review PR #102).\n // `validateArgs` still rejects the empty / whitespace-only case via\n // `args.fqdn.trim() === ''`.\n const fqdn = args.action === 'set' ? args.fqdn.trim().toLowerCase() : '';\n\n // Cancellation seam (ENG-374, shared via internals/cancellation.ts). Race ONLY\n // the pre-broadcast `onConfirm`; the post-broadcast verifier routes into\n // recovery (D4.6) and is never cancelled.\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain update',\n broadcasts: true,\n });\n cx.throwIfCancelled();\n\n // --- Confirmation block ---------------------------------------------\n const block = renderConfirmationBlock(args);\n if (callbacks.onConfirm) {\n const yesNo = await cx.race(callbacks.onConfirm(block));\n if (yesNo !== 'yes') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.OPERATION_CANCELLED,\n `User declined to proceed with manage-domain ${args.action}.`,\n );\n }\n }\n callbacks.onProgress?.({ kind: 'user_confirmed' });\n\n // --- Broadcast ------------------------------------------------------\n // txCtx has no signer (ManageDomainOptions carries no walletProvider); the\n // sender resolves from ctx.chain (the CosmosClientManager wallet). See OI-SENDER.\n // The raw MCP `leaseUuid`/`fqdn` strings are unbranded → parse at the boundary.\n const leaseUuid = parseLeaseUuid(args.leaseUuid);\n cx.throwIfCancelled();\n await setItemCustomDomain(\n { chain: opts.clientManager, logger: noopLogger },\n args.action === 'set'\n ? { leaseUuid, customDomain: parseFqdn(fqdn), serviceName }\n : { leaseUuid, clear: true, serviceName },\n );\n\n // --- Verify ---------------------------------------------------------\n // Direct single-lease query (Copilot review PR #60, comment 3275999569):\n // the previous `leasesByTenant` + page-1-only pagination would\n // false-`not_found` for tenants with >100 leases. `billing.v1.lease`\n // is the same query shape `troubleshoot.ts` already uses; it's\n // tenant-agnostic and bounded to a single lease.\n //\n // We wrap the single-lease result as `{ leases: [result.lease] }`\n // (or an empty array if the chain returns no match) so\n // `verifyDomainState` stays untouched — its `findLease` walks the\n // same shape, and a `not_found` outcome falls out naturally when the\n // wrapper array is empty.\n const spec: VerificationSpec<\n unknown,\n VerifyDomainOutcome,\n VerifyDomainResult\n > = {\n verifier: async () => {\n // Wrap the chain call in try/catch (Copilot review PR #60,\n // comment 3276419210): if `billing.v1.lease` rejects (RPC down,\n // transport, structured `ManifestMCPError`), the error would\n // otherwise propagate OUT of `verifyAndRecover` and bypass the\n // post-verify `onFailure({ reason })` callback below. Mirror\n // the disambiguation pattern from `lookupDomain` (commit aaa5cc5)\n // and `troubleshootDeployment` (commit f1a4737): invoke\n // `onFailure` first, then re-throw `ManifestMCPError` as-is or\n // wrap plain errors as `QUERY_FAILED`.\n let result: unknown;\n try {\n const queryClient = await opts.clientManager.getQueryClient();\n result = await queryClient.liftedinit.billing.v1.lease({\n leaseUuid: args.leaseUuid,\n });\n } catch (err) {\n const reason = `Failed to query lease ${args.leaseUuid} during ${args.action}-verify: ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const lease = (result as { lease?: unknown })?.lease;\n const leases = lease === null || lease === undefined ? [] : [lease];\n const decoded = verifyDomainState(\n { leases },\n {\n leaseUuid: args.leaseUuid,\n ...(serviceName ? { serviceName } : {}),\n expected: fqdn,\n },\n );\n return { outcome: decoded.outcome, diagnostic: decoded };\n },\n successValues: ['match'],\n branches: {\n mismatch: {\n branchId: 'domain_verification_mismatch',\n journalActionTags: ['domain-verification-mismatch'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n args.action === 'set'\n ? `Chain shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected \"${fqdn}\".`\n : `Chain still shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected cleared.`,\n }),\n buildRecoveryOptions: () => [],\n },\n not_found: {\n branchId: 'domain_not_found',\n journalActionTags: ['domain-verification-not-found'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n d.reason ??\n `Lease ${args.leaseUuid} not found when verifying domain state.`,\n }),\n buildRecoveryOptions: () => [],\n },\n },\n };\n\n const verifyResult = await verifyAndRecover(spec, undefined);\n const verified = verifyResult.result === 'success';\n const finalCustomDomain = deriveFinalCustomDomain(\n verifyResult.diagnostic,\n args.action,\n );\n\n if (!verified) {\n const reason =\n verifyResult.failure?.reason ??\n `manage-domain ${args.action} verification failed.`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.TX_FAILED, reason);\n }\n\n const result: ManageDomainResult = {\n action: args.action,\n leaseUuid: args.leaseUuid,\n verified,\n finalCustomDomain,\n };\n callbacks.onComplete?.(result);\n return result;\n}\n\n// --- Helpers --------------------------------------------------------\n\nfunction validateArgs(args: ManageDomainArgs): void {\n if (\n args.action !== 'set' &&\n args.action !== 'clear' &&\n args.action !== 'lookup'\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain: unknown action \"${(args as { action?: string }).action}\".`,\n );\n }\n if (args.action === 'lookup') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain lookup: fqdn must be a non-empty string.',\n );\n }\n return;\n }\n if (typeof args.leaseUuid !== 'string' || !args.leaseUuid.match(UUID_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain ${args.action}: leaseUuid must be a UUID; got \"${args.leaseUuid}\".`,\n );\n }\n if (args.action === 'set') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain set: fqdn must be a non-empty string.',\n );\n }\n // Validate against the trimmed candidate (Copilot review PR #60,\n // comment 3276519081): surrounding whitespace is silently stripped\n // (like `lookupDomain`) rather than rejected. Note `setItemCustomDomain`\n // does NOT re-trim — it takes an already-normalized branded `Fqdn`\n // (parse-once at the boundary) — so the normalization lives here and at\n // the `fqdn` assignment above, not in the primitive.\n const candidate = args.fqdn.trim();\n if (candidate.match(SCHEME_PREFIX_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn must be a bare hostname (no scheme); got \"${args.fqdn}\".`,\n );\n }\n if (!candidate.match(FQDN_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn \"${args.fqdn}\" is not a valid RFC 1123 hostname (≤253 chars, ≥2 dot-separated labels of 1-63 alphanumeric/hyphen chars; no leading/trailing hyphens).`,\n );\n }\n }\n}\n\nfunction renderConfirmationBlock(\n args: Exclude<ManageDomainArgs, { action: 'lookup' }>,\n): DeploymentPlanBlock {\n const lines: string[] = [];\n if (args.action === 'set') {\n lines.push(`Set custom domain on lease ${args.leaseUuid}:`);\n // Display the trimmed FQDN — matches the value that will be\n // broadcast (per the silent-trim semantics aligned with\n // setItemCustomDomain) so users don't see whitespace in the\n // confirm prompt that won't appear on-chain.\n lines.push(` FQDN: ${args.fqdn.trim()}`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n } else {\n lines.push(`Clear custom domain on lease ${args.leaseUuid}:`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n }\n return { text: lines.join('\\n') };\n}\n\nasync function lookupDomain(\n fqdn: string,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n const customDomain = fqdn.trim();\n // Cancellation seam (ENG-374): read-only flow races the single query for\n // withReadSignal parity. Manifestjs queries take no AbortSignal, so on abort\n // we stop awaiting (the RPC is not actually cancelled).\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain lookup',\n broadcasts: false,\n });\n cx.throwIfCancelled();\n let result: unknown;\n try {\n // Pull `getQueryClient()` INSIDE the try (Copilot review PR #60,\n // comment 3276719558). `getQueryClient()` can throw\n // `INVALID_CONFIG` (neither rpcUrl nor restUrl set) or\n // `RPC_CONNECTION_FAILED` (connect failure). Catching here routes\n // those init-time failures through the same `onFailure` +\n // QUERY_FAILED / structured-passthrough normalization the chain-\n // query failure mode already gets. The set/clear verifier closure\n // (in `manageDomain` body above) already wraps `getQueryClient()`\n // since commit d9793c1; this brings `lookupDomain` to parity.\n const queryClient = await opts.clientManager.getQueryClient();\n result = await cx.race(\n queryClient.liftedinit.billing.v1.leaseByCustomDomain({\n customDomain,\n }),\n );\n } catch (err) {\n // Cancellation short-circuit (ENG-374): an aborted read is neither a\n // \"not found\" nor a query failure — re-throw BEFORE the not-found /\n // onFailure handling so it never invokes `onFailure`.\n if (\n err instanceof ManifestMCPError &&\n err.code === ManifestMCPErrorCode.OPERATION_CANCELLED\n ) {\n throw err;\n }\n // Narrowed disambiguation (Copilot review PR #60): the chain keeper\n // raises a NotFound-shaped error when the FQDN is unclaimed (cosmjs/\n // grpc surfaces this as a plain `Error` whose message matches\n // `/not.?found|no.?such|does.?not.?exist/i`). Only that case is\n // collapsed to the typed `{ lease: null }` result. Every other\n // failure mode (RPC transport, decoding, structured\n // `ManifestMCPError`, etc.) flows through `onFailure({ reason })`\n // then a typed throw — matching the lease-package's\n // `lease_by_custom_domain` handler (packages/lease/src/index.ts:442)\n // and `getBalance`'s `catchNotFound` pattern (packages/core/src/\n // tools/getBalance.ts:4). The bare `catch` was masking real failures.\n if (isNotFoundError(err)) {\n const notFoundResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: null,\n };\n callbacks.onComplete?.(notFoundResult);\n return notFoundResult;\n }\n const reason = `lease_by_custom_domain lookup failed for \"${customDomain}\": ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const uuid = readLeaseUuid((result as { lease?: unknown })?.lease);\n const lookupResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: uuid ? { leaseUuid: uuid } : null,\n };\n // Symmetric `onComplete` fire (Copilot review PR #60, comment\n // 3288656598). Pre-fix, the lookup path returned without invoking\n // `onComplete` — asymmetric vs the set/clear paths in this same\n // function and vs `closeLease` / `troubleshootDeployment`. Was\n // documented as \"intentional\" in PR_DESCRIPTION.md Risks #1 but\n // was really an oversight rationalized post-hoc. Now consistent.\n callbacks.onComplete?.(lookupResult);\n return lookupResult;\n}\n\nfunction isNotFoundError(err: unknown): boolean {\n // Pass-through guard for structured failures: a `ManifestMCPError` is\n // always a real, intentional error — never silently re-classified as\n // \"FQDN unclaimed\" even if its message happens to contain \"not found\".\n if (err instanceof ManifestMCPError) return false;\n if (!(err instanceof Error)) return false;\n const msg = err.message;\n return NOT_FOUND_RES.some((re) => msg.match(re) !== null);\n}\n\nfunction readLeaseUuid(lease: unknown): string | undefined {\n if (lease === null || typeof lease !== 'object') return undefined;\n const r = lease as {\n uuid?: unknown;\n lease_uuid?: unknown;\n leaseUuid?: unknown;\n };\n const u = r.uuid ?? r.lease_uuid ?? r.leaseUuid;\n return typeof u === 'string' && u.length > 0 ? u : undefined;\n}\n\nfunction deriveFinalCustomDomain(\n diagnostic: VerifyDomainResult,\n action: 'set' | 'clear',\n): string | null {\n if (action === 'clear') return null;\n const actual = diagnostic.actual ?? '';\n return actual.length > 0 ? actual : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,UACJ;AAeF,MAAM,UACJ;AAEF,MAAM,mBAAmB;;;;;;;;;;;;;AAczB,MAAM,gBAAmC;CACvC;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,aACpB,MACA,WACA,MAC6B;CAC7B,aAAa,IAAI;CAEjB,IAAI,KAAK,WAAW,UAClB,OAAO,MAAM,aAAa,KAAK,MAAM,WAAW,IAAI;CAGtD,MAAM,cAAc,KAAK;CAUzB,MAAM,OAAO,KAAK,WAAW,QAAQ,KAAK,KAAK,KAAK,EAAE,YAAY,IAAI;CAKtE,MAAM,KAAK,sBAAsB;EAC/B;EACA,YAAY,UAAU;EACtB,SAAS;EACT,YAAY;CACd,CAAC;CACD,GAAG,iBAAiB;CAGpB,MAAM,QAAQ,wBAAwB,IAAI;CAC1C,IAAI,UAAU;MAER,MADgB,GAAG,KAAK,UAAU,UAAU,KAAK,CAAC,MACxC,OACZ,MAAM,IAAI,iBACR,qBAAqB,qBACrB,+CAA+C,KAAK,OAAO,EAC7D;CAAA;CAGJ,UAAU,aAAa,EAAE,MAAM,iBAAiB,CAAC;CAMjD,MAAM,YAAY,eAAe,KAAK,SAAS;CAC/C,GAAG,iBAAiB;CACpB,MAAM,oBACJ;EAAE,OAAO,KAAK;EAAe,QAAQ;CAAW,GAChD,KAAK,WAAW,QACZ;EAAE;EAAW,cAAc,UAAU,IAAI;EAAG;CAAY,IACxD;EAAE;EAAW,OAAO;EAAM;CAAY,CAC5C;CAuFA,MAAM,eAAe,MAAM,iBAAiB;EApE1C,UAAU,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,OAAO,EAAE,WAAW,KAAK,IAAI;CACtC;CAOA,UAAU,aAAa,YAAY;CACnC,OAAO;AACT;AAEA,SAAS,gBAAgB,KAAuB;CAI9C,IAAI,eAAe,kBAAkB,OAAO;CAC5C,IAAI,EAAE,eAAe,QAAQ,OAAO;CACpC,MAAM,MAAM,IAAI;CAChB,OAAO,cAAc,MAAM,OAAO,IAAI,MAAM,EAAE,MAAM,IAAI;AAC1D;AAEA,SAAS,cAAc,OAAoC;CACzD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,MAAM,IAAI;CAKV,MAAM,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE;CACtC,OAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI,KAAA;AACrD;AAEA,SAAS,wBACP,YACA,QACe;CACf,IAAI,WAAW,SAAS,OAAO;CAC/B,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO,OAAO,SAAS,IAAI,SAAS;AACtC"}
1
+ {"version":3,"file":"manage-domain.js","names":[],"sources":["../src/manage-domain.ts"],"sourcesContent":["/**\n * Public entry point: orchestrate setting, clearing, or looking up a\n * lease item's custom domain.\n *\n * Composition (mirrors `deploy-app.ts`'s shape):\n *\n * - `set` / `clear` render a confirmation block, optionally call\n * `onConfirm`, broadcast `setItemCustomDomain` against the agent's\n * bound chain client, then verify the post-broadcast on-chain state\n * via `verifyAndRecover` driving `verify-domain-state` over a direct\n * `billing.v1.lease({ leaseUuid })` single-lease query (tenant-\n * agnostic, no pagination edge cases). Branches are inline closures\n * bound to the per-action context; recovery options are intentionally\n * empty so the verifier surfaces failures via the simple-form\n * `onFailure({ reason })` adapter rather than the rich-form\n * `RecoveryOption[]` prompt (manage-domain has no recovery primitives\n * the orchestrator can dispatch; the user re-runs after a real fix).\n *\n * - `lookup` skips broadcast/verify and resolves the FQDN via the\n * `lease_by_custom_domain` chain query; returns `null` lease when\n * the FQDN isn't claimed.\n */\n\nimport {\n isNotFoundError,\n ManifestMCPError,\n ManifestMCPErrorCode,\n noopLogger,\n parseFqdn,\n parseLeaseUuid,\n setItemCustomDomain,\n} from '@manifest-network/manifest-mcp-core';\nimport { makeCancellationScope } from './internals/cancellation.js';\nimport {\n type VerifyDomainOutcome,\n type VerifyDomainResult,\n verifyDomainState,\n} from './internals/verify-domain-state.js';\nimport {\n type VerificationSpec,\n verifyAndRecover,\n} from './internals/verify-recover.js';\nimport type {\n DeploymentPlanBlock,\n ManageDomainArgs,\n ManageDomainCallbacks,\n ManageDomainOptions,\n ManageDomainResult,\n} from './types.js';\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// RFC 1123 hostname: each label 1-63 chars, alphanumeric + hyphens, no leading/\n// trailing hyphen; total ≤253 chars; ≥2 labels (FQDN, not single-label host).\n// Rejects scheme prefixes ('http://'), whitespace, trailing dots, and raw\n// unicode (ASCII punycode `xn--...` is accepted — it matches the regex's\n// `[A-Za-z0-9-]` label character class, which is the standard wire form\n// for IDN labels).\n//\n// Client-side typo gate only. The chain's `MsgSetItemCustomDomain` keeper is\n// the authoritative validator (canonical lowercase, reserved-suffix rules,\n// FQDN format). This anchored regex catches the obvious-malformed-input\n// cases pre-broadcast so we don't waste a tx on `\"\"`, `\" \"`, `\"http://x.y\"`,\n// or `\"not a domain\"`. Anything that passes here still goes through the\n// chain's own validation.\nconst FQDN_RE =\n /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;\n\nconst SCHEME_PREFIX_RE = /^https?:\\/\\//i;\n\n/**\n * Set / clear / look up a lease item's custom domain.\n *\n * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation.\n * @throws `ManifestMCPError(OPERATION_CANCELLED)` when `onConfirm` returns\n * `'no'` (deliberate user cancellation — ENG-272).\n * @throws `ManifestMCPError` (typically `TX_FAILED`) propagated as-is\n * from the `setItemCustomDomain()` broadcast step in `set` / `clear`\n * paths. Broadcast errors do NOT invoke `onFailure` — that callback\n * is reserved for post-broadcast verification failures.\n * `setItemCustomDomain` already raises a structured `ManifestMCPError`\n * from the core package; wrapping it again at this layer would be\n * redundant. Callers wanting to react to broadcast errors should\n * catch them at the call site.\n * @throws `ManifestMCPError(TX_FAILED)` when post-broadcast verification\n * reaches a `not_found` / `mismatch` outcome (after `onFailure` has\n * been invoked so the caller can react).\n * @throws `ManifestMCPError(QUERY_FAILED)` when a chain query raises a\n * non-NotFound error (RPC / transport / decoding failure). Two paths\n * surface this:\n * - the `lookup` chain query (`lease_by_custom_domain`); the keeper's\n * `NotFound` on an unclaimed FQDN is surfaced as a typed\n * `{ lease: null }` result, not a throw.\n * - the post-broadcast verify chain query (`billing.v1.lease`) in\n * the `set` / `clear` paths (wrapped inside the verifier closure\n * so the failure flows through `onFailure({ reason })` before the\n * throw).\n * Structured `ManifestMCPError`s raised by the chain client are\n * re-thrown as-is (with `onFailure` invoked first).\n */\nexport async function manageDomain(\n args: ManageDomainArgs,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n validateArgs(args);\n\n if (args.action === 'lookup') {\n return await lookupDomain(args.fqdn, callbacks, opts);\n }\n\n const serviceName = args.serviceName;\n // Normalize the FQDN once for `set`: trim surrounding whitespace\n // (Copilot review PR #60, comment 3276519081) AND lowercase (RFC 4343),\n // matching what `parseFqdn` does to the broadcast value below. Both the\n // broadcast (`parseFqdn(fqdn)`) and the post-broadcast verification\n // (`expected: fqdn`) must compare the SAME normalized value — otherwise a\n // mixed-case input broadcasts lowercased but verifies against the raw\n // casing, producing a spurious mismatch (code-review PR #102).\n // `validateArgs` still rejects the empty / whitespace-only case via\n // `args.fqdn.trim() === ''`.\n const fqdn = args.action === 'set' ? args.fqdn.trim().toLowerCase() : '';\n\n // Cancellation seam (ENG-374, shared via internals/cancellation.ts). Race ONLY\n // the pre-broadcast `onConfirm`; the post-broadcast verifier routes into\n // recovery (D4.6) and is never cancelled.\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain update',\n broadcasts: true,\n });\n cx.throwIfCancelled();\n\n // --- Confirmation block ---------------------------------------------\n const block = renderConfirmationBlock(args);\n if (callbacks.onConfirm) {\n const yesNo = await cx.race(callbacks.onConfirm(block));\n if (yesNo !== 'yes') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.OPERATION_CANCELLED,\n `User declined to proceed with manage-domain ${args.action}.`,\n );\n }\n }\n callbacks.onProgress?.({ kind: 'user_confirmed' });\n\n // --- Broadcast ------------------------------------------------------\n // txCtx has no signer (ManageDomainOptions carries no walletProvider); the\n // sender resolves from ctx.chain (the CosmosClientManager wallet). See OI-SENDER.\n // The raw MCP `leaseUuid`/`fqdn` strings are unbranded → parse at the boundary.\n const leaseUuid = parseLeaseUuid(args.leaseUuid);\n cx.throwIfCancelled();\n await setItemCustomDomain(\n { chain: opts.clientManager, logger: noopLogger },\n args.action === 'set'\n ? { leaseUuid, customDomain: parseFqdn(fqdn), serviceName }\n : { leaseUuid, clear: true, serviceName },\n );\n\n // --- Verify ---------------------------------------------------------\n // Direct single-lease query (Copilot review PR #60, comment 3275999569):\n // the previous `leasesByTenant` + page-1-only pagination would\n // false-`not_found` for tenants with >100 leases. `billing.v1.lease`\n // is the same query shape `troubleshoot.ts` already uses; it's\n // tenant-agnostic and bounded to a single lease.\n //\n // We wrap the single-lease result as `{ leases: [result.lease] }`\n // (or an empty array if the chain returns no match) so\n // `verifyDomainState` stays untouched — its `findLease` walks the\n // same shape, and a `not_found` outcome falls out naturally when the\n // wrapper array is empty.\n const spec: VerificationSpec<\n unknown,\n VerifyDomainOutcome,\n VerifyDomainResult\n > = {\n verifier: async () => {\n // Wrap the chain call in try/catch (Copilot review PR #60,\n // comment 3276419210): if `billing.v1.lease` rejects (RPC down,\n // transport, structured `ManifestMCPError`), the error would\n // otherwise propagate OUT of `verifyAndRecover` and bypass the\n // post-verify `onFailure({ reason })` callback below. Mirror\n // the disambiguation pattern from `lookupDomain` (commit aaa5cc5)\n // and `troubleshootDeployment` (commit f1a4737): invoke\n // `onFailure` first, then re-throw `ManifestMCPError` as-is or\n // wrap plain errors as `QUERY_FAILED`.\n let result: unknown;\n try {\n const queryClient = await opts.clientManager.getQueryClient();\n result = await queryClient.liftedinit.billing.v1.lease({\n leaseUuid: args.leaseUuid,\n });\n } catch (err) {\n const reason = `Failed to query lease ${args.leaseUuid} during ${args.action}-verify: ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const lease = (result as { lease?: unknown })?.lease;\n const leases = lease === null || lease === undefined ? [] : [lease];\n const decoded = verifyDomainState(\n { leases },\n {\n leaseUuid: args.leaseUuid,\n ...(serviceName ? { serviceName } : {}),\n expected: fqdn,\n },\n );\n return { outcome: decoded.outcome, diagnostic: decoded };\n },\n successValues: ['match'],\n branches: {\n mismatch: {\n branchId: 'domain_verification_mismatch',\n journalActionTags: ['domain-verification-mismatch'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n args.action === 'set'\n ? `Chain shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected \"${fqdn}\".`\n : `Chain still shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected cleared.`,\n }),\n buildRecoveryOptions: () => [],\n },\n not_found: {\n branchId: 'domain_not_found',\n journalActionTags: ['domain-verification-not-found'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n d.reason ??\n `Lease ${args.leaseUuid} not found when verifying domain state.`,\n }),\n buildRecoveryOptions: () => [],\n },\n },\n };\n\n const verifyResult = await verifyAndRecover(spec, undefined);\n const verified = verifyResult.result === 'success';\n const finalCustomDomain = deriveFinalCustomDomain(\n verifyResult.diagnostic,\n args.action,\n );\n\n if (!verified) {\n const reason =\n verifyResult.failure?.reason ??\n `manage-domain ${args.action} verification failed.`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.TX_FAILED, reason);\n }\n\n const result: ManageDomainResult = {\n action: args.action,\n leaseUuid: args.leaseUuid,\n verified,\n finalCustomDomain,\n };\n callbacks.onComplete?.(result);\n return result;\n}\n\n// --- Helpers --------------------------------------------------------\n\nfunction validateArgs(args: ManageDomainArgs): void {\n if (\n args.action !== 'set' &&\n args.action !== 'clear' &&\n args.action !== 'lookup'\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain: unknown action \"${(args as { action?: string }).action}\".`,\n );\n }\n if (args.action === 'lookup') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain lookup: fqdn must be a non-empty string.',\n );\n }\n return;\n }\n if (typeof args.leaseUuid !== 'string' || !args.leaseUuid.match(UUID_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain ${args.action}: leaseUuid must be a UUID; got \"${args.leaseUuid}\".`,\n );\n }\n if (args.action === 'set') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain set: fqdn must be a non-empty string.',\n );\n }\n // Validate against the trimmed candidate (Copilot review PR #60,\n // comment 3276519081): surrounding whitespace is silently stripped\n // (like `lookupDomain`) rather than rejected. Note `setItemCustomDomain`\n // does NOT re-trim — it takes an already-normalized branded `Fqdn`\n // (parse-once at the boundary) — so the normalization lives here and at\n // the `fqdn` assignment above, not in the primitive.\n const candidate = args.fqdn.trim();\n if (candidate.match(SCHEME_PREFIX_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn must be a bare hostname (no scheme); got \"${args.fqdn}\".`,\n );\n }\n if (!candidate.match(FQDN_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn \"${args.fqdn}\" is not a valid RFC 1123 hostname (≤253 chars, ≥2 dot-separated labels of 1-63 alphanumeric/hyphen chars; no leading/trailing hyphens).`,\n );\n }\n }\n}\n\nfunction renderConfirmationBlock(\n args: Exclude<ManageDomainArgs, { action: 'lookup' }>,\n): DeploymentPlanBlock {\n const lines: string[] = [];\n if (args.action === 'set') {\n lines.push(`Set custom domain on lease ${args.leaseUuid}:`);\n // Display the trimmed FQDN — matches the value that will be\n // broadcast (per the silent-trim semantics aligned with\n // setItemCustomDomain) so users don't see whitespace in the\n // confirm prompt that won't appear on-chain.\n lines.push(` FQDN: ${args.fqdn.trim()}`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n } else {\n lines.push(`Clear custom domain on lease ${args.leaseUuid}:`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n }\n return { text: lines.join('\\n') };\n}\n\nasync function lookupDomain(\n fqdn: string,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n const customDomain = fqdn.trim();\n // Cancellation seam (ENG-374): read-only flow races the single query for\n // withReadSignal parity. Manifestjs queries take no AbortSignal, so on abort\n // we stop awaiting (the RPC is not actually cancelled).\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain lookup',\n broadcasts: false,\n });\n cx.throwIfCancelled();\n let result: unknown;\n try {\n // Pull `getQueryClient()` INSIDE the try (Copilot review PR #60,\n // comment 3276719558). `getQueryClient()` can throw\n // `INVALID_CONFIG` (neither rpcUrl nor restUrl set) or\n // `RPC_CONNECTION_FAILED` (connect failure). Catching here routes\n // those init-time failures through the same `onFailure` +\n // QUERY_FAILED / structured-passthrough normalization the chain-\n // query failure mode already gets. The set/clear verifier closure\n // (in `manageDomain` body above) already wraps `getQueryClient()`\n // since commit d9793c1; this brings `lookupDomain` to parity.\n const queryClient = await opts.clientManager.getQueryClient();\n result = await cx.race(\n queryClient.liftedinit.billing.v1.leaseByCustomDomain({\n customDomain,\n }),\n );\n } catch (err) {\n // Cancellation short-circuit (ENG-374): an aborted read is neither a\n // \"not found\" nor a query failure — re-throw BEFORE the not-found /\n // onFailure handling so it never invokes `onFailure`.\n if (\n err instanceof ManifestMCPError &&\n err.code === ManifestMCPErrorCode.OPERATION_CANCELLED\n ) {\n throw err;\n }\n // Narrowed disambiguation (ENG-536): the keeper's NotFound now arrives as\n // a structured `NOT_FOUND` — classified from the grpc envelope in core's\n // LCD adapter, or from cosmjs's `rpc error: code = NotFound` text over\n // RPC (see core's `internals/classify-query-error.ts`). Only that case\n // is collapsed to the typed `{ lease: null }` result (via `onComplete`).\n // Every other failure — including a proxy 404 whose message merely\n // contains \"not found\" — flows through `onFailure({ reason })` then a\n // typed throw. `isNotFoundError` used to be a local loose-regex helper\n // here; it is now core's shared predicate (imported above) so all\n // callers agree on what \"not found\" means.\n if (isNotFoundError(err)) {\n const notFoundResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: null,\n };\n callbacks.onComplete?.(notFoundResult);\n return notFoundResult;\n }\n const reason = `lease_by_custom_domain lookup failed for \"${customDomain}\": ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const uuid = readLeaseUuid((result as { lease?: unknown })?.lease);\n const lookupResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: uuid ? { leaseUuid: uuid } : null,\n };\n // Symmetric `onComplete` fire (Copilot review PR #60, comment\n // 3288656598). Pre-fix, the lookup path returned without invoking\n // `onComplete` — asymmetric vs the set/clear paths in this same\n // function and vs `closeLease` / `troubleshootDeployment`. Was\n // documented as \"intentional\" in PR_DESCRIPTION.md Risks #1 but\n // was really an oversight rationalized post-hoc. Now consistent.\n callbacks.onComplete?.(lookupResult);\n return lookupResult;\n}\n\nfunction readLeaseUuid(lease: unknown): string | undefined {\n if (lease === null || typeof lease !== 'object') return undefined;\n const r = lease as {\n uuid?: unknown;\n lease_uuid?: unknown;\n leaseUuid?: unknown;\n };\n const u = r.uuid ?? r.lease_uuid ?? r.leaseUuid;\n return typeof u === 'string' && u.length > 0 ? u : undefined;\n}\n\nfunction deriveFinalCustomDomain(\n diagnostic: VerifyDomainResult,\n action: 'set' | 'clear',\n): string | null {\n if (action === 'clear') return null;\n const actual = diagnostic.actual ?? '';\n return actual.length > 0 ? actual : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,UACJ;AAeF,MAAM,UACJ;AAEF,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCzB,eAAsB,aACpB,MACA,WACA,MAC6B;CAC7B,aAAa,IAAI;CAEjB,IAAI,KAAK,WAAW,UAClB,OAAO,MAAM,aAAa,KAAK,MAAM,WAAW,IAAI;CAGtD,MAAM,cAAc,KAAK;CAUzB,MAAM,OAAO,KAAK,WAAW,QAAQ,KAAK,KAAK,KAAK,EAAE,YAAY,IAAI;CAKtE,MAAM,KAAK,sBAAsB;EAC/B;EACA,YAAY,UAAU;EACtB,SAAS;EACT,YAAY;CACd,CAAC;CACD,GAAG,iBAAiB;CAGpB,MAAM,QAAQ,wBAAwB,IAAI;CAC1C,IAAI,UAAU;MAER,MADgB,GAAG,KAAK,UAAU,UAAU,KAAK,CAAC,MACxC,OACZ,MAAM,IAAI,iBACR,qBAAqB,qBACrB,+CA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ACA,UAAU,aAAa,cAAc;GACrC,OAAO;EACT;EACA,MAAM,SAAS,6CAA6C,aAAa,KACvE,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EAEjD,IAAI,UAAU,WACZ,MAAM,UAAU,UAAU,EAAE,OAAO,CAAC;EAEtC,IAAI,eAAe,kBACjB,MAAM;EAER,MAAM,IAAI,iBAAiB,qBAAqB,cAAc,MAAM;CACtE;CACA,MAAM,OAAO,cAAe,QAAgC,KAAK;CACjE,MAAM,eAAmC;EACvC,QAAQ;EACR,MAAM;EACN,OAAO,OAAO,EAAE,WAAW,KAAK,IAAI;CACtC;CAOA,UAAU,aAAa,YAAY;CACnC,OAAO;AACT;AAEA,SAAS,cAAc,OAAoC;CACzD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,MAAM,IAAI;CAKV,MAAM,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE;CACtC,OAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI,KAAA;AACrD;AAEA,SAAS,wBACP,YACA,QACe;CACf,IAAI,WAAW,SAAS,OAAO;CAC/B,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO,OAAO,SAAS,IAAI,SAAS;AACtC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@manifest-network/manifest-agent-core",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "TypeScript orchestration surface for Manifest agent flows (deploy / manage-domain / troubleshoot / close-lease). Type contract only — see ENG-127.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -49,12 +49,12 @@
49
49
  "dist"
50
50
  ],
51
51
  "peerDependencies": {
52
- "@manifest-network/manifest-mcp-core": "^0.17.0",
53
- "@manifest-network/manifest-mcp-fred": "^0.17.0"
52
+ "@manifest-network/manifest-mcp-core": "^0.19.0",
53
+ "@manifest-network/manifest-mcp-fred": "^0.19.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@manifest-network/manifest-mcp-core": "0.17.0",
57
- "@manifest-network/manifest-mcp-fred": "0.17.0",
56
+ "@manifest-network/manifest-mcp-core": "0.19.0",
57
+ "@manifest-network/manifest-mcp-fred": "0.19.0",
58
58
  "@types/node": "22.19.19",
59
59
  "typescript": "5.9.3",
60
60
  "vitest": "4.1.8"