@manifest-network/manifest-agent-core 0.9.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.
Files changed (99) hide show
  1. package/README.md +39 -0
  2. package/dist/close-lease.d.ts +33 -0
  3. package/dist/close-lease.d.ts.map +1 -0
  4. package/dist/close-lease.js +138 -0
  5. package/dist/close-lease.js.map +1 -0
  6. package/dist/deploy-app.d.ts +24 -0
  7. package/dist/deploy-app.d.ts.map +1 -0
  8. package/dist/deploy-app.js +446 -0
  9. package/dist/deploy-app.js.map +1 -0
  10. package/dist/index.d.ts +8 -0
  11. package/dist/index.js +7 -0
  12. package/dist/internals/classify-deploy-error.d.ts +41 -0
  13. package/dist/internals/classify-deploy-error.d.ts.map +1 -0
  14. package/dist/internals/classify-deploy-error.js +79 -0
  15. package/dist/internals/classify-deploy-error.js.map +1 -0
  16. package/dist/internals/classify-deploy-response.d.ts +56 -0
  17. package/dist/internals/classify-deploy-response.d.ts.map +1 -0
  18. package/dist/internals/classify-deploy-response.js +33 -0
  19. package/dist/internals/classify-deploy-response.js.map +1 -0
  20. package/dist/internals/connection.d.ts +76 -0
  21. package/dist/internals/connection.d.ts.map +1 -0
  22. package/dist/internals/connection.js +94 -0
  23. package/dist/internals/connection.js.map +1 -0
  24. package/dist/internals/evaluate-readiness.d.ts +55 -0
  25. package/dist/internals/evaluate-readiness.d.ts.map +1 -0
  26. package/dist/internals/evaluate-readiness.js +131 -0
  27. package/dist/internals/evaluate-readiness.js.map +1 -0
  28. package/dist/internals/find-sku-uuid.d.ts +40 -0
  29. package/dist/internals/find-sku-uuid.d.ts.map +1 -0
  30. package/dist/internals/find-sku-uuid.js +20 -0
  31. package/dist/internals/find-sku-uuid.js.map +1 -0
  32. package/dist/internals/format-success.d.ts +35 -0
  33. package/dist/internals/format-success.d.ts.map +1 -0
  34. package/dist/internals/format-success.js +80 -0
  35. package/dist/internals/format-success.js.map +1 -0
  36. package/dist/internals/guarded-fetch.d.ts +138 -0
  37. package/dist/internals/guarded-fetch.d.ts.map +1 -0
  38. package/dist/internals/guarded-fetch.js +242 -0
  39. package/dist/internals/guarded-fetch.js.map +1 -0
  40. package/dist/internals/humanize-denom.d.ts +45 -0
  41. package/dist/internals/humanize-denom.d.ts.map +1 -0
  42. package/dist/internals/humanize-denom.js +105 -0
  43. package/dist/internals/humanize-denom.js.map +1 -0
  44. package/dist/internals/inspect-image.d.ts +31 -0
  45. package/dist/internals/inspect-image.d.ts.map +1 -0
  46. package/dist/internals/inspect-image.js +345 -0
  47. package/dist/internals/inspect-image.js.map +1 -0
  48. package/dist/internals/lease-items.d.ts +46 -0
  49. package/dist/internals/lease-items.d.ts.map +1 -0
  50. package/dist/internals/lease-items.js +58 -0
  51. package/dist/internals/lease-items.js.map +1 -0
  52. package/dist/internals/lease-state.d.ts +32 -0
  53. package/dist/internals/lease-state.d.ts.map +1 -0
  54. package/dist/internals/lease-state.js +80 -0
  55. package/dist/internals/lease-state.js.map +1 -0
  56. package/dist/internals/render-deployment-plan.d.ts +22 -0
  57. package/dist/internals/render-deployment-plan.d.ts.map +1 -0
  58. package/dist/internals/render-deployment-plan.js +135 -0
  59. package/dist/internals/render-deployment-plan.js.map +1 -0
  60. package/dist/internals/render-intent-recap.d.ts +43 -0
  61. package/dist/internals/render-intent-recap.d.ts.map +1 -0
  62. package/dist/internals/render-intent-recap.js +136 -0
  63. package/dist/internals/render-intent-recap.js.map +1 -0
  64. package/dist/internals/render-partial-success-prompt.d.ts +26 -0
  65. package/dist/internals/render-partial-success-prompt.d.ts.map +1 -0
  66. package/dist/internals/render-partial-success-prompt.js +53 -0
  67. package/dist/internals/render-partial-success-prompt.js.map +1 -0
  68. package/dist/internals/save-manifest.d.ts +105 -0
  69. package/dist/internals/save-manifest.d.ts.map +1 -0
  70. package/dist/internals/save-manifest.js +122 -0
  71. package/dist/internals/save-manifest.js.map +1 -0
  72. package/dist/internals/secret-denylist.d.ts +42 -0
  73. package/dist/internals/secret-denylist.d.ts.map +1 -0
  74. package/dist/internals/secret-denylist.js +59 -0
  75. package/dist/internals/secret-denylist.js.map +1 -0
  76. package/dist/internals/spec-normalize.d.ts +84 -0
  77. package/dist/internals/spec-normalize.d.ts.map +1 -0
  78. package/dist/internals/spec-normalize.js +169 -0
  79. package/dist/internals/spec-normalize.js.map +1 -0
  80. package/dist/internals/verify-domain-state.d.ts +20 -0
  81. package/dist/internals/verify-domain-state.d.ts.map +1 -0
  82. package/dist/internals/verify-domain-state.js +63 -0
  83. package/dist/internals/verify-domain-state.js.map +1 -0
  84. package/dist/internals/verify-recover.d.ts +120 -0
  85. package/dist/internals/verify-recover.d.ts.map +1 -0
  86. package/dist/internals/verify-recover.js +91 -0
  87. package/dist/internals/verify-recover.js.map +1 -0
  88. package/dist/manage-domain.d.ts +36 -0
  89. package/dist/manage-domain.d.ts.map +1 -0
  90. package/dist/manage-domain.js +230 -0
  91. package/dist/manage-domain.js.map +1 -0
  92. package/dist/troubleshoot.d.ts +23 -0
  93. package/dist/troubleshoot.d.ts.map +1 -0
  94. package/dist/troubleshoot.js +124 -0
  95. package/dist/troubleshoot.js.map +1 -0
  96. package/dist/types.d.ts +294 -0
  97. package/dist/types.d.ts.map +1 -0
  98. package/dist/types.js +0 -0
  99. package/package.json +56 -0
@@ -0,0 +1,169 @@
1
+ //#region src/internals/spec-normalize.ts
2
+ /**
3
+ * Spec normalization + summarization helpers. Exports `isStack`,
4
+ * `firstImage`, `normalizeServices`, `summarizeSpec`, and `validateSpec`
5
+ * (the latter surfaces pre-broadcast shape violations).
6
+ *
7
+ * Two spec shapes are supported (frozen in ENG-128's `types.ts`):
8
+ * - **services-map (StackSpec)** — `{ services: { <name>: ServiceDef }, customDomain?, serviceName? }`
9
+ * - **legacy single-service (SingleServiceSpec)** — `{ image, port?, env?, customDomain? }`
10
+ *
11
+ * `normalizeServices` collapses the two shapes into a single iterable form
12
+ * so callers (Plan summary, manifest builder, etc.) walk one structure
13
+ * regardless of which form the user passed.
14
+ *
15
+ * Validation: `validateSpec` throws a plain `TypeError` on shape violations
16
+ * — agent-core has no workspace dep on `@manifest-network/manifest-mcp-core`
17
+ * in PR 1/2 (per parent's REV 1), so `ManifestMCPError` isn't available
18
+ * here. PR 3's high-level `deployApp` re-wraps `TypeError` into
19
+ * `ManifestMCPError(INVALID_CONFIG)` at the public-API boundary.
20
+ */
21
+ /**
22
+ * True when `spec` uses the services-map shape (StackSpec). Mirrors
23
+ * `_spec.cjs#isStack`: `services` is a non-null, non-array object.
24
+ */
25
+ function isStackSpec(spec) {
26
+ if (spec === null || spec === void 0 || typeof spec !== "object") return false;
27
+ const services = spec.services;
28
+ return services !== null && typeof services === "object" && !Array.isArray(services);
29
+ }
30
+ /**
31
+ * Return the canonical first image string for a spec. For legacy single-
32
+ * service: `spec.image`. For stack: the first non-empty `image` in
33
+ * `Object.values(spec.services)`. Returns `null` when neither shape
34
+ * carries an image (or `spec` is malformed).
35
+ */
36
+ function firstImage(spec) {
37
+ if (spec === null || spec === void 0 || typeof spec !== "object") return null;
38
+ const single = spec;
39
+ if (typeof single.image === "string" && single.image.length > 0) return single.image;
40
+ if (isStackSpec(spec)) {
41
+ for (const svc of Object.values(spec.services)) if (svc !== null && typeof svc === "object") {
42
+ const image = svc.image;
43
+ if (typeof image === "string" && image.length > 0) return image;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+ function normalizeServices(spec) {
49
+ if (isStackSpec(spec)) return Object.entries(spec.services).map(([name, raw]) => ({
50
+ name,
51
+ raw: raw ?? {}
52
+ }));
53
+ return [{
54
+ name: null,
55
+ raw: spec ?? {}
56
+ }];
57
+ }
58
+ /**
59
+ * Produce the frozen `SpecSummary` shape for inclusion in the `Plan`
60
+ * (camelCase fields: `serviceCount`, etc.).
61
+ *
62
+ * Port count rules:
63
+ * - SingleServiceSpec `port: number` → +1 port.
64
+ * - SingleServiceSpec `port: number[]` → +length ports.
65
+ * - ServiceDef `ports: number[]` (per type) → +length ports.
66
+ * - ServiceDef `ports` shaped as a Record (older codepath) → +key count.
67
+ *
68
+ * Env key uniqueness is computed across services (one `env_keys` set
69
+ * spans the whole spec); `envCount` is the size of that set; `envKeys`
70
+ * is sorted ascending.
71
+ */
72
+ function summarizeSpec(spec) {
73
+ const format = isStackSpec(spec) ? "stack" : "single";
74
+ const services = normalizeServices(spec);
75
+ let portCount = 0;
76
+ const envKeys = /* @__PURE__ */ new Set();
77
+ const images = [];
78
+ for (const { raw: svc } of services) if (svc !== null && typeof svc === "object") {
79
+ const svcRecord = svc;
80
+ const image = svcRecord.image;
81
+ if (typeof image === "string" && image.length > 0) images.push(image);
82
+ const port = svcRecord.port;
83
+ if (typeof port === "number") portCount += 1;
84
+ else if (Array.isArray(port)) portCount += port.length;
85
+ const ports = svcRecord.ports;
86
+ if (Array.isArray(ports)) portCount += ports.length;
87
+ else if (ports !== null && typeof ports === "object") portCount += Object.keys(ports).length;
88
+ const env = svcRecord.env;
89
+ if (env !== null && typeof env === "object" && !Array.isArray(env)) for (const k of Object.keys(env)) envKeys.add(k);
90
+ }
91
+ return {
92
+ format,
93
+ serviceCount: services.length,
94
+ portCount,
95
+ envCount: envKeys.size,
96
+ envKeys: Array.from(envKeys).sort(),
97
+ images
98
+ };
99
+ }
100
+ /**
101
+ * Validate a `DeploySpec` shape pre-broadcast. Throws `TypeError` on the
102
+ * first violation. The frozen type union (`SingleServiceSpec | StackSpec`)
103
+ * already enforces most structural rules at compile time; this runtime
104
+ * check defends against `unknown`-cast callers and `JSON.parse`-decoded
105
+ * inputs.
106
+ *
107
+ * Rules (mirror fred's `deployApp.ts` input validation):
108
+ * - `spec` must be a non-null object.
109
+ * - Stack: `services` must have ≥1 entry; each entry's `image` must be a
110
+ * non-empty string.
111
+ * - Single: `image` must be a non-empty string.
112
+ * - Mutually exclusive `image` AND `services` not allowed.
113
+ *
114
+ * The high-level `deployApp` in PR 3 layers domain checks on top
115
+ * (`customDomain` shape, `serviceName` membership, etc.).
116
+ */
117
+ function validateSpec(spec) {
118
+ if (spec === null || spec === void 0 || typeof spec !== "object") throw new TypeError("validateSpec: spec must be a non-null object");
119
+ const record = spec;
120
+ const hasImageKey = "image" in record;
121
+ const hasServicesKey = "services" in record;
122
+ if (hasImageKey && hasServicesKey) throw new TypeError("validateSpec: spec has both `image` and `services` keys; these are mutually exclusive (regardless of value validity)");
123
+ const hasImage = typeof record.image === "string" && record.image.length > 0;
124
+ const hasServices = isStackSpec(spec);
125
+ if (!hasImage && !hasServices) throw new TypeError("validateSpec: spec must declare either `image` (SingleServiceSpec) or `services` (StackSpec)");
126
+ if ("customDomain" in record) {
127
+ const cd = record.customDomain;
128
+ if (cd !== void 0) {
129
+ if (!(typeof cd === "string" && cd.length > 0 && cd.trim() === cd)) {
130
+ const got = typeof cd === "string" ? cd.trim().length === 0 ? `"${cd}"` : `"${cd}" (has surrounding whitespace)` : cd === null ? "null" : typeof cd;
131
+ throw new TypeError(`validateSpec: \`customDomain\` must be a non-empty trimmed string or absent (got ${got}).`);
132
+ }
133
+ }
134
+ }
135
+ if (hasServices) {
136
+ const entries = Object.entries(spec.services);
137
+ if (entries.length === 0) throw new TypeError("validateSpec: stack spec `services` must have at least one entry");
138
+ for (const [name, svc] of entries) {
139
+ if (svc === null || typeof svc !== "object") throw new TypeError(`validateSpec: stack service "${name}" must be a non-null object`);
140
+ const image = svc.image;
141
+ if (typeof image !== "string" || image.length === 0) throw new TypeError(`validateSpec: stack service "${name}" must declare a non-empty \`image\` string`);
142
+ }
143
+ const stackDomain = spec.customDomain;
144
+ if (typeof stackDomain === "string" && stackDomain.length > 0) {
145
+ const stackServiceName = spec.serviceName;
146
+ if (typeof stackServiceName !== "string" || stackServiceName.length === 0) throw new TypeError("validateSpec: stack spec with `customDomain` requires `serviceName` identifying which service receives the domain.");
147
+ if (!Object.keys(spec.services).includes(stackServiceName)) throw new TypeError(`validateSpec: stack spec \`serviceName\` "${stackServiceName}" must be a key in \`services\` (got services: [${Object.keys(spec.services).join(", ")}]).`);
148
+ }
149
+ } else {
150
+ const port = spec.port;
151
+ if (!(isValidPortNumber(port) || Array.isArray(port) && port.length > 0 && port.every(isValidPortNumber))) throw new TypeError(`validateSpec: single-service specs require at least one port (port must be a finite positive integer in the TCP range (1-65535), or a non-empty array of such); got port=${JSON.stringify(port)}. For internal-only services, use a stack spec instead.`);
152
+ }
153
+ }
154
+ /**
155
+ * Predicate: `p` is a finite positive integer in the TCP port range
156
+ * (1-65535). Used by `validateSpec` to gate single-service `port`
157
+ * shapes against the broad `typeof === 'number'` bypass.
158
+ *
159
+ * Co-located in this module because it's exclusive to the port-
160
+ * validation boundary; if a future caller needs the same check,
161
+ * promote it to a shared utility then.
162
+ */
163
+ function isValidPortNumber(p) {
164
+ return typeof p === "number" && Number.isInteger(p) && p > 0 && p <= 65535;
165
+ }
166
+ //#endregion
167
+ export { firstImage, isStackSpec, normalizeServices, summarizeSpec, validateSpec };
168
+
169
+ //# sourceMappingURL=spec-normalize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spec-normalize.js","names":[],"sources":["../../src/internals/spec-normalize.ts"],"sourcesContent":["import type {\n DeploySpec,\n ServiceDef,\n SingleServiceSpec,\n SpecSummary,\n StackSpec,\n} from '../types.js';\n\n/**\n * Spec normalization + summarization helpers. Exports `isStack`,\n * `firstImage`, `normalizeServices`, `summarizeSpec`, and `validateSpec`\n * (the latter surfaces pre-broadcast shape violations).\n *\n * Two spec shapes are supported (frozen in ENG-128's `types.ts`):\n * - **services-map (StackSpec)** — `{ services: { <name>: ServiceDef }, customDomain?, serviceName? }`\n * - **legacy single-service (SingleServiceSpec)** — `{ image, port?, env?, customDomain? }`\n *\n * `normalizeServices` collapses the two shapes into a single iterable form\n * so callers (Plan summary, manifest builder, etc.) walk one structure\n * regardless of which form the user passed.\n *\n * Validation: `validateSpec` throws a plain `TypeError` on shape violations\n * — agent-core has no workspace dep on `@manifest-network/manifest-mcp-core`\n * in PR 1/2 (per parent's REV 1), so `ManifestMCPError` isn't available\n * here. PR 3's high-level `deployApp` re-wraps `TypeError` into\n * `ManifestMCPError(INVALID_CONFIG)` at the public-API boundary.\n */\n\n/**\n * True when `spec` uses the services-map shape (StackSpec). Mirrors\n * `_spec.cjs#isStack`: `services` is a non-null, non-array object.\n */\nexport function isStackSpec(\n spec: DeploySpec | null | undefined,\n): spec is StackSpec {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return false;\n const services = (spec as { services?: unknown }).services;\n return (\n services !== null &&\n typeof services === 'object' &&\n !Array.isArray(services)\n );\n}\n\n/**\n * Return the canonical first image string for a spec. For legacy single-\n * service: `spec.image`. For stack: the first non-empty `image` in\n * `Object.values(spec.services)`. Returns `null` when neither shape\n * carries an image (or `spec` is malformed).\n */\nexport function firstImage(spec: DeploySpec | null | undefined): string | null {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return null;\n const single = spec as Partial<SingleServiceSpec>;\n if (typeof single.image === 'string' && single.image.length > 0) {\n return single.image;\n }\n if (isStackSpec(spec)) {\n for (const svc of Object.values(spec.services)) {\n if (svc !== null && typeof svc === 'object') {\n const image = (svc as Partial<ServiceDef>).image;\n if (typeof image === 'string' && image.length > 0) return image;\n }\n }\n }\n return null;\n}\n\n/**\n * Walk a spec as `[{name, raw}]` where:\n * - `name === null` for legacy single-service (only one entry, raw is the spec itself).\n * - `name === <key>` for each services-map entry; `raw` is the per-service ServiceDef.\n *\n * Stable iteration order matches `Object.entries` (insertion order in v8/modern engines).\n */\nexport interface NormalizedService {\n /** `null` for legacy single-service; the services-map key for stack leases. */\n name: string | null;\n /** The per-service object exactly as the spec stores it. No field projection. */\n raw: ServiceDef | SingleServiceSpec;\n}\n\nexport function normalizeServices(\n spec: DeploySpec | null | undefined,\n): NormalizedService[] {\n if (isStackSpec(spec)) {\n return Object.entries(spec.services).map(([name, raw]) => ({\n name,\n raw: (raw ?? {}) as ServiceDef,\n }));\n }\n return [\n {\n name: null,\n raw: (spec ?? {}) as SingleServiceSpec,\n },\n ];\n}\n\n/**\n * Produce the frozen `SpecSummary` shape for inclusion in the `Plan`\n * (camelCase fields: `serviceCount`, etc.).\n *\n * Port count rules:\n * - SingleServiceSpec `port: number` → +1 port.\n * - SingleServiceSpec `port: number[]` → +length ports.\n * - ServiceDef `ports: number[]` (per type) → +length ports.\n * - ServiceDef `ports` shaped as a Record (older codepath) → +key count.\n *\n * Env key uniqueness is computed across services (one `env_keys` set\n * spans the whole spec); `envCount` is the size of that set; `envKeys`\n * is sorted ascending.\n */\nexport function summarizeSpec(spec: DeploySpec): SpecSummary {\n const format: 'single' | 'stack' = isStackSpec(spec) ? 'stack' : 'single';\n const services = normalizeServices(spec);\n\n let portCount = 0;\n const envKeys = new Set<string>();\n const images: string[] = [];\n\n for (const { raw: svc } of services) {\n if (svc !== null && typeof svc === 'object') {\n const svcRecord = svc as unknown as Record<string, unknown>;\n const image = svcRecord.image;\n if (typeof image === 'string' && image.length > 0) images.push(image);\n\n const port = svcRecord.port;\n if (typeof port === 'number') portCount += 1;\n else if (Array.isArray(port)) portCount += port.length;\n\n const ports = svcRecord.ports;\n if (Array.isArray(ports)) {\n portCount += ports.length;\n } else if (ports !== null && typeof ports === 'object') {\n portCount += Object.keys(ports).length;\n }\n\n const env = svcRecord.env;\n if (env !== null && typeof env === 'object' && !Array.isArray(env)) {\n for (const k of Object.keys(env)) envKeys.add(k);\n }\n }\n }\n\n return {\n format,\n serviceCount: services.length,\n portCount,\n envCount: envKeys.size,\n envKeys: Array.from(envKeys).sort(),\n images,\n };\n}\n\n/**\n * Validate a `DeploySpec` shape pre-broadcast. Throws `TypeError` on the\n * first violation. The frozen type union (`SingleServiceSpec | StackSpec`)\n * already enforces most structural rules at compile time; this runtime\n * check defends against `unknown`-cast callers and `JSON.parse`-decoded\n * inputs.\n *\n * Rules (mirror fred's `deployApp.ts` input validation):\n * - `spec` must be a non-null object.\n * - Stack: `services` must have ≥1 entry; each entry's `image` must be a\n * non-empty string.\n * - Single: `image` must be a non-empty string.\n * - Mutually exclusive `image` AND `services` not allowed.\n *\n * The high-level `deployApp` in PR 3 layers domain checks on top\n * (`customDomain` shape, `serviceName` membership, etc.).\n */\nexport function validateSpec(spec: DeploySpec | null | undefined): void {\n if (spec === null || spec === undefined || typeof spec !== 'object') {\n throw new TypeError('validateSpec: spec must be a non-null object');\n }\n const record = spec as unknown as Record<string, unknown>;\n\n // Mutual-exclusion gate uses KEY presence (not value validity). This\n // closes the bypass where a caller supplies a malformed `image` value\n // (empty string, number, null) alongside a valid `services` map: the\n // value-based check would silently treat `image` as \"absent\" and accept\n // the spec, but the caller's intent was ambiguous (which shape did they\n // mean?). Rejecting on key-presence forces the caller to delete one key\n // before submission and removes the ambiguity.\n const hasImageKey = 'image' in record;\n const hasServicesKey = 'services' in record;\n if (hasImageKey && hasServicesKey) {\n throw new TypeError(\n 'validateSpec: spec has both `image` and `services` keys; these are mutually exclusive (regardless of value validity)',\n );\n }\n\n // Downstream value-validity check (after the mutual-exclusion gate has\n // ruled out the ambiguous case). An `image` key with a non-string or\n // empty-string value still fails here when `services` is absent.\n const hasImage = typeof record.image === 'string' && record.image.length > 0;\n const hasServices = isStackSpec(spec);\n if (!hasImage && !hasServices) {\n throw new TypeError(\n 'validateSpec: spec must declare either `image` (SingleServiceSpec) or `services` (StackSpec)',\n );\n }\n\n // Copilot review fix (PR #58 r3266786899): `customDomain` shape at\n // the boundary. The orchestrator's `buildFredDeployInput`\n // (`deploy-app.ts:701`) uses a `if (customDomain)` truthiness check,\n // which silently drops `''`, `null`, `false`, `0`, `NaN` from the\n // emitted `fredInput`. A user spec like `{ ..., customDomain: '' }`\n // passes validation today, fred receives `fredInput` WITHOUT the\n // domain, deploy proceeds — the user's requested domain silently\n // not claimed, no error signal.\n //\n // Boundary check: when `customDomain` is present, it must be a\n // non-empty string. `undefined` (key absent) is fine; that's the\n // \"no domain requested\" case. Fires before the stack-customDomain\n // serviceName check (r3249684707) so the user gets a clear\n // customDomain-shape error rather than a misleading\n // requires-serviceName one.\n // Copilot review fix (PR #58 r3267373001): reject whitespace-only\n // strings AND strings with surrounding whitespace (option (i) from\n // the team-lead's brief — strict; let the caller send a clean,\n // already-trimmed value rather than silently trim for them). The\n // prior `cd.length === 0` predicate accepted `' '`, `'\\t\\n'`,\n // and `' app.example.com '`; fred would either accept the\n // surrounding whitespace as part of the domain (correctness bug)\n // or trim-and-reject (worse UX than agent-core's clear error).\n if ('customDomain' in record) {\n const cd = record.customDomain;\n if (cd !== undefined) {\n const isCleanNonEmptyString =\n typeof cd === 'string' && cd.length > 0 && cd.trim() === cd;\n if (!isCleanNonEmptyString) {\n const got =\n typeof cd === 'string'\n ? cd.trim().length === 0\n ? `\"${cd}\"`\n : `\"${cd}\" (has surrounding whitespace)`\n : cd === null\n ? 'null'\n : typeof cd;\n throw new TypeError(\n `validateSpec: \\`customDomain\\` must be a non-empty trimmed string or absent (got ${got}).`,\n );\n }\n }\n }\n\n if (hasServices) {\n const entries = Object.entries(spec.services);\n if (entries.length === 0) {\n throw new TypeError(\n 'validateSpec: stack spec `services` must have at least one entry',\n );\n }\n for (const [name, svc] of entries) {\n if (svc === null || typeof svc !== 'object') {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must be a non-null object`,\n );\n }\n const image = (svc as Partial<ServiceDef>).image;\n if (typeof image !== 'string' || image.length === 0) {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must declare a non-empty \\`image\\` string`,\n );\n }\n }\n\n // Copilot review fix (PR #58 r3249684707): a stack spec with a\n // `customDomain` MUST declare which service receives the domain\n // via `serviceName`, and that value must be a key in `services`.\n // Without this guard, `customDomainServiceOf` in `deploy-app.ts`\n // returns `undefined`, planning proceeds with no target, renderers\n // misrepresent the claim, and fred rejects the set-domain tx\n // ONLY after `create-lease` commits — leaving the user with an\n // orphan lease + a failed domain claim. Catching this at\n // validate-time is fail-fast at the boundary.\n //\n // Single-service specs are unaffected: their `customDomain` is\n // claimed against the implicit single lease item — no\n // serviceName disambiguation needed.\n const stackDomain = (spec as Partial<StackSpec>).customDomain;\n if (typeof stackDomain === 'string' && stackDomain.length > 0) {\n const stackServiceName = (spec as Partial<StackSpec>).serviceName;\n if (\n typeof stackServiceName !== 'string' ||\n stackServiceName.length === 0\n ) {\n throw new TypeError(\n 'validateSpec: stack spec with `customDomain` requires `serviceName` identifying which service receives the domain.',\n );\n }\n // Copilot review fix (PR #58 r3250331968): use an own-key check.\n // The `in` operator walks the prototype chain, so `serviceName:\n // 'constructor'` (or `'toString'`, `'hasOwnProperty'`, etc.)\n // would falsely pass against a `services` map that doesn't\n // declare those names. Mirrors fred's own choice at\n // `packages/fred/src/tools/deployApp.ts:254` for cross-package\n // symmetry. `Object.keys().includes()` (not `Object.hasOwn`,\n // which is ES2022 and our `tsdown.config.ts` targets ES2020).\n if (!Object.keys(spec.services).includes(stackServiceName)) {\n throw new TypeError(\n `validateSpec: stack spec \\`serviceName\\` \"${stackServiceName}\" must be a key in \\`services\\` (got services: [${Object.keys(spec.services).join(', ')}]).`,\n );\n }\n }\n } else {\n // Single-service spec port requirement.\n //\n // Copilot review fix (PR #58 r3249097051): fred's image-mode rejects\n // portless inputs with `port is required when using image`\n // (`packages/fred/src/tools/deployApp.ts:202` +\n // `packages/fred/src/tools/buildManifestPreview.ts:181`). Without\n // an agent-core boundary check the orchestrator silently passed\n // `port: undefined` through `buildManifestPreviewInput` /\n // `buildFredDeployInput`, surfacing fred's error mid-orchestration\n // (after readiness check + plan render). Failing fast at validate\n // time produces a clearer message and avoids partial work.\n //\n // The escape hatch for genuinely internal-only services is the\n // stack spec — service-level `ports` is optional, so a stack with\n // `{ services: { mysvc: { image, env } } }` deploys without ports.\n //\n // Copilot review fix (PR #58 r3249294877): tighten the predicate to\n // a finite positive integer in the TCP port range. The prior\n // `typeof p === 'number'` check accepted `0`, `NaN`, `Infinity`,\n // negative numbers, non-integers, and out-of-range ports —\n // partially defeating the fail-fast intent. Fred catches `port: 0`\n // via `!input.port`, but the other shapes either flow through to a\n // less helpful error or get coerced silently. The shared predicate\n // `isValidPortNumber` (below) is the single source of truth.\n const port = (spec as Partial<SingleServiceSpec>).port;\n const hasValidPort =\n isValidPortNumber(port) ||\n (Array.isArray(port) && port.length > 0 && port.every(isValidPortNumber));\n if (!hasValidPort) {\n throw new TypeError(\n 'validateSpec: single-service specs require at least one port (port must be a finite positive integer in the TCP range (1-65535), or a non-empty array of such); got ' +\n `port=${JSON.stringify(port)}. For internal-only services, use a stack spec instead.`,\n );\n }\n }\n}\n\n/**\n * Predicate: `p` is a finite positive integer in the TCP port range\n * (1-65535). Used by `validateSpec` to gate single-service `port`\n * shapes against the broad `typeof === 'number'` bypass.\n *\n * Co-located in this module because it's exclusive to the port-\n * validation boundary; if a future caller needs the same check,\n * promote it to a shared utility then.\n */\nfunction isValidPortNumber(p: unknown): p is number {\n return typeof p === 'number' && Number.isInteger(p) && p > 0 && p <= 65535;\n}\n"],"mappings":"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"}
@@ -0,0 +1,20 @@
1
+ //#region src/internals/verify-domain-state.d.ts
2
+ type VerifyDomainOutcome = 'match' | 'mismatch' | 'not_found';
3
+ interface VerifyDomainResult {
4
+ outcome: VerifyDomainOutcome;
5
+ /** Present when outcome is 'match' or 'mismatch'. The lease item's actual customDomain. */
6
+ actual?: string;
7
+ /** Present when outcome is 'not_found'. Human-readable detail. */
8
+ reason?: string;
9
+ }
10
+ interface VerifyDomainArgs {
11
+ leaseUuid: string;
12
+ /** DNS label addressing an item inside a stack lease. Omit / leave empty for legacy 1-item leases. */
13
+ serviceName?: string;
14
+ /** FQDN to compare against the chain's stored value. Use '' for clear-mode (post-clear verification). */
15
+ expected: string;
16
+ }
17
+ declare function verifyDomainState(leasesPayload: unknown, args: VerifyDomainArgs): VerifyDomainResult;
18
+ //#endregion
19
+ export { VerifyDomainArgs, VerifyDomainOutcome, VerifyDomainResult, verifyDomainState };
20
+ //# sourceMappingURL=verify-domain-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-domain-state.d.ts","names":[],"sources":["../../src/internals/verify-domain-state.ts"],"mappings":";KA8BY,mBAAA;AAAA,UAEK,kBAAA;EACf,OAAA,EAAS,mBAAA;;EAET,MAAA;EAL6B;EAO7B,MAAA;AAAA;AAAA,UAGe,gBAAA;EACf,SAAA;EARA;EAUA,WAAA;EARA;EAUA,QAAA;AAAA;AAAA,iBAGc,iBAAA,CACd,aAAA,WACA,IAAA,EAAM,gBAAA,GACL,kBAAA"}
@@ -0,0 +1,63 @@
1
+ import { findLease, normalizeItem } from "./lease-items.js";
2
+ //#region src/internals/verify-domain-state.ts
3
+ /**
4
+ * Verify a lease item's `customDomain` against an expected value after a
5
+ * `set_item_custom_domain` broadcast.
6
+ *
7
+ * Decodes the same lease shape as `lease-items.ts`, then compares the
8
+ * matched item's `customDomain` to the expected FQDN (or empty string for
9
+ * clear-mode). Used by the in-process `verifyAndRecover` driver in PR 1
10
+ * and by the high-level `manageDomain` set/clear flows in PR 4.
11
+ *
12
+ * Outcome semantics:
13
+ * - `'match'` — actual `customDomain` equals expected
14
+ * - `'mismatch'` — actual differs from expected (item carries `actual` for surfacing)
15
+ * - `'not_found'` — lease UUID not present in the verification payload, OR multi-item lease but no `serviceName` supplied, OR `serviceName` not present in the lease's items
16
+ *
17
+ * Single-item leases (legacy 1-item lease with `serviceName === ''`) ignore
18
+ * the `serviceName` argument and always use the only item. Multi-item
19
+ * stack leases require `serviceName` to address the target item.
20
+ *
21
+ * Throws `TypeError` for malformed args (non-string leaseUuid, leaseUuid
22
+ * that doesn't match UUID grammar). The CJS exits 1 via stderr; the TS
23
+ * port surfaces a typed error instead of a synthetic `not_found` result
24
+ * so caller-side argument bugs don't masquerade as a chain-state outcome.
25
+ */
26
+ /** Anchored UUID-shape regex (8-4-4-4-12, version-byte lenient — matches `_uuid.cjs#UUID_RE`). */
27
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
28
+ function verifyDomainState(leasesPayload, args) {
29
+ if (typeof args.leaseUuid !== "string") throw new TypeError(`verifyDomainState: leaseUuid must be a string, got ${typeof args.leaseUuid}`);
30
+ if (!UUID_RE.test(args.leaseUuid)) throw new TypeError(`verifyDomainState: leaseUuid must be a UUID; got "${args.leaseUuid}"`);
31
+ if (typeof args.expected !== "string") throw new TypeError(`verifyDomainState: expected must be a string (use '' for clear-mode), got ${typeof args.expected}`);
32
+ const lease = findLease(leasesPayload, args.leaseUuid);
33
+ if (lease === null) return {
34
+ outcome: "not_found",
35
+ reason: "lease UUID not found in verification payload"
36
+ };
37
+ const rawItems = lease.items;
38
+ const items = (Array.isArray(rawItems) ? rawItems : []).map(normalizeItem);
39
+ const singleItem = items.length === 1 && items[0]?.serviceName === "";
40
+ const requestedService = (args.serviceName ?? "").trim();
41
+ let item;
42
+ if (singleItem) item = items[0];
43
+ else if (requestedService === "") return {
44
+ outcome: "not_found",
45
+ reason: "lease has multiple items but --service-name was not supplied"
46
+ };
47
+ else {
48
+ item = items.find((i) => i.serviceName === requestedService);
49
+ if (!item) return {
50
+ outcome: "not_found",
51
+ reason: `service-name "${requestedService}" not found in lease items`
52
+ };
53
+ }
54
+ const actual = item?.customDomain ?? "";
55
+ return {
56
+ outcome: actual === args.expected ? "match" : "mismatch",
57
+ actual
58
+ };
59
+ }
60
+ //#endregion
61
+ export { verifyDomainState };
62
+
63
+ //# sourceMappingURL=verify-domain-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-domain-state.js","names":[],"sources":["../../src/internals/verify-domain-state.ts"],"sourcesContent":["import { findLease, normalizeItem } from './lease-items.js';\n\n/**\n * Verify a lease item's `customDomain` against an expected value after a\n * `set_item_custom_domain` broadcast.\n *\n * Decodes the same lease shape as `lease-items.ts`, then compares the\n * matched item's `customDomain` to the expected FQDN (or empty string for\n * clear-mode). Used by the in-process `verifyAndRecover` driver in PR 1\n * and by the high-level `manageDomain` set/clear flows in PR 4.\n *\n * Outcome semantics:\n * - `'match'` — actual `customDomain` equals expected\n * - `'mismatch'` — actual differs from expected (item carries `actual` for surfacing)\n * - `'not_found'` — lease UUID not present in the verification payload, OR multi-item lease but no `serviceName` supplied, OR `serviceName` not present in the lease's items\n *\n * Single-item leases (legacy 1-item lease with `serviceName === ''`) ignore\n * the `serviceName` argument and always use the only item. Multi-item\n * stack leases require `serviceName` to address the target item.\n *\n * Throws `TypeError` for malformed args (non-string leaseUuid, leaseUuid\n * that doesn't match UUID grammar). The CJS exits 1 via stderr; the TS\n * port surfaces a typed error instead of a synthetic `not_found` result\n * so caller-side argument bugs don't masquerade as a chain-state outcome.\n */\n\n/** Anchored UUID-shape regex (8-4-4-4-12, version-byte lenient — matches `_uuid.cjs#UUID_RE`). */\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\nexport type VerifyDomainOutcome = 'match' | 'mismatch' | 'not_found';\n\nexport interface VerifyDomainResult {\n outcome: VerifyDomainOutcome;\n /** Present when outcome is 'match' or 'mismatch'. The lease item's actual customDomain. */\n actual?: string;\n /** Present when outcome is 'not_found'. Human-readable detail. */\n reason?: string;\n}\n\nexport interface VerifyDomainArgs {\n leaseUuid: string;\n /** DNS label addressing an item inside a stack lease. Omit / leave empty for legacy 1-item leases. */\n serviceName?: string;\n /** FQDN to compare against the chain's stored value. Use '' for clear-mode (post-clear verification). */\n expected: string;\n}\n\nexport function verifyDomainState(\n leasesPayload: unknown,\n args: VerifyDomainArgs,\n): VerifyDomainResult {\n if (typeof args.leaseUuid !== 'string') {\n throw new TypeError(\n `verifyDomainState: leaseUuid must be a string, got ${typeof args.leaseUuid}`,\n );\n }\n if (!UUID_RE.test(args.leaseUuid)) {\n throw new TypeError(\n `verifyDomainState: leaseUuid must be a UUID; got \"${args.leaseUuid}\"`,\n );\n }\n if (typeof args.expected !== 'string') {\n throw new TypeError(\n `verifyDomainState: expected must be a string (use '' for clear-mode), got ${typeof args.expected}`,\n );\n }\n\n const lease = findLease(leasesPayload, args.leaseUuid);\n if (lease === null) {\n return {\n outcome: 'not_found',\n reason: 'lease UUID not found in verification payload',\n };\n }\n\n // The lease shape is opaque to TS — pickLeasesArray + findLease validate\n // structural keys but the items array can be missing or non-array.\n const rawItems = (lease as { items?: unknown }).items;\n const itemsArray = Array.isArray(rawItems) ? rawItems : [];\n const items = itemsArray.map(normalizeItem);\n\n const singleItem = items.length === 1 && items[0]?.serviceName === '';\n const requestedService = (args.serviceName ?? '').trim();\n\n let item: ReturnType<typeof normalizeItem> | undefined;\n if (singleItem) {\n item = items[0];\n } else if (requestedService === '') {\n return {\n outcome: 'not_found',\n reason: 'lease has multiple items but --service-name was not supplied',\n };\n } else {\n item = items.find((i) => i.serviceName === requestedService);\n if (!item) {\n return {\n outcome: 'not_found',\n reason: `service-name \"${requestedService}\" not found in lease items`,\n };\n }\n }\n\n const actual = item?.customDomain ?? '';\n const outcome: VerifyDomainOutcome =\n actual === args.expected ? 'match' : 'mismatch';\n return { outcome, actual };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,UACJ;AAoBF,SAAgB,kBACd,eACA,MACoB;AACpB,KAAI,OAAO,KAAK,cAAc,SAC5B,OAAM,IAAI,UACR,sDAAsD,OAAO,KAAK,YACnE;AAEH,KAAI,CAAC,QAAQ,KAAK,KAAK,UAAU,CAC/B,OAAM,IAAI,UACR,qDAAqD,KAAK,UAAU,GACrE;AAEH,KAAI,OAAO,KAAK,aAAa,SAC3B,OAAM,IAAI,UACR,6EAA6E,OAAO,KAAK,WAC1F;CAGH,MAAM,QAAQ,UAAU,eAAe,KAAK,UAAU;AACtD,KAAI,UAAU,KACZ,QAAO;EACL,SAAS;EACT,QAAQ;EACT;CAKH,MAAM,WAAY,MAA8B;CAEhD,MAAM,SADa,MAAM,QAAQ,SAAS,GAAG,WAAW,EAAE,EACjC,IAAI,cAAc;CAE3C,MAAM,aAAa,MAAM,WAAW,KAAK,MAAM,IAAI,gBAAgB;CACnE,MAAM,oBAAoB,KAAK,eAAe,IAAI,MAAM;CAExD,IAAI;AACJ,KAAI,WACF,QAAO,MAAM;UACJ,qBAAqB,GAC9B,QAAO;EACL,SAAS;EACT,QAAQ;EACT;MACI;AACL,SAAO,MAAM,MAAM,MAAM,EAAE,gBAAgB,iBAAiB;AAC5D,MAAI,CAAC,KACH,QAAO;GACL,SAAS;GACT,QAAQ,iBAAiB,iBAAiB;GAC3C;;CAIL,MAAM,SAAS,MAAM,gBAAgB;AAGrC,QAAO;EAAE,SADP,WAAW,KAAK,WAAW,UAAU;EACrB;EAAQ"}
@@ -0,0 +1,120 @@
1
+ import { FailureEnvelope, RecoveryChoice, RecoveryOption } from "../types.js";
2
+
3
+ //#region src/internals/verify-recover.d.ts
4
+ /**
5
+ * In-process verify-and-recover driver. Uses an inline async verifier
6
+ * function (L7: agent-core MUST NOT spawn subprocesses).
7
+ *
8
+ * Out of scope (subprocess-only concerns):
9
+ * - verifier-script path sanitization (no path; verifier is a function)
10
+ * - stdin-source indirection (verifier receives typed context)
11
+ * - argv interpolation (verifier closes over context)
12
+ * - `{{var}}` template interpolation on user_message (recovery options
13
+ * carry their own typed-diagnostic closures via `buildRecoveryOptions`)
14
+ * - `timeout` / `maxBuffer` operational caps (no subprocess; an optional
15
+ * AbortController-based timeout can be added per-verifier if needed)
16
+ * - `NODE_ENV` test-override env vars (none of the above need them)
17
+ *
18
+ * Keeps (in-process security still relevant):
19
+ * - `SECRET_KEY_DENYLIST` strip on the diagnostic before it reaches
20
+ * `buildFailureEnvelope` / `buildRecoveryOptions` / the host callback / the result.
21
+ * - Prototype-pollution guard on `__proto__` / `constructor` / `prototype`
22
+ * in the diagnostic walk (defense for verifier-output objects that
23
+ * could have come via `JSON.parse`).
24
+ * - Branch dispatch: `branches[outcome]` → `branches.__other__` →
25
+ * synthesized `unclassified` fallback (CJS calls it `'other'`; the TS
26
+ * port uses `'__other__'` to avoid collisions with a literal outcome
27
+ * string `'other'`).
28
+ *
29
+ * Branch IDs are an internal, closed-set string-literal union — they
30
+ * identify branches for journal/logging purposes but are NOT part of the
31
+ * public type contract (Option A from ENG-128). The public surface for
32
+ * recovery is the frozen `RecoveryOption[]` array, materialized by each
33
+ * branch's inline `buildRecoveryOptions(diag)` closure.
34
+ */
35
+ /** Closed-set internal branch identifier. Surfaces via journal/log only. */
36
+ type BranchId = 'partial_success_domain' | 'lease_terminal' | 'domain_verification_mismatch' | 'domain_not_found' | 'pending_drift' | 'unclassified';
37
+ /**
38
+ * Per-branch behavior contract. Authored inline at each high-level
39
+ * function's call site (deployApp, manageDomain, etc.) so the closures
40
+ * can bind diagnostic data into the surfaced label/description text.
41
+ */
42
+ interface VerificationBranch<TDiag = Record<string, unknown>> {
43
+ /** Internal id for journal write + log; not surfaced to host callbacks directly. */
44
+ readonly branchId: BranchId;
45
+ /** Pass-through tags for the ENG-124 journal `recovery_actions[]`. Empty when not journaling. */
46
+ readonly journalActionTags: readonly string[];
47
+ /** Synthesize the public `FailureEnvelope` (frozen contract) from the post-strip diagnostic. */
48
+ buildFailureEnvelope: (diagnostic: TDiag) => FailureEnvelope;
49
+ /**
50
+ * Materialize the `RecoveryOption[]` for the host's `onFailure` callback.
51
+ * Returning an empty array marks the branch as inform-only:
52
+ * `verifyAndRecover` will return the failure envelope without invoking
53
+ * `onFailure` so callers don't waste a user prompt asking what to do
54
+ * when there's nothing to choose between.
55
+ */
56
+ buildRecoveryOptions: (diagnostic: TDiag) => RecoveryOption[];
57
+ }
58
+ /** Verifier function — async; receives typed context; returns typed outcome + free-form diagnostic. */
59
+ type Verifier<TContext, TOutcome extends string, TDiag = Record<string, unknown>> = (context: TContext) => Promise<VerifierResult<TOutcome, TDiag>>;
60
+ /** Shape returned by every verifier. `outcome` drives branch selection; `diagnostic` flows into the branch's closures. */
61
+ interface VerifierResult<TOutcome extends string, TDiag> {
62
+ outcome: TOutcome;
63
+ diagnostic: TDiag;
64
+ }
65
+ /**
66
+ * Verification spec — declarative description of how to verify post-state
67
+ * and dispatch to a recovery branch. Mirrors the CJS spec shape with
68
+ * the subprocess-specific fields dropped.
69
+ *
70
+ * `__other__` is the catch-all branch key, equivalent to the CJS's `'other'`.
71
+ * Renamed to avoid collisions with an outcome literally equal to `'other'`.
72
+ */
73
+ interface VerificationSpec<TContext, TOutcome extends string, TDiag = Record<string, unknown>> {
74
+ readonly verifier: Verifier<TContext, TOutcome, TDiag>;
75
+ /** Outcome values that count as success — no branch dispatch, host's `onFailure` is NOT called. */
76
+ readonly successValues: readonly TOutcome[];
77
+ /** Branch dictionary keyed by outcome string. `__other__` is the catch-all fallback. */
78
+ readonly branches: Partial<Record<TOutcome | '__other__', VerificationBranch<TDiag>>>;
79
+ }
80
+ interface VerifyAndRecoverResult<TOutcome extends string, TDiag = Record<string, unknown>> {
81
+ result: 'success' | 'failure';
82
+ verifierOutcome: TOutcome;
83
+ /** `null` on success; the matched branch's id (or `'unclassified'`) on failure. */
84
+ branchId: BranchId | null;
85
+ journalActionTags: readonly string[];
86
+ /** Post-strip diagnostic. Same value the branch closures received. */
87
+ diagnostic: TDiag;
88
+ /** Present iff failure. The synthesized public-surface envelope. */
89
+ failure?: FailureEnvelope;
90
+ /** Present iff failure AND `onFailure` was called AND it returned (i.e., a non-empty `RecoveryOption[]` was presented). */
91
+ recoveryChoice?: RecoveryChoice;
92
+ }
93
+ interface VerifyAndRecoverCallbacks {
94
+ /**
95
+ * Rich-form failure handler used by `deployApp`. Receives the
96
+ * `FailureEnvelope` synthesized by the matched branch + the closure-
97
+ * built `RecoveryOption[]` and returns the user's pick.
98
+ *
99
+ * Simple-form callers (manageDomain / closeLease / troubleshoot) wrap
100
+ * via an adapter in PR 4 — they don't pass an `onFailure` here directly.
101
+ */
102
+ onFailure?: (failure: FailureEnvelope, options: RecoveryOption[]) => Promise<RecoveryChoice>;
103
+ }
104
+ /**
105
+ * Run the verifier; classify the outcome; on failure, build the public
106
+ * envelope + recovery options and (optionally) invoke the host's
107
+ * `onFailure` callback for a user pick.
108
+ *
109
+ * Throws synchronously on:
110
+ * - Spec runtime-shape violations (missing verifier function, non-array
111
+ * successValues, non-object branches).
112
+ * - Verifier-returned shape violations (missing `outcome` key,
113
+ * non-string `outcome`, missing `diagnostic` key, non-object
114
+ * `diagnostic`).
115
+ * Propagates any error the verifier itself throws.
116
+ */
117
+ declare function verifyAndRecover<TContext, TOutcome extends string, TDiag = Record<string, unknown>>(spec: VerificationSpec<TContext, TOutcome, TDiag>, context: TContext, callbacks?: VerifyAndRecoverCallbacks): Promise<VerifyAndRecoverResult<TOutcome, TDiag>>;
118
+ //#endregion
119
+ export { BranchId, VerificationBranch, VerificationSpec, Verifier, VerifierResult, VerifyAndRecoverCallbacks, VerifyAndRecoverResult, verifyAndRecover };
120
+ //# sourceMappingURL=verify-recover.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-recover.d.ts","names":[],"sources":["../../src/internals/verify-recover.ts"],"mappings":";;;;;AAwCA;;;;;AAaA;;;;;;;;;;;;;;;;;;;;;;;;;KAbY,QAAA;AA+BZ;;;;;AAAA,UAlBiB,kBAAA,SAA2B,MAAA;EAsBgB;EAAA,SApBjD,QAAA,EAAU,QAAA;EAoBM;EAAA,SAlBhB,iBAAA;EAkBuB;EAhBhC,oBAAA,GAAuB,UAAA,EAAY,KAAA,KAAU,eAAA;EAc7C;;;;;;;EANA,oBAAA,GAAuB,UAAA,EAAY,KAAA,KAAU,cAAA;AAAA;;KAInC,QAAA,4CAGF,MAAA,sBACL,OAAA,EAAS,QAAA,KAAa,OAAA,CAAQ,cAAA,CAAe,QAAA,EAAU,KAAA;AAG5D;AAAA,UAAiB,cAAA;EACf,OAAA,EAAS,QAAA;EACT,UAAA,EAAY,KAAA;AAAA;;;;;;;;AAWd;UAAiB,gBAAA,4CAGP,MAAA;EAAA,SAEC,QAAA,EAAU,QAAA,CAAS,QAAA,EAAU,QAAA,EAAU,KAAA;EAFxC;EAAA,SAIC,aAAA,WAAwB,QAAA;EAFK;EAAA,SAI7B,QAAA,EAAU,OAAA,CACjB,MAAA,CAAO,QAAA,gBAAwB,kBAAA,CAAmB,KAAA;AAAA;AAAA,UAIrC,sBAAA,kCAEP,MAAA;EAER,MAAA;EACA,eAAA,EAAiB,QAAA;EATgB;EAWjC,QAAA,EAAU,QAAA;EACV,iBAAA;EAb0B;EAe1B,UAAA,EAAY,KAAA;EAvBZ;EAyBA,OAAA,GAAU,eAAA;EAvBV;EAyBA,cAAA,GAAiB,cAAA;AAAA;AAAA,UAGF,yBAAA;EA1Ba;;;;;;;;EAmC5B,SAAA,IACE,OAAA,EAAS,eAAA,EACT,OAAA,EAAS,cAAA,OACN,OAAA,CAAQ,cAAA;AAAA;;;;AA7Bf;;;;;;;;;;iBA6CsB,gBAAA,4CAGZ,MAAA,kBAAA,CAER,IAAA,EAAM,gBAAA,CAAiB,QAAA,EAAU,QAAA,EAAU,KAAA,GAC3C,OAAA,EAAS,QAAA,EACT,SAAA,GAAW,yBAAA,GACV,OAAA,CAAQ,sBAAA,CAAuB,QAAA,EAAU,KAAA"}
@@ -0,0 +1,91 @@
1
+ import { stripDenylist } from "./secret-denylist.js";
2
+ //#region src/internals/verify-recover.ts
3
+ /**
4
+ * Run the verifier; classify the outcome; on failure, build the public
5
+ * envelope + recovery options and (optionally) invoke the host's
6
+ * `onFailure` callback for a user pick.
7
+ *
8
+ * Throws synchronously on:
9
+ * - Spec runtime-shape violations (missing verifier function, non-array
10
+ * successValues, non-object branches).
11
+ * - Verifier-returned shape violations (missing `outcome` key,
12
+ * non-string `outcome`, missing `diagnostic` key, non-object
13
+ * `diagnostic`).
14
+ * Propagates any error the verifier itself throws.
15
+ */
16
+ async function verifyAndRecover(spec, context, callbacks = {}) {
17
+ validateSpec(spec);
18
+ const verifierResult = await spec.verifier(context);
19
+ validateVerifierResult(verifierResult);
20
+ const diagnostic = stripDenylist(verifierResult.diagnostic);
21
+ const outcome = verifierResult.outcome;
22
+ if (spec.successValues.includes(outcome)) return {
23
+ result: "success",
24
+ verifierOutcome: outcome,
25
+ branchId: null,
26
+ journalActionTags: [],
27
+ diagnostic
28
+ };
29
+ const branch = selectBranch(spec.branches, outcome);
30
+ const failure = branch.buildFailureEnvelope(diagnostic);
31
+ const options = branch.buildRecoveryOptions(diagnostic);
32
+ if (options.length === 0 || callbacks.onFailure === void 0) return {
33
+ result: "failure",
34
+ verifierOutcome: outcome,
35
+ branchId: branch.branchId,
36
+ journalActionTags: branch.journalActionTags,
37
+ diagnostic,
38
+ failure
39
+ };
40
+ const recoveryChoice = await callbacks.onFailure(failure, options);
41
+ return {
42
+ result: "failure",
43
+ verifierOutcome: outcome,
44
+ branchId: branch.branchId,
45
+ journalActionTags: branch.journalActionTags,
46
+ diagnostic,
47
+ failure,
48
+ recoveryChoice
49
+ };
50
+ }
51
+ function validateSpec(spec) {
52
+ if (spec === null || typeof spec !== "object") throw new Error("verifyAndRecover: spec must be an object");
53
+ if (typeof spec.verifier !== "function") throw new Error("verifyAndRecover: spec.verifier must be a function");
54
+ if (!Array.isArray(spec.successValues)) throw new Error("verifyAndRecover: spec.successValues must be an array");
55
+ if (spec.branches === null || typeof spec.branches !== "object" || Array.isArray(spec.branches)) throw new Error("verifyAndRecover: spec.branches must be an object");
56
+ }
57
+ function validateVerifierResult(value) {
58
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("verifyAndRecover: verifier must return an object with shape { outcome, diagnostic }");
59
+ const r = value;
60
+ if (typeof r.outcome !== "string") throw new Error("verifyAndRecover: verifier result is missing the required \"outcome\" string field");
61
+ if (r.diagnostic === null || typeof r.diagnostic !== "object" || Array.isArray(r.diagnostic)) throw new Error("verifyAndRecover: verifier result is missing a \"diagnostic\" object field");
62
+ }
63
+ function selectBranch(branches, outcome) {
64
+ const named = branches[outcome];
65
+ if (named !== void 0) return named;
66
+ const other = branches.__other__;
67
+ if (other !== void 0) return other;
68
+ return synthesizeUnclassified(outcome);
69
+ }
70
+ /**
71
+ * Fabricate the `unclassified` fallback when no named branch and no
72
+ * `__other__` catch-all match. Mirrors the CJS behavior at line 222-232:
73
+ * journal action tag is `verify-unclassified`; the recovery options list
74
+ * is empty (inform-only); the failure envelope conveys the unrecognized
75
+ * outcome verbatim in `reason`.
76
+ */
77
+ function synthesizeUnclassified(outcome) {
78
+ return {
79
+ branchId: "unclassified",
80
+ journalActionTags: ["verify-unclassified"],
81
+ buildFailureEnvelope: () => ({
82
+ outcome: "failed",
83
+ reason: `Verifier returned outcome '${outcome}' — unrecognized; no branch matched.`
84
+ }),
85
+ buildRecoveryOptions: () => []
86
+ };
87
+ }
88
+ //#endregion
89
+ export { verifyAndRecover };
90
+
91
+ //# sourceMappingURL=verify-recover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-recover.js","names":[],"sources":["../../src/internals/verify-recover.ts"],"sourcesContent":["import type {\n FailureEnvelope,\n RecoveryChoice,\n RecoveryOption,\n} from '../types.js';\nimport { stripDenylist } from './secret-denylist.js';\n\n/**\n * In-process verify-and-recover driver. Uses an inline async verifier\n * function (L7: agent-core MUST NOT spawn subprocesses).\n *\n * Out of scope (subprocess-only concerns):\n * - verifier-script path sanitization (no path; verifier is a function)\n * - stdin-source indirection (verifier receives typed context)\n * - argv interpolation (verifier closes over context)\n * - `{{var}}` template interpolation on user_message (recovery options\n * carry their own typed-diagnostic closures via `buildRecoveryOptions`)\n * - `timeout` / `maxBuffer` operational caps (no subprocess; an optional\n * AbortController-based timeout can be added per-verifier if needed)\n * - `NODE_ENV` test-override env vars (none of the above need them)\n *\n * Keeps (in-process security still relevant):\n * - `SECRET_KEY_DENYLIST` strip on the diagnostic before it reaches\n * `buildFailureEnvelope` / `buildRecoveryOptions` / the host callback / the result.\n * - Prototype-pollution guard on `__proto__` / `constructor` / `prototype`\n * in the diagnostic walk (defense for verifier-output objects that\n * could have come via `JSON.parse`).\n * - Branch dispatch: `branches[outcome]` → `branches.__other__` →\n * synthesized `unclassified` fallback (CJS calls it `'other'`; the TS\n * port uses `'__other__'` to avoid collisions with a literal outcome\n * string `'other'`).\n *\n * Branch IDs are an internal, closed-set string-literal union — they\n * identify branches for journal/logging purposes but are NOT part of the\n * public type contract (Option A from ENG-128). The public surface for\n * recovery is the frozen `RecoveryOption[]` array, materialized by each\n * branch's inline `buildRecoveryOptions(diag)` closure.\n */\n\n/** Closed-set internal branch identifier. Surfaces via journal/log only. */\nexport type BranchId =\n | 'partial_success_domain'\n | 'lease_terminal'\n | 'domain_verification_mismatch'\n | 'domain_not_found'\n | 'pending_drift'\n | 'unclassified';\n\n/**\n * Per-branch behavior contract. Authored inline at each high-level\n * function's call site (deployApp, manageDomain, etc.) so the closures\n * can bind diagnostic data into the surfaced label/description text.\n */\nexport interface VerificationBranch<TDiag = Record<string, unknown>> {\n /** Internal id for journal write + log; not surfaced to host callbacks directly. */\n readonly branchId: BranchId;\n /** Pass-through tags for the ENG-124 journal `recovery_actions[]`. Empty when not journaling. */\n readonly journalActionTags: readonly string[];\n /** Synthesize the public `FailureEnvelope` (frozen contract) from the post-strip diagnostic. */\n buildFailureEnvelope: (diagnostic: TDiag) => FailureEnvelope;\n /**\n * Materialize the `RecoveryOption[]` for the host's `onFailure` callback.\n * Returning an empty array marks the branch as inform-only:\n * `verifyAndRecover` will return the failure envelope without invoking\n * `onFailure` so callers don't waste a user prompt asking what to do\n * when there's nothing to choose between.\n */\n buildRecoveryOptions: (diagnostic: TDiag) => RecoveryOption[];\n}\n\n/** Verifier function — async; receives typed context; returns typed outcome + free-form diagnostic. */\nexport type Verifier<\n TContext,\n TOutcome extends string,\n TDiag = Record<string, unknown>,\n> = (context: TContext) => Promise<VerifierResult<TOutcome, TDiag>>;\n\n/** Shape returned by every verifier. `outcome` drives branch selection; `diagnostic` flows into the branch's closures. */\nexport interface VerifierResult<TOutcome extends string, TDiag> {\n outcome: TOutcome;\n diagnostic: TDiag;\n}\n\n/**\n * Verification spec — declarative description of how to verify post-state\n * and dispatch to a recovery branch. Mirrors the CJS spec shape with\n * the subprocess-specific fields dropped.\n *\n * `__other__` is the catch-all branch key, equivalent to the CJS's `'other'`.\n * Renamed to avoid collisions with an outcome literally equal to `'other'`.\n */\nexport interface VerificationSpec<\n TContext,\n TOutcome extends string,\n TDiag = Record<string, unknown>,\n> {\n readonly verifier: Verifier<TContext, TOutcome, TDiag>;\n /** Outcome values that count as success — no branch dispatch, host's `onFailure` is NOT called. */\n readonly successValues: readonly TOutcome[];\n /** Branch dictionary keyed by outcome string. `__other__` is the catch-all fallback. */\n readonly branches: Partial<\n Record<TOutcome | '__other__', VerificationBranch<TDiag>>\n >;\n}\n\nexport interface VerifyAndRecoverResult<\n TOutcome extends string,\n TDiag = Record<string, unknown>,\n> {\n result: 'success' | 'failure';\n verifierOutcome: TOutcome;\n /** `null` on success; the matched branch's id (or `'unclassified'`) on failure. */\n branchId: BranchId | null;\n journalActionTags: readonly string[];\n /** Post-strip diagnostic. Same value the branch closures received. */\n diagnostic: TDiag;\n /** Present iff failure. The synthesized public-surface envelope. */\n failure?: FailureEnvelope;\n /** Present iff failure AND `onFailure` was called AND it returned (i.e., a non-empty `RecoveryOption[]` was presented). */\n recoveryChoice?: RecoveryChoice;\n}\n\nexport interface VerifyAndRecoverCallbacks {\n /**\n * Rich-form failure handler used by `deployApp`. Receives the\n * `FailureEnvelope` synthesized by the matched branch + the closure-\n * built `RecoveryOption[]` and returns the user's pick.\n *\n * Simple-form callers (manageDomain / closeLease / troubleshoot) wrap\n * via an adapter in PR 4 — they don't pass an `onFailure` here directly.\n */\n onFailure?: (\n failure: FailureEnvelope,\n options: RecoveryOption[],\n ) => Promise<RecoveryChoice>;\n}\n\n/**\n * Run the verifier; classify the outcome; on failure, build the public\n * envelope + recovery options and (optionally) invoke the host's\n * `onFailure` callback for a user pick.\n *\n * Throws synchronously on:\n * - Spec runtime-shape violations (missing verifier function, non-array\n * successValues, non-object branches).\n * - Verifier-returned shape violations (missing `outcome` key,\n * non-string `outcome`, missing `diagnostic` key, non-object\n * `diagnostic`).\n * Propagates any error the verifier itself throws.\n */\nexport async function verifyAndRecover<\n TContext,\n TOutcome extends string,\n TDiag = Record<string, unknown>,\n>(\n spec: VerificationSpec<TContext, TOutcome, TDiag>,\n context: TContext,\n callbacks: VerifyAndRecoverCallbacks = {},\n): Promise<VerifyAndRecoverResult<TOutcome, TDiag>> {\n validateSpec(spec);\n\n const verifierResult = await spec.verifier(context);\n validateVerifierResult(verifierResult);\n\n // Strip secret-shaped keys + prototype-pollution keys from the\n // diagnostic BEFORE it flows into any branch closure, host callback,\n // or the result object. The strip is the same posture `_journal.cjs`'s\n // `validateRecord` enforces on the write side.\n const diagnostic = stripDenylist(verifierResult.diagnostic) as TDiag;\n const outcome = verifierResult.outcome;\n\n const isSuccess = spec.successValues.includes(outcome);\n if (isSuccess) {\n return {\n result: 'success',\n verifierOutcome: outcome,\n branchId: null,\n journalActionTags: [],\n diagnostic,\n };\n }\n\n // Failure path: dispatch to named branch, `__other__` fallback, or\n // synthesized `unclassified`.\n const branch = selectBranch<TOutcome, TDiag>(spec.branches, outcome);\n const failure = branch.buildFailureEnvelope(diagnostic);\n const options = branch.buildRecoveryOptions(diagnostic);\n\n // Inform-only branches (lease_terminal, unclassified) return [] for\n // RecoveryOption[]. Surface the failure envelope without prompting\n // the host — there's no choice to present.\n if (options.length === 0 || callbacks.onFailure === undefined) {\n return {\n result: 'failure',\n verifierOutcome: outcome,\n branchId: branch.branchId,\n journalActionTags: branch.journalActionTags,\n diagnostic,\n failure,\n };\n }\n\n const recoveryChoice = await callbacks.onFailure(failure, options);\n return {\n result: 'failure',\n verifierOutcome: outcome,\n branchId: branch.branchId,\n journalActionTags: branch.journalActionTags,\n diagnostic,\n failure,\n recoveryChoice,\n };\n}\n\nfunction validateSpec<TContext, TOutcome extends string, TDiag>(\n spec: VerificationSpec<TContext, TOutcome, TDiag>,\n): void {\n if (spec === null || typeof spec !== 'object') {\n throw new Error('verifyAndRecover: spec must be an object');\n }\n if (typeof spec.verifier !== 'function') {\n throw new Error('verifyAndRecover: spec.verifier must be a function');\n }\n if (!Array.isArray(spec.successValues)) {\n throw new Error('verifyAndRecover: spec.successValues must be an array');\n }\n // `typeof null === 'object'` would otherwise let a `branches: null` value\n // slip past a bare typeof check and silently route every failure through\n // the synthesized `unclassified` branch. Explicit guard mirrors the\n // CJS's null-check at line 256-263 of verify-recover.cjs.\n if (\n spec.branches === null ||\n typeof spec.branches !== 'object' ||\n Array.isArray(spec.branches)\n ) {\n throw new Error('verifyAndRecover: spec.branches must be an object');\n }\n}\n\nfunction validateVerifierResult(\n value: unknown,\n): asserts value is VerifierResult<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(\n 'verifyAndRecover: verifier must return an object with shape { outcome, diagnostic }',\n );\n }\n const r = value as { outcome?: unknown; diagnostic?: unknown };\n if (typeof r.outcome !== 'string') {\n throw new Error(\n 'verifyAndRecover: verifier result is missing the required \"outcome\" string field',\n );\n }\n if (\n r.diagnostic === null ||\n typeof r.diagnostic !== 'object' ||\n Array.isArray(r.diagnostic)\n ) {\n throw new Error(\n 'verifyAndRecover: verifier result is missing a \"diagnostic\" object field',\n );\n }\n}\n\nfunction selectBranch<TOutcome extends string, TDiag>(\n branches: Partial<Record<TOutcome | '__other__', VerificationBranch<TDiag>>>,\n outcome: TOutcome,\n): VerificationBranch<TDiag> {\n const named = branches[outcome];\n if (named !== undefined) return named;\n const other = branches.__other__;\n if (other !== undefined) return other;\n return synthesizeUnclassified<TDiag>(outcome);\n}\n\n/**\n * Fabricate the `unclassified` fallback when no named branch and no\n * `__other__` catch-all match. Mirrors the CJS behavior at line 222-232:\n * journal action tag is `verify-unclassified`; the recovery options list\n * is empty (inform-only); the failure envelope conveys the unrecognized\n * outcome verbatim in `reason`.\n */\nfunction synthesizeUnclassified<TDiag>(\n outcome: string,\n): VerificationBranch<TDiag> {\n return {\n branchId: 'unclassified',\n journalActionTags: ['verify-unclassified'],\n buildFailureEnvelope: () => ({\n outcome: 'failed',\n reason: `Verifier returned outcome '${outcome}' — unrecognized; no branch matched.`,\n }),\n buildRecoveryOptions: () => [],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsJA,eAAsB,iBAKpB,MACA,SACA,YAAuC,EAAE,EACS;AAClD,cAAa,KAAK;CAElB,MAAM,iBAAiB,MAAM,KAAK,SAAS,QAAQ;AACnD,wBAAuB,eAAe;CAMtC,MAAM,aAAa,cAAc,eAAe,WAAW;CAC3D,MAAM,UAAU,eAAe;AAG/B,KADkB,KAAK,cAAc,SAAS,QAAQ,CAEpD,QAAO;EACL,QAAQ;EACR,iBAAiB;EACjB,UAAU;EACV,mBAAmB,EAAE;EACrB;EACD;CAKH,MAAM,SAAS,aAA8B,KAAK,UAAU,QAAQ;CACpE,MAAM,UAAU,OAAO,qBAAqB,WAAW;CACvD,MAAM,UAAU,OAAO,qBAAqB,WAAW;AAKvD,KAAI,QAAQ,WAAW,KAAK,UAAU,cAAc,KAAA,EAClD,QAAO;EACL,QAAQ;EACR,iBAAiB;EACjB,UAAU,OAAO;EACjB,mBAAmB,OAAO;EAC1B;EACA;EACD;CAGH,MAAM,iBAAiB,MAAM,UAAU,UAAU,SAAS,QAAQ;AAClE,QAAO;EACL,QAAQ;EACR,iBAAiB;EACjB,UAAU,OAAO;EACjB,mBAAmB,OAAO;EAC1B;EACA;EACA;EACD;;AAGH,SAAS,aACP,MACM;AACN,KAAI,SAAS,QAAQ,OAAO,SAAS,SACnC,OAAM,IAAI,MAAM,2CAA2C;AAE7D,KAAI,OAAO,KAAK,aAAa,WAC3B,OAAM,IAAI,MAAM,qDAAqD;AAEvE,KAAI,CAAC,MAAM,QAAQ,KAAK,cAAc,CACpC,OAAM,IAAI,MAAM,wDAAwD;AAM1E,KACE,KAAK,aAAa,QAClB,OAAO,KAAK,aAAa,YACzB,MAAM,QAAQ,KAAK,SAAS,CAE5B,OAAM,IAAI,MAAM,oDAAoD;;AAIxE,SAAS,uBACP,OACkD;AAClD,KAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CACrE,OAAM,IAAI,MACR,sFACD;CAEH,MAAM,IAAI;AACV,KAAI,OAAO,EAAE,YAAY,SACvB,OAAM,IAAI,MACR,qFACD;AAEH,KACE,EAAE,eAAe,QACjB,OAAO,EAAE,eAAe,YACxB,MAAM,QAAQ,EAAE,WAAW,CAE3B,OAAM,IAAI,MACR,6EACD;;AAIL,SAAS,aACP,UACA,SAC2B;CAC3B,MAAM,QAAQ,SAAS;AACvB,KAAI,UAAU,KAAA,EAAW,QAAO;CAChC,MAAM,QAAQ,SAAS;AACvB,KAAI,UAAU,KAAA,EAAW,QAAO;AAChC,QAAO,uBAA8B,QAAQ;;;;;;;;;AAU/C,SAAS,uBACP,SAC2B;AAC3B,QAAO;EACL,UAAU;EACV,mBAAmB,CAAC,sBAAsB;EAC1C,6BAA6B;GAC3B,SAAS;GACT,QAAQ,8BAA8B,QAAQ;GAC/C;EACD,4BAA4B,EAAE;EAC/B"}
@@ -0,0 +1,36 @@
1
+ import { ManageDomainArgs, ManageDomainCallbacks, ManageDomainOptions, ManageDomainResult } from "./types.js";
2
+
3
+ //#region src/manage-domain.d.ts
4
+ /**
5
+ * Set / clear / look up a lease item's custom domain.
6
+ *
7
+ * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation or when
8
+ * `onConfirm` returns `'no'`.
9
+ * @throws `ManifestMCPError` (typically `TX_FAILED`) propagated as-is
10
+ * from the `setItemCustomDomain()` broadcast step in `set` / `clear`
11
+ * paths. Broadcast errors do NOT invoke `onFailure` — that callback
12
+ * is reserved for post-broadcast verification failures.
13
+ * `setItemCustomDomain` already raises a structured `ManifestMCPError`
14
+ * from the core package; wrapping it again at this layer would be
15
+ * redundant. Callers wanting to react to broadcast errors should
16
+ * catch them at the call site.
17
+ * @throws `ManifestMCPError(TX_FAILED)` when post-broadcast verification
18
+ * reaches a `not_found` / `mismatch` outcome (after `onFailure` has
19
+ * been invoked so the caller can react).
20
+ * @throws `ManifestMCPError(QUERY_FAILED)` when a chain query raises a
21
+ * non-NotFound error (RPC / transport / decoding failure). Two paths
22
+ * surface this:
23
+ * - the `lookup` chain query (`lease_by_custom_domain`); the keeper's
24
+ * `NotFound` on an unclaimed FQDN is surfaced as a typed
25
+ * `{ lease: null }` result, not a throw.
26
+ * - the post-broadcast verify chain query (`billing.v1.lease`) in
27
+ * the `set` / `clear` paths (wrapped inside the verifier closure
28
+ * so the failure flows through `onFailure({ reason })` before the
29
+ * throw).
30
+ * Structured `ManifestMCPError`s raised by the chain client are
31
+ * re-thrown as-is (with `onFailure` invoked first).
32
+ */
33
+ declare function manageDomain(args: ManageDomainArgs, callbacks: ManageDomainCallbacks, opts: ManageDomainOptions): Promise<ManageDomainResult>;
34
+ //#endregion
35
+ export { manageDomain };
36
+ //# sourceMappingURL=manage-domain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manage-domain.d.ts","names":[],"sources":["../src/manage-domain.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiHsB,YAAA,CACpB,IAAA,EAAM,gBAAA,EACN,SAAA,EAAW,qBAAA,EACX,IAAA,EAAM,mBAAA,GACL,OAAA,CAAQ,kBAAA"}