@huaweidevtools/aishell-dsh-deploy 0.0.0-stage → 0.0.1-beta.3

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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +164 -2
  3. package/cordis.patch.yml +15 -0
  4. package/lib/data/permission-registry.json +1 -0
  5. package/lib/data/terraform-examples.zip +0 -0
  6. package/lib/index.js +4796 -0
  7. package/lib/types/auth-http.d.ts +44 -0
  8. package/lib/types/auth-obs-signer.d.ts +46 -0
  9. package/lib/types/auth-signer.d.ts +46 -0
  10. package/lib/types/bridge.d.ts +70 -0
  11. package/lib/types/credentials.d.ts +105 -0
  12. package/lib/types/data-paths.d.ts +70 -0
  13. package/lib/types/deployment-state.d.ts +69 -0
  14. package/lib/types/gates/cost_gate.d.ts +24 -0
  15. package/lib/types/gates/credential_gate.d.ts +21 -0
  16. package/lib/types/gates/mirror.d.ts +27 -0
  17. package/lib/types/gates/networking_gate.d.ts +9 -0
  18. package/lib/types/gates/terraform_env.d.ts +26 -0
  19. package/lib/types/index.d.ts +96 -0
  20. package/lib/types/permission/gate.d.ts +87 -0
  21. package/lib/types/permission/mode.d.ts +69 -0
  22. package/lib/types/permission/registry.d.ts +109 -0
  23. package/lib/types/permission-context.d.ts +84 -0
  24. package/lib/types/permission-route.d.ts +78 -0
  25. package/lib/types/permission.d.ts +37 -0
  26. package/lib/types/prompt.d.ts +59 -0
  27. package/lib/types/schemas/cost.d.ts +108 -0
  28. package/lib/types/schemas/networking.d.ts +115 -0
  29. package/lib/types/security-groups.d.ts +43 -0
  30. package/lib/types/tools/annotations.d.ts +94 -0
  31. package/lib/types/tools/balance_summary.d.ts +69 -0
  32. package/lib/types/tools/cost.d.ts +16 -0
  33. package/lib/types/tools/deployment.d.ts +14 -0
  34. package/lib/types/tools/errors.d.ts +40 -0
  35. package/lib/types/tools/examples.d.ts +4 -0
  36. package/lib/types/tools/existing_resources.d.ts +29 -0
  37. package/lib/types/tools/index.d.ts +32 -0
  38. package/lib/types/tools/networking.d.ts +13 -0
  39. package/lib/types/tools/openapi.d.ts +113 -0
  40. package/lib/types/tools/provider_schema.d.ts +19 -0
  41. package/lib/types/tools/terraform.d.ts +32 -0
  42. package/lib/types/types.d.ts +84 -0
  43. package/lib/types/utils/hash.d.ts +11 -0
  44. package/lib/types/utils/tar.d.ts +29 -0
  45. package/lib/types/version.d.ts +18 -0
  46. package/package.json +59 -3
package/lib/index.js ADDED
@@ -0,0 +1,4796 @@
1
+ import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
2
+ import { z } from "zod";
3
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import { readFileSync } from "node:fs";
5
+ import { dirname, join, relative } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dshHome } from "@huaweidevtools/aishell-dsh-credentials-store/paths";
8
+ import { JSONPath } from "jsonpath-plus";
9
+ import { createHash, createHmac } from "node:crypto";
10
+ import { readStoredPair } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
11
+ import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
12
+ import AdmZip from "adm-zip";
13
+ import { spawn } from "node:child_process";
14
+ import { homedir } from "node:os";
15
+
16
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
17
+ /** Return true when a value is `null` or `undefined`. */
18
+ function isNullable(value) {
19
+ return value === null || value === void 0;
20
+ }
21
+ /** Return true for non-array object values. */
22
+ function isPlainObject(data) {
23
+ return data && typeof data === "object" && !Array.isArray(data);
24
+ }
25
+ /** Filter object entries and return a new object. */
26
+ function filterKeys(object, filter) {
27
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
28
+ }
29
+ /** Map object values while preserving the original key set. */
30
+ function mapValues(object, transform) {
31
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
32
+ }
33
+ /** Pick selected keys from an object, optionally including `undefined` values. */
34
+ function pick(source$1, keys, forced) {
35
+ if (!keys) return { ...source$1 };
36
+ const result = {};
37
+ for (const key of keys) if (forced || source$1[key] !== void 0) result[key] = source$1[key];
38
+ return result;
39
+ }
40
+ /** Shared config references used by schema validators and plugin runtimes. */
41
+ const write = Symbol.for("cosmokit.volatile.write");
42
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
43
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
44
+ if (value === null || typeof value !== "object") return value;
45
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
46
+ ancestors.add(value);
47
+ try {
48
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
49
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
50
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
51
+ } finally {
52
+ ancestors.delete(value);
53
+ }
54
+ }
55
+ /**
56
+ * Create a detached reference containing an immutable copy of the supplied data.
57
+ * @param value - validated config data; class instances and functions are unsupported.
58
+ * @returns a reference whose value is updated only by its owning runtime.
59
+ */
60
+ function createVolatile(value) {
61
+ let current$1 = snapshot(value);
62
+ return Object.freeze({
63
+ get: () => current$1,
64
+ [write]: (value$1) => {
65
+ current$1 = value$1;
66
+ }
67
+ });
68
+ }
69
+ /**
70
+ * Identify references across ESM/CJS copies of the shared library.
71
+ * @param value - a parsed config value.
72
+ * @returns whether the value implements the shared reference protocol.
73
+ */
74
+ function isVolatile(value) {
75
+ return typeof value === "object" && value !== null && write in value;
76
+ }
77
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
78
+ function is(type, value) {
79
+ if (arguments.length === 1) return (value$1) => is(type, value$1);
80
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
81
+ }
82
+ function isArrayBufferLike(value) {
83
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
84
+ }
85
+ function isArrayBufferSource(value) {
86
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
87
+ }
88
+ /** Binary source detection and base64/hex conversion helpers. */
89
+ var Binary;
90
+ (function(Binary$1) {
91
+ Binary$1.is = isArrayBufferLike;
92
+ Binary$1.isSource = isArrayBufferSource;
93
+ function fromSource(source$1) {
94
+ if (ArrayBuffer.isView(source$1)) return source$1.buffer.slice(source$1.byteOffset, source$1.byteOffset + source$1.byteLength);
95
+ else return source$1;
96
+ }
97
+ Binary$1.fromSource = fromSource;
98
+ function toBase64(source$1) {
99
+ source$1 = fromSource(source$1);
100
+ if (typeof Buffer !== "undefined") return Buffer.from(source$1).toString("base64");
101
+ let binary = "";
102
+ const bytes = new Uint8Array(source$1);
103
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
104
+ return btoa(binary);
105
+ }
106
+ Binary$1.toBase64 = toBase64;
107
+ function fromBase64(source$1) {
108
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source$1, "base64"));
109
+ return Uint8Array.from(atob(source$1), (c) => c.charCodeAt(0));
110
+ }
111
+ Binary$1.fromBase64 = fromBase64;
112
+ function toHex(source$1) {
113
+ source$1 = fromSource(source$1);
114
+ if (typeof Buffer !== "undefined") return Buffer.from(source$1).toString("hex");
115
+ return Array.from(new Uint8Array(source$1), (byte) => byte.toString(16).padStart(2, "0")).join("");
116
+ }
117
+ Binary$1.toHex = toHex;
118
+ function fromHex(source$1) {
119
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source$1, "hex"));
120
+ const hex = source$1.length % 2 === 0 ? source$1 : source$1.slice(0, source$1.length - 1);
121
+ const buffer = [];
122
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
123
+ return Uint8Array.from(buffer).buffer;
124
+ }
125
+ Binary$1.fromHex = fromHex;
126
+ })(Binary || (Binary = {}));
127
+ /** Decode a base64 string into binary data. */
128
+ const base64ToArrayBuffer = Binary.fromBase64;
129
+ /** Encode binary data as base64. */
130
+ const arrayBufferToBase64 = Binary.toBase64;
131
+ /** Decode a hex string into binary data. */
132
+ const hexToArrayBuffer = Binary.fromHex;
133
+ /** Encode binary data as hex. */
134
+ const arrayBufferToHex = Binary.toHex;
135
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
136
+ function clone(source$1, refs = /* @__PURE__ */ new Map()) {
137
+ if (!source$1 || typeof source$1 !== "object") return source$1;
138
+ if (is("Date", source$1)) return new Date(source$1.valueOf());
139
+ if (is("RegExp", source$1)) return new RegExp(source$1.source, source$1.flags);
140
+ if (isArrayBufferLike(source$1)) return source$1.slice(0);
141
+ if (ArrayBuffer.isView(source$1)) return source$1.buffer.slice(source$1.byteOffset, source$1.byteOffset + source$1.byteLength);
142
+ const cached = refs.get(source$1);
143
+ if (cached) return cached;
144
+ if (Array.isArray(source$1)) {
145
+ const result$1 = [];
146
+ refs.set(source$1, result$1);
147
+ source$1.forEach((value, index) => {
148
+ result$1[index] = Reflect.apply(clone, null, [value, refs]);
149
+ });
150
+ return result$1;
151
+ }
152
+ const result = Object.create(Object.getPrototypeOf(source$1));
153
+ refs.set(source$1, result);
154
+ for (const key of Reflect.ownKeys(source$1)) {
155
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source$1, key) };
156
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
157
+ Reflect.defineProperty(result, key, descriptor);
158
+ }
159
+ return result;
160
+ }
161
+ /**
162
+ * Compare values recursively, treating two volatile references as equal regardless of value.
163
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
164
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
165
+ * @param a - first value.
166
+ * @param b - second value.
167
+ * @param strict - whether to require strict data equality outside volatile references.
168
+ * @returns whether the values compare equal.
169
+ */
170
+ function deepEqual(a, b, strict) {
171
+ const ancestors = /* @__PURE__ */ new Set();
172
+ function compare(a$1, b$1) {
173
+ if (a$1 === b$1) return true;
174
+ if (isVolatile(a$1) || isVolatile(b$1)) return isVolatile(a$1) && isVolatile(b$1);
175
+ if (!strict && isNullable(a$1) && isNullable(b$1)) return true;
176
+ if (typeof a$1 !== typeof b$1 || typeof a$1 !== "object" || !a$1 || !b$1) return false;
177
+ if (ancestors.has(a$1)) return false;
178
+ function check(test, then) {
179
+ return test(a$1) ? test(b$1) ? then(a$1, b$1) : false : test(b$1) ? false : void 0;
180
+ }
181
+ ancestors.add(a$1);
182
+ try {
183
+ return check(Array.isArray, (a$2, b$2) => {
184
+ if (a$2.length !== b$2.length) return false;
185
+ for (let index = 0; index < a$2.length; index++) if (!compare(a$2[index], b$2[index])) return false;
186
+ return true;
187
+ }) ?? check(is("Date"), (a$2, b$2) => a$2.valueOf() === b$2.valueOf()) ?? check(is("URL"), (a$2, b$2) => a$2.href === b$2.href) ?? check(is("RegExp"), (a$2, b$2) => a$2.source === b$2.source && a$2.flags === b$2.flags) ?? check(isArrayBufferLike, (a$2, b$2) => {
188
+ if (a$2.byteLength !== b$2.byteLength) return false;
189
+ const viewA = new Uint8Array(a$2);
190
+ const viewB = new Uint8Array(b$2);
191
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
192
+ return true;
193
+ }) ?? ((!strict || [a$1, b$1].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
194
+ ...a$1,
195
+ ...b$1
196
+ }).every((key) => compare(a$1[key], b$1[key])));
197
+ } finally {
198
+ ancestors.delete(a$1);
199
+ }
200
+ }
201
+ return compare(a, b);
202
+ }
203
+ /** Time constants plus parsing and formatting helpers. */
204
+ var Time;
205
+ (function(Time$1) {
206
+ Time$1.millisecond = 1;
207
+ Time$1.second = 1e3;
208
+ Time$1.minute = Time$1.second * 60;
209
+ Time$1.hour = Time$1.minute * 60;
210
+ Time$1.day = Time$1.hour * 24;
211
+ Time$1.week = Time$1.day * 7;
212
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
213
+ function setTimezoneOffset(offset) {
214
+ timezoneOffset = offset;
215
+ }
216
+ Time$1.setTimezoneOffset = setTimezoneOffset;
217
+ function getTimezoneOffset() {
218
+ return timezoneOffset;
219
+ }
220
+ Time$1.getTimezoneOffset = getTimezoneOffset;
221
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
222
+ if (typeof date === "number") date = new Date(date);
223
+ if (offset === void 0) offset = timezoneOffset;
224
+ return Math.floor((date.valueOf() / Time$1.minute - offset) / 1440);
225
+ }
226
+ Time$1.getDateNumber = getDateNumber;
227
+ function fromDateNumber(value, offset) {
228
+ const date = new Date(value * Time$1.day);
229
+ if (offset === void 0) offset = timezoneOffset;
230
+ return new Date(+date + offset * Time$1.minute);
231
+ }
232
+ Time$1.fromDateNumber = fromDateNumber;
233
+ const numeric = /\d+(?:\.\d+)?/.source;
234
+ const timeRegExp = new RegExp(`^${[
235
+ "w(?:eek(?:s)?)?",
236
+ "d(?:ay(?:s)?)?",
237
+ "h(?:our(?:s)?)?",
238
+ "m(?:in(?:ute)?(?:s)?)?",
239
+ "s(?:ec(?:ond)?(?:s)?)?"
240
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
241
+ function parseTime(source$1) {
242
+ const capture = timeRegExp.exec(source$1);
243
+ if (!capture) return 0;
244
+ return (parseFloat(capture[1]) * Time$1.week || 0) + (parseFloat(capture[2]) * Time$1.day || 0) + (parseFloat(capture[3]) * Time$1.hour || 0) + (parseFloat(capture[4]) * Time$1.minute || 0) + (parseFloat(capture[5]) * Time$1.second || 0);
245
+ }
246
+ Time$1.parseTime = parseTime;
247
+ function parseDate(date) {
248
+ const parsed = parseTime(date);
249
+ if (parsed) date = Date.now() + parsed;
250
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
251
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
252
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
253
+ }
254
+ Time$1.parseDate = parseDate;
255
+ function format(ms) {
256
+ const abs = Math.abs(ms);
257
+ if (abs >= Time$1.day - Time$1.hour / 2) return Math.round(ms / Time$1.day) + "d";
258
+ else if (abs >= Time$1.hour - Time$1.minute / 2) return Math.round(ms / Time$1.hour) + "h";
259
+ else if (abs >= Time$1.minute - Time$1.second / 2) return Math.round(ms / Time$1.minute) + "m";
260
+ else if (abs >= Time$1.second) return Math.round(ms / Time$1.second) + "s";
261
+ return ms + "ms";
262
+ }
263
+ Time$1.format = format;
264
+ function toDigits(source$1, length = 2) {
265
+ return source$1.toString().padStart(length, "0");
266
+ }
267
+ Time$1.toDigits = toDigits;
268
+ function template(template$1, time = /* @__PURE__ */ new Date()) {
269
+ return template$1.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
270
+ }
271
+ Time$1.template = template;
272
+ })(Time || (Time = {}));
273
+
274
+ //#endregion
275
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.4/node_modules/@deepseek-ai/schemastery/lib/index.mjs
276
+ const kSchema = Symbol.for("schemastery");
277
+ const kValidationError = Symbol.for("ValidationError");
278
+ globalThis.__schemastery_index__ ??= 0;
279
+ globalThis.__schemastery_refs__ = void 0;
280
+ var ValidationError = class extends TypeError {
281
+ options;
282
+ name = "ValidationError";
283
+ constructor(message, options) {
284
+ let prefix = "$";
285
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
286
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
287
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
288
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
289
+ super((prefix === "$" ? "" : `${prefix} `) + message);
290
+ this.options = options;
291
+ }
292
+ static is(error) {
293
+ return !!error?.[kValidationError];
294
+ }
295
+ };
296
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
297
+ const Schema = function(options) {
298
+ const schema = function(data, options$1 = {}) {
299
+ return Schema.resolve(data, schema, options$1)[0];
300
+ };
301
+ if (options.refs) {
302
+ const refs = mapValues(options.refs, (options$1) => new Schema(options$1));
303
+ const getRef = (uid) => refs[uid];
304
+ for (const key in refs) {
305
+ const options$1 = refs[key];
306
+ options$1.sKey = getRef(options$1.sKey);
307
+ options$1.inner = getRef(options$1.inner);
308
+ options$1.list = options$1.list && options$1.list.map(getRef);
309
+ options$1.dict = options$1.dict && mapValues(options$1.dict, getRef);
310
+ }
311
+ return refs[options.uid];
312
+ }
313
+ Object.assign(schema, options);
314
+ if (typeof schema.callback === "string") try {
315
+ schema.callback = new Function("return " + schema.callback)();
316
+ } catch {}
317
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
318
+ Object.setPrototypeOf(schema, Schema.prototype);
319
+ schema.meta ||= {};
320
+ schema.toString = schema.toString.bind(schema);
321
+ return schema;
322
+ };
323
+ Schema.prototype = Object.create(Function.prototype);
324
+ Schema.prototype[kSchema] = true;
325
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
326
+ return {
327
+ version: 1,
328
+ vendor: "schemastery",
329
+ validate: (value) => {
330
+ try {
331
+ return { value: Schema.resolve(value, this, {})[0] };
332
+ } catch (error) {
333
+ if (ValidationError.is(error)) return { issues: [{
334
+ message: error.message,
335
+ path: error.options.path
336
+ }] };
337
+ throw error;
338
+ }
339
+ }
340
+ };
341
+ } });
342
+ Schema.ValidationError = ValidationError;
343
+ Schema.prototype.toJSON = function toJSON() {
344
+ if (globalThis.__schemastery_refs__) {
345
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
346
+ return this.uid;
347
+ }
348
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
349
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
350
+ const result = {
351
+ uid: this.uid,
352
+ refs: globalThis.__schemastery_refs__
353
+ };
354
+ globalThis.__schemastery_refs__ = void 0;
355
+ return result;
356
+ };
357
+ Schema.prototype.set = function set(key, value) {
358
+ this.dict[key] = value;
359
+ return this;
360
+ };
361
+ Schema.prototype.push = function push(value) {
362
+ this.list.push(value);
363
+ return this;
364
+ };
365
+ function mergeDesc(original, messages) {
366
+ const result = typeof original === "string" ? { "": original } : { ...original };
367
+ for (const locale in messages) {
368
+ const value = messages[locale];
369
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
370
+ else if (typeof value === "string") result[locale] = value;
371
+ }
372
+ return result;
373
+ }
374
+ function getInner(value) {
375
+ return value?.$value ?? value?.$inner;
376
+ }
377
+ function extractKeys(data) {
378
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
379
+ }
380
+ Schema.prototype.i18n = function i18n(messages) {
381
+ const schema = Schema(this);
382
+ const desc = mergeDesc(schema.meta.description, messages);
383
+ if (Object.keys(desc).length) schema.meta.description = desc;
384
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
385
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
386
+ });
387
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
388
+ return inner.i18n(mapValues(messages, (data = {}) => {
389
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
390
+ if (Array.isArray(data)) return data[index];
391
+ return extractKeys(data);
392
+ }));
393
+ });
394
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
395
+ if (getInner(data)) return getInner(data);
396
+ return extractKeys(data);
397
+ }));
398
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
399
+ return schema;
400
+ };
401
+ Schema.prototype.extra = function extra(key, value) {
402
+ const schema = Schema(this);
403
+ schema.meta = {
404
+ ...schema.meta,
405
+ [key]: value
406
+ };
407
+ return schema;
408
+ };
409
+ for (const key of [
410
+ "required",
411
+ "disabled",
412
+ "collapse",
413
+ "hidden",
414
+ "loose"
415
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
416
+ const schema = Schema(this);
417
+ schema.meta = {
418
+ ...schema.meta,
419
+ [key]: value
420
+ };
421
+ return schema;
422
+ } });
423
+ Schema.prototype.deprecated = function deprecated() {
424
+ const schema = Schema(this);
425
+ schema.meta.badges ||= [];
426
+ schema.meta.badges.push({
427
+ text: "deprecated",
428
+ type: "danger"
429
+ });
430
+ return schema;
431
+ };
432
+ Schema.prototype.experimental = function experimental() {
433
+ const schema = Schema(this);
434
+ schema.meta.badges ||= [];
435
+ schema.meta.badges.push({
436
+ text: "experimental",
437
+ type: "warning"
438
+ });
439
+ return schema;
440
+ };
441
+ Schema.prototype.pattern = function pattern(regexp) {
442
+ const schema = Schema(this);
443
+ const pattern$1 = pick(regexp, ["source", "flags"]);
444
+ schema.meta = {
445
+ ...schema.meta,
446
+ pattern: pattern$1
447
+ };
448
+ return schema;
449
+ };
450
+ Schema.prototype.simplify = function simplify(value) {
451
+ if (isVolatile(value)) value = value.get();
452
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
453
+ if (isNullable(value)) return value;
454
+ if (this.type === "object" || this.type === "dict") {
455
+ const result = {};
456
+ for (const key in value) {
457
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
458
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
459
+ }
460
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
461
+ return result;
462
+ } else if (this.type === "array" || this.type === "tuple") {
463
+ const result = [];
464
+ value.forEach((value$1, index) => {
465
+ const schema = this.type === "array" ? this.inner : this.list[index];
466
+ const item = schema ? schema.simplify(value$1) : value$1;
467
+ result.push(item);
468
+ });
469
+ return result;
470
+ } else if (this.type === "intersect") {
471
+ const result = {};
472
+ for (const item of this.list) Object.assign(result, item.simplify(value));
473
+ return result;
474
+ } else if (this.type === "union") for (const schema of this.list) try {
475
+ Schema.resolve(value, schema, {});
476
+ return schema.simplify(value);
477
+ } catch {}
478
+ return value;
479
+ };
480
+ Schema.prototype.toString = function toString(inline) {
481
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
482
+ };
483
+ Schema.prototype.role = function role(role$1, extra) {
484
+ const schema = Schema(this);
485
+ schema.meta = {
486
+ ...schema.meta,
487
+ role: role$1,
488
+ extra
489
+ };
490
+ return schema;
491
+ };
492
+ for (const key of [
493
+ "default",
494
+ "link",
495
+ "comment",
496
+ "description",
497
+ "max",
498
+ "min",
499
+ "step"
500
+ ]) Object.assign(Schema.prototype, { [key](value) {
501
+ const schema = Schema(this);
502
+ schema.meta = {
503
+ ...schema.meta,
504
+ [key]: value
505
+ };
506
+ return schema;
507
+ } });
508
+ Schema.prototype.volatile = function volatile() {
509
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
510
+ return this.extra("volatile", true);
511
+ };
512
+ const resolvers = {};
513
+ const checkedVolatile = Symbol("checked-volatile-schema");
514
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
515
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
516
+ if (states.has(blocked)) return;
517
+ states.add(blocked);
518
+ seen.set(schema, states);
519
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
520
+ const nested = blocked || !!schema.meta?.volatile;
521
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
522
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
523
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
524
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
525
+ }
526
+ Schema.extend = function extend(type, resolve) {
527
+ resolvers[type] = resolve;
528
+ };
529
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
530
+ if (!schema) return [data];
531
+ if (!options[checkedVolatile]) {
532
+ validateVolatileSchema(schema, options.path);
533
+ options = {
534
+ ...options,
535
+ [checkedVolatile]: true
536
+ };
537
+ }
538
+ if (schema.meta?.volatile) {
539
+ const inner = Schema(schema);
540
+ inner.meta = {
541
+ ...schema.meta,
542
+ volatile: false
543
+ };
544
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
545
+ try {
546
+ return [createVolatile(value), adapted];
547
+ } catch (error) {
548
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
549
+ }
550
+ }
551
+ if (options.ignore?.(data, schema)) return [data];
552
+ if (isNullable(data) && schema.type !== "lazy") {
553
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
554
+ let current$1 = schema;
555
+ let fallback = schema.meta.default;
556
+ while (current$1?.type === "intersect" && isNullable(fallback)) {
557
+ current$1 = current$1.list[0];
558
+ fallback = current$1?.meta.default;
559
+ }
560
+ if (isNullable(fallback)) return [data];
561
+ data = clone(fallback);
562
+ }
563
+ const callback = resolvers[schema.type];
564
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
565
+ try {
566
+ return callback(data, schema, options, strict);
567
+ } catch (error) {
568
+ if (!schema.meta.loose) throw error;
569
+ return [schema.meta.default];
570
+ }
571
+ };
572
+ Schema.from = function from(source$1) {
573
+ if (isNullable(source$1)) return Schema.any();
574
+ else if ([
575
+ "string",
576
+ "number",
577
+ "boolean"
578
+ ].includes(typeof source$1)) return Schema.const(source$1).required();
579
+ else if (source$1[kSchema]) return source$1;
580
+ else if (typeof source$1 === "function") switch (source$1) {
581
+ case String: return Schema.string().required();
582
+ case Number: return Schema.number().required();
583
+ case Boolean: return Schema.boolean().required();
584
+ case Function: return Schema.function().required();
585
+ default: return Schema.is(source$1).required();
586
+ }
587
+ else throw new TypeError(`cannot infer schema from ${source$1}`);
588
+ };
589
+ Schema.lazy = function lazy(builder) {
590
+ const toJSON = () => {
591
+ if (!schema.inner[kSchema]) {
592
+ schema.inner = schema.builder();
593
+ schema.inner.meta = {
594
+ ...schema.meta,
595
+ ...schema.inner.meta
596
+ };
597
+ }
598
+ return schema.inner.toJSON();
599
+ };
600
+ const schema = new Schema({
601
+ type: "lazy",
602
+ builder,
603
+ inner: { toJSON }
604
+ });
605
+ return schema;
606
+ };
607
+ Schema.natural = function natural() {
608
+ return Schema.number().step(1).min(0);
609
+ };
610
+ Schema.percent = function percent() {
611
+ return Schema.number().step(.01).min(0).max(1).role("slider");
612
+ };
613
+ Schema.date = function date() {
614
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
615
+ const date$1 = new Date(value);
616
+ if (isNaN(+date$1)) throw new ValidationError(`invalid date "${value}"`, options);
617
+ return date$1;
618
+ }, true)]);
619
+ };
620
+ Schema.regExp = function regExp(flag = "") {
621
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
622
+ try {
623
+ return new RegExp(value, flag);
624
+ } catch (e) {
625
+ throw new ValidationError(e.message, options);
626
+ }
627
+ }, true)]);
628
+ };
629
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
630
+ return Schema.union([
631
+ Schema.is(ArrayBuffer),
632
+ Schema.is(SharedArrayBuffer),
633
+ Schema.transform(Schema.any(), (value, options) => {
634
+ if (Binary.isSource(value)) return Binary.fromSource(value);
635
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
636
+ }, true),
637
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
638
+ try {
639
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
640
+ } catch (e) {
641
+ throw new ValidationError(e.message, options);
642
+ }
643
+ }, true)] : []
644
+ ]);
645
+ };
646
+ Schema.extend("lazy", (data, schema, options, strict) => {
647
+ if (!schema.inner[kSchema]) {
648
+ schema.inner = schema.builder();
649
+ schema.inner.meta = {
650
+ ...schema.meta,
651
+ ...schema.inner.meta
652
+ };
653
+ validateVolatileSchema(schema.inner, options.path, true);
654
+ }
655
+ return Schema.resolve(data, schema.inner, options, strict);
656
+ });
657
+ Schema.extend("any", (data) => {
658
+ return [data];
659
+ });
660
+ Schema.extend("never", (data, _, options) => {
661
+ throw new ValidationError(`expected nullable but got ${data}`, options);
662
+ });
663
+ Schema.extend("const", (data, { value }, options) => {
664
+ if (deepEqual(data, value)) return [value];
665
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
666
+ });
667
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
668
+ const { max = Infinity, min = -Infinity } = meta;
669
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
670
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
671
+ }
672
+ Schema.extend("string", (data, { meta }, options) => {
673
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
674
+ if (meta.pattern) {
675
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
676
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
677
+ }
678
+ checkWithinRange(data.length, meta, "string length", options);
679
+ return [data];
680
+ });
681
+ function decimalShift(data, digits) {
682
+ const str = data.toString();
683
+ if (str.includes("e")) return data * Math.pow(10, digits);
684
+ const index = str.indexOf(".");
685
+ if (index === -1) return data * Math.pow(10, digits);
686
+ const frac = str.slice(index + 1);
687
+ const integer = str.slice(0, index);
688
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
689
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
690
+ }
691
+ function isMultipleOf(data, min, step) {
692
+ step = Math.abs(step);
693
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
694
+ const index = step.toString().indexOf(".");
695
+ const digits = step.toString().slice(index + 1).length;
696
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
697
+ }
698
+ Schema.extend("number", (data, { meta }, options) => {
699
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
700
+ checkWithinRange(data, meta, "number", options);
701
+ const { step } = meta;
702
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
703
+ return [data];
704
+ });
705
+ Schema.extend("boolean", (data, _, options) => {
706
+ if (typeof data === "boolean") return [data];
707
+ throw new ValidationError(`expected boolean but got ${data}`, options);
708
+ });
709
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
710
+ let value = 0, keys = [];
711
+ if (typeof data === "number") {
712
+ value = data;
713
+ for (const key in bits) if (data & bits[key]) keys.push(key);
714
+ } else if (Array.isArray(data)) {
715
+ keys = data;
716
+ for (const key of keys) {
717
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
718
+ if (key in bits) value |= bits[key];
719
+ }
720
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
721
+ if (value === meta.default) return [value];
722
+ return [value, keys];
723
+ });
724
+ Schema.extend("function", (data, _, options) => {
725
+ if (typeof data === "function") return [data];
726
+ throw new ValidationError(`expected function but got ${data}`, options);
727
+ });
728
+ Schema.extend("is", (data, { constructor }, options) => {
729
+ if (typeof constructor === "function") {
730
+ if (data instanceof constructor) return [data];
731
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
732
+ } else {
733
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
734
+ let prototype = Object.getPrototypeOf(data);
735
+ while (prototype) {
736
+ if (prototype.constructor?.name === constructor) return [data];
737
+ prototype = Object.getPrototypeOf(prototype);
738
+ }
739
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
740
+ }
741
+ });
742
+ function property(data, key, schema, options) {
743
+ try {
744
+ const [value, adapted] = Schema.resolve(data[key], schema, {
745
+ ...options,
746
+ path: [...options.path || [], key]
747
+ });
748
+ if (adapted !== void 0) data[key] = adapted;
749
+ return value;
750
+ } catch (e) {
751
+ if (!options?.autofix) throw e;
752
+ delete data[key];
753
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
754
+ }
755
+ }
756
+ Schema.extend("array", (data, { inner, meta }, options) => {
757
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
758
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
759
+ return [data.map((_, index) => property(data, index, inner, options))];
760
+ });
761
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
762
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
763
+ const result = {};
764
+ for (const key in data) {
765
+ let rKey;
766
+ try {
767
+ rKey = Schema.resolve(key, sKey, options)[0];
768
+ } catch (error) {
769
+ if (strict) continue;
770
+ throw error;
771
+ }
772
+ result[rKey] = property(data, key, inner, options);
773
+ data[rKey] = data[key];
774
+ if (key !== rKey) delete data[key];
775
+ }
776
+ return [result];
777
+ });
778
+ Schema.extend("tuple", (data, { list }, options, strict) => {
779
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
780
+ const result = list.map((inner, index) => property(data, index, inner, options));
781
+ if (strict) return [result];
782
+ result.push(...data.slice(list.length));
783
+ return [result];
784
+ });
785
+ function merge(result, data) {
786
+ for (const key in data) {
787
+ if (key in result) continue;
788
+ result[key] = data[key];
789
+ }
790
+ }
791
+ Schema.extend("object", (data, { dict }, options, strict) => {
792
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
793
+ const result = {};
794
+ for (const key in dict) {
795
+ const value = property(data, key, dict[key], options);
796
+ if (!isNullable(value) || key in data) result[key] = value;
797
+ }
798
+ if (!strict) merge(result, data);
799
+ return [result];
800
+ });
801
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
802
+ const messages = [];
803
+ for (const inner of list) try {
804
+ return Schema.resolve(data, inner, options, strict);
805
+ } catch (error) {
806
+ messages.push(error);
807
+ }
808
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
809
+ });
810
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
811
+ if (!list.length) return [data];
812
+ let result;
813
+ for (const inner of list) {
814
+ const value = Schema.resolve(data, inner, options, true)[0];
815
+ if (isNullable(value)) continue;
816
+ if (isNullable(result)) result = value;
817
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
818
+ else if (typeof value === "object") merge(result ??= {}, value);
819
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
820
+ }
821
+ if (!strict && isPlainObject(data)) merge(result, data);
822
+ return [result];
823
+ });
824
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
825
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
826
+ if (preserve) return [callback(result)];
827
+ else return [callback(result), callback(adapted)];
828
+ });
829
+ const formatters = {};
830
+ function defineMethod(name$1, keys, format) {
831
+ formatters[name$1] = format;
832
+ Object.assign(Schema, { [name$1](...args) {
833
+ const schema = new Schema({ type: name$1 });
834
+ keys.forEach((key, index) => {
835
+ switch (key) {
836
+ case "sKey":
837
+ schema.sKey = args[index] ?? Schema.string();
838
+ break;
839
+ case "inner":
840
+ schema.inner = Schema.from(args[index]);
841
+ break;
842
+ case "list":
843
+ schema.list = args[index].map(Schema.from);
844
+ break;
845
+ case "dict":
846
+ schema.dict = mapValues(args[index], Schema.from);
847
+ break;
848
+ case "bits":
849
+ schema.bits = {};
850
+ for (const key$1 in args[index]) {
851
+ if (typeof args[index][key$1] !== "number") continue;
852
+ schema.bits[key$1] = args[index][key$1];
853
+ }
854
+ break;
855
+ case "callback": {
856
+ const callback = schema.callback = args[index];
857
+ callback["toJSON"] ||= () => callback.toString();
858
+ break;
859
+ }
860
+ case "constructor": {
861
+ const constructor = schema.constructor = args[index];
862
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
863
+ break;
864
+ }
865
+ default: schema[key] = args[index];
866
+ }
867
+ });
868
+ if (name$1 === "object" || name$1 === "dict") schema.meta.default = {};
869
+ else if (name$1 === "array" || name$1 === "tuple") schema.meta.default = [];
870
+ else if (name$1 === "bitset") schema.meta.default = 0;
871
+ return schema;
872
+ } });
873
+ }
874
+ defineMethod("is", ["constructor"], ({ constructor }) => {
875
+ if (typeof constructor === "function") return constructor.name;
876
+ else return constructor;
877
+ });
878
+ defineMethod("any", [], () => "any");
879
+ defineMethod("never", [], () => "never");
880
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
881
+ defineMethod("string", [], () => "string");
882
+ defineMethod("number", [], () => "number");
883
+ defineMethod("boolean", [], () => "boolean");
884
+ defineMethod("bitset", ["bits"], () => "bitset");
885
+ defineMethod("function", [], () => "function");
886
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
887
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
888
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
889
+ defineMethod("object", ["dict"], ({ dict }) => {
890
+ if (Object.keys(dict).length === 0) return "{}";
891
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
892
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
893
+ }).join(", ")} }`;
894
+ });
895
+ defineMethod("union", ["list"], ({ list }, inline) => {
896
+ const result = list.map(({ toString: format }) => format()).join(" | ");
897
+ return inline ? `(${result})` : result;
898
+ });
899
+ defineMethod("intersect", ["list"], ({ list }) => {
900
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
901
+ });
902
+ defineMethod("transform", [
903
+ "inner",
904
+ "callback",
905
+ "preserve"
906
+ ], ({ inner }, isInner) => inner.toString(isInner));
907
+
908
+ //#endregion
909
+ //#region src/bridge.ts
910
+ /**
911
+ * Collect the tools the `register*()` functions register.
912
+ *
913
+ * @returns the registrar the tool modules write into, and the list it fills.
914
+ */
915
+ function createRegistrar() {
916
+ const captured = [];
917
+ const registrar = { registerTool(name$1, config, handler) {
918
+ captured.push({
919
+ name: name$1,
920
+ config,
921
+ handler
922
+ });
923
+ } };
924
+ return {
925
+ registrar,
926
+ captured
927
+ };
928
+ }
929
+ /**
930
+ * The model-facing name for one tool.
931
+ *
932
+ * Registered as `aishell__<name>`. The prefix exists because this plugin is not
933
+ * the only source of cloud tools in a deployment, and a bare `terraform_apply`
934
+ * in a shared namespace is one collision away from calling someone else's tool.
935
+ *
936
+ * @param rawName - the tool's own name.
937
+ */
938
+ function publicToolName(rawName) {
939
+ return `aishell__${rawName}`;
940
+ }
941
+ /**
942
+ * Convert one registration into a DSH tool definition.
943
+ *
944
+ * @param tool - the captured registration.
945
+ * @param timeoutMs - per-call budget handed to the harness.
946
+ * @returns the definition to hand to `ctx.tools.register`.
947
+ */
948
+ function toToolDefinition(tool, timeoutMs) {
949
+ const name$1 = publicToolName(tool.name);
950
+ const description = tool.config.description ?? "";
951
+ const parameters = toJsonSchema(tool.config.inputSchema, tool.name);
952
+ return {
953
+ name: name$1,
954
+ description,
955
+ parameters,
956
+ output: {
957
+ schema: { type: "object" },
958
+ render: (_args, value) => renderResult(value)
959
+ },
960
+ timeoutMs,
961
+ async execute(args, exec) {
962
+ const result = await tool.handler(args, contextFor(exec));
963
+ return unwrapOrThrow(result);
964
+ }
965
+ };
966
+ }
967
+ /**
968
+ * The handler context for one execution.
969
+ *
970
+ * Empty today: nothing the tool modules read lives on the harness context.
971
+ * It stays a function so the next handler that needs the caller's session or
972
+ * signal has one obvious place to take it from, rather than reaching into the
973
+ * harness from a tool module.
974
+ *
975
+ * @param _exec - the harness execution context.
976
+ * @returns the handler context.
977
+ */
978
+ function contextFor(_exec) {
979
+ return {};
980
+ }
981
+ /**
982
+ * Turn a handler's return into the canonical value, or throw on failure.
983
+ *
984
+ * @param result - what the handler returned.
985
+ * @returns the canonical value (the result itself).
986
+ * @throws when the handler reported an error, with the diagnostic as the message.
987
+ */
988
+ function unwrapOrThrow(result) {
989
+ if (result.isError === true) throw new Error(textOf(result.content));
990
+ return result;
991
+ }
992
+ /**
993
+ * Project a canonical value into the blocks the model reads.
994
+ *
995
+ * DSH's content vocabulary is text/reasoning/image-with-attachment; these
996
+ * handlers only ever produce text. Dropping an unexpected block would render a
997
+ * successful call as empty, which reads like a broken tool — so anything that
998
+ * is not text is reported instead of silently discarded.
999
+ *
1000
+ * @param value - the tool result.
1001
+ * @returns its content blocks.
1002
+ */
1003
+ function renderResult(value) {
1004
+ const blocks = [];
1005
+ for (const block of value.content) if (block.type === "text") blocks.push({
1006
+ type: "text",
1007
+ text: block.text
1008
+ });
1009
+ else blocks.push({
1010
+ type: "text",
1011
+ text: "[content unavailable: this tool produced a block type this deployment cannot render]"
1012
+ });
1013
+ return blocks.length === 0 ? [{
1014
+ type: "text",
1015
+ text: "(no output)"
1016
+ }] : blocks;
1017
+ }
1018
+ /** Concatenate a result's text blocks, for use as an error message. */
1019
+ function textOf(content) {
1020
+ const text = content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
1021
+ return text === "" ? "the tool reported an error without a message" : text;
1022
+ }
1023
+ /**
1024
+ * Convert a tool's declared `inputSchema` into JSON Schema.
1025
+ *
1026
+ * The tools declare zod objects. `z.toJSONSchema` is exact for every shape they
1027
+ * use (objects, arrays, enums, optional fields, `describe`) and drops only the
1028
+ * runtime refinements — `superRefine` cannot be expressed in JSON Schema at all.
1029
+ * That is not a gap: the handlers re-run their own `safeParse` where the
1030
+ * refinement matters, which is why every one of them still parses its
1031
+ * arguments itself.
1032
+ *
1033
+ * @param schema - whatever the tool declared.
1034
+ * @param toolName - for the failure message.
1035
+ * @returns a JSON Schema object DSH can hand the model.
1036
+ */
1037
+ function toJsonSchema(schema, toolName) {
1038
+ if (!isZodType(schema)) throw new Error(`aishell-deploy: tool "${toolName}" declared an input schema that is not a zod type`);
1039
+ const json$1 = z.toJSONSchema(schema, {
1040
+ io: "input",
1041
+ reused: "inline"
1042
+ });
1043
+ delete json$1.$schema;
1044
+ return json$1;
1045
+ }
1046
+ /**
1047
+ * Whether a value is a zod type.
1048
+ *
1049
+ * Structural rather than `instanceof`: there is exactly one zod copy in this
1050
+ * package's tree, but a structural check keeps this module independent of that
1051
+ * fact — and `instanceof` across two copies fails in the least legible way. The
1052
+ * `_zod` brand is what zod 4 puts on every schema.
1053
+ */
1054
+ function isZodType(value) {
1055
+ return typeof value === "object" && value !== null && "_zod" in value && value._zod?.def !== void 0;
1056
+ }
1057
+
1058
+ //#endregion
1059
+ //#region src/tools/annotations.ts
1060
+ /**
1061
+ * Reads HuaweiCloud / the local filesystem, changes nothing.
1062
+ * e.g. apiexplorer, list_existing_resources.
1063
+ */
1064
+ const READ_ONLY_CLOUD = {
1065
+ readOnlyHint: true,
1066
+ destructiveHint: false,
1067
+ idempotentHint: true,
1068
+ openWorldHint: true
1069
+ };
1070
+ /**
1071
+ * Reads only local state, no external system, changes nothing.
1072
+ * e.g. provider_schema, terraform_state.
1073
+ */
1074
+ const READ_ONLY_LOCAL = {
1075
+ readOnlyHint: true,
1076
+ destructiveHint: false,
1077
+ idempotentHint: true,
1078
+ openWorldHint: false
1079
+ };
1080
+ /**
1081
+ * Writes files inside the deployment workspace only; creates nothing, destroys
1082
+ * nothing, no external system. Re-running with the same input converges.
1083
+ * e.g. create_deployment, update_networking, update_cost.
1084
+ */
1085
+ const LOCAL_WRITE = {
1086
+ readOnlyHint: false,
1087
+ destructiveHint: false,
1088
+ idempotentHint: true,
1089
+ openWorldHint: false
1090
+ };
1091
+ /**
1092
+ * Removes local data and cannot be undone (delete_deployment `rm -rf`).
1093
+ * Re-running is safe (a second delete finds nothing) but the first is final.
1094
+ */
1095
+ const LOCAL_DESTRUCTIVE = {
1096
+ readOnlyHint: false,
1097
+ destructiveHint: true,
1098
+ idempotentHint: true,
1099
+ openWorldHint: false
1100
+ };
1101
+ /**
1102
+ * Writes remote state / downloads artifacts; does not create or destroy cloud
1103
+ * resources. e.g. terraform_init, terraform_install.
1104
+ */
1105
+ const CLOUD_WRITE = {
1106
+ readOnlyHint: false,
1107
+ destructiveHint: false,
1108
+ idempotentHint: true,
1109
+ openWorldHint: true
1110
+ };
1111
+ /**
1112
+ * Creates, changes, or destroys cloud resources, and *converges* — a retry
1113
+ * with the same input is a no-op. e.g. terraform_apply (re-apply converges),
1114
+ * terraform_destroy (re-destroy finds nothing).
1115
+ */
1116
+ const CLOUD_DESTRUCTIVE = {
1117
+ readOnlyHint: false,
1118
+ destructiveHint: true,
1119
+ idempotentHint: true,
1120
+ openWorldHint: true
1121
+ };
1122
+ /**
1123
+ * A raw API call whose effect depends on the argument: `openapi_request` is
1124
+ * safe as a GET and destructive as a DELETE.
1125
+ *
1126
+ * Tool-level annotations cannot vary by argument, so **every** field reflects
1127
+ * the worst case:
1128
+ * - readOnlyHint false — it can DELETE. Marking it read-only would let a
1129
+ * client skip confirmation for a call that destroys a resource, the exact
1130
+ * failure this file exists to avoid.
1131
+ * - idempotentHint false — it can POST, and a retried POST may create a
1132
+ * second resource. (Not idempotent even though GET/HEAD are.)
1133
+ * - destructiveHint true — a DELETE is never recoverable.
1134
+ *
1135
+ * The per-argument nuance cannot live in the annotation; it belongs in the
1136
+ * tool description and the gates above.
1137
+ */
1138
+ const CLOUD_MUTABLE_API = {
1139
+ readOnlyHint: false,
1140
+ destructiveHint: true,
1141
+ idempotentHint: false,
1142
+ openWorldHint: true
1143
+ };
1144
+
1145
+ //#endregion
1146
+ //#region src/permission/mode.ts
1147
+ /**
1148
+ * Environment variable holding the startup default.
1149
+ *
1150
+ * Read once at module load and never re-read, so the mode cannot be changed
1151
+ * by anything the agent can influence at runtime. It is intentionally absent
1152
+ * from every tool description and from the prompt: it is an operator knob,
1153
+ * not something the model is meant to reason about.
1154
+ */
1155
+ const DEFAULT_MODE_ENV = "HW_DEFAULT_PERMISSION";
1156
+ /** The mode when nothing overrides it. */
1157
+ const FALLBACK_MODE = "read_only";
1158
+ /**
1159
+ * Parse a mode string.
1160
+ *
1161
+ * Accepts the wire spellings plus a few the operator is likely to type in an
1162
+ * environment variable. Anything unrecognised yields `undefined` rather than
1163
+ * throwing, so a typo degrades to the default instead of failing startup.
1164
+ *
1165
+ * @param value - candidate string.
1166
+ * @returns the mode, or `undefined` when unrecognised.
1167
+ */
1168
+ function parseMode(value) {
1169
+ if (value === void 0) return void 0;
1170
+ switch (value.trim().toLowerCase()) {
1171
+ case "read_only":
1172
+ case "read-only":
1173
+ case "readonly":
1174
+ case "ro": return "read_only";
1175
+ case "read_write":
1176
+ case "read-write":
1177
+ case "readwrite":
1178
+ case "rw": return "read_write";
1179
+ default: return void 0;
1180
+ }
1181
+ }
1182
+ /** Current mode. Module-level state — one server instance per connection. */
1183
+ let current = parseMode(process.env[DEFAULT_MODE_ENV]) ?? FALLBACK_MODE;
1184
+ /** The mode in effect. */
1185
+ function getMode$1() {
1186
+ return current;
1187
+ }
1188
+ /**
1189
+ * Set the mode.
1190
+ *
1191
+ * @param mode - the mode to apply.
1192
+ * @returns the previous mode, for a change log.
1193
+ */
1194
+ function setMode$1(mode) {
1195
+ const previous = current;
1196
+ current = mode;
1197
+ return previous;
1198
+ }
1199
+ /** Whether mutations are currently permitted. */
1200
+ function writesAllowed() {
1201
+ return current === "read_write";
1202
+ }
1203
+ /** Startup default, for logging and for `permission/get_mode`. */
1204
+ function defaultMode() {
1205
+ return parseMode(process.env[DEFAULT_MODE_ENV]) ?? FALLBACK_MODE;
1206
+ }
1207
+
1208
+ //#endregion
1209
+ //#region src/data-paths.ts
1210
+ /**
1211
+ * The directory holding the shipped data files.
1212
+ *
1213
+ * Resolved from this module's own URL. Because the bundle is flat, this file
1214
+ * and `lib/index.js` share a directory once compiled, so the result is
1215
+ * `<package>/lib/data` in the installed package; the test run exercises the
1216
+ * same resolution through the source tree.
1217
+ */
1218
+ const DATA_DIR = join(dirname(fileURLToPath(import.meta.url)), "data");
1219
+ /**
1220
+ * Path of one data file.
1221
+ *
1222
+ * @param name - file name inside the data directory.
1223
+ * @returns its absolute path.
1224
+ */
1225
+ function dataFile(name$1) {
1226
+ return join(DATA_DIR, name$1);
1227
+ }
1228
+ /**
1229
+ * The terraform directory: binary cache and provider plugins.
1230
+ *
1231
+ * Created on demand by the caller that writes into it. Kept as one root rather
1232
+ * than a bare `bin`/`plugins` pair so every path under it resolves through
1233
+ * `join`, and so a future artifact has an obvious home.
1234
+ *
1235
+ * @returns `<DSH_HOME>/terraform`; not created here.
1236
+ */
1237
+ function terraformRoot() {
1238
+ return join(dshHome(), "terraform");
1239
+ }
1240
+ /** The terraform binary cache: `<DSH_HOME>/terraform/bin`. */
1241
+ function terraformBinDir() {
1242
+ return join(terraformRoot(), "bin");
1243
+ }
1244
+ /** The terraform provider-plugin cache: `<DSH_HOME>/terraform/plugins`. */
1245
+ function terraformPluginDir() {
1246
+ return join(terraformRoot(), "plugins");
1247
+ }
1248
+
1249
+ //#endregion
1250
+ //#region src/permission/registry.ts
1251
+ /** Lazily-loaded compiled registry, or the failure that prevented loading. */
1252
+ let compiled;
1253
+ let loadError;
1254
+ /** Number of patterns loaded, for diagnostics. */
1255
+ let patternCount = 0;
1256
+ /**
1257
+ * Locate the registry artifact.
1258
+ *
1259
+ * Resolved through `../data-paths`, because the bundle is flat: a path written
1260
+ * relative to this module would point outside the package once everything
1261
+ * compiles into `lib/index.js`. See that module.
1262
+ *
1263
+ * @returns absolute path to the registry artifact.
1264
+ */
1265
+ function artifactPath() {
1266
+ return dataFile("permission-registry.json");
1267
+ }
1268
+ /**
1269
+ * Load and compile the registry.
1270
+ *
1271
+ * Called once. A failure is recorded, not thrown: the caller denies, which is
1272
+ * the correct behaviour for an unusable registry in read-only mode.
1273
+ *
1274
+ * @returns the compiled registry, or `undefined` when it could not be loaded.
1275
+ */
1276
+ function load() {
1277
+ if (compiled !== void 0) return compiled;
1278
+ if (loadError !== void 0) return void 0;
1279
+ let raw;
1280
+ try {
1281
+ raw = readFileSync(artifactPath(), "utf8");
1282
+ } catch (err) {
1283
+ loadError = `permission registry not found at ${artifactPath()} (${err instanceof Error ? err.message : String(err)}) — run \`npm run build-permission-registry\``;
1284
+ return void 0;
1285
+ }
1286
+ let parsed;
1287
+ try {
1288
+ parsed = JSON.parse(raw);
1289
+ } catch (err) {
1290
+ loadError = `permission registry is not valid JSON: ${err instanceof Error ? err.message : String(err)}`;
1291
+ return void 0;
1292
+ }
1293
+ if (parsed === null || typeof parsed !== "object" || parsed.methods === null || typeof parsed.methods !== "object") {
1294
+ loadError = "permission registry has an unexpected shape (no `methods`)";
1295
+ return void 0;
1296
+ }
1297
+ const result = new Map();
1298
+ let count = 0;
1299
+ for (const [method, labels] of Object.entries(parsed.methods)) {
1300
+ const byLabel = new Map();
1301
+ for (const [label, sources] of Object.entries(labels)) {
1302
+ const patterns = [];
1303
+ for (const source$1 of sources) try {
1304
+ patterns.push(new RegExp(source$1));
1305
+ } catch (err) {
1306
+ loadError = `permission registry pattern ${JSON.stringify(source$1)} did not compile: ${err instanceof Error ? err.message : String(err)}`;
1307
+ return void 0;
1308
+ }
1309
+ byLabel.set(label, patterns);
1310
+ count += patterns.length;
1311
+ }
1312
+ result.set(method, byLabel);
1313
+ }
1314
+ compiled = result;
1315
+ patternCount = count;
1316
+ return compiled;
1317
+ }
1318
+ /**
1319
+ * Host's first label — the registry's service key.
1320
+ *
1321
+ * The edition suffix is not part of a service's identity. `bss` and `bss-intl`
1322
+ * are the China-site and international-site endpoints of one product, and
1323
+ * whether an operation reads or writes does not change with the site, so both
1324
+ * normalize to the same key. The cached metadata carries only one edition for
1325
+ * most such services (it holds `bss-intl` and no `bss`), which is why the
1326
+ * normalization matters: without it a request to the other edition lands in a
1327
+ * bucket that does not exist.
1328
+ *
1329
+ * `scripts/build-permission-registry.ts` applies the same rule, so the
1330
+ * artifact's buckets and the runtime's lookups agree.
1331
+ *
1332
+ * The limit of what this rests on: the metadata cannot confirm that an
1333
+ * operation registered under one edition exists and behaves the same under the
1334
+ * other. APIExplorer returns no per-operation detail for the products where
1335
+ * this matters most (`ListApis?productshort=BSS` and `=BSSINTL` both answer
1336
+ * with zero entries), and `smn` against `smnglobal` shows the two editions can
1337
+ * carry entirely different operation sets — disjoint, 44 against 2. Those
1338
+ * cases overlap in nothing, so nothing is admitted twice; but the general
1339
+ * claim is a statement about how HuaweiCloud versions these products, not
1340
+ * something this repository measured.
1341
+ *
1342
+ * @param hostname - URL hostname.
1343
+ * @returns the first label with any edition suffix removed.
1344
+ */
1345
+ function serviceLabel(hostname) {
1346
+ const label = hostname.split(".")[0] ?? hostname;
1347
+ if (label === "") return hostname;
1348
+ for (const suffix of EDITION_SUFFIXES) if (label.endsWith(suffix) && label.length > suffix.length) return label.slice(0, -suffix.length);
1349
+ return label;
1350
+ }
1351
+ /** Suffixes naming a service's international or global endpoint. */
1352
+ const EDITION_SUFFIXES = ["-intl", "-global"];
1353
+ /** Methods admitted without a lookup — HTTP defines them as safe. */
1354
+ const SAFE_METHODS = new Set(["GET", "HEAD"]);
1355
+ /**
1356
+ * Decide whether a request may proceed in read-only mode.
1357
+ *
1358
+ * @param method - HTTP method, any case.
1359
+ * @param url - the full request URL.
1360
+ * @returns the decision, with the reason for it.
1361
+ */
1362
+ function isReadOnlyPermitted(method, url) {
1363
+ const upper = method.toUpperCase();
1364
+ if (SAFE_METHODS.has(upper)) return {
1365
+ allowed: true,
1366
+ reason: "safe-method"
1367
+ };
1368
+ const registry = load();
1369
+ if (registry === void 0) return {
1370
+ allowed: false,
1371
+ reason: "registry-unavailable"
1372
+ };
1373
+ const patterns = registry.get(upper)?.get(serviceLabel(url.hostname));
1374
+ if (patterns === void 0 || patterns.length === 0) return {
1375
+ allowed: false,
1376
+ reason: "registry-miss"
1377
+ };
1378
+ for (const pattern of patterns) if (pattern.test(url.pathname)) return {
1379
+ allowed: true,
1380
+ reason: "registry-match"
1381
+ };
1382
+ return {
1383
+ allowed: false,
1384
+ reason: "registry-miss"
1385
+ };
1386
+ }
1387
+
1388
+ //#endregion
1389
+ //#region src/permission/gate.ts
1390
+ /**
1391
+ * Tools that change cloud state without going through `signedHttp`.
1392
+ *
1393
+ * Anything reached by `signedHttp` is covered by gate 1 and must NOT be listed
1394
+ * here — listing it would refuse reads that gate 1 already admits. A new tool
1395
+ * that mutates cloud state by some other route (a new binary, a direct fetch)
1396
+ * must be added.
1397
+ */
1398
+ const CLOUD_MUTATING_TOOLS = new Set(["terraform_apply", "terraform_destroy"]);
1399
+ /** Prefix for every diagnostic this module writes. */
1400
+ const LOG_PREFIX = "permission:";
1401
+ /**
1402
+ * A refusal from the read-only gate.
1403
+ *
1404
+ * Its own type so callers can tell a policy decision from a transport failure:
1405
+ * tool code that wraps errors would otherwise report a refusal as
1406
+ * "request failed", which reads like a bug rather than a rule. `openapi.ts`
1407
+ * checks for this and returns the message verbatim.
1408
+ */
1409
+ var PermissionRefusalError = class extends Error {
1410
+ constructor(..._args) {
1411
+ super(..._args);
1412
+ this.name = "PermissionRefusalError";
1413
+ }
1414
+ };
1415
+ /**
1416
+ * Write a denial diagnostic to stderr.
1417
+ *
1418
+ * stderr, never a tool result: the model reads tool results, and the mode is
1419
+ * out of band. What the operator needs is the URL that was refused and the
1420
+ * reason — that is how a registry gap gets noticed and fixed.
1421
+ *
1422
+ * @param detail - what was denied and why.
1423
+ */
1424
+ function logDenial(detail) {
1425
+ process.stderr.write(`${LOG_PREFIX} ${detail}\n`);
1426
+ }
1427
+ /**
1428
+ * Check a tool call against read-only mode.
1429
+ *
1430
+ * @param toolName - the tool about to run.
1431
+ * @returns a message to return as a failed tool result, or `undefined` to proceed.
1432
+ */
1433
+ function denyTool(toolName) {
1434
+ if (writesAllowed()) return void 0;
1435
+ if (!CLOUD_MUTATING_TOOLS.has(toolName)) return void 0;
1436
+ logDenial(`refused tool ${toolName} (mode=${getMode$1()})`);
1437
+ return `Refused: ${toolName} changes HuaweiCloud resources, and this session is in read-only mode.\n\nRead-only mode is controlled outside this conversation — a person switches it in the client UI, and no tool or argument can change it. To run ${toolName}, ask the user to switch the session to read-write mode.\n\nOperations that only inspect state remain available: terraform_plan, terraform_state, terraform_refresh, apiexplorer, existing_resources, balance_summary, and read-only openapi_request calls.`;
1438
+ }
1439
+ /**
1440
+ * Check a signed HTTP request against read-only mode.
1441
+ *
1442
+ * @param method - HTTP method.
1443
+ * @param url - the full request URL.
1444
+ * @returns a message describing the refusal, or `undefined` to proceed.
1445
+ */
1446
+ function denyHttp(method, url) {
1447
+ if (writesAllowed()) return void 0;
1448
+ const decision = isReadOnlyPermitted(method, url);
1449
+ if (decision.allowed) return void 0;
1450
+ logDenial(`refused ${method.toUpperCase()} ${url.hostname}${url.pathname} (mode=${getMode$1()}, reason=${decision.reason})`);
1451
+ switch (decision.reason) {
1452
+ case "registry-unavailable": return "Refused: this session is in read-only mode and the permission registry could not be loaded, so the request cannot be cleared. GET and HEAD requests still work.\n\nReinstall this plugin; the packaged build is missing its registry artifact.";
1453
+ case "registry-miss":
1454
+ default: return `Refused: ${method.toUpperCase()} ${url.hostname}${url.pathname} is not a known read-only operation, and this session is in read-only mode.\n\nRead-only mode permits GET and HEAD, plus operations the API catalog marks as queries. It is controlled outside this conversation — a person switches it in the client UI, and no tool or argument can change it. If this operation only reads data, ask the user to switch the session to read-write mode; if it modifies or deletes resources, it must stay refused.`;
1455
+ }
1456
+ }
1457
+
1458
+ //#endregion
1459
+ //#region src/tools/errors.ts
1460
+ /**
1461
+ * A successful tool result: text content (and optional structured content).
1462
+ *
1463
+ * Tools return `content` arrays. `isError` is omitted
1464
+ * (defaults to false) on success.
1465
+ */
1466
+ function ok(text, structured) {
1467
+ const content = [{
1468
+ type: "text",
1469
+ text
1470
+ }];
1471
+ if (structured !== void 0) return {
1472
+ content,
1473
+ structuredContent: structured
1474
+ };
1475
+ return { content };
1476
+ }
1477
+ /**
1478
+ * A failed tool result: `isError: true` + text content.
1479
+ *
1480
+ * All tool failures return this shape. The model
1481
+ * checks `isError`, reads `content[0].text` for the diagnostic.
1482
+ */
1483
+ function fail(message) {
1484
+ return {
1485
+ content: [{
1486
+ type: "text",
1487
+ text: message
1488
+ }],
1489
+ isError: true
1490
+ };
1491
+ }
1492
+ /**
1493
+ * Wrap an async tool handler so thrown errors become `fail()` results
1494
+ * instead of propagating as JSON-RPC internal errors.
1495
+ *
1496
+ * Tool handlers throw for unexpected failures (network, filesystem, bugs).
1497
+ * The message belongs in `content[0].text`, where the model reads and acts on
1498
+ * it — a thrown stack trace that never reaches the result tells the model
1499
+ * nothing it can use.
1500
+ *
1501
+ * The read-only gate runs first, before the handler body: a refused call must
1502
+ * not reach any part of its implementation, including argument validation that
1503
+ * might touch the filesystem. A tool declared in `CLOUD_MUTATING_TOOLS` is
1504
+ * refused here in read-only mode and never starts.
1505
+ */
1506
+ function guard(fn, toolName) {
1507
+ return async (args, ctx) => {
1508
+ if (toolName !== void 0) {
1509
+ const refusal = denyTool(toolName);
1510
+ if (refusal !== void 0) return fail(refusal);
1511
+ }
1512
+ try {
1513
+ return await fn(args, ctx);
1514
+ } catch (err) {
1515
+ const msg = err instanceof Error ? err.message : String(err);
1516
+ return fail(msg);
1517
+ }
1518
+ };
1519
+ }
1520
+
1521
+ //#endregion
1522
+ //#region src/version.ts
1523
+ /**
1524
+ * The version recorded in a deployment's `.deployment.json`.
1525
+ *
1526
+ * A deployment snapshot names the code that wrote it, so an old workspace can
1527
+ * be traced to the path that produced it. This plugin's version is the honest
1528
+ * value: there is no separate build to name.
1529
+ *
1530
+ * @module @huaweidevtools/aishell-dsh-deploy/version
1531
+ */
1532
+ /**
1533
+ * What a snapshot records as `server_version`.
1534
+ *
1535
+ * The field name is fixed by `.deployment.json`'s published shape — workspaces
1536
+ * written by earlier releases carry it — so it is kept even though there is no
1537
+ * server.
1538
+ */
1539
+ const SERVER_VERSION = "aishell-deploy 0.1.0";
1540
+
1541
+ //#endregion
1542
+ //#region src/deployment-state.ts
1543
+ const DEPLOYMENT_STATE_FILE = ".deployment.json";
1544
+ /** Check whether a directory is a deployment (has .deployment.json). */
1545
+ async function isDeploymentDir(dir) {
1546
+ try {
1547
+ await readFile(join(dir, DEPLOYMENT_STATE_FILE), "utf8");
1548
+ return true;
1549
+ } catch {
1550
+ return false;
1551
+ }
1552
+ }
1553
+ /** Create a deployment directory + initial .deployment.json. Refuse if non-empty. */
1554
+ async function ensureDeployment(dir) {
1555
+ let entries = [];
1556
+ try {
1557
+ entries = await readdir(dir);
1558
+ } catch {}
1559
+ if (entries.length > 0) throw new Error("directory is not empty and not a deployment");
1560
+ await mkdir(dir, { recursive: true });
1561
+ const now = new Date().toISOString();
1562
+ const snapshot$1 = {
1563
+ created_at: now,
1564
+ created_with: "aishell-deploy",
1565
+ server_version: SERVER_VERSION,
1566
+ status: {
1567
+ networking_written: false,
1568
+ cost_written: false,
1569
+ applied: false,
1570
+ destroyed: false,
1571
+ last_operation: "create_deployment",
1572
+ last_operation_at: now
1573
+ }
1574
+ };
1575
+ await writeFile(join(dir, DEPLOYMENT_STATE_FILE), JSON.stringify(snapshot$1, null, 2));
1576
+ return snapshot$1;
1577
+ }
1578
+ /** Update the status snapshot (called by other modules after state changes). */
1579
+ async function updateSnapshot(dir, patch) {
1580
+ const raw = await readFile(join(dir, DEPLOYMENT_STATE_FILE), "utf8");
1581
+ const snap = JSON.parse(raw);
1582
+ snap.status = {
1583
+ ...snap.status,
1584
+ ...patch,
1585
+ last_operation_at: new Date().toISOString()
1586
+ };
1587
+ await writeFile(join(dir, DEPLOYMENT_STATE_FILE), JSON.stringify(snap, null, 2));
1588
+ }
1589
+ /**
1590
+ * Backfill the account field in .deployment.json if it's empty and the
1591
+ * server is now authenticated (§4.3: "后续 auth 后 server 操作该 deployment
1592
+ * 时补写").
1593
+ *
1594
+ * Called by runTerraform after resolveTerraformEnv succeeds. The account
1595
+ * identity was resolved at auth time (GET /v3/projects → domain_id + name)
1596
+ * and stored alongside the credentials; runTerraform reads it via
1597
+ * loadAccount() — no IAM re-query here. This is a stateless write: the
1598
+ * account is only backfilled once (idempotent — already-filled is a no-op).
1599
+ *
1600
+ * This is intentionally a no-op when:
1601
+ * - the deployment has no .deployment.json (not a deployment dir)
1602
+ * - account is already filled (idempotent)
1603
+ * - loadAccount returns null (not authenticated, or payload predates
1604
+ * IAM verification wiring)
1605
+ */
1606
+ async function backfillAccount(dir, account) {
1607
+ let snap;
1608
+ try {
1609
+ const raw = await readFile(join(dir, DEPLOYMENT_STATE_FILE), "utf8");
1610
+ snap = JSON.parse(raw);
1611
+ } catch {
1612
+ return;
1613
+ }
1614
+ if (snap.account) return;
1615
+ snap.account = account;
1616
+ await writeFile(join(dir, DEPLOYMENT_STATE_FILE), JSON.stringify(snap, null, 2));
1617
+ }
1618
+ /**
1619
+ * Count resources recorded in terraform.tfstate (0 = clean / never applied).
1620
+ *
1621
+ * This is the count RECORDED in the state file, NOT the live count on the
1622
+ * cloud — tfstate may be stale if resources were changed outside terraform.
1623
+ * For the live count, run terraform_refresh first. Used by delete_deployment
1624
+ * and terraform_destroy to guard against destroying/emptying a deployment
1625
+ * that still has recorded resources.
1626
+ */
1627
+ async function stateRecordedResourceCount(dir) {
1628
+ try {
1629
+ const raw = await readFile(join(dir, "terraform.tfstate"), "utf8");
1630
+ const state = JSON.parse(raw);
1631
+ return state.resources?.length ?? 0;
1632
+ } catch {
1633
+ return 0;
1634
+ }
1635
+ }
1636
+ /** Remove the deployment directory. */
1637
+ async function removeDeploymentDir(dir) {
1638
+ await rm(dir, {
1639
+ recursive: true,
1640
+ force: true
1641
+ });
1642
+ }
1643
+
1644
+ //#endregion
1645
+ //#region src/tools/deployment.ts
1646
+ /**
1647
+ * create_deployment + delete_deployment (§3.2).
1648
+ *
1649
+ * create: create or reuse a deployment workspace directory, writing
1650
+ * .deployment.json (state snapshot). If the dir exists and is a deployment,
1651
+ * return existing info + status. If it exists but is non-empty and not a
1652
+ * deployment, refuse.
1653
+ *
1654
+ * delete: refuse if the deployment still has live cloud resources (check
1655
+ * terraform.tfstate); if clean, remove the directory.
1656
+ */
1657
+ function registerDeploymentTools(registrar) {
1658
+ registrar.registerTool("create_deployment", {
1659
+ title: "Create deployment",
1660
+ description: "Create or reuse a deployment workspace directory. If the directory does not exist, create it and write .deployment.json (state snapshot). Does NOT create networking.json/cost.json placeholders. If the directory exists but is not a deployment (non-empty, no .deployment.json), return an error.",
1661
+ annotations: LOCAL_WRITE,
1662
+ inputSchema: z.object({ deployment: deploymentParam })
1663
+ }, guard(async (args) => handleCreate(args.deployment)));
1664
+ registrar.registerTool("delete_deployment", {
1665
+ title: "Delete deployment",
1666
+ description: "Delete a deployment workspace directory. Refuses if the deployment still has live cloud resources — checks terraform.tfstate; if resources exist, run terraform_destroy first. If no resources, removes the directory.",
1667
+ annotations: LOCAL_DESTRUCTIVE,
1668
+ inputSchema: z.object({ deployment: deploymentParam })
1669
+ }, guard(async (args) => handleDelete(args.deployment)));
1670
+ }
1671
+ async function handleCreate(dir) {
1672
+ if (await isDeploymentDir(dir)) {
1673
+ const statePath = `${dir}/${DEPLOYMENT_STATE_FILE}`;
1674
+ try {
1675
+ const raw = await readFile(statePath, "utf8");
1676
+ const snapshot$1 = JSON.parse(raw);
1677
+ return ok(JSON.stringify({
1678
+ deployment: dir,
1679
+ status: "existing",
1680
+ snapshot: snapshot$1
1681
+ }));
1682
+ } catch {
1683
+ return fail(`failed to read ${statePath}`);
1684
+ }
1685
+ }
1686
+ try {
1687
+ const snapshot$1 = await ensureDeployment(dir);
1688
+ return ok(JSON.stringify({
1689
+ deployment: dir,
1690
+ status: "created",
1691
+ snapshot: snapshot$1
1692
+ }));
1693
+ } catch (err) {
1694
+ const msg = err instanceof Error ? err.message : String(err);
1695
+ if (msg.includes("not empty")) return fail("directory is not empty and not a deployment");
1696
+ return fail(`create_deployment failed: ${msg}`);
1697
+ }
1698
+ }
1699
+ async function handleDelete(dir) {
1700
+ if (!await isDeploymentDir(dir)) return fail("not a deployment directory (no .deployment.json)");
1701
+ const recordedCount = await stateRecordedResourceCount(dir);
1702
+ if (recordedCount > 0) return fail(`deployment has ${recordedCount} resources recorded in tfstate — run terraform_destroy first`);
1703
+ try {
1704
+ await removeDeploymentDir(dir);
1705
+ return ok(JSON.stringify({
1706
+ deployment: dir,
1707
+ status: "deleted"
1708
+ }));
1709
+ } catch (err) {
1710
+ return fail(`delete_deployment failed: ${err instanceof Error ? err.message : String(err)}`);
1711
+ }
1712
+ }
1713
+
1714
+ //#endregion
1715
+ //#region src/schemas/networking.ts
1716
+ const cidrRegex = /^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/;
1717
+ const cidr = z.string().regex(cidrRegex, "invalid CIDR");
1718
+ const az = z.string().min(1);
1719
+ const routeSchema = z.object({
1720
+ destination: cidr,
1721
+ next_hop_type: z.enum([
1722
+ "nat",
1723
+ "vpn",
1724
+ "peering",
1725
+ "internet"
1726
+ ]),
1727
+ next_hop: z.string().min(1)
1728
+ });
1729
+ const routeTableSchema = z.object({
1730
+ name: z.string().min(1),
1731
+ routes: z.array(routeSchema)
1732
+ });
1733
+ const secgroupRuleSchema = z.object({
1734
+ direction: z.enum(["ingress", "egress"]),
1735
+ protocol: z.enum([
1736
+ "tcp",
1737
+ "udp",
1738
+ "icmp",
1739
+ "icmpv6",
1740
+ "any"
1741
+ ]).describe("HuaweiCloud provider supports tcp/udp/icmp/icmpv6. \"any\" means no protocol filter — in .tf omit the protocol argument (provider default)."),
1742
+ ports: z.string().min(1),
1743
+ source: z.string().optional(),
1744
+ destination: z.string().optional(),
1745
+ description: z.string().optional()
1746
+ });
1747
+ const secgroupSchema = z.object({
1748
+ name: z.string().min(1),
1749
+ rules: z.array(secgroupRuleSchema).min(1)
1750
+ });
1751
+ const subnetSchema = z.object({
1752
+ name: z.string().min(1),
1753
+ cidr,
1754
+ az,
1755
+ route_table: z.string().optional()
1756
+ });
1757
+ const topologySchema = z.object({
1758
+ vpc: z.object({
1759
+ name: z.string().min(1),
1760
+ cidr
1761
+ }),
1762
+ subnets: z.array(subnetSchema).min(1),
1763
+ route_tables: z.array(routeTableSchema).optional(),
1764
+ security_groups: z.array(secgroupSchema).min(1)
1765
+ });
1766
+ const eipAttachSchema = z.object({
1767
+ kind: z.enum([
1768
+ "instance",
1769
+ "port",
1770
+ "nat"
1771
+ ]),
1772
+ target: z.string().min(1)
1773
+ });
1774
+ const eipSchema = z.object({
1775
+ id: z.string().min(1),
1776
+ bandwidth: z.string().min(1),
1777
+ attached_to: eipAttachSchema
1778
+ });
1779
+ const natSchema = z.object({
1780
+ id: z.string().min(1),
1781
+ subnet: z.string().min(1),
1782
+ snat_eip: z.string().min(1),
1783
+ snat_source_cidr: z.string().min(1)
1784
+ });
1785
+ const listenerSchema = z.object({
1786
+ port: z.number().int().min(1).max(65535),
1787
+ protocol: z.enum([
1788
+ "http",
1789
+ "https",
1790
+ "tcp",
1791
+ "udp"
1792
+ ])
1793
+ });
1794
+ const memberSchema = z.object({
1795
+ target: z.string().min(1),
1796
+ port: z.number().int().min(1).max(65535)
1797
+ });
1798
+ const loadbalancerSchema = z.object({
1799
+ id: z.string().min(1),
1800
+ subnet: z.string().min(1),
1801
+ vip_type: z.enum(["internal", "external"]),
1802
+ listeners: z.array(listenerSchema).min(1),
1803
+ members: z.array(memberSchema).min(1)
1804
+ });
1805
+ const networkObjectsSchema = z.object({
1806
+ eips: z.array(eipSchema).optional(),
1807
+ nat_gateways: z.array(natSchema).optional(),
1808
+ loadbalancers: z.array(loadbalancerSchema).optional()
1809
+ });
1810
+ const componentSchema = z.object({
1811
+ id: z.string().min(1),
1812
+ type: z.string().regex(/^huaweicloud_/, "type must start with huaweicloud_"),
1813
+ subnet: z.string().optional(),
1814
+ security_groups: z.array(z.string()).optional(),
1815
+ instance: z.string().optional()
1816
+ });
1817
+ const NetworkingSchema = z.object({
1818
+ $schema: z.string().optional(),
1819
+ topology: topologySchema,
1820
+ network_objects: networkObjectsSchema.optional(),
1821
+ components: z.array(componentSchema).min(1)
1822
+ }).superRefine((data, ctx) => {
1823
+ validateReferences(data, ctx);
1824
+ });
1825
+ function indexRefs(data) {
1826
+ const refs = {
1827
+ subnetNames: new Set(),
1828
+ secgroupNames: new Set(),
1829
+ routeTableNames: new Set(),
1830
+ eipIds: new Set(),
1831
+ natIds: new Set(),
1832
+ componentIds: new Set()
1833
+ };
1834
+ for (const s of data.topology.subnets) refs.subnetNames.add(s.name);
1835
+ for (const sg of data.topology.security_groups) refs.secgroupNames.add(sg.name);
1836
+ for (const rt of data.topology.route_tables ?? []) refs.routeTableNames.add(rt.name);
1837
+ for (const e of data.network_objects?.eips ?? []) refs.eipIds.add(e.id);
1838
+ for (const n of data.network_objects?.nat_gateways ?? []) refs.natIds.add(n.id);
1839
+ for (const c of data.components) refs.componentIds.add(c.id);
1840
+ return refs;
1841
+ }
1842
+ function validateReferences(data, ctx) {
1843
+ const refs = indexRefs(data);
1844
+ const seenSubnets = new Set();
1845
+ for (const s of data.topology.subnets) {
1846
+ if (seenSubnets.has(s.name)) ctx.addIssue({
1847
+ code: z.ZodIssueCode.custom,
1848
+ message: `duplicate subnet name: ${s.name}`,
1849
+ path: ["topology", "subnets"]
1850
+ });
1851
+ seenSubnets.add(s.name);
1852
+ if (s.route_table && !refs.routeTableNames.has(s.route_table)) ctx.addIssue({
1853
+ code: z.ZodIssueCode.custom,
1854
+ message: `subnet ${s.name} references unknown route_table: ${s.route_table}`,
1855
+ path: ["topology", "subnets"]
1856
+ });
1857
+ }
1858
+ const seenSg = new Set();
1859
+ for (const sg of data.topology.security_groups) {
1860
+ if (seenSg.has(sg.name)) ctx.addIssue({
1861
+ code: z.ZodIssueCode.custom,
1862
+ message: `duplicate security_group name: ${sg.name}`,
1863
+ path: ["topology", "security_groups"]
1864
+ });
1865
+ seenSg.add(sg.name);
1866
+ for (const [i, rule] of sg.rules.entries()) {
1867
+ if (rule.direction === "ingress" && !rule.source) ctx.addIssue({
1868
+ code: z.ZodIssueCode.custom,
1869
+ message: `ingress rule in ${sg.name} missing source`,
1870
+ path: [
1871
+ "topology",
1872
+ "security_groups",
1873
+ i,
1874
+ "rules"
1875
+ ]
1876
+ });
1877
+ if (rule.direction === "egress" && !rule.destination) ctx.addIssue({
1878
+ code: z.ZodIssueCode.custom,
1879
+ message: `egress rule in ${sg.name} missing destination`,
1880
+ path: [
1881
+ "topology",
1882
+ "security_groups",
1883
+ i,
1884
+ "rules"
1885
+ ]
1886
+ });
1887
+ }
1888
+ }
1889
+ for (const [i, e] of (data.network_objects?.eips ?? []).entries()) if (e.attached_to.kind === "instance" || e.attached_to.kind === "port") {
1890
+ if (!refs.componentIds.has(e.attached_to.target)) ctx.addIssue({
1891
+ code: z.ZodIssueCode.custom,
1892
+ message: `eip ${e.id} attached_to.target references unknown component: ${e.attached_to.target}`,
1893
+ path: [
1894
+ "network_objects",
1895
+ "eips",
1896
+ i
1897
+ ]
1898
+ });
1899
+ } else if (e.attached_to.kind === "nat") {
1900
+ if (!refs.natIds.has(e.attached_to.target)) ctx.addIssue({
1901
+ code: z.ZodIssueCode.custom,
1902
+ message: `eip ${e.id} attached_to.target references unknown nat_gateway: ${e.attached_to.target}`,
1903
+ path: [
1904
+ "network_objects",
1905
+ "eips",
1906
+ i
1907
+ ]
1908
+ });
1909
+ }
1910
+ for (const [i, n] of (data.network_objects?.nat_gateways ?? []).entries()) {
1911
+ if (!refs.eipIds.has(n.snat_eip)) ctx.addIssue({
1912
+ code: z.ZodIssueCode.custom,
1913
+ message: `nat ${n.id} snat_eip references unknown eip: ${n.snat_eip}`,
1914
+ path: [
1915
+ "network_objects",
1916
+ "nat_gateways",
1917
+ i
1918
+ ]
1919
+ });
1920
+ if (!refs.subnetNames.has(n.subnet)) ctx.addIssue({
1921
+ code: z.ZodIssueCode.custom,
1922
+ message: `nat ${n.id} subnet references unknown subnet: ${n.subnet}`,
1923
+ path: [
1924
+ "network_objects",
1925
+ "nat_gateways",
1926
+ i
1927
+ ]
1928
+ });
1929
+ }
1930
+ for (const [i, lb] of (data.network_objects?.loadbalancers ?? []).entries()) {
1931
+ if (!refs.subnetNames.has(lb.subnet)) ctx.addIssue({
1932
+ code: z.ZodIssueCode.custom,
1933
+ message: `lb ${lb.id} subnet references unknown subnet: ${lb.subnet}`,
1934
+ path: [
1935
+ "network_objects",
1936
+ "loadbalancers",
1937
+ i
1938
+ ]
1939
+ });
1940
+ for (const [j, m] of lb.members.entries()) if (!refs.componentIds.has(m.target)) ctx.addIssue({
1941
+ code: z.ZodIssueCode.custom,
1942
+ message: `lb ${lb.id} member target references unknown component: ${m.target}`,
1943
+ path: [
1944
+ "network_objects",
1945
+ "loadbalancers",
1946
+ i,
1947
+ "members",
1948
+ j
1949
+ ]
1950
+ });
1951
+ }
1952
+ const seenComp = new Set();
1953
+ for (const [i, c] of data.components.entries()) {
1954
+ if (seenComp.has(c.id)) ctx.addIssue({
1955
+ code: z.ZodIssueCode.custom,
1956
+ message: `duplicate component id: ${c.id}`,
1957
+ path: ["components", i]
1958
+ });
1959
+ seenComp.add(c.id);
1960
+ if (c.subnet && !refs.subnetNames.has(c.subnet)) ctx.addIssue({
1961
+ code: z.ZodIssueCode.custom,
1962
+ message: `component ${c.id} subnet references unknown subnet: ${c.subnet}`,
1963
+ path: ["components", i]
1964
+ });
1965
+ for (const sg of c.security_groups ?? []) if (!refs.secgroupNames.has(sg)) ctx.addIssue({
1966
+ code: z.ZodIssueCode.custom,
1967
+ message: `component ${c.id} references unknown security_group: ${sg}`,
1968
+ path: ["components", i]
1969
+ });
1970
+ if (c.type === "huaweicloud_compute_interface_attach" && !c.instance) ctx.addIssue({
1971
+ code: z.ZodIssueCode.custom,
1972
+ message: `compute_interface_attach ${c.id} missing instance (host ECS)`,
1973
+ path: ["components", i]
1974
+ });
1975
+ }
1976
+ }
1977
+
1978
+ //#endregion
1979
+ //#region src/tools/networking.ts
1980
+ /**
1981
+ * update_networking.
1982
+ *
1983
+ * inputSchema uses NetworkingSchema directly — the zod-to-JSON-Schema
1984
+ * conversion preserves the full structure (topology/components/network_objects),
1985
+ * so the model sees exactly what fields to pass. superRefine (A-layer
1986
+ * reference consistency) is runtime validation only; it does NOT block the
1987
+ * JSON Schema export (verified: z.toJSONSchema emits the object shape
1988
+ * regardless of superRefine).
1989
+ */
1990
+ function registerNetworkingTool(registrar) {
1991
+ registrar.registerTool("update_networking", {
1992
+ title: "Write networking design",
1993
+ description: "Write or update networking.json for a deployment. Three layers: topology (VPC/subnets/route_tables/security_groups), network_objects (eips/nat_gateways/loadbalancers), components (resource identity + optional network attach). Design this before writing .tf — it is the physical networking contract. Validates structure and A-layer reference consistency (id uniqueness, subnet/sg/eip/nat refs).",
1994
+ annotations: LOCAL_WRITE,
1995
+ inputSchema: z.object({
1996
+ deployment: deploymentParam,
1997
+ networking: NetworkingSchema
1998
+ })
1999
+ }, guard(async (args) => {
2000
+ const parsed = NetworkingSchema.safeParse(args.networking);
2001
+ if (!parsed.success) return fail(`schema validation: ${parsed.error.message}`);
2002
+ try {
2003
+ await writeFile(join(args.deployment, "networking.json"), JSON.stringify(parsed.data, null, 2));
2004
+ await updateSnapshot(args.deployment, {
2005
+ networking_written: true,
2006
+ last_operation: "update_networking"
2007
+ });
2008
+ return ok(JSON.stringify({
2009
+ deployment: args.deployment,
2010
+ written: true,
2011
+ note: "IMPORTANT 自检:你是否已经把组网拓扑图展示给用户、并取得用户明确同意?若没有,禁止推进后续任何步骤(update_cost / 写 .tf / terraform_*)。拓扑须含 VPC + 子网 CIDR + 安全组规则 + network_objects 连接关系,优先 HTML 渲染。用户有修改意见则继续调整,直到用户明确采纳后再次调用该工具。"
2012
+ }));
2013
+ } catch (err) {
2014
+ return fail(`update_networking failed: ${err instanceof Error ? err.message : String(err)}`);
2015
+ }
2016
+ }));
2017
+ }
2018
+
2019
+ //#endregion
2020
+ //#region src/schemas/cost.ts
2021
+ const chargingSchema = z.object({
2022
+ mode: z.enum([
2023
+ "prepaid",
2024
+ "on-demand",
2025
+ "bandwidth",
2026
+ "traffic"
2027
+ ]),
2028
+ period: z.number().int().positive().optional(),
2029
+ period_unit: z.enum(["month", "year"]).optional(),
2030
+ auto_renew: z.boolean().optional(),
2031
+ share_type: z.enum([
2032
+ "PER",
2033
+ "WHOLE",
2034
+ "STANDARD"
2035
+ ]).optional(),
2036
+ size: z.number().int().positive().optional()
2037
+ }).superRefine((c, ctx) => {
2038
+ if (c.mode === "prepaid") {
2039
+ if (c.period === void 0) ctx.addIssue({
2040
+ code: z.ZodIssueCode.custom,
2041
+ message: "prepaid charging requires period",
2042
+ path: ["period"]
2043
+ });
2044
+ if (c.period_unit === void 0) ctx.addIssue({
2045
+ code: z.ZodIssueCode.custom,
2046
+ message: "prepaid charging requires period_unit",
2047
+ path: ["period_unit"]
2048
+ });
2049
+ }
2050
+ });
2051
+ const costItemSchema = z.object({
2052
+ resource: z.string().min(1),
2053
+ source: z.enum(["reuse", "new"]),
2054
+ existing_id: z.string().optional(),
2055
+ spec: z.string().min(1),
2056
+ charging: chargingSchema,
2057
+ monthly: z.union([z.number(), z.literal(null)])
2058
+ });
2059
+ const CostSchema = z.object({
2060
+ $schema: z.string().optional(),
2061
+ currency: z.enum(["CNY", "USD"]),
2062
+ items: z.array(costItemSchema).min(1),
2063
+ total_monthly: z.union([z.number(), z.literal(null)]).optional(),
2064
+ tf_hash: z.union([z.string(), z.literal(null)]).optional(),
2065
+ estimated_at: z.string().optional()
2066
+ }).superRefine((data, ctx) => {
2067
+ for (const [i, item] of data.items.entries()) if (item.source === "reuse" && !item.existing_id) ctx.addIssue({
2068
+ code: z.ZodIssueCode.custom,
2069
+ message: `reuse item ${item.resource} requires existing_id`,
2070
+ path: [
2071
+ "items",
2072
+ i,
2073
+ "existing_id"
2074
+ ]
2075
+ });
2076
+ });
2077
+
2078
+ //#endregion
2079
+ //#region src/tools/cost.ts
2080
+ /**
2081
+ * update_cost.
2082
+ *
2083
+ * inputSchema uses CostSchema directly — the zod-to-JSON-Schema conversion
2084
+ * preserves the full structure (currency/items/charging), so the model sees
2085
+ * exactly what fields to pass. superRefine (reuse→existing_id check) is
2086
+ * runtime validation only; it does NOT block the JSON Schema export.
2087
+ *
2088
+ * Cross-file reference check (§5.2 A-layer): items[].resource must reference
2089
+ * a component id in networking.json. This CANNOT be done in the zod schema
2090
+ * (it validates one file; the reference target is another file). It's done
2091
+ * in the handler after schema parse succeeds.
2092
+ */
2093
+ function registerCostTool(registrar) {
2094
+ registrar.registerTool("update_cost", {
2095
+ title: "Write cost estimate",
2096
+ description: "Write or update cost.json for a deployment. Records spec + charging + price + source (reuse/new) per component. Server validates structure + A-layer refs (resource → networking components), auto-computes total_monthly (sum of new items only), sets tf_hash=null, writes estimated_at. Called BEFORE writing .tf (cost.json precedes .tf).",
2097
+ annotations: LOCAL_WRITE,
2098
+ inputSchema: z.object({
2099
+ deployment: deploymentParam,
2100
+ cost: CostSchema
2101
+ })
2102
+ }, guard(async (args) => {
2103
+ const parsed = CostSchema.safeParse(args.cost);
2104
+ if (!parsed.success) return fail(`schema validation: ${parsed.error.message}`);
2105
+ const cost = parsed.data;
2106
+ const refErrors = await validateResourceRefs(args.deployment, cost.items);
2107
+ if (refErrors.length > 0) return fail(`schema validation: ${refErrors.join("; ")}`);
2108
+ cost.total_monthly = computeTotalMonthly(cost.items);
2109
+ cost.tf_hash = null;
2110
+ cost.estimated_at = new Date().toISOString();
2111
+ try {
2112
+ await writeFile(join(args.deployment, "cost.json"), JSON.stringify(cost, null, 2));
2113
+ await updateSnapshot(args.deployment, {
2114
+ cost_written: true,
2115
+ last_operation: "update_cost"
2116
+ });
2117
+ return ok(JSON.stringify({
2118
+ deployment: args.deployment,
2119
+ written: true,
2120
+ total_monthly: cost.total_monthly
2121
+ }));
2122
+ } catch (err) {
2123
+ return fail(`update_cost failed: ${err instanceof Error ? err.message : String(err)}`);
2124
+ }
2125
+ }));
2126
+ }
2127
+ /**
2128
+ * Validate that every items[].resource references a component id in
2129
+ * networking.json. Returns a list of error messages (empty = ok).
2130
+ *
2131
+ * If networking.json doesn't exist, that's not a cost-schema error — it's
2132
+ * an ordering error (update_networking should be called first). We return
2133
+ * a single error telling the client to call update_networking first.
2134
+ */
2135
+ async function validateResourceRefs(deployment, items) {
2136
+ let networking;
2137
+ try {
2138
+ const raw = await readFile(join(deployment, "networking.json"), "utf8");
2139
+ networking = JSON.parse(raw);
2140
+ } catch {
2141
+ return ["networking.json not found — call update_networking first (cost.json items[].resource must reference networking components or network_objects)"];
2142
+ }
2143
+ const validIds = new Set();
2144
+ for (const c of networking.components ?? []) validIds.add(c.id);
2145
+ for (const e of networking.network_objects?.eips ?? []) validIds.add(e.id);
2146
+ for (const n of networking.network_objects?.nat_gateways ?? []) validIds.add(n.id);
2147
+ for (const l of networking.network_objects?.loadbalancers ?? []) validIds.add(l.id);
2148
+ if (validIds.size === 0) return ["networking.json has no components or network_objects — cost.json items[].resource has nothing to reference"];
2149
+ const errors = [];
2150
+ for (const item of items) {
2151
+ const base = item.resource.split(".")[0] ?? item.resource;
2152
+ if (!validIds.has(item.resource) && !validIds.has(base)) errors.push(`items[].resource "${item.resource}" references unknown component/network_object (not in networking.json)`);
2153
+ }
2154
+ return errors;
2155
+ }
2156
+ /** Sum monthly of new items only (§2.2). null treated as 0; all-null → null. */
2157
+ function computeTotalMonthly(items) {
2158
+ const newItems = items.filter((i) => i.source === "new");
2159
+ let allNull = true;
2160
+ const sum = newItems.reduce((acc, i) => {
2161
+ if (i.monthly === null) return acc;
2162
+ allNull = false;
2163
+ return acc + i.monthly;
2164
+ }, 0);
2165
+ return allNull ? null : sum;
2166
+ }
2167
+
2168
+ //#endregion
2169
+ //#region src/auth-signer.ts
2170
+ /**
2171
+ * Sign a HuaweiCloud API request. Mutates headers in place to add
2172
+ * Authorization, X-Sdk-Date, and (if STS) X-Security-Token.
2173
+ *
2174
+ * @see https://support.huaweicloud.com/api-iam/iam_30_0001.html
2175
+ */
2176
+ function signRequest(params) {
2177
+ const { method, url, headers, body, ak, sk } = params;
2178
+ const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
2179
+ const sdkDate = timestamp.replace(/[-:]/g, "");
2180
+ headers["X-Sdk-Date"] = sdkDate;
2181
+ const bodyHash = sha256Hex(body);
2182
+ const headerEntries = Object.entries(headers).map(([k, v]) => [k.toLowerCase().trim(), v.trim()]).sort(([a], [b]) => a.localeCompare(b));
2183
+ const canonicalHeaders = headerEntries.map(([k, v]) => `${k}:${v}\n`).join("");
2184
+ const signedHeaders = headerEntries.map(([k]) => k).join(";");
2185
+ const trimmed = url.pathname.replace(/^\/+|\/+$/g, "");
2186
+ const canonicalUri = trimmed === "" ? "/" : "/" + trimmed.split("/").map(encodeRfc3986).join("/") + "/";
2187
+ const canonicalQueryString = canonicalQuery(url.searchParams);
2188
+ const canonicalRequest = [
2189
+ method.toUpperCase(),
2190
+ canonicalUri,
2191
+ canonicalQueryString,
2192
+ canonicalHeaders,
2193
+ signedHeaders,
2194
+ bodyHash
2195
+ ].join("\n");
2196
+ const stringToSign = [
2197
+ "SDK-HMAC-SHA256",
2198
+ sdkDate,
2199
+ sha256Hex(canonicalRequest)
2200
+ ].join("\n");
2201
+ const signature = createHmac("sha256", sk).update(stringToSign).digest("hex");
2202
+ const auth = [
2203
+ `SDK-HMAC-SHA256 Access=${ak}`,
2204
+ `SignedHeaders=${signedHeaders}`,
2205
+ `Signature=${signature}`
2206
+ ].join(", ");
2207
+ headers["Authorization"] = auth;
2208
+ if (params.securityToken) headers["X-Security-Token"] = params.securityToken;
2209
+ return {
2210
+ method,
2211
+ url,
2212
+ headers,
2213
+ body
2214
+ };
2215
+ }
2216
+ /** SHA-256 hex digest of a string. */
2217
+ function sha256Hex(s) {
2218
+ return createHash("sha256").update(s, "utf8").digest("hex");
2219
+ }
2220
+ /** Canonical query string: keys sorted, RFC 3986 encoded, key=value joined by &. */
2221
+ function canonicalQuery(params) {
2222
+ const pairs = [];
2223
+ for (const [k, v] of params.entries()) pairs.push([encodeRfc3986(k), encodeRfc3986(v)]);
2224
+ pairs.sort(([a], [b]) => a.localeCompare(b));
2225
+ return pairs.map(([k, v]) => `${k}=${v}`).join("&");
2226
+ }
2227
+ function encodeRfc3986(s) {
2228
+ return encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2229
+ }
2230
+
2231
+ //#endregion
2232
+ //#region src/auth-obs-signer.ts
2233
+ /**
2234
+ * Sub-resources that participate in CanonicalizedResource.
2235
+ *
2236
+ * Only query params in this whitelist enter the signature; all others are
2237
+ * ignored by the OBS server's canonical-resource construction. This is NOT
2238
+ * optional — including a non-whitelisted param would mismatch the service's
2239
+ * own StringToSign and produce 403 SignatureDoesNotMatch.
2240
+ *
2241
+ * Copied verbatim from esdk-obs-nodejs utils.js line 145-224.
2242
+ */
2243
+ const ALLOWED_RESOURCE_PARAMETER_NAMES = new Set([
2244
+ "acl",
2245
+ "backtosource",
2246
+ "policy",
2247
+ "torrent",
2248
+ "logging",
2249
+ "location",
2250
+ "storageinfo",
2251
+ "quota",
2252
+ "storageclass",
2253
+ "storagepolicy",
2254
+ "requestpayment",
2255
+ "versions",
2256
+ "versioning",
2257
+ "versionid",
2258
+ "uploads",
2259
+ "uploadid",
2260
+ "partnumber",
2261
+ "website",
2262
+ "notification",
2263
+ "replication",
2264
+ "lifecycle",
2265
+ "deletebucket",
2266
+ "delete",
2267
+ "cors",
2268
+ "restore",
2269
+ "tagging",
2270
+ "append",
2271
+ "position",
2272
+ "response-content-type",
2273
+ "response-content-language",
2274
+ "response-expires",
2275
+ "response-cache-control",
2276
+ "response-content-disposition",
2277
+ "response-content-encoding",
2278
+ "x-image-process",
2279
+ "x-oss-process",
2280
+ "x-image-save-object",
2281
+ "x-image-save-bucket",
2282
+ "encryption",
2283
+ "directcoldaccess",
2284
+ "rename",
2285
+ "name",
2286
+ "requestpayment",
2287
+ "metadata",
2288
+ "modify",
2289
+ "attname",
2290
+ "truncate",
2291
+ "x-obs-security-token",
2292
+ "x-workflow-prefix",
2293
+ "x-workflow-start",
2294
+ "x-workflow-limit",
2295
+ "x-workflow-template-name",
2296
+ "x-workflow-graph-name",
2297
+ "x-workflow-execution-state",
2298
+ "x-workflow-execution-type",
2299
+ "x-workflow-next-marker",
2300
+ "obsworkflowtriggerpolicy",
2301
+ "obsbucketalias",
2302
+ "obsalias",
2303
+ "publicaccessblock",
2304
+ "bucketstatus",
2305
+ "policystatus",
2306
+ "customdomain",
2307
+ "inventory",
2308
+ "object-lock",
2309
+ "retention",
2310
+ "mirrorbacktosource",
2311
+ "obscompresspolicy",
2312
+ "length",
2313
+ "position"
2314
+ ]);
2315
+ /** Header prefix for OBS custom headers (x-obs-). */
2316
+ const HEADER_PREFIX = "x-obs-";
2317
+ /** Header prefix for OBS user-metadata headers (x-obs-meta-). Values are trimmed. */
2318
+ const HEADER_META_PREFIX = "x-obs-meta-";
2319
+ /**
2320
+ * Sign a HuaweiCloud OBS API request. Mutates `params.headers` to add:
2321
+ * - `Date` (RFC 1123 GMT) — if not already set by the caller
2322
+ * - `x-obs-security-token` — if `securityToken` is provided
2323
+ * - `Authorization` — `OBS <AK>:<base64 signature>`
2324
+ *
2325
+ * The caller must set Content-Type and Content-MD5 (when applicable) BEFORE
2326
+ * calling this — they participate in the signature.
2327
+ *
2328
+ * @see https://support.huaweicloud.com/api-obs/obs_04_0010.html
2329
+ */
2330
+ function signObsRequest(params) {
2331
+ const { method, url, headers, ak, sk } = params;
2332
+ if (params.securityToken) headers["x-obs-security-token"] = params.securityToken;
2333
+ if (!headers["Date"]) headers["Date"] = new Date().toUTCString();
2334
+ let stringToSign = method.toUpperCase() + "\n";
2335
+ const md5 = findHeader(headers, "content-md5");
2336
+ const contentType = findHeader(headers, "content-type");
2337
+ const date = findHeader(headers, "date");
2338
+ stringToSign += (md5 ?? "") + "\n";
2339
+ stringToSign += (contentType ?? "") + "\n";
2340
+ stringToSign += (date ?? "") + "\n";
2341
+ const obsHeaders = [];
2342
+ for (const [key, value] of Object.entries(headers)) {
2343
+ const lowerKey = key.toLowerCase();
2344
+ if (lowerKey.startsWith(HEADER_PREFIX)) {
2345
+ const isMeta = lowerKey.startsWith(HEADER_META_PREFIX);
2346
+ obsHeaders.push({
2347
+ key: lowerKey,
2348
+ value: isMeta ? value.trim() : value
2349
+ });
2350
+ }
2351
+ }
2352
+ obsHeaders.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
2353
+ for (const h of obsHeaders) stringToSign += h.key + ":" + h.value + "\n";
2354
+ stringToSign += canonicalizedResource(url);
2355
+ const signature = createHmac("sha1", sk).update(stringToSign, "utf8").digest("base64");
2356
+ headers["Authorization"] = "OBS " + ak + ":" + signature;
2357
+ }
2358
+ /**
2359
+ * Case-insensitive header lookup. HTTP headers are case-insensitive (RFC 7230);
2360
+ * our http.ts uses canonical case but callers via openapi_request may not.
2361
+ */
2362
+ function findHeader(headers, name$1) {
2363
+ const lower = name$1.toLowerCase();
2364
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === lower) return v;
2365
+ return void 0;
2366
+ }
2367
+ /**
2368
+ * CanonicalizedResource: bucket/object path + whitelisted sub-resources.
2369
+ *
2370
+ * OBS supports two addressing styles:
2371
+ * - Virtual-hosted: https://<bucket>.obs.<region>.myhuaweicloud.com/<object>
2372
+ * → host carries the bucket name; pathname is /<object>
2373
+ * - Path-style: https://obs.<region>.myhuaweicloud.com/<bucket>/<object>
2374
+ * → pathname carries the bucket name
2375
+ *
2376
+ * The canonical resource must ALWAYS be `/<bucket>/<object>` regardless of
2377
+ * addressing style — the OBS server extracts the bucket from host (virtual-
2378
+ * hosted) or path (path-style) when verifying. For virtual-hosted style we
2379
+ * must pull the bucket out of the host and prepend it to the pathname,
2380
+ * because url.pathname alone would be `/<object>` (missing the bucket).
2381
+ *
2382
+ * Global endpoints (no bucket in host, e.g. ListAllMyBuckets): canonical
2383
+ * resource is just `/` + sub-resources.
2384
+ *
2385
+ * Sub-resources: query params whose key is in ALLOWED_RESOURCE_PARAMETER_NAMES
2386
+ * (case-insensitive), sorted by key, joined as `key=value` with `&`. If a
2387
+ * param has no value, it's just `key`. Prefixed with `?` when non-empty.
2388
+ * Non-whitelisted query params do NOT enter the canonical resource.
2389
+ */
2390
+ function canonicalizedResource(url) {
2391
+ let path = url.pathname || "/";
2392
+ const host = url.host;
2393
+ const obsIdx = host.indexOf(".obs.");
2394
+ if (obsIdx > 0) {
2395
+ const bucket = host.slice(0, obsIdx);
2396
+ path = "/" + bucket + (path === "/" ? "/" : path);
2397
+ }
2398
+ const subResources = [];
2399
+ for (const [key, value] of url.searchParams.entries()) if (ALLOWED_RESOURCE_PARAMETER_NAMES.has(key.toLowerCase())) subResources.push({
2400
+ key,
2401
+ value: value || null
2402
+ });
2403
+ if (subResources.length > 0) {
2404
+ subResources.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
2405
+ const parts = subResources.map((s) => s.value === null ? s.key : s.key + "=" + s.value);
2406
+ path += "?" + parts.join("&");
2407
+ }
2408
+ return path;
2409
+ }
2410
+
2411
+ //#endregion
2412
+ //#region src/credentials.ts
2413
+ let source;
2414
+ /**
2415
+ * Bind the credential source. Called once from the plugin's `apply()`.
2416
+ *
2417
+ * A module-level setter carries a real hazard worth naming: it is
2418
+ * process-wide, so two mounts of this plugin in one process would share the
2419
+ * last-configured reader. That cannot happen under DSH — a loader row mounts
2420
+ * once — and the alternative (threading a reader through 18 tool registrars)
2421
+ * would touch every file for a case that does not exist.
2422
+ *
2423
+ * @param next - the store and region this plugin was configured with.
2424
+ */
2425
+ function configureCredentials(next) {
2426
+ source = next;
2427
+ }
2428
+ /** The bound source, or an error naming the wiring bug. */
2429
+ function requireSource() {
2430
+ if (source === void 0) throw new Error("aishell-deploy: credential source not configured — the plugin must call configureCredentials() during activation");
2431
+ return source;
2432
+ }
2433
+ /**
2434
+ * Read the current credentials.
2435
+ *
2436
+ * @returns the pair with the configured region, or `undefined` when the AK/SK
2437
+ * pair is incomplete.
2438
+ */
2439
+ function readStoredCredentials() {
2440
+ const { store, region } = requireSource();
2441
+ const pair = readStoredPair(store);
2442
+ return pair === void 0 ? void 0 : {
2443
+ ...pair,
2444
+ region
2445
+ };
2446
+ }
2447
+ /**
2448
+ * Load credentials or fail with the remedy the model can act on.
2449
+ *
2450
+ * The message names the condition and stops: which control opens the credential
2451
+ * form is the UI's business, and a tool message naming a button would be a
2452
+ * second copy of that path to keep in step.
2453
+ *
2454
+ * @returns the credentials in hand.
2455
+ * @throws when nothing usable is stored.
2456
+ */
2457
+ async function loadCredentials() {
2458
+ const found = readStoredCredentials();
2459
+ if (found === void 0) throw new Error("Not authenticated with Huawei Cloud IAM. Please authenticate, then retry.");
2460
+ return found;
2461
+ }
2462
+ /**
2463
+ * The account identity, resolved from IAM and cached for this process.
2464
+ *
2465
+ * @see loadAccount for the contract.
2466
+ */
2467
+ let cachedAccount;
2468
+ /**
2469
+ * Resolve and cache the account identity.
2470
+ *
2471
+ * Verification goes through the shared `verifyCredentials`, so "is this
2472
+ * account" is answered by the same call the credential form uses — no second
2473
+ * notion of validity.
2474
+ *
2475
+ * @returns the identity, or `undefined` when the stored credentials cannot be
2476
+ * verified. A missing identity is diagnostic-only, so this never fails a tool
2477
+ * call; `list_existing_resources` is the one tool that turns it into its own
2478
+ * error, because RMS needs the id as a path parameter.
2479
+ */
2480
+ async function loadAccount() {
2481
+ if (cachedAccount !== void 0) return cachedAccount;
2482
+ const credentials = readStoredCredentials();
2483
+ if (credentials === void 0) return void 0;
2484
+ const result = await verifyCredentials(credentials, { region: credentials.region });
2485
+ if (!result.ok) return void 0;
2486
+ cachedAccount = {
2487
+ account_id: result.account.accountId,
2488
+ account_name: result.account.name
2489
+ };
2490
+ return cachedAccount;
2491
+ }
2492
+ /**
2493
+ * Drop the cached identity, so the next read resolves it again.
2494
+ *
2495
+ * Called when the stored credentials change: the account a deployment is
2496
+ * recorded under must follow the credentials in hand, not the ones this
2497
+ * process started with.
2498
+ */
2499
+ function forgetAccount() {
2500
+ cachedAccount = void 0;
2501
+ }
2502
+
2503
+ //#endregion
2504
+ //#region src/auth-http.ts
2505
+ /**
2506
+ * Whether a host targets OBS (Object Storage Service).
2507
+ *
2508
+ * OBS endpoints take two forms:
2509
+ * - Global: obs.<region>.myhuaweicloud.com
2510
+ * - Bucket: <bucket>.obs.<region>.myhuaweicloud.com (virtual-hosted style)
2511
+ *
2512
+ * The rule `startsWith("obs.") || includes(".obs.")` matches both and does not
2513
+ * match other services (ecs/rds/bss/iam never contain ".obs.").
2514
+ */
2515
+ function isObsHost(host) {
2516
+ return host.startsWith("obs.") || host.includes(".obs.");
2517
+ }
2518
+ /**
2519
+ * Send a signed HTTP request to a HuaweiCloud API endpoint.
2520
+ *
2521
+ * The request is signed with SDK-HMAC-SHA256 (signer.ts). Host header is set
2522
+ * automatically; caller-provided headers are merged on top.
2523
+ *
2524
+ * @param creds optional explicit credentials. Omit to read the plugin store
2525
+ * (the normal path).
2526
+ * @throws if not authenticated (call auth first) — only when `creds` is
2527
+ * omitted and no credentials are stored.
2528
+ * @throws if read-only mode is in effect and the request is not a permitted
2529
+ * read. The gate is unconditional — see permission/gate.ts.
2530
+ */
2531
+ async function signedHttp(method, url, body, extraHeaders = {}, creds) {
2532
+ const refusal = denyHttp(method, url);
2533
+ if (refusal !== void 0) throw new PermissionRefusalError(refusal);
2534
+ const resolved = creds ?? await loadCredentials();
2535
+ const isObs = isObsHost(url.host);
2536
+ const headers = {
2537
+ Host: url.host,
2538
+ ...isObs ? {} : { "Content-Type": "application/json" },
2539
+ ...extraHeaders
2540
+ };
2541
+ if (isObs) signObsRequest({
2542
+ method,
2543
+ url,
2544
+ headers,
2545
+ body,
2546
+ ak: resolved.ak,
2547
+ sk: resolved.sk,
2548
+ securityToken: resolved.securityToken
2549
+ });
2550
+ else signRequest({
2551
+ method,
2552
+ url,
2553
+ headers,
2554
+ body,
2555
+ ak: resolved.ak,
2556
+ sk: resolved.sk,
2557
+ region: resolved.region,
2558
+ securityToken: resolved.securityToken
2559
+ });
2560
+ const init = {
2561
+ method,
2562
+ headers
2563
+ };
2564
+ if (body) init.body = body;
2565
+ init.signal = AbortSignal.timeout(3e4);
2566
+ const r = await fetch(url, init);
2567
+ const respHeaders = {};
2568
+ r.headers.forEach((v, k) => {
2569
+ respHeaders[k] = v;
2570
+ });
2571
+ return {
2572
+ status: r.status,
2573
+ headers: respHeaders,
2574
+ body: await r.text()
2575
+ };
2576
+ }
2577
+
2578
+ //#endregion
2579
+ //#region src/tools/openapi.ts
2580
+ /**
2581
+ * apiexplorer + openapi_request (§3.2).
2582
+ *
2583
+ * apiexplorer wraps HuaweiCloud APIExplorer (the "API of APIs") — a dedicated
2584
+ * tool, NOT just openapi_request, because:
2585
+ * - ListApis is paginated (a service can have 100+ APIs); this tool handles
2586
+ * limit/offset + has_more so the LLM doesn't hand-compute pagination.
2587
+ * - ShowApi returns a large swagger with metadata the LLM doesn't need; the
2588
+ * server strips to paths/parameters/definitions.
2589
+ *
2590
+ * Five recursive levels (APIExplorer is a global service, one unified host):
2591
+ * 1. No args → ListProductsV4: all cloud services (productshort + api_count).
2592
+ * The LLM learns productshort values here.
2593
+ * 2. productshort (no api_name) → ListApis: that service's APIs. Paginated.
2594
+ * 3. productshort + api_name → ShowApi: the API's swagger — the parameter
2595
+ * contract the LLM needs to call openapi_request correctly.
2596
+ * 4. regions=true → ListRegionsV4: regions where the service/API is available
2597
+ * (region_id + project_id). Use before openapi_request to confirm region
2598
+ * support and get the project_id for region-scoped endpoints.
2599
+ * 5. endpoints=true → ListGroups: per-region endpoint hosts (domain_url) for
2600
+ * the service. Use to construct the full API URL for openapi_request.
2601
+ *
2602
+ * APIExplorer is itself a HuaweiCloud API — signedHttp signs it like any other
2603
+ * (RMS, BSS).
2604
+ */
2605
+ function registerOpenApiTools(registrar) {
2606
+ registrar.registerTool("apiexplorer", {
2607
+ title: "Query HuaweiCloud API definitions",
2608
+ description: "Discover HuaweiCloud API definitions via APIExplorer. Five levels: (1) no args → list all cloud services (productshort + api_count); (2) productshort → list that service's APIs (name + summary, paginated); (3) productshort + api_name → API contract; pass compact=true for a minimal contract (method/path/required_params/optional_params, ~500B) instead of the full swagger (5-10KB). compact is recommended — it has every field needed to call openapi_request and is easier to scan. (4) regions=true → regions where the service/API is available (region_id + project_id); (5) endpoints=true → per-region endpoint hosts for the service (domain_url). Use these to find correct endpoints and parameters before calling openapi_request.",
2609
+ annotations: READ_ONLY_CLOUD,
2610
+ inputSchema: z.object({
2611
+ productshort: z.string().optional().describe("Service short name, obtained by calling this tool without productshort to list all services. e.g. \"ECS\"|\"VPC\"|\"RDS\"|\"EIP\"|\"ELB\"|\"ModelArts\". Omit on first call to get the full list."),
2612
+ api_name: z.string().optional().describe("API name within the service, e.g. ListCloudServers. Requires productshort."),
2613
+ compact: z.boolean().optional().describe("Level 3 only: return a minimal contract (method/path/required_params/optional_params) instead of the full swagger. Recommended — 5KB→~500B, has every field needed to call openapi_request. Use compact=false if you need body schema details (definitions)."),
2614
+ regions: z.boolean().optional().describe("List regions where this service/API is available (region_id + project_id). Requires productshort."),
2615
+ endpoints: z.boolean().optional().describe("List per-region endpoint hosts for the service (domain_url). Requires productshort. Use to construct the full URL for openapi_request."),
2616
+ limit: z.number().int().min(1).max(100).optional().describe("Page size for ListApis/ListGroups (default 50, max 100 per APIExplorer swagger)."),
2617
+ offset: z.number().int().min(0).optional().describe("Pagination offset for ListApis/ListGroups.")
2618
+ })
2619
+ }, guard(async (args) => handleApiExplorer(args.productshort, args.api_name, args.compact, args.regions, args.endpoints, args.limit, args.offset)));
2620
+ registrar.registerTool("openapi_request", {
2621
+ title: "Call HuaweiCloud API",
2622
+ description: "Send a signed HTTP request to a HuaweiCloud API endpoint. Credentials are read from secure storage and used to sign the request — AK/SK are never exposed in arguments. GET requests are safe; POST/PUT/DELETE execute but the response includes a warning to inform the user of consequences.",
2623
+ annotations: CLOUD_MUTABLE_API,
2624
+ inputSchema: z.object({
2625
+ method: z.enum([
2626
+ "GET",
2627
+ "POST",
2628
+ "PUT",
2629
+ "DELETE",
2630
+ "PATCH",
2631
+ "HEAD"
2632
+ ]).describe("HTTP method"),
2633
+ url: z.string().describe("Full URL, e.g. https://ecs.cn-north-4.myhuaweicloud.com/v1/..."),
2634
+ body: z.string().optional().describe("Request body (JSON string) for POST/PUT"),
2635
+ headers: z.record(z.string(), z.string()).optional(),
2636
+ fields: z.array(z.string()).optional().describe("JSONPath expressions (RFC 9535) to extract from the JSON response, e.g. [\"$.account_balances[*].amount\", \"$.currency\"]. Supports array wildcards ([*]), indices ([0]), filters ([?(@.amount>0)]), and recursive descent (..). Simple dot-paths like \"data.bills\" still work. Returns {path, value} pairs; missing paths → null, wildcard paths → array of matches. Avoids pulling large responses into context. Ignored if body is not valid JSON.")
2637
+ })
2638
+ }, guard(async (args) => handleOpenApiRequest(args.method, args.url, args.body, args.headers ?? {}, args.fields)));
2639
+ }
2640
+ const APIEXPLORER_HOST = "apiexplorer.cn-north-4.myhuaweicloud.com";
2641
+ const ZH_CN_HEADERS = { "X-Language": "zh-cn" };
2642
+ async function handleApiExplorer(productshort, apiName, compact, regions, endpoints, limit = 50, offset = 0) {
2643
+ if (apiName && !productshort) return fail("api_name requires productshort — call apiexplorer without args to list services first");
2644
+ if ((regions || endpoints) && !productshort) return fail("regions/endpoints requires productshort — call apiexplorer without args to list services first");
2645
+ if (!productshort) return await listProducts();
2646
+ if (endpoints) return await listEndpoints(productshort, limit, offset);
2647
+ if (regions) return await listRegions(productshort, apiName);
2648
+ if (!apiName) return await listApis(productshort, limit, offset);
2649
+ return await showApi(productshort, apiName, compact ?? false);
2650
+ }
2651
+ /**
2652
+ * Level 1: list all cloud services with their productshort + api_count.
2653
+ *
2654
+ * ListProductsV4 has no pagination (swagger defines no limit/offset). It returns
2655
+ * ~310 services; the tool strips each product to the 5 fields the LLM needs
2656
+ * (group/name/productshort/api_count/is_global), dropping link/icon/description/
2657
+ * has_data/etc. — 65KB raw → ~28KB slim, fits one response without paging.
2658
+ */
2659
+ async function listProducts() {
2660
+ const url = new URL(`https://${APIEXPLORER_HOST}/v4/products`);
2661
+ try {
2662
+ const resp = await signedHttp("GET", url, "", ZH_CN_HEADERS);
2663
+ if (resp.status !== 200) return fail(`APIExplorer ListProductsV4 failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
2664
+ const data = JSON.parse(resp.body);
2665
+ const products = (data.groups ?? []).flatMap((g) => (g.products ?? []).map((p) => ({
2666
+ group: g.name,
2667
+ name: p.name,
2668
+ productshort: p.productshort,
2669
+ api_count: p.api_count,
2670
+ is_global: p.is_global ?? false
2671
+ })));
2672
+ return ok(JSON.stringify({
2673
+ products,
2674
+ count: products.length
2675
+ }));
2676
+ } catch (err) {
2677
+ return fail(`APIExplorer ListProductsV4 failed: ${err instanceof Error ? err.message : String(err)}`);
2678
+ }
2679
+ }
2680
+ /** Level 2: list APIs for a service. Paginated via limit/offset. */
2681
+ async function listApis(productshort, limit, offset) {
2682
+ const url = new URL(`https://${APIEXPLORER_HOST}/v2/apis`);
2683
+ url.searchParams.set("productshort", productshort);
2684
+ url.searchParams.set("limit", String(limit));
2685
+ url.searchParams.set("offset", String(offset));
2686
+ try {
2687
+ const resp = await signedHttp("GET", url, "", ZH_CN_HEADERS);
2688
+ if (resp.status !== 200) return fail(`APIExplorer ListApis failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
2689
+ const data = JSON.parse(resp.body);
2690
+ const apis = (data.apis ?? []).map((a) => ({
2691
+ name: a.name,
2692
+ summary: a.summary ?? "",
2693
+ tags: a.tags ?? ""
2694
+ }));
2695
+ return ok(JSON.stringify({
2696
+ productshort,
2697
+ apis,
2698
+ count: apis.length,
2699
+ total: data.count ?? apis.length,
2700
+ offset,
2701
+ ...apis.length + offset < (data.count ?? apis.length) ? {
2702
+ has_more: true,
2703
+ next_offset: offset + limit
2704
+ } : { has_more: false }
2705
+ }));
2706
+ } catch (err) {
2707
+ return fail(`APIExplorer ListApis failed: ${err instanceof Error ? err.message : String(err)}`);
2708
+ }
2709
+ }
2710
+ /** Level 3: API contract. compact=true → minimal contract; false → full swagger. */
2711
+ async function showApi(productshort, apiName, compact) {
2712
+ const url = new URL(`https://${APIEXPLORER_HOST}/v3/apis/detail`);
2713
+ url.searchParams.set("productshort", productshort);
2714
+ url.searchParams.set("name", apiName);
2715
+ try {
2716
+ const resp = await signedHttp("GET", url, "", ZH_CN_HEADERS);
2717
+ if (resp.status !== 200) return fail(`APIExplorer ShowApi failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
2718
+ const data = JSON.parse(resp.body);
2719
+ if (compact) return ok(JSON.stringify(extractCompactContract(data)));
2720
+ return ok(JSON.stringify({
2721
+ name: data.name,
2722
+ summary: data.summary ?? "",
2723
+ host: data.host ?? "",
2724
+ base_path: data.base_path ?? "",
2725
+ paths: data.paths ?? {},
2726
+ parameters: data.parameters ?? {},
2727
+ definitions: data.definitions ?? {}
2728
+ }));
2729
+ } catch (err) {
2730
+ return fail(`APIExplorer ShowApi failed: ${err instanceof Error ? err.message : String(err)}`);
2731
+ }
2732
+ }
2733
+ const HTTP_METHODS = [
2734
+ "get",
2735
+ "post",
2736
+ "put",
2737
+ "delete",
2738
+ "patch",
2739
+ "head",
2740
+ "options"
2741
+ ];
2742
+ /**
2743
+ * Extract a minimal API contract from a swagger 2.0 ShowApi response.
2744
+ *
2745
+ * For each path+method, collect the operation's parameters split into
2746
+ * required/optional groups. Each parameter carries name/in/type/description —
2747
+ * everything the LLM needs to construct the request. definitions/responses are
2748
+ * dropped (use compact=false if body schema detail is needed).
2749
+ *
2750
+ * $ref parameters ("#/parameters/Foo") are resolved from the top-level
2751
+ * `parameters` map. body parameters (in: "body") keep their description but
2752
+ * don't expand the schema — that would re-introduce the large JSON compact
2753
+ * is meant to avoid.
2754
+ */
2755
+ function extractCompactContract(data) {
2756
+ const operations = [];
2757
+ const paths = data.paths ?? {};
2758
+ const sharedParams = data.parameters ?? {};
2759
+ for (const [path, methods] of Object.entries(paths)) {
2760
+ if (!methods || typeof methods !== "object") continue;
2761
+ for (const method of HTTP_METHODS) {
2762
+ const op = methods[method];
2763
+ if (!op || typeof op !== "object") continue;
2764
+ const rawParams = op.parameters ?? [];
2765
+ const resolved = rawParams.map((p) => resolveParam(p, sharedParams));
2766
+ const definitions = data.definitions ?? {};
2767
+ const compactParams = resolved.map((p) => toCompactParam(p, definitions));
2768
+ operations.push({
2769
+ method: method.toUpperCase(),
2770
+ path,
2771
+ required_params: compactParams.filter((p) => p.required),
2772
+ optional_params: compactParams.filter((p) => !p.required)
2773
+ });
2774
+ }
2775
+ }
2776
+ return {
2777
+ name: data.name,
2778
+ summary: data.summary ?? "",
2779
+ host: data.host ?? "",
2780
+ host_note: "This host is APIExplorer's documentation example and may not match your region. Use apiexplorer endpoints=true to get the real per-region endpoint host.",
2781
+ base_path: data.base_path ?? "",
2782
+ operations
2783
+ };
2784
+ }
2785
+ /** Resolve a $ref parameter against the top-level parameters map. */
2786
+ function resolveParam(p, shared) {
2787
+ if (!p.$ref) return p;
2788
+ const refName = p.$ref.split("/").pop();
2789
+ if (refName && shared[refName]) return shared[refName];
2790
+ return {
2791
+ name: `(unresolved ref: ${refName ?? p.$ref})`,
2792
+ in: "unknown",
2793
+ required: false
2794
+ };
2795
+ }
2796
+ /**
2797
+ * Convert a resolved swagger parameter to the compact shape.
2798
+ *
2799
+ * For body parameters (in: "body"), recursively expand the schema into a
2800
+ * flat list of field paths with types — e.g. "product_infos[].cloud_service_type".
2801
+ * This gives the LLM every required field needed to construct the body,
2802
+ * including nested array items, without pulling the full swagger.
2803
+ */
2804
+ function toCompactParam(p, definitions) {
2805
+ if (p.in !== "body") return {
2806
+ name: p.name ?? "",
2807
+ in: p.in ?? "query",
2808
+ type: p.type ?? p.schema?.type ?? "string",
2809
+ required: p.required ?? false,
2810
+ description: p.description ?? ""
2811
+ };
2812
+ const fields = expandBodySchema(p.schema ?? {}, definitions, "");
2813
+ return {
2814
+ name: p.name ?? "body",
2815
+ in: "body",
2816
+ type: "object",
2817
+ required: p.required ?? false,
2818
+ description: p.description ?? p.schema?.description ?? "",
2819
+ ...fields.length > 0 ? { fields } : {}
2820
+ };
2821
+ }
2822
+ /**
2823
+ * Recursively expand a swagger schema into flat field paths.
2824
+ *
2825
+ * - Object: expand each property, prefix with parent path
2826
+ * - Array: expand items, mark path with "[]"
2827
+ * - $ref: resolve from definitions, continue expanding
2828
+ * - Leaf (string/number/boolean): emit the path
2829
+ *
2830
+ * Stops at leaves or when a $ref can't be resolved. All fields are
2831
+ * included — each marked required/optional so the LLM knows which are
2832
+ * mandatory and which are optional.
2833
+ */
2834
+ function expandBodySchema(schema, definitions, pathPrefix) {
2835
+ if (schema.$ref) {
2836
+ const refName = schema.$ref.split("/").pop();
2837
+ if (!refName) return [];
2838
+ const def = definitions[refName];
2839
+ if (!def) return [];
2840
+ return expandBodySchema(def, definitions, pathPrefix);
2841
+ }
2842
+ if (schema.type && schema.type !== "object" && schema.type !== "array") return [];
2843
+ if (schema.type === "object" || schema.properties) {
2844
+ const props = schema.properties ?? {};
2845
+ const required = new Set(schema.required ?? []);
2846
+ const fields = [];
2847
+ for (const [name$1, subSchema] of Object.entries(props)) {
2848
+ const sub = subSchema;
2849
+ const path = pathPrefix ? `${pathPrefix}.${name$1}` : name$1;
2850
+ const isRequired = required.has(name$1);
2851
+ const nested = expandBodySchema(sub, definitions, path);
2852
+ if (nested.length > 0) fields.push(...nested);
2853
+ else fields.push({
2854
+ path,
2855
+ type: sub.type ?? "string",
2856
+ required: isRequired,
2857
+ description: sub.description ?? ""
2858
+ });
2859
+ }
2860
+ return fields;
2861
+ }
2862
+ if (schema.type === "array" && schema.items) {
2863
+ const itemSchema = schema.items;
2864
+ const arrayPath = `${pathPrefix}[]`;
2865
+ const nested = expandBodySchema(itemSchema, definitions, arrayPath);
2866
+ if (nested.length > 0) return nested;
2867
+ return [{
2868
+ path: arrayPath,
2869
+ type: `array<${itemSchema.type ?? "string"}>`,
2870
+ required: true,
2871
+ description: schema.description ?? ""
2872
+ }];
2873
+ }
2874
+ return [];
2875
+ }
2876
+ /**
2877
+ * Level 4: list regions where a service (or specific API) is available.
2878
+ *
2879
+ * HuaweiCloud doesn't expose every service in every region — the LLM needs
2880
+ * this to confirm a target region supports the service/API before calling
2881
+ * openapi_request, and to get the project_id for region-scoped endpoints.
2882
+ * If api_name is given, regions are scoped to that API; otherwise to the
2883
+ * service (productshort).
2884
+ */
2885
+ async function listRegions(productshort, apiName) {
2886
+ const url = new URL(`https://${APIEXPLORER_HOST}/v4/regions`);
2887
+ url.searchParams.set("product_short", productshort);
2888
+ if (apiName) url.searchParams.set("api_name", apiName);
2889
+ try {
2890
+ const resp = await signedHttp("GET", url, "", ZH_CN_HEADERS);
2891
+ if (resp.status !== 200) return fail(`APIExplorer ListRegionsV4 failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
2892
+ const data = JSON.parse(resp.body);
2893
+ const regions = (data.regions ?? []).map((r) => ({
2894
+ name: r.name_cn ?? r.name ?? r.region_id,
2895
+ region_id: r.region_id,
2896
+ has_permission: r.has_permission ?? false,
2897
+ project_id: r.projects?.project_id ?? ""
2898
+ }));
2899
+ return ok(JSON.stringify({
2900
+ productshort,
2901
+ ...apiName ? { api_name: apiName } : {},
2902
+ regions,
2903
+ count: regions.length
2904
+ }));
2905
+ } catch (err) {
2906
+ return fail(`APIExplorer ListRegionsV4 failed: ${err instanceof Error ? err.message : String(err)}`);
2907
+ }
2908
+ }
2909
+ /**
2910
+ * Level 5: per-region endpoint hosts for a service (ListGroups).
2911
+ *
2912
+ * Returns {region_id, domain_url} per region — the LLM needs domain_url to
2913
+ * construct the full API URL for openapi_request (e.g.
2914
+ * https://ecs.cn-north-4.myhuaweicloud.com/v1/...). ShowApi returns one
2915
+ * host for one region; this gives all regions' endpoint hosts.
2916
+ */
2917
+ async function listEndpoints(productshort, limit, offset) {
2918
+ const url = new URL(`https://${APIEXPLORER_HOST}/v1/groups`);
2919
+ url.searchParams.set("productshort", productshort);
2920
+ url.searchParams.set("limit", String(limit));
2921
+ url.searchParams.set("offset", String(offset));
2922
+ try {
2923
+ const resp = await signedHttp("GET", url, "", ZH_CN_HEADERS);
2924
+ if (resp.status !== 200) return fail(`APIExplorer ListGroups failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
2925
+ const data = JSON.parse(resp.body);
2926
+ const endpoints = (data.groups ?? []).map((g) => ({
2927
+ region: g.region_id,
2928
+ host: g.domain_url
2929
+ }));
2930
+ return ok(JSON.stringify({
2931
+ productshort,
2932
+ endpoints,
2933
+ count: endpoints.length
2934
+ }));
2935
+ } catch (err) {
2936
+ return fail(`APIExplorer ListGroups failed: ${err instanceof Error ? err.message : String(err)}`);
2937
+ }
2938
+ }
2939
+ async function handleOpenApiRequest(method, url, body, headers, fields) {
2940
+ let parsedUrl;
2941
+ try {
2942
+ parsedUrl = new URL(url);
2943
+ } catch {
2944
+ return fail(`invalid URL: ${url}`);
2945
+ }
2946
+ let resp;
2947
+ try {
2948
+ resp = await signedHttp(method.toUpperCase(), parsedUrl, body ?? "", headers);
2949
+ } catch (err) {
2950
+ if (err instanceof PermissionRefusalError) return fail(err.message);
2951
+ const msg = err instanceof Error ? err.message : String(err);
2952
+ if (msg.includes("not authenticated")) return fail("not authenticated — call auth first");
2953
+ return fail(`request failed: ${msg}`);
2954
+ }
2955
+ const result = {
2956
+ status: resp.status,
2957
+ headers: resp.headers
2958
+ };
2959
+ if (method.toUpperCase() !== "GET") result["warning"] = "Unless the user explicitly requests it, the agent should not proactively call POST/DELETE or other impactful APIs. Every such call must inform the user of the potential consequences.";
2960
+ if (fields && fields.length > 0) {
2961
+ const extracted = extractFields(resp.body, fields);
2962
+ if (extracted !== void 0) {
2963
+ result["extracted"] = extracted;
2964
+ if (extracted.some((e) => e.value === null)) try {
2965
+ const parsed = JSON.parse(resp.body);
2966
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) result["hint"] = `one or more fields not found — top-level keys: ${Object.keys(parsed).join(", ")}`;
2967
+ } catch {}
2968
+ return ok(JSON.stringify(result));
2969
+ }
2970
+ }
2971
+ if (resp.body) {
2972
+ const ct = (resp.headers["content-type"] ?? "").toLowerCase();
2973
+ if (ct.includes("json")) try {
2974
+ result["body"] = JSON.parse(resp.body);
2975
+ } catch {
2976
+ result["body"] = resp.body;
2977
+ }
2978
+ else result["body"] = resp.body;
2979
+ }
2980
+ return ok(JSON.stringify(result));
2981
+ }
2982
+ /**
2983
+ * Extract fields from a JSON string using JSONPath (RFC 9535). Returns
2984
+ * undefined if the body is not valid JSON (caller falls back to returning
2985
+ * the raw body). Each path is evaluated via jsonpath-plus; a missing path
2986
+ * yields null, a single-match path yields the bare value (backward compat
2987
+ * with the old dot-path behavior), and a multi-match path (wildcards [*],
2988
+ * indices [N], recursive descent ..) yields an array of matches.
2989
+ *
2990
+ * Upgraded from a hand-rolled dot-path walker that could not descend into
2991
+ * arrays — HuaweiCloud APIs return arrays (resource lists, bill details),
2992
+ * so account_balances[*].amount must work. jsonpath-plus is the RFC 9535
2993
+ * reference implementation for JS.
2994
+ */
2995
+ function extractFields(jsonBody, fields) {
2996
+ let parsed;
2997
+ try {
2998
+ parsed = JSON.parse(jsonBody);
2999
+ } catch {
3000
+ return void 0;
3001
+ }
3002
+ return fields.map((path) => {
3003
+ const result = JSONPath({
3004
+ path,
3005
+ json: parsed,
3006
+ resultType: "value"
3007
+ });
3008
+ const value = result.length === 0 ? null : result.length === 1 ? result[0] : result;
3009
+ return {
3010
+ path,
3011
+ value
3012
+ };
3013
+ });
3014
+ }
3015
+
3016
+ //#endregion
3017
+ //#region src/utils/tar.ts
3018
+ /**
3019
+ * Extract a zip archive to a destination directory.
3020
+ *
3021
+ * NOTE: adm-zip's extractAllTo does NOT preserve unix exec permission bits —
3022
+ * extracted files are mode 0666. Callers that need an executable binary (e.g.
3023
+ * terraform_install's downloadAndExtract) must chmod it themselves after
3024
+ * extraction. This is documented rather than fixed here because not every
3025
+ * caller needs exec (data-asset zips don't), and a blanket chmod-all would
3026
+ * be wrong for archives mixing executable and non-executable files.
3027
+ *
3028
+ * @returns the number of files extracted.
3029
+ * @throws on read/extract failure (corrupt zip, disk full, permission).
3030
+ */
3031
+ async function extractArchive(archivePath, dest) {
3032
+ const zip = new AdmZip(archivePath);
3033
+ const entries = zip.getEntries();
3034
+ zip.extractAllTo(dest, true);
3035
+ return { files: entries.length };
3036
+ }
3037
+
3038
+ //#endregion
3039
+ //#region src/tools/examples.ts
3040
+ /** terraform_examples_export (§3.2). */
3041
+ function registerExamplesTool(registrar) {
3042
+ registrar.registerTool("terraform_examples_export", {
3043
+ title: "Export terraform examples",
3044
+ description: "Export HuaweiCloud terraform provider examples (.tf reference files) to a target directory. Organized by cloud service category (ecs, vpc, rds, ...). Serve as cross-resource assembly templates. Note: example providers.tf may contain access_key lines from the provider's own examples — IGNORE those (credentials go via env vars, never in .tf).",
3045
+ annotations: LOCAL_WRITE,
3046
+ inputSchema: z.object({ dest: destParam })
3047
+ }, guard(async (args) => handleExamplesExport(args.dest)));
3048
+ }
3049
+ async function handleExamplesExport(dest) {
3050
+ try {
3051
+ const entries = await readdir(dest);
3052
+ if (entries.length > 0) return fail(`dest directory is not empty: ${dest}. Use an empty directory to avoid overwriting existing files.`);
3053
+ } catch {}
3054
+ const zipPath = dataFile("terraform-examples.zip");
3055
+ let zipBuf;
3056
+ try {
3057
+ zipBuf = await readFile(zipPath);
3058
+ } catch {
3059
+ return fail(`examples data package not found at ${zipPath}. Run \`npm run fetch-examples\` to generate it before building.`);
3060
+ }
3061
+ try {
3062
+ await mkdir(dest, { recursive: true });
3063
+ } catch (err) {
3064
+ return fail(`cannot create dest directory ${dest}: ${err instanceof Error ? err.message : String(err)}`);
3065
+ }
3066
+ const { writeFile: writeFileFs, unlink } = await import("node:fs/promises");
3067
+ const tmpZip = join(dest, ".terraform-examples.zip");
3068
+ await writeFileFs(tmpZip, zipBuf);
3069
+ try {
3070
+ const { files } = await extractArchive(tmpZip, dest);
3071
+ const categories = await listCategories(dest);
3072
+ return ok(JSON.stringify({
3073
+ dest,
3074
+ files,
3075
+ categories,
3076
+ note: "Examples extracted. providers.tf may contain access_key lines from the provider's own examples — ignore those (credentials go via env vars)."
3077
+ }));
3078
+ } catch (err) {
3079
+ return fail(`failed to extract examples: ${err instanceof Error ? err.message : String(err)}`);
3080
+ } finally {
3081
+ await unlink(tmpZip).catch(() => {});
3082
+ }
3083
+ }
3084
+ /** List service categories (top-level dirs under examples/). */
3085
+ async function listCategories(dest) {
3086
+ try {
3087
+ const entries = await readdir(join(dest, "examples"), { withFileTypes: true });
3088
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
3089
+ } catch {
3090
+ return [];
3091
+ }
3092
+ }
3093
+
3094
+ //#endregion
3095
+ //#region src/tools/balance_summary.ts
3096
+ /** Signed GET helper — wraps signedHttp with empty body. */
3097
+ async function signedGet(url) {
3098
+ const resp = await signedHttp("GET", url, "");
3099
+ return {
3100
+ status: resp.status,
3101
+ body: resp.body
3102
+ };
3103
+ }
3104
+ /**
3105
+ * Query account balances (ShowCustomerAccountBalances).
3106
+ * GET /v2/accounts/customer-accounts/balances — no params.
3107
+ * Response: { account_balances: [{ account_type, amount, currency, credit_amount? }] }
3108
+ */
3109
+ const ACCOUNT_TYPE_NAMES = {
3110
+ 1: "余额",
3111
+ 2: "信用",
3112
+ 5: "奖励金",
3113
+ 7: "保证金"
3114
+ };
3115
+ const COUPON_TYPE_NAMES = {
3116
+ 1: "代金券",
3117
+ 2: "折扣券",
3118
+ 3: "产品券",
3119
+ 4: "现金券"
3120
+ };
3121
+ async function queryAccountBalances() {
3122
+ const url = new URL("https://bss.myhuaweicloud.com/v2/accounts/customer-accounts/balances");
3123
+ try {
3124
+ const { status, body } = await signedGet(url);
3125
+ if (status !== 200) return [];
3126
+ const data = JSON.parse(body);
3127
+ return (data.account_balances ?? []).map((b) => {
3128
+ const at = typeof b["account_type"] === "number" ? b["account_type"] : 0;
3129
+ const item = {
3130
+ account_type: at,
3131
+ account_type_name: ACCOUNT_TYPE_NAMES[at] ?? "未知",
3132
+ amount: typeof b["amount"] === "number" ? b["amount"] : 0,
3133
+ currency: typeof b["currency"] === "string" ? b["currency"] : ""
3134
+ };
3135
+ if (typeof b["credit_amount"] === "number") item.credit_amount = b["credit_amount"];
3136
+ if (typeof b["designated_amount"] === "number") item.designated_amount = b["designated_amount"];
3137
+ return item;
3138
+ }).filter((b) => b.amount !== 0 || b.account_type === 2);
3139
+ } catch {
3140
+ return [];
3141
+ }
3142
+ }
3143
+ /**
3144
+ * Query coupons (ListSubCustomerCoupons).
3145
+ * GET /v2/promotions/benefits/coupons — no params.
3146
+ * Response: { count, user_coupons: [{ coupon_id, status, balance, effective_time, expire_time, ... }] }
3147
+ */
3148
+ async function queryCoupons() {
3149
+ const url = new URL("https://bss.myhuaweicloud.com/v2/promotions/benefits/coupons");
3150
+ try {
3151
+ const { status, body } = await signedGet(url);
3152
+ if (status !== 200) return {
3153
+ count: 0,
3154
+ total_balance: null,
3155
+ items: []
3156
+ };
3157
+ const data = JSON.parse(body);
3158
+ const rawCoupons = data.user_coupons ?? [];
3159
+ let total = 0;
3160
+ let allParseable = true;
3161
+ const items = [];
3162
+ for (const c of rawCoupons) {
3163
+ const balance = typeof c["balance"] === "number" ? c["balance"] : null;
3164
+ const ct = typeof c["coupon_type"] === "number" ? c["coupon_type"] : null;
3165
+ const expireTime = typeof c["expire_time"] === "string" ? c["expire_time"] : null;
3166
+ const faceValue = typeof c["face_value"] === "number" ? c["face_value"] : null;
3167
+ if (balance !== null) total += balance;
3168
+ else allParseable = false;
3169
+ items.push({
3170
+ coupon_id: String(c["coupon_id"] ?? ""),
3171
+ coupon_type: ct,
3172
+ coupon_type_name: ct !== null ? COUPON_TYPE_NAMES[ct] ?? "未知" : null,
3173
+ balance,
3174
+ face_value: faceValue,
3175
+ coupon_usage: typeof c["coupon_usage"] === "string" ? c["coupon_usage"] : null,
3176
+ plan_name: typeof c["plan_name"] === "string" ? c["plan_name"] : null,
3177
+ expire_time: expireTime,
3178
+ coupon_version: typeof c["coupon_version"] === "number" ? c["coupon_version"] : null,
3179
+ is_frozen: typeof c["is_frozen"] === "number" ? c["is_frozen"] : null
3180
+ });
3181
+ }
3182
+ return {
3183
+ count: data.count ?? rawCoupons.length,
3184
+ total_balance: allParseable ? total : null,
3185
+ items
3186
+ };
3187
+ } catch {
3188
+ return {
3189
+ count: 0,
3190
+ total_balance: null,
3191
+ items: []
3192
+ };
3193
+ }
3194
+ }
3195
+ /** Query both balances and coupons, return the combined summary. */
3196
+ async function queryBalanceSummary() {
3197
+ const [balances, coupons] = await Promise.all([queryAccountBalances(), queryCoupons()]);
3198
+ return {
3199
+ balances,
3200
+ coupons
3201
+ };
3202
+ }
3203
+
3204
+ //#endregion
3205
+ //#region src/tools/existing_resources.ts
3206
+ /**
3207
+ * list_existing_resources (§3.2).
3208
+ *
3209
+ * Lists HuaweiCloud resources the user already owns, for reuse in a deployment.
3210
+ * Two-stage query against RMS (Resource Management Service) — the unified
3211
+ * inventory API that covers ALL services (ECS, RDS, EIP, VPC, ELB, ...):
3212
+ *
3213
+ * Stage 1 (default, no service/region/detail args): CollectAllResourcesSummary.
3214
+ * Returns a lightweight grouped count: provider → type → region → count.
3215
+ * Cross-region by default — the user sees where resources live before
3216
+ * drilling in. Cheap call, small response, ideal for the "what do I have?"
3217
+ * first question.
3218
+ *
3219
+ * Stage 2 (service, region, or detail=true): ListAllResources. Returns the
3220
+ * actual resource list (id/name/provider/type/region/status/properties).
3221
+ * Service + region narrow the query. Use after the summary tells you which
3222
+ * service/region to drill into — avoids pulling a large list blindly.
3223
+ *
3224
+ * Also returns balance_summary (BSS balances + coupons) for the full cost
3225
+ * context at the reuse/budget decision point. Balance is best-effort.
3226
+ *
3227
+ * Verified: both RMS APIs accept AK/SK signing (despite swagger
3228
+ * marking PkiTokenAuth) and return 200. domain_id in the path IS the
3229
+ * account_id (resolved at auth, stored alongside credentials). RMS host is
3230
+ * global (rms.myhuaweicloud.com, no region prefix).
3231
+ */
3232
+ function registerExistingResourcesTool(registrar) {
3233
+ registrar.registerTool("list_existing_resources", {
3234
+ title: "List existing cloud resources",
3235
+ description: "List HuaweiCloud resources the user already owns (for reuse in a deployment) via RMS (Resource Management Service). Two stages: by default returns a SUMMARY (provider→type→region→count, cheap, cross-region) so you see what exists before drilling in. Pass service, region, or detail=true to get the full resource list (id/name/properties — use after the summary to narrow down). Detail mode is paginated: if the response has next_marker, pass it back as marker to fetch the next page. Also returns balance_summary (balances + coupons). Call AFTER update_networking and BEFORE update_cost. Reuse eligibility is a judgment call, not decided here. NOTE: RMS data may lag — resources recently created or destroyed may not reflect immediately. When timing matters (e.g. verifying cleanup after destroy), be aware this data source is not real-time.",
3236
+ annotations: READ_ONLY_CLOUD,
3237
+ inputSchema: z.object({
3238
+ service: z.string().optional().describe("Filter by RMS provider in detail mode: \"vpc\"|\"ecs\"|\"rds\"|\"elb\"|..."),
3239
+ region: z.string().optional().describe("Filter by region in detail mode. If omitted, details span all regions."),
3240
+ detail: z.boolean().optional().describe("Force detail mode (full resource list) even without service/region. Default: summary mode."),
3241
+ limit: z.number().int().min(1).max(200).optional().describe("Page size in detail mode (default 100, max 200). Ignored in summary mode."),
3242
+ marker: z.string().optional().describe("Pagination cursor from a previous detail-mode response's next_marker. Fetches the next page.")
3243
+ })
3244
+ }, guard(async (args) => handleListExistingResources(args.service, args.region, args.detail, args.limit, args.marker)));
3245
+ }
3246
+ /**
3247
+ * Resolve the account_id (== RMS domain_id) for the RMS path param.
3248
+ * Credentials for signing are loaded separately by signedHttp at call time.
3249
+ */
3250
+ async function resolveDomainId() {
3251
+ const account = await loadAccount();
3252
+ if (account?.account_id) return account.account_id;
3253
+ throw new Error("account_id not available — the stored credentials could not be verified against IAM. Re-authenticate, then retry.");
3254
+ }
3255
+ async function handleListExistingResources(serviceFilter, regionFilter, detail, limit = 100, marker) {
3256
+ let domainId;
3257
+ try {
3258
+ domainId = await resolveDomainId();
3259
+ } catch (err) {
3260
+ return fail(err instanceof Error ? err.message : String(err));
3261
+ }
3262
+ const wantDetail = detail === true || serviceFilter !== void 0 || regionFilter !== void 0;
3263
+ let balanceSummary = null;
3264
+ try {
3265
+ balanceSummary = await queryBalanceSummary();
3266
+ } catch {}
3267
+ if (!wantDetail) return await summaryStage(domainId, balanceSummary);
3268
+ return await detailStage(domainId, serviceFilter, regionFilter, limit, marker, balanceSummary);
3269
+ }
3270
+ /** Stage 1: CollectAllResourcesSummary — grouped counts, cross-region. */
3271
+ async function summaryStage(domainId, balanceSummary) {
3272
+ const url = new URL(`https://rms.myhuaweicloud.com/v1/resource-manager/domains/${domainId}/all-resources/summary`);
3273
+ try {
3274
+ const resp = await signedHttp("GET", url, "");
3275
+ if (resp.status !== 200) return fail(`RMS summary failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
3276
+ const entries = JSON.parse(resp.body);
3277
+ const summary = entries.map((e) => ({
3278
+ provider: e.provider,
3279
+ types: e.types.map((t) => ({
3280
+ type: t.type,
3281
+ total: t.regions.reduce((sum, r) => sum + r.count, 0),
3282
+ regions: t.regions.map((r) => ({
3283
+ region: r.region_id,
3284
+ count: r.count
3285
+ }))
3286
+ }))
3287
+ }));
3288
+ const totalResources = summary.reduce((sum, p) => sum + p.types.reduce((s, t) => s + t.total, 0), 0);
3289
+ return ok(JSON.stringify({
3290
+ mode: "summary",
3291
+ providers: summary,
3292
+ total_resources: totalResources,
3293
+ hint: "Pass service, region, or detail=true to list specific resources.",
3294
+ balance_summary: balanceSummary
3295
+ }));
3296
+ } catch (err) {
3297
+ return fail(`RMS summary failed: ${err instanceof Error ? err.message : String(err)}`);
3298
+ }
3299
+ }
3300
+ /**
3301
+ * Stage 2: ListAllResources — one page of the resource list.
3302
+ *
3303
+ * Pagination is caller-controlled: the caller passes
3304
+ * `marker` from a previous response's `next_marker` to fetch the next page.
3305
+ * This tool does NOT auto-paginate or truncate — that would either hide
3306
+ * resources behind a cap (deployment-decision bug) or fetch unboundedly
3307
+ * (slow, large response). The caller decides whether to keep paging.
3308
+ *
3309
+ * service filter is client-side (RMS v1 `type` param requires "provider.type"
3310
+ * format, no provider-only filter). When a service filter is given WITHOUT a
3311
+ * region filter, RMS returns mixed-service pages that may contain zero
3312
+ * matching resources — the caller would see `count: 0, has_more: true` and
3313
+ * waste turns paging through empty pages. To avoid this, the tool
3314
+ * auto-advances through empty pages (up to MAX_AUTO_PAGES) when filtering by
3315
+ * service without region, collecting matching resources until the page has
3316
+ * results or RMS is exhausted.
3317
+ */
3318
+ const MAX_AUTO_PAGES = 10;
3319
+ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker, balanceSummary) {
3320
+ const autoAdvance = Boolean(serviceFilter) && !regionFilter;
3321
+ let collected = [];
3322
+ let nextMarker = marker;
3323
+ let pagesFetched = 0;
3324
+ let exhausted = false;
3325
+ try {
3326
+ do {
3327
+ const url = new URL(`https://rms.myhuaweicloud.com/v1/resource-manager/domains/${domainId}/all-resources`);
3328
+ url.searchParams.set("limit", String(limit));
3329
+ if (regionFilter) url.searchParams.set("region_id", regionFilter);
3330
+ if (nextMarker) url.searchParams.set("marker", nextMarker);
3331
+ const resp = await signedHttp("GET", url, "");
3332
+ if (resp.status !== 200) return fail(`RMS list failed (HTTP ${resp.status}): ${resp.body.slice(0, 200)}`);
3333
+ const data = JSON.parse(resp.body);
3334
+ const pageResources = data.resources ?? [];
3335
+ nextMarker = data.page_info?.next_marker;
3336
+ pagesFetched++;
3337
+ const matching = serviceFilter ? pageResources.filter((r) => r.provider === serviceFilter) : pageResources;
3338
+ collected.push(...matching);
3339
+ if (!nextMarker) {
3340
+ exhausted = true;
3341
+ break;
3342
+ }
3343
+ if (!autoAdvance || matching.length > 0) break;
3344
+ } while (autoAdvance && pagesFetched < MAX_AUTO_PAGES);
3345
+ } catch (err) {
3346
+ return fail(`RMS list failed: ${err instanceof Error ? err.message : String(err)}`);
3347
+ }
3348
+ const normalized = collected.map((r) => ({
3349
+ id: r.id,
3350
+ name: r.name,
3351
+ provider: r.provider,
3352
+ type: r.type,
3353
+ region: r.region_id,
3354
+ project_id: r.project_id,
3355
+ enterprise_project: r.ep_name,
3356
+ status: r.provisioning_state,
3357
+ created: r.created,
3358
+ updated: r.updated,
3359
+ tags: r.tags,
3360
+ properties: r.properties
3361
+ }));
3362
+ const hitAutoPageLimit = autoAdvance && pagesFetched >= MAX_AUTO_PAGES && !exhausted;
3363
+ return ok(JSON.stringify({
3364
+ mode: "detail",
3365
+ resources: normalized,
3366
+ count: normalized.length,
3367
+ region: regionFilter ?? "(all regions)",
3368
+ ...serviceFilter ? { service_filter: serviceFilter } : {},
3369
+ ...nextMarker && !exhausted ? {
3370
+ next_marker: nextMarker,
3371
+ has_more: true,
3372
+ ...autoAdvance ? { note: `auto-skipped ${pagesFetched} empty page(s); pass next_marker as marker to continue` } : { note: "pass next_marker as marker to fetch the next page" }
3373
+ } : { has_more: false },
3374
+ ...hitAutoPageLimit ? { warning: `stopped after ${MAX_AUTO_PAGES} pages — narrow with region to reduce scope` } : {},
3375
+ balance_summary: balanceSummary
3376
+ }));
3377
+ }
3378
+
3379
+ //#endregion
3380
+ //#region src/gates/credential_gate.ts
3381
+ const PATTERNS = [
3382
+ {
3383
+ name: "access_key",
3384
+ re: /access_key\s*=\s*"[^"]+"/
3385
+ },
3386
+ {
3387
+ name: "secret_key",
3388
+ re: /secret_key\s*=\s*"[^"]+"/
3389
+ },
3390
+ {
3391
+ name: "security_token",
3392
+ re: /security_token\s*=\s*"[^"]+"/
3393
+ },
3394
+ {
3395
+ name: "password",
3396
+ re: /password\s*=\s*"[^"]+"/
3397
+ }
3398
+ ];
3399
+ /**
3400
+ * Recursively collect all .tf file paths under dir. Skips dotdirs/dotfiles
3401
+ * (.terraform/, .git/, etc. — none contain user-authored .tf). Terraform
3402
+ * modules (modules/xxx/main.tf) ARE included — they compile into the plan,
3403
+ * so credentials there are just as much a leak risk as root .tf.
3404
+ */
3405
+ async function collectTfFiles$1(dir) {
3406
+ const entries = await readdir(dir, { withFileTypes: true });
3407
+ const files = [];
3408
+ for (const e of entries) {
3409
+ if (e.name.startsWith(".")) continue;
3410
+ const full = join(dir, e.name);
3411
+ if (e.isDirectory()) files.push(...await collectTfFiles$1(full));
3412
+ else if (e.isFile() && e.name.endsWith(".tf")) files.push(full);
3413
+ }
3414
+ return files;
3415
+ }
3416
+ /** Scan all .tf files (recursively, including modules/) for plaintext credentials. */
3417
+ async function scanTfCredentials(dir) {
3418
+ const tfFiles = await collectTfFiles$1(dir);
3419
+ const findings = [];
3420
+ for (const path of tfFiles) {
3421
+ const relPath = relative(dir, path);
3422
+ const content = await readFile(path, "utf8");
3423
+ const lines = content.split("\n");
3424
+ for (const [lineNum, line] of lines.entries()) {
3425
+ const trimmed = line.trim();
3426
+ if (trimmed.startsWith("#") || trimmed.startsWith("//")) continue;
3427
+ if (/=\s*(var\.|data\.)/.test(line)) continue;
3428
+ for (const { name: name$1, re } of PATTERNS) if (re.test(line)) findings.push({
3429
+ file: relPath,
3430
+ line: lineNum + 1,
3431
+ pattern: name$1
3432
+ });
3433
+ }
3434
+ }
3435
+ return findings;
3436
+ }
3437
+ /** Throw if any plaintext credential is found. */
3438
+ async function assertNoCredentials(dir) {
3439
+ const findings = await scanTfCredentials(dir);
3440
+ if (findings.length > 0) {
3441
+ const first = findings[0];
3442
+ throw new Error(`plaintext credential found in ${first.file}: line ${first.line} — remove access_key/secret_key/security_token assignments (see §6.2)`);
3443
+ }
3444
+ }
3445
+
3446
+ //#endregion
3447
+ //#region src/gates/networking_gate.ts
3448
+ async function networkingJsonExists(dir) {
3449
+ try {
3450
+ await readFile(join(dir, "networking.json"), "utf8");
3451
+ return true;
3452
+ } catch {
3453
+ return false;
3454
+ }
3455
+ }
3456
+ async function assertNetworking(dir) {
3457
+ if (!await networkingJsonExists(dir)) throw new Error("networking.json not found — call update_networking first");
3458
+ }
3459
+
3460
+ //#endregion
3461
+ //#region src/utils/hash.ts
3462
+ /**
3463
+ * Recursively collect .tf file paths (same logic as credential_gate —
3464
+ * skips dotdirs, includes modules/). Deterministic hash requires
3465
+ * consistent file ordering: relative paths sorted lexicographically.
3466
+ */
3467
+ async function collectTfFiles(dir) {
3468
+ const entries = await readdir(dir, { withFileTypes: true });
3469
+ const files = [];
3470
+ for (const e of entries) {
3471
+ if (e.name.startsWith(".")) continue;
3472
+ const full = join(dir, e.name);
3473
+ if (e.isDirectory()) files.push(...await collectTfFiles(full));
3474
+ else if (e.isFile() && e.name.endsWith(".tf")) files.push(full);
3475
+ }
3476
+ return files;
3477
+ }
3478
+ async function computeTfHash(dir) {
3479
+ const tfFiles = (await collectTfFiles(dir)).map((f) => relative(dir, f)).sort();
3480
+ const parts = [];
3481
+ for (const name$1 of tfFiles) {
3482
+ const content = await readFile(join(dir, name$1), "utf8");
3483
+ const h = createHash("sha256").update(content, "utf8").digest("hex");
3484
+ parts.push(`${name$1}${h}`);
3485
+ }
3486
+ const concatenated = parts.join("");
3487
+ const hash = createHash("sha256").update(concatenated, "utf8").digest("hex");
3488
+ return `sha256:${hash}`;
3489
+ }
3490
+
3491
+ //#endregion
3492
+ //#region src/gates/cost_gate.ts
3493
+ async function loadCost(dir) {
3494
+ const raw = await readFile(join(dir, "cost.json"), "utf8");
3495
+ return JSON.parse(raw);
3496
+ }
3497
+ async function costJsonExists(dir) {
3498
+ try {
3499
+ await readFile(join(dir, "cost.json"), "utf8");
3500
+ return true;
3501
+ } catch {
3502
+ return false;
3503
+ }
3504
+ }
3505
+ /**
3506
+ * Run the cost gate. Returns the cost.json (with its tf_hash) so the
3507
+ * caller can fill it after a successful apply.
3508
+ *
3509
+ * @throws Error if cost.json missing or tf_hash mismatch
3510
+ */
3511
+ async function runCostGate(dir) {
3512
+ if (!await costJsonExists(dir)) throw new Error("cost.json not found — call update_cost first");
3513
+ const cost = await loadCost(dir);
3514
+ if (cost.tf_hash === null || cost.tf_hash === void 0) return cost;
3515
+ const currentHash = await computeTfHash(dir);
3516
+ if (currentHash !== cost.tf_hash) throw new Error("cost.json.tf_hash does not match current .tf files — .tf changed after cost estimate, re-run update_cost");
3517
+ return cost;
3518
+ }
3519
+ /** Fill tf_hash in cost.json after a successful apply (§6.3). */
3520
+ async function fillTfHash(dir) {
3521
+ const cost = await loadCost(dir);
3522
+ cost.tf_hash = await computeTfHash(dir);
3523
+ const { writeFile: writeFile$1 } = await import("node:fs/promises");
3524
+ await writeFile$1(join(dir, "cost.json"), JSON.stringify(cost, null, 2));
3525
+ }
3526
+
3527
+ //#endregion
3528
+ //#region src/gates/terraform_env.ts
3529
+ /**
3530
+ * Resolve the terraform binary path + env for a deployment.
3531
+ * Throws if no binary can be found.
3532
+ */
3533
+ async function resolveTerraformEnv(deployment, extraEnv = []) {
3534
+ const binary = await resolveBinary(deployment);
3535
+ const env = {};
3536
+ await resolveTerraformrc(deployment, env);
3537
+ await resolvePluginCache(env);
3538
+ try {
3539
+ const creds = await loadCredentials();
3540
+ env["HW_ACCESS_KEY"] = creds.ak;
3541
+ env["HW_SECRET_KEY"] = creds.sk;
3542
+ env["HW_REGION_NAME"] = creds.region;
3543
+ if (creds.securityToken) env["HW_SECURITY_TOKEN"] = creds.securityToken;
3544
+ } catch {}
3545
+ for (const entry of extraEnv) {
3546
+ const eq = entry.indexOf("=");
3547
+ if (eq >= 0) env[entry.slice(0, eq)] = entry.slice(eq + 1);
3548
+ }
3549
+ return {
3550
+ binary,
3551
+ env
3552
+ };
3553
+ }
3554
+ /** Binary priority: HW_TERRAFORM_PATH env > PATH > global cache > deployment fallback. */
3555
+ async function resolveBinary(deployment) {
3556
+ const envPath = process.env["HW_TERRAFORM_PATH"];
3557
+ if (envPath && await fileExists(envPath)) return envPath;
3558
+ const pathBinary = await findInPath("terraform");
3559
+ if (pathBinary) return pathBinary;
3560
+ const globalBin = await findGlobalCacheBinary();
3561
+ if (globalBin) return globalBin;
3562
+ const depBin = join(deployment, ".terraform", "bin", "terraform");
3563
+ if (await fileExists(depBin)) return depBin;
3564
+ throw new Error("terraform not found — call terraform_install first");
3565
+ }
3566
+ /** .terraformrc resolution: deployment file > user env > user home > none. */
3567
+ async function resolveTerraformrc(deployment, env) {
3568
+ const depRc = join(deployment, ".terraformrc");
3569
+ if (await fileExists(depRc)) {
3570
+ env["TF_CLI_CONFIG_FILE"] = depRc;
3571
+ return;
3572
+ }
3573
+ if (process.env["TF_CLI_CONFIG_FILE"]) return;
3574
+ const homeRc = join(homedir(), ".terraformrc");
3575
+ if (await fileExists(homeRc)) return;
3576
+ }
3577
+ /** TF_PLUGIN_CACHE_DIR — global cache when HOME is writable. */
3578
+ async function resolvePluginCache(env) {
3579
+ if (process.env["TF_PLUGIN_CACHE_DIR"]) return;
3580
+ const pluginDir = terraformPluginDir();
3581
+ try {
3582
+ await mkdir(pluginDir, { recursive: true });
3583
+ env["TF_PLUGIN_CACHE_DIR"] = pluginDir;
3584
+ } catch {}
3585
+ }
3586
+ /**
3587
+ * Find terraform in PATH by running `terraform version`.
3588
+ *
3589
+ * This is the only reliable way to confirm the binary is actually usable —
3590
+ * `which`/`where` only confirm the file exists on PATH, not that it's a
3591
+ * working terraform binary (could be a same-named empty file, a corrupt
3592
+ * binary, or an architecture mismatch). `terraform version` succeeding
3593
+ * means the binary genuinely runs.
3594
+ *
3595
+ * The extra spawn is negligible: each terraform tool call already spawns a
3596
+ * subprocess that runs for seconds-to-minutes (init/plan/apply); a
3597
+ * `terraform version` probe takes tens of milliseconds.
3598
+ *
3599
+ * Using `which` was tried and rejected: Alpine Linux lacks `which` by
3600
+ * default, busybox's `which` behaves differently, and Windows `where`
3601
+ * emits multiple lines — all for no real benefit.
3602
+ */
3603
+ async function findInPath(_name) {
3604
+ return new Promise((resolve) => {
3605
+ const child = spawn("terraform", ["version"], { stdio: [
3606
+ "ignore",
3607
+ "pipe",
3608
+ "pipe"
3609
+ ] });
3610
+ child.on("error", () => resolve(null));
3611
+ child.on("close", (code) => resolve(code === 0 ? "terraform" : null));
3612
+ });
3613
+ }
3614
+ /** Find a cached binary in `<DSH_HOME>/terraform/bin` (terraform-<ver>). */
3615
+ async function findGlobalCacheBinary() {
3616
+ try {
3617
+ const { readdir: readdir$1 } = await import("node:fs/promises");
3618
+ const binDir = terraformBinDir();
3619
+ const entries = await readdir$1(binDir);
3620
+ const versioned = entries.filter((e) => e.startsWith("terraform-"));
3621
+ if (versioned.length > 0) {
3622
+ versioned.sort().reverse();
3623
+ const path = join(binDir, versioned[0]);
3624
+ if (await fileExists(path)) return path;
3625
+ }
3626
+ const plain = join(binDir, "terraform");
3627
+ if (await fileExists(plain)) return plain;
3628
+ return null;
3629
+ } catch {
3630
+ return null;
3631
+ }
3632
+ }
3633
+ async function fileExists(path) {
3634
+ try {
3635
+ const info = await stat(path);
3636
+ return info.isFile();
3637
+ } catch {
3638
+ return false;
3639
+ }
3640
+ }
3641
+
3642
+ //#endregion
3643
+ //#region src/gates/mirror.ts
3644
+ const DEFAULT_PROVIDER_MIRRORS = ["https://mirrors.huaweicloud.com/terraform/"];
3645
+ const HUAWEICLOUD_PROVIDER_MIRRORS = DEFAULT_PROVIDER_MIRRORS;
3646
+ /**
3647
+ * Write <deployment>/.terraformrc with provider mirror config.
3648
+ * Does NOT overwrite if the file already exists (user-provided).
3649
+ * Returns the path, or null if no file was written.
3650
+ */
3651
+ async function writeProviderMirrorConfig(deployment, mirrors = DEFAULT_PROVIDER_MIRRORS) {
3652
+ if (mirrors.length === 0) return null;
3653
+ const rcPath = join(deployment, ".terraformrc");
3654
+ try {
3655
+ const { stat: stat$1 } = await import("node:fs/promises");
3656
+ await stat$1(rcPath);
3657
+ return null;
3658
+ } catch {}
3659
+ const lines = ["provider_installation {"];
3660
+ for (const m of mirrors) {
3661
+ const trimmed = m.trim();
3662
+ if (!trimmed) continue;
3663
+ if (isURL(trimmed)) lines.push(` network_mirror {`, ` url = ${JSON.stringify(trimmed)}`, ` include = ["registry.terraform.io/huaweicloud/*"]`, ` }`);
3664
+ else lines.push(` filesystem_mirror {`, ` path = ${JSON.stringify(trimmed)}`, ` include = ["registry.terraform.io/huaweicloud/*"]`, ` }`);
3665
+ }
3666
+ lines.push(` direct {`, ` exclude = ["registry.terraform.io/huaweicloud/*"]`, ` }`, `}`);
3667
+ await writeFile(rcPath, lines.join("\n") + "\n", "utf8");
3668
+ return rcPath;
3669
+ }
3670
+ function isURL(s) {
3671
+ return s.startsWith("http://") || s.startsWith("https://");
3672
+ }
3673
+
3674
+ //#endregion
3675
+ //#region src/security-groups.ts
3676
+ /** Extract secgroup rules from a `terraform show -json` plan or state output. */
3677
+ function extractSecurityGroups(planOrStateJson) {
3678
+ const resources = planOrStateJson.planned_values?.root_module?.resources ?? planOrStateJson.values?.root_module?.resources ?? [];
3679
+ const rules = [];
3680
+ for (const res of resources) {
3681
+ if (!res.type.endsWith("_secgroup_rule") && !res.type.endsWith("_security_group_rule")) continue;
3682
+ const vals = res.values ?? {};
3683
+ const ports = portsToString(vals);
3684
+ rules.push({
3685
+ address: res.address,
3686
+ rule_local_name: extractRuleLocalName(res.address),
3687
+ direction: String(vals["direction"] ?? ""),
3688
+ protocol: String(vals["protocol"] ?? ""),
3689
+ ports,
3690
+ source: String(vals["remote_ip_prefix"] ?? "")
3691
+ });
3692
+ }
3693
+ return rules;
3694
+ }
3695
+ /** Render ports: prefer `ports` string, else `port_range_min..port_range_max`. */
3696
+ function portsToString(vals) {
3697
+ const p = vals["ports"];
3698
+ if (typeof p === "string" && p !== "") return p;
3699
+ const min = vals["port_range_min"];
3700
+ const max = vals["port_range_max"];
3701
+ if (typeof min === "number" && typeof max === "number") return min === max ? String(min) : `${min}..${max}`;
3702
+ return "";
3703
+ }
3704
+ /**
3705
+ * Extract the rule's local name from its address.
3706
+ * e.g. huaweicloud_networking_secgroup_rule.ssh → "ssh"
3707
+ *
3708
+ * Plan-time security_group_id is "known after apply" — we CANNOT reliably
3709
+ * correlate a rule to its owning secgroup from the plan JSON. So we surface
3710
+ * only the rule's local name as a label, not a secgroup resource address.
3711
+ */
3712
+ function extractRuleLocalName(ruleAddress) {
3713
+ const dotIdx = ruleAddress.indexOf(".");
3714
+ if (dotIdx < 0) return ruleAddress;
3715
+ return ruleAddress.slice(dotIdx + 1);
3716
+ }
3717
+
3718
+ //#endregion
3719
+ //#region src/tools/terraform.ts
3720
+ /** Max stdout/stderr size per subprocess — 50MB. Prevents OOM on huge plans. */
3721
+ const MAX_OUTPUT_BYTES = 50 * 1024 * 1024;
3722
+ /** Default timeout for terraform commands (30 min — apply can be long). */
3723
+ const TERRAFORM_TIMEOUT_MS = 30 * 60 * 1e3;
3724
+ /**
3725
+ * Refuse a cloud-mutating `terraform apply` in read-only mode, at the funnel.
3726
+ *
3727
+ * The tool-level gate in `guard` names `terraform_apply` explicitly, which
3728
+ * covers today's call sites. This check covers tomorrow's: every terraform
3729
+ * invocation in this module goes through `runTerraform`, so deciding here
3730
+ * means a future call site cannot introduce a mutation that the read-only
3731
+ * switch silently fails to see.
3732
+ *
3733
+ * The subject is the `apply` subcommand specifically. `terraform_apply` runs
3734
+ * `apply -auto-approve`; `terraform_refresh` runs
3735
+ * `apply -refresh-only -auto-approve`, which reconciles local state against
3736
+ * the cloud and changes nothing in the account — the same "reads are fine"
3737
+ * rule the HTTP gate applies to GET. Testing for `-refresh-only` rather than
3738
+ * allowing a fixed set of argument vectors keeps that distinction exact: drop
3739
+ * the flag from the refresh path and this refuses it, which is precisely the
3740
+ * edit that would otherwise turn a read into a write unnoticed.
3741
+ *
3742
+ * @param args - argv passed to the terraform binary.
3743
+ * @returns a refusal message, or `undefined` to proceed.
3744
+ */
3745
+ function denyTerraformMutation(args) {
3746
+ if (writesAllowed()) return void 0;
3747
+ const subcommand = args[0];
3748
+ if (subcommand !== "apply" && subcommand !== "destroy") return void 0;
3749
+ if (args.includes("-refresh-only")) return void 0;
3750
+ return `Refused: \`terraform ${subcommand}\` changes HuaweiCloud resources, and this session is in read-only mode. Ask the user to switch the session to read-write mode. Read-only alternatives: terraform_plan, terraform_state, terraform_refresh.`;
3751
+ }
3752
+ async function runTerraform(cwd, args, extraEnv = []) {
3753
+ const refusal = denyTerraformMutation(args);
3754
+ if (refusal !== void 0) throw new Error(refusal);
3755
+ const { binary, env } = await resolveTerraformEnv(cwd, extraEnv);
3756
+ if (env["HW_ACCESS_KEY"]) {
3757
+ const account = await loadAccount();
3758
+ if (account) await backfillAccount(cwd, {
3759
+ name: account.account_name,
3760
+ account_id: account.account_id
3761
+ }).catch(() => {});
3762
+ }
3763
+ return new Promise((resolve) => {
3764
+ const child = spawn(binary, args, {
3765
+ cwd,
3766
+ env: {
3767
+ ...process.env,
3768
+ ...env
3769
+ },
3770
+ stdio: [
3771
+ "ignore",
3772
+ "pipe",
3773
+ "pipe"
3774
+ ]
3775
+ });
3776
+ let stdout = "";
3777
+ let stderr = "";
3778
+ let stdoutTruncated = false;
3779
+ let stderrTruncated = false;
3780
+ child.stdout.on("data", (d) => {
3781
+ if (!stdoutTruncated && stdout.length + d.length > MAX_OUTPUT_BYTES) {
3782
+ stdout += d.toString().slice(0, MAX_OUTPUT_BYTES - stdout.length);
3783
+ stdoutTruncated = true;
3784
+ child.kill("SIGTERM");
3785
+ } else if (!stdoutTruncated) stdout += d.toString();
3786
+ });
3787
+ child.stderr.on("data", (d) => {
3788
+ if (!stderrTruncated && stderr.length + d.length > MAX_OUTPUT_BYTES) {
3789
+ stderr += d.toString().slice(0, MAX_OUTPUT_BYTES - stderr.length);
3790
+ stderrTruncated = true;
3791
+ } else if (!stderrTruncated) stderr += d.toString();
3792
+ });
3793
+ const timer = setTimeout(() => {
3794
+ child.kill("SIGTERM");
3795
+ setTimeout(() => child.kill("SIGKILL"), 5e3);
3796
+ }, TERRAFORM_TIMEOUT_MS);
3797
+ child.on("close", (code) => {
3798
+ clearTimeout(timer);
3799
+ resolve({
3800
+ exitCode: code ?? 0,
3801
+ stdout,
3802
+ stderr,
3803
+ stdoutTruncated,
3804
+ stderrTruncated
3805
+ });
3806
+ });
3807
+ child.on("error", (err) => {
3808
+ clearTimeout(timer);
3809
+ resolve({
3810
+ exitCode: -1,
3811
+ stdout,
3812
+ stderr: err.message,
3813
+ stdoutTruncated,
3814
+ stderrTruncated
3815
+ });
3816
+ });
3817
+ });
3818
+ }
3819
+ /** Register all 9 terraform tools. */
3820
+ function registerTerraformTools(registrar) {
3821
+ registerInstall(registrar);
3822
+ registerInit(registrar);
3823
+ registerPlan(registrar);
3824
+ registerApply(registrar);
3825
+ registerDestroy(registrar);
3826
+ registerRefresh(registrar);
3827
+ registerState(registrar);
3828
+ registerImport(registrar);
3829
+ }
3830
+ const envParam = z.array(z.string()).optional().describe("Extra env vars for the terraform subprocess, each KEY=VALUE. e.g. [\"TF_LOG=DEBUG\", \"TF_LOG_PROVIDER=OFF\", \"TF_CLI_ARGS_plan=-refresh=false\"]");
3831
+ function registerInstall(registrar) {
3832
+ registrar.registerTool("terraform_install", {
3833
+ title: "Install terraform",
3834
+ description: "Ensure a terraform binary is available. Only installs the binary — provider plugins are pulled by terraform_init. Priority: terraform_path param > PATH > the host cache ($DSH_HOME/terraform/bin) > download from binary_mirrors. Download falls back to <deployment>/.terraform/bin/ when that is not writable.",
3835
+ annotations: CLOUD_WRITE,
3836
+ inputSchema: z.object({
3837
+ deployment: deploymentParam.describe("Used only as download fallback when HOME is not writable."),
3838
+ terraform_path: z.string().optional().describe("Explicit path to a terraform binary."),
3839
+ binary_mirrors: z.array(z.string()).optional().describe("Binary download mirror URLs, tried in order."),
3840
+ env: envParam
3841
+ })
3842
+ }, guard(async (args) => handleInstall(args.deployment, args.terraform_path, args.binary_mirrors, args.env ?? [])));
3843
+ }
3844
+ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv = []) {
3845
+ if (terraformPath) {
3846
+ const { stat: stat$1 } = await import("node:fs/promises");
3847
+ try {
3848
+ const info = await stat$1(terraformPath);
3849
+ if (!info.isFile()) return fail(`terraform_path is not a file: ${terraformPath}`);
3850
+ } catch {
3851
+ return fail(`terraform_path not found: ${terraformPath}`);
3852
+ }
3853
+ return ok(JSON.stringify({
3854
+ terraform: "(user-specified)",
3855
+ path: terraformPath,
3856
+ source: "parameter",
3857
+ cached: true
3858
+ }));
3859
+ }
3860
+ try {
3861
+ const { binary } = await resolveTerraformEnv(deployment, extraEnv);
3862
+ const ver = await getTerraformVersion(binary);
3863
+ return ok(JSON.stringify({
3864
+ terraform: ver,
3865
+ path: binary,
3866
+ source: "path-or-cache",
3867
+ cached: true
3868
+ }));
3869
+ } catch {}
3870
+ const mirrors = binaryMirrors ?? DEFAULT_BINARY_MIRRORS;
3871
+ const { version, arch, platform } = detectPlatform();
3872
+ const destDir = await resolveDownloadDir(deployment);
3873
+ const binPath = join(destDir, `terraform${version ? "-" + version : ""}`);
3874
+ return runOperation(async () => {
3875
+ const failures = [];
3876
+ for (const mirror of mirrors) try {
3877
+ await downloadAndExtract(mirror, version, platform, arch, destDir);
3878
+ const ver = await getTerraformVersion(binPath);
3879
+ return {
3880
+ exit_code: 0,
3881
+ outputs: {
3882
+ terraform: ver,
3883
+ path: binPath,
3884
+ source: "downloaded",
3885
+ cached: false
3886
+ }
3887
+ };
3888
+ } catch (err) {
3889
+ const kind = err.kind ?? "network";
3890
+ failures.push({
3891
+ mirror,
3892
+ reason: err instanceof Error ? err.message : String(err),
3893
+ kind
3894
+ });
3895
+ }
3896
+ const detail = failures.map((f) => ` - ${f.mirror}: ${f.reason}`).join("\n");
3897
+ const kinds = new Set(failures.map((f) => f.kind));
3898
+ const actions = [];
3899
+ if (kinds.has("http_4xx")) actions.push(`the mirror does not host terraform ${version} for ${platform}_${arch} (HTTP 4xx). Retrying won't help — re-invoke terraform_install with a different version, or pass binary_mirrors pointing at a mirror that has it.`);
3900
+ if (kinds.has("network")) actions.push("the mirror is unreachable (DNS/connection/TLS). A transient blip may clear on retry — re-invoke terraform_install once; if it fails again, obtain a terraform binary yourself (via shell: download + unzip, or a package manager) and re-invoke with terraform_path.");
3901
+ if (kinds.has("http_5xx")) actions.push("the mirror returned a server error (HTTP 5xx) — temporarily broken. Retry terraform_install after a short wait, or pass a different binary_mirrors.");
3902
+ if (kinds.has("extraction")) actions.push("the downloaded zip is corrupt or unreadable. Retry terraform_install once; if it fails again, the mirror may be serving a bad artifact — try a different binary_mirrors.");
3903
+ actions.push("If mirrors keep failing, obtain a terraform binary yourself (e.g. via shell: download from https://releases.hashicorp.com/terraform/<ver>/terraform_<ver>_<os>_<arch>.zip and unzip it, or use a package manager), then re-invoke terraform_install with terraform_path pointing at the executable.");
3904
+ return {
3905
+ exit_code: 1,
3906
+ outputs: { error: `terraform not found and download failed from all ${mirrors.length} mirror(s):\n${detail}\nNext actions:\n${actions.map((a) => ` - ${a}`).join("\n")}` }
3907
+ };
3908
+ });
3909
+ }
3910
+ function registerInit(registrar) {
3911
+ registrar.registerTool("terraform_init", {
3912
+ title: "Terraform init",
3913
+ description: "Run `terraform init`. Generates <deployment>/.terraformrc with provider mirror config (if not user-provided), sets TF_PLUGIN_CACHE_DIR, pulls provider plugins. Credential env injected from keychain.",
3914
+ annotations: CLOUD_WRITE,
3915
+ inputSchema: z.object({
3916
+ deployment: deploymentParam,
3917
+ provider_mirrors: z.array(z.string()).optional().describe("Provider mirror URLs/paths."),
3918
+ env: envParam
3919
+ })
3920
+ }, guard(async (args) => handleInit(args.deployment, args.provider_mirrors, args.env ?? [])));
3921
+ }
3922
+ async function handleInit(deployment, providerMirrors, extraEnv = []) {
3923
+ try {
3924
+ await assertNoCredentials(deployment);
3925
+ } catch (err) {
3926
+ return fail(err instanceof Error ? err.message : String(err));
3927
+ }
3928
+ const mirrors = providerMirrors ?? HUAWEICLOUD_PROVIDER_MIRRORS;
3929
+ await writeProviderMirrorConfig(deployment, mirrors);
3930
+ return runOperation(async () => {
3931
+ const result = await runTerraform(deployment, ["init"], extraEnv);
3932
+ if (result.exitCode !== 0) return {
3933
+ exit_code: result.exitCode,
3934
+ outputs: {
3935
+ stdout: result.stdout,
3936
+ stderr: result.stderr
3937
+ }
3938
+ };
3939
+ return {
3940
+ exit_code: 0,
3941
+ outputs: {
3942
+ stdout: result.stdout,
3943
+ stderr: result.stderr
3944
+ }
3945
+ };
3946
+ });
3947
+ }
3948
+ function registerPlan(registrar) {
3949
+ registrar.registerTool("terraform_plan", {
3950
+ title: "Terraform plan",
3951
+ description: "Run `terraform plan`. Returns a STRUCTURED plan (terraform show -json) to parse and reorganize into human-readable form for the user.",
3952
+ annotations: READ_ONLY_CLOUD,
3953
+ inputSchema: z.object({
3954
+ deployment: deploymentParam,
3955
+ env: envParam
3956
+ })
3957
+ }, guard(async (args) => handlePlan(args.deployment, args.env ?? [])));
3958
+ }
3959
+ async function handlePlan(deployment, extraEnv = []) {
3960
+ return runOperation(async () => {
3961
+ const result = await runTerraform(deployment, [
3962
+ "plan",
3963
+ "-out=plan.tfplan",
3964
+ "-json"
3965
+ ], extraEnv);
3966
+ if (result.exitCode !== 0) return {
3967
+ exit_code: result.exitCode,
3968
+ outputs: {
3969
+ stdout: result.stdout,
3970
+ stderr: result.stderr
3971
+ }
3972
+ };
3973
+ let planJson = null;
3974
+ let sgRules = [];
3975
+ let planTruncated = false;
3976
+ try {
3977
+ const showResult = await runTerraform(deployment, [
3978
+ "show",
3979
+ "-json",
3980
+ "plan.tfplan"
3981
+ ], extraEnv);
3982
+ if (showResult.exitCode === 0) {
3983
+ if (showResult.stdoutTruncated) planTruncated = true;
3984
+ planJson = JSON.parse(showResult.stdout);
3985
+ sgRules = extractSecurityGroups(planJson);
3986
+ }
3987
+ } catch {}
3988
+ const summary = planJson ? summaryFromPlanJson(planJson) : parsePlanSummary(result.stdout);
3989
+ return {
3990
+ exit_code: 0,
3991
+ outputs: {
3992
+ plan_json: planJson,
3993
+ summary: {
3994
+ ...summary,
3995
+ security_group_rules: sgRules
3996
+ },
3997
+ ...planTruncated ? { warning: "plan output exceeded size limit and was truncated — plan_json may be incomplete or null" } : {}
3998
+ }
3999
+ };
4000
+ });
4001
+ }
4002
+ function registerApply(registrar) {
4003
+ registrar.registerTool(
4004
+ "terraform_apply",
4005
+ {
4006
+ title: "Terraform apply",
4007
+ description: "Run `terraform apply`. Enforces four safety gates: networking.json exists, cost.json exists, tf_hash state machine, no plaintext credentials.",
4008
+ annotations: CLOUD_DESTRUCTIVE,
4009
+ inputSchema: z.object({
4010
+ deployment: deploymentParam,
4011
+ env: envParam
4012
+ })
4013
+ },
4014
+ // Named so the read-only gate can refuse it: this tool creates and
4015
+ // modifies cloud resources, and never calls signedHttp, so the HTTP gate
4016
+ // cannot see it (see permission/gate.ts).
4017
+ guard(async (args) => handleApply(args.deployment, args.env ?? []), "terraform_apply")
4018
+ );
4019
+ }
4020
+ async function handleApply(deployment, extraEnv = []) {
4021
+ try {
4022
+ await assertNetworking(deployment);
4023
+ await runCostGate(deployment);
4024
+ await assertNoCredentials(deployment);
4025
+ } catch (err) {
4026
+ return fail(err instanceof Error ? err.message : String(err));
4027
+ }
4028
+ return runOperation(async () => {
4029
+ const result = await runTerraform(deployment, ["apply", "-auto-approve"], extraEnv);
4030
+ if (result.exitCode !== 0) return {
4031
+ exit_code: result.exitCode,
4032
+ outputs: {
4033
+ stdout: result.stdout,
4034
+ stderr: result.stderr
4035
+ }
4036
+ };
4037
+ try {
4038
+ await fillTfHash(deployment);
4039
+ } catch {}
4040
+ await updateSnapshot(deployment, {
4041
+ applied: true,
4042
+ last_operation: "terraform_apply"
4043
+ });
4044
+ return {
4045
+ exit_code: 0,
4046
+ outputs: {
4047
+ stdout: result.stdout,
4048
+ stderr: result.stderr
4049
+ }
4050
+ };
4051
+ });
4052
+ }
4053
+ function registerDestroy(registrar) {
4054
+ registrar.registerTool(
4055
+ "terraform_destroy",
4056
+ {
4057
+ title: "Terraform destroy",
4058
+ description: "Run `terraform destroy`. Permanently deletes cloud resources managed by this deployment — irreversible. MUST confirm with the user before calling. Safety gate: refuses if tfstate is empty (nothing to destroy) or if .tf files contain plaintext credentials (same scan as init/apply). By default destroys ALL resources in the deployment. Pass `target` to destroy only specific resources by address — use this to spare imported (reuse) resources: destroy only the newly-created resources, leaving imported ones in state. Call terraform_state first to list resource addresses. A future enhancement will return a structured plan -destroy preview for the user to review before the actual destroy.",
4059
+ annotations: CLOUD_DESTRUCTIVE,
4060
+ inputSchema: z.object({
4061
+ deployment: deploymentParam,
4062
+ target: z.array(z.string()).optional().describe("Resource addresses to destroy selectively. e.g. [\"huaweicloud_vpc.main\", \"huaweicloud_vpc_subnet.sub1\"]. Omit to destroy ALL resources (default). Use terraform_state to list addresses. Use this to spare imported resources: destroy only newly-created resources, leaving imported ones in state."),
4063
+ env: envParam
4064
+ })
4065
+ },
4066
+ // Named so the read-only gate can refuse it: destroy deletes cloud
4067
+ // resources and never calls signedHttp (see permission/gate.ts).
4068
+ guard(async (args) => {
4069
+ const recordedCount = await stateRecordedResourceCount(args.deployment);
4070
+ if (recordedCount === 0) return fail("no resources recorded in tfstate — nothing to destroy (already destroyed or never applied)");
4071
+ try {
4072
+ await assertNoCredentials(args.deployment);
4073
+ } catch (err) {
4074
+ return fail(err instanceof Error ? err.message : String(err));
4075
+ }
4076
+ return runOperation(async () => {
4077
+ const tfArgs = ["destroy", "-auto-approve"];
4078
+ if (args.target && args.target.length > 0) for (const t of args.target) tfArgs.push(`-target=${t}`);
4079
+ const result = await runTerraform(args.deployment, tfArgs, args.env ?? []);
4080
+ if (result.exitCode !== 0) return {
4081
+ exit_code: result.exitCode,
4082
+ outputs: {
4083
+ stdout: result.stdout,
4084
+ stderr: result.stderr
4085
+ }
4086
+ };
4087
+ await updateSnapshot(args.deployment, {
4088
+ destroyed: true,
4089
+ last_operation: "terraform_destroy"
4090
+ });
4091
+ return {
4092
+ exit_code: 0,
4093
+ outputs: {
4094
+ stdout: result.stdout,
4095
+ stderr: result.stderr,
4096
+ resources_destroyed: args.target ? args.target.length : recordedCount,
4097
+ ...args.target ? { targeted: args.target } : {}
4098
+ }
4099
+ };
4100
+ });
4101
+ }, "terraform_destroy")
4102
+ );
4103
+ }
4104
+ function registerRefresh(registrar) {
4105
+ registrar.registerTool("terraform_refresh", {
4106
+ title: "Terraform refresh",
4107
+ description: "Run `terraform apply -refresh-only`. Updates tfstate to reflect real cloud state.",
4108
+ annotations: READ_ONLY_CLOUD,
4109
+ inputSchema: z.object({
4110
+ deployment: deploymentParam,
4111
+ env: envParam
4112
+ })
4113
+ }, guard(async (args) => {
4114
+ return runOperation(async () => {
4115
+ const result = await runTerraform(args.deployment, [
4116
+ "apply",
4117
+ "-refresh-only",
4118
+ "-auto-approve"
4119
+ ], args.env ?? []);
4120
+ if (result.exitCode !== 0) return {
4121
+ exit_code: result.exitCode,
4122
+ outputs: {
4123
+ stdout: result.stdout,
4124
+ stderr: result.stderr
4125
+ }
4126
+ };
4127
+ return {
4128
+ exit_code: 0,
4129
+ outputs: {
4130
+ stdout: result.stdout,
4131
+ stderr: result.stderr
4132
+ }
4133
+ };
4134
+ });
4135
+ }));
4136
+ }
4137
+ function registerState(registrar) {
4138
+ registrar.registerTool("terraform_state", {
4139
+ title: "Read tfstate",
4140
+ description: "Read terraform state via `terraform show -json`. Returns structured state. Uses terraform's stable show -json interface (not direct tfstate parse).",
4141
+ annotations: READ_ONLY_LOCAL,
4142
+ inputSchema: z.object({
4143
+ deployment: deploymentParam,
4144
+ env: envParam
4145
+ })
4146
+ }, guard(async (args) => {
4147
+ const result = await runTerraform(args.deployment, ["show", "-json"], args.env ?? []);
4148
+ if (result.exitCode !== 0) return fail(`terraform state read failed: exit ${result.exitCode}: ${result.stderr}`);
4149
+ if (result.stdoutTruncated) return fail("terraform state output exceeded size limit and was truncated — state too large to parse");
4150
+ try {
4151
+ const stateJson = JSON.parse(result.stdout);
4152
+ let sgRules = [];
4153
+ try {
4154
+ sgRules = extractSecurityGroups(stateJson);
4155
+ } catch {}
4156
+ return ok(JSON.stringify({
4157
+ state_json: stateJson,
4158
+ security_group_rules: sgRules
4159
+ }));
4160
+ } catch (err) {
4161
+ return fail(`failed to parse state: ${err instanceof Error ? err.message : String(err)}`);
4162
+ }
4163
+ }));
4164
+ }
4165
+ function registerImport(registrar) {
4166
+ registrar.registerTool("terraform_import", {
4167
+ title: "Terraform import",
4168
+ description: "Run `terraform import` to bring an existing cloud resource into tfstate without creating it. Use after list_existing_resources to reuse an existing resource: write the resource block in .tf (with the same address), then import to populate its state. The resource address and ID format depend on the provider type — check provider docs or apiexplorer for the import syntax (e.g. huaweicloud_compute_instance.myvm <instance-id>).",
4169
+ annotations: READ_ONLY_CLOUD,
4170
+ inputSchema: z.object({
4171
+ deployment: deploymentParam,
4172
+ address: z.string().min(1).describe("Terraform resource address, e.g. huaweicloud_compute_instance.myvm"),
4173
+ id: z.string().min(1).describe("Cloud resource ID to import (provider-specific format)"),
4174
+ env: envParam
4175
+ })
4176
+ }, guard(async (args) => handleImport(args.deployment, args.address, args.id, args.env ?? [])));
4177
+ }
4178
+ async function handleImport(deployment, address, id, extraEnv = []) {
4179
+ try {
4180
+ await assertNoCredentials(deployment);
4181
+ } catch (err) {
4182
+ return fail(err instanceof Error ? err.message : String(err));
4183
+ }
4184
+ const result = await runTerraform(deployment, [
4185
+ "import",
4186
+ address,
4187
+ id
4188
+ ], extraEnv);
4189
+ if (result.exitCode !== 0) return fail(JSON.stringify({
4190
+ stdout: result.stdout,
4191
+ stderr: result.stderr
4192
+ }));
4193
+ return ok(JSON.stringify({
4194
+ address,
4195
+ id,
4196
+ imported: true,
4197
+ stdout: result.stdout,
4198
+ stderr: result.stderr
4199
+ }));
4200
+ }
4201
+ /** Get terraform version string via `terraform version`. */
4202
+ async function getTerraformVersion(binary) {
4203
+ return new Promise((resolve) => {
4204
+ const child = spawn(binary, ["version"], { stdio: [
4205
+ "ignore",
4206
+ "pipe",
4207
+ "pipe"
4208
+ ] });
4209
+ let out = "";
4210
+ child.stdout.on("data", (d) => {
4211
+ out += d.toString();
4212
+ });
4213
+ child.on("close", () => {
4214
+ const m = out.match(/Terraform v(\S+)/);
4215
+ resolve(m ? m[1] : "unknown");
4216
+ });
4217
+ child.on("error", () => resolve("unknown"));
4218
+ });
4219
+ }
4220
+ /**
4221
+ * Default terraform version to download when the user doesn't pin one.
4222
+ *
4223
+ * Pinned rather than "latest" to keep installs reproducible and avoid a
4224
+ * network round-trip to probe the latest version. Bump this when a newer
4225
+ * version is vetted. Verified available:
4226
+ * https://releases.hashicorp.com/terraform/1.9.5/terraform_1.9.5_linux_amd64.zip
4227
+ */
4228
+ const DEFAULT_TERRAFORM_VERSION = "1.9.5";
4229
+ /**
4230
+ * Default binary download mirrors, tried in order.
4231
+ *
4232
+ * HuaweiCloud does NOT mirror the terraform binary (verified:
4233
+ * mirrors.huaweicloud.com/terraform/ hosts only the provider registry;
4234
+ * .../hashicorp/terraform/ returns HTML, not zip). The only source is
4235
+ * HashiCorp's official releases. A continental-CDN mirror would help
4236
+ * download speed in CN, but none was found — the user can pass
4237
+ * binary_mirrors to override with a known-good mirror.
4238
+ */
4239
+ const DEFAULT_BINARY_MIRRORS = ["https://releases.hashicorp.com/terraform/"];
4240
+ /** Detect platform for download URL construction. */
4241
+ function detectPlatform() {
4242
+ const platform = process.platform === "win32" ? "windows" : process.platform === "darwin" ? "darwin" : "linux";
4243
+ const arch = process.arch === "arm64" ? "arm64" : "amd64";
4244
+ return {
4245
+ version: DEFAULT_TERRAFORM_VERSION,
4246
+ arch,
4247
+ platform
4248
+ };
4249
+ }
4250
+ /** Resolve download dir: the host cache preferred, deployment fallback. */
4251
+ async function resolveDownloadDir(deployment) {
4252
+ const globalDir = terraformBinDir();
4253
+ try {
4254
+ await mkdir(globalDir, { recursive: true });
4255
+ const testFile = join(globalDir, ".write-test");
4256
+ await writeFile(testFile, "");
4257
+ const { unlink } = await import("node:fs/promises");
4258
+ await unlink(testFile);
4259
+ return globalDir;
4260
+ } catch {
4261
+ const depDir = join(deployment, ".terraform", "bin");
4262
+ await mkdir(depDir, { recursive: true });
4263
+ return depDir;
4264
+ }
4265
+ }
4266
+ function downloadError(kind, message) {
4267
+ const e = new Error(message);
4268
+ e.kind = kind;
4269
+ return e;
4270
+ }
4271
+ async function downloadAndExtract(mirror, version, platform, arch, destDir) {
4272
+ const base = mirror.endsWith("/") ? mirror : mirror + "/";
4273
+ const url = `${base}${version}/terraform_${version}_${platform}_${arch}.zip`;
4274
+ let resp;
4275
+ try {
4276
+ resp = await fetch(url, { signal: AbortSignal.timeout(3e5) });
4277
+ } catch (err) {
4278
+ const cause = err instanceof Error && err.cause instanceof Error ? err.cause : null;
4279
+ const detail = cause ? `${cause.code ?? cause.name}: ${cause.message}` : err instanceof Error ? err.message : String(err);
4280
+ throw downloadError("network", `network error fetching ${url}: ${detail}`);
4281
+ }
4282
+ if (!resp.ok) {
4283
+ const kind = resp.status >= 500 ? "http_5xx" : "http_4xx";
4284
+ throw downloadError(kind, `HTTP ${resp.status} ${resp.statusText} fetching ${url}`);
4285
+ }
4286
+ const buf = Buffer.from(await resp.arrayBuffer());
4287
+ const { writeFile: writeFileFs, unlink, rename } = await import("node:fs/promises");
4288
+ const tmpZip = join(destDir, `.terraform-${version}-${Date.now()}.zip`);
4289
+ await writeFileFs(tmpZip, buf);
4290
+ try {
4291
+ await extractArchive(tmpZip, destDir);
4292
+ } catch (err) {
4293
+ throw downloadError("extraction", `zip extraction failed for ${url}: ${err instanceof Error ? err.message : String(err)}`);
4294
+ } finally {
4295
+ await unlink(tmpZip).catch(() => {});
4296
+ }
4297
+ const extractedPath = join(destDir, "terraform");
4298
+ const versionedPath = join(destDir, `terraform-${version}`);
4299
+ await rename(extractedPath, versionedPath);
4300
+ if (platform !== "windows") {
4301
+ const { chmod } = await import("node:fs/promises");
4302
+ await chmod(versionedPath, 493);
4303
+ }
4304
+ }
4305
+ /** Parse `terraform plan -json` output for create/change/destroy counts. */
4306
+ function parsePlanSummary(stdout) {
4307
+ const summary = {
4308
+ create: 0,
4309
+ change: 0,
4310
+ destroy: 0
4311
+ };
4312
+ for (const line of stdout.split("\n")) try {
4313
+ const obj = JSON.parse(line);
4314
+ if (obj.type === "summary" && obj.changes) {
4315
+ summary.create = obj.changes.add ?? 0;
4316
+ summary.change = obj.changes.change ?? 0;
4317
+ summary.destroy = obj.changes.destroy ?? 0;
4318
+ break;
4319
+ }
4320
+ } catch {}
4321
+ return summary;
4322
+ }
4323
+ /**
4324
+ * Derive create/change/destroy counts from `terraform show -json <plan>`
4325
+ * resource_changes — the authoritative, version-independent source.
4326
+ *
4327
+ * terraform 1.9+ changed the `plan -json` stdout summary line to
4328
+ * type:"change_summary" (from type:"summary"), so parsePlanSummary returns 0.
4329
+ * The show -json output's resource_changes[].change.actions is stable across
4330
+ * versions: actions is an array like ["create"], ["update"], ["delete"],
4331
+ * ["no-op"], or composite like ["create","delete"] (replace). We take the
4332
+ * first action as the primary — same mapping convention as terraform's own
4333
+ * tfjson (planFromJSON actionFromTFJSON).
4334
+ */
4335
+ function summaryFromPlanJson(planJson) {
4336
+ const summary = {
4337
+ create: 0,
4338
+ change: 0,
4339
+ destroy: 0
4340
+ };
4341
+ const rc = planJson?.resource_changes;
4342
+ if (!rc) return summary;
4343
+ for (const r of rc) {
4344
+ const actions = r.change?.actions ?? [];
4345
+ if (actions.length === 0) continue;
4346
+ const primary = actions[0];
4347
+ if (primary === "create") summary.create++;
4348
+ else if (primary === "update") summary.change++;
4349
+ else if (primary === "delete") summary.destroy++;
4350
+ }
4351
+ return summary;
4352
+ }
4353
+ /**
4354
+ * Run a long terraform operation and return the tool-call result.
4355
+ *
4356
+ * Synchronous by construction. There is no background-task variant and no
4357
+ * progress channel: the harness bounds the call with the tool's own timeout,
4358
+ * and a caller that wants to give up sooner cancels the call.
4359
+ *
4360
+ * Safety gates MUST run before this — they are the synchronous fast-fail that
4361
+ * stops a doomed run before terraform starts doing anything.
4362
+ *
4363
+ * @param work - the operation, returning its exit code and outputs.
4364
+ * @returns the outputs on success, or the outputs-or-exit-code as a failure.
4365
+ */
4366
+ async function runOperation(work) {
4367
+ const result = await work();
4368
+ if (result.exit_code === 0) return ok(JSON.stringify(result.outputs ?? {}));
4369
+ return fail(JSON.stringify(result.outputs ?? { error: `exit ${result.exit_code}` }));
4370
+ }
4371
+
4372
+ //#endregion
4373
+ //#region src/tools/provider_schema.ts
4374
+ /**
4375
+ * provider_schema (§3.2).
4376
+ *
4377
+ * Runs `terraform providers schema -json` and extracts the huaweicloud
4378
+ * provider's schema. The full output is ~6MB (thousands of resource and
4379
+ * data-source schemas) — returning it whole would blow the LLM context. So:
4380
+ * - With resource_type: return that single type's full schema (block,
4381
+ * attributes, nested blocks) — small, focused.
4382
+ * - Without resource_type: return only the type-name lists (resource_types
4383
+ * + data_source_types), so the LLM can discover what exists and then
4384
+ * drill in with a resource_type arg.
4385
+ *
4386
+ * The provider_schemas key is the full registry address
4387
+ * "registry.terraform.io/huaweicloud/huaweicloud", NOT the short name
4388
+ * "huaweicloud" (verified against terraform providers schema -json output).
4389
+ */
4390
+ function registerProviderSchemaTool(registrar) {
4391
+ registrar.registerTool("provider_schema", {
4392
+ title: "Extract provider schema",
4393
+ description: "Extract the schema of the locally installed huaweicloud terraform provider by running `terraform providers schema -json` in the deployment directory. Without resource_type: return the list of all resource and data-source type names (the full schema is ~6MB, too large to return whole). Use the `filter` arg to narrow by substring (e.g. filter=\"vpc\" returns huaweicloud_vpc, huaweicloud_vpc_route, ...). With resource_type: return that type's full schema (attributes, types, required-ness, nested blocks). Call AFTER terraform_init.",
4394
+ annotations: READ_ONLY_LOCAL,
4395
+ inputSchema: z.object({
4396
+ deployment: deploymentParam,
4397
+ resource_type: z.string().optional().describe("e.g. \"huaweicloud_compute_instance\""),
4398
+ filter: z.string().optional().describe("Substring filter for type names (only when resource_type is absent).")
4399
+ })
4400
+ }, guard(async (args) => {
4401
+ const result = await runTerraform(args.deployment, [
4402
+ "providers",
4403
+ "schema",
4404
+ "-json"
4405
+ ]);
4406
+ if (result.exitCode !== 0) return fail(`provider_schema failed: exit ${result.exitCode}: ${result.stderr}`);
4407
+ try {
4408
+ const schema = JSON.parse(result.stdout);
4409
+ const providerSchemas = schema.provider_schemas ?? {};
4410
+ const hcKey = Object.keys(providerSchemas).find((k) => k.includes("huaweicloud/huaweicloud"));
4411
+ if (!hcKey) return fail("huaweicloud provider not found in schema — run terraform_init first");
4412
+ const hc = providerSchemas[hcKey];
4413
+ if (args.resource_type) {
4414
+ const rs = hc.resource_schemas?.[args.resource_type];
4415
+ if (rs) return ok(JSON.stringify({
4416
+ resource_type: args.resource_type,
4417
+ schema: rs
4418
+ }));
4419
+ const ds = hc.data_source_schemas?.[args.resource_type];
4420
+ if (ds) return ok(JSON.stringify({
4421
+ data_source: args.resource_type,
4422
+ schema: ds
4423
+ }));
4424
+ return fail(`resource_type not found: ${args.resource_type}. Call provider_schema without resource_type to list all available types.`);
4425
+ }
4426
+ const f = args.filter?.toLowerCase();
4427
+ const matchFilter = (name$1) => !f || name$1.toLowerCase().includes(f);
4428
+ const resourceTypes = Object.keys(hc.resource_schemas ?? {}).filter(matchFilter);
4429
+ const dataSourceTypes = Object.keys(hc.data_source_schemas ?? {}).filter(matchFilter);
4430
+ return ok(JSON.stringify({
4431
+ resource_types: resourceTypes,
4432
+ data_source_types: dataSourceTypes,
4433
+ ...f ? {
4434
+ filter: f,
4435
+ note: `filtered by substring "${f}"`
4436
+ } : {}
4437
+ }));
4438
+ } catch (err) {
4439
+ return fail(`failed to parse provider schema: ${err instanceof Error ? err.message : String(err)}`);
4440
+ }
4441
+ }));
4442
+ }
4443
+
4444
+ //#endregion
4445
+ //#region src/tools/index.ts
4446
+ /**
4447
+ * Register this plugin's tools on the DSH tool registry.
4448
+ *
4449
+ * Tool count: 17.
4450
+ *
4451
+ * 部署目录 2 + 状态文件 2 + 华为云能力 4 + terraform 9 = 17
4452
+ *
4453
+ * `auth` is not among them: it lives in `aishell-credentials`, which owns the
4454
+ * credential lifecycle and the form that collects AK/SK. A verify tool here
4455
+ * would mean two tools answering "is this account authenticated", one of them
4456
+ * depending on a store it does not own.
4457
+ *
4458
+ * The six long-running terraform tools (install/init/plan/apply/destroy/
4459
+ * refresh) run synchronously. Each call is bounded by the tool's own timeout,
4460
+ * not by any progress mechanism.
4461
+ */
4462
+ function registerAllTools(registrar) {
4463
+ registerDeploymentTools(registrar);
4464
+ registerNetworkingTool(registrar);
4465
+ registerCostTool(registrar);
4466
+ registerOpenApiTools(registrar);
4467
+ registerExamplesTool(registrar);
4468
+ registerExistingResourcesTool(registrar);
4469
+ registerProviderSchemaTool(registrar);
4470
+ registerTerraformTools(registrar);
4471
+ }
4472
+ /**
4473
+ * Shared zod string schema for the `deployment` parameter — an absolute or
4474
+ * relative path to the deployment workspace directory. Used by every tool
4475
+ * that operates on a deployment.
4476
+ */
4477
+ const deploymentParam = z.string().min(1).describe("部署工作区目录路径(绝对或相对)");
4478
+ /**
4479
+ * Shared zod string schema for `dest` — the reference-data extraction
4480
+ * target, distinct from the deployment workspace (§3.2: "distinct from
4481
+ * the deployment workspace — this is where reference data is extracted").
4482
+ */
4483
+ const destParam = z.string().min(1).describe("导出目标目录路径(参考数据,不是 deployment 工作区)");
4484
+
4485
+ //#endregion
4486
+ //#region src/permission.ts
4487
+ /**
4488
+ * The permission mode vocabulary the route and the prompt share.
4489
+ *
4490
+ * The mode itself lives in `./permission/mode.ts`, next to the gate that
4491
+ * enforces it — the tools read it directly (`writesAllowed()`, `getMode()`), so
4492
+ * there is no client half to write and no request to make.
4493
+ *
4494
+ * What stays here is the *wire* vocabulary: the two spellings the browser sends
4495
+ * and the shapes the route answers with. Declared separately from the internal
4496
+ * module rather than imported from it, so a change to the module's internal
4497
+ * naming cannot silently change the wire.
4498
+ *
4499
+ * @module @huaweidevtools/aishell-dsh-deploy/permission
4500
+ */
4501
+ /** The two modes, spelled as the browser sends them. */
4502
+ const PERMISSION_MODES = ["read_only", "read_write"];
4503
+
4504
+ //#endregion
4505
+ //#region src/permission-route.ts
4506
+ /** Route path, mounted under the host's authenticated `/api` fence. */
4507
+ const PERMISSION_PATH = "/api/aishell/permission";
4508
+ /** JSON response helper. */
4509
+ function json(body, status = 200) {
4510
+ return Response.json(body, { status });
4511
+ }
4512
+ /**
4513
+ * Report the current mode.
4514
+ *
4515
+ * @param deps - route collaborators.
4516
+ */
4517
+ function getMode(deps) {
4518
+ return Promise.resolve(json({
4519
+ ok: true,
4520
+ ...deps.read()
4521
+ }));
4522
+ }
4523
+ /**
4524
+ * Apply a mode.
4525
+ *
4526
+ * @param deps - route collaborators.
4527
+ * @param request - the incoming POST; its body carries `{ mode }`.
4528
+ */
4529
+ async function setMode(deps, request) {
4530
+ let body;
4531
+ try {
4532
+ body = await request.json();
4533
+ } catch {
4534
+ return json({
4535
+ ok: false,
4536
+ error: "Request body is not valid JSON."
4537
+ }, 400);
4538
+ }
4539
+ const mode = body?.mode;
4540
+ if (typeof mode !== "string" || !PERMISSION_MODES.includes(mode)) return json({
4541
+ ok: false,
4542
+ error: `mode must be one of: ${PERMISSION_MODES.join(", ")}`
4543
+ }, 400);
4544
+ const change = deps.write(mode);
4545
+ return json({
4546
+ ok: true,
4547
+ ...change
4548
+ });
4549
+ }
4550
+ /**
4551
+ * Build the route handlers.
4552
+ *
4553
+ * @param deps - route collaborators.
4554
+ * @returns handlers for the fetch registry.
4555
+ */
4556
+ function createPermissionRoutes(deps) {
4557
+ return {
4558
+ get: () => getMode(deps),
4559
+ set: (request) => setMode(deps, request)
4560
+ };
4561
+ }
4562
+
4563
+ //#endregion
4564
+ //#region src/permission-context.ts
4565
+ /** Name this contribution registers under; unique across the assembled prompt. */
4566
+ const PERMISSION_CONTEXT_NAME = "aishell:permission-policy";
4567
+ /**
4568
+ * What the model reads while mutations are refused.
4569
+ *
4570
+ * Three paragraphs, each doing one job: the state and its scope, the route
4571
+ * the gate does not cover, and the way of working that keeps a read-only
4572
+ * session useful.
4573
+ */
4574
+ const READ_ONLY_POLICY = `Current HuaweiCloud permission mode: read-only — nothing in the HuaweiCloud account is to change, by any route, including resources reachable directly.
4575
+
4576
+ An EIP, a tunnel, or an internal address that answers is still the same account. Reads over such a path are fine; state changes are not. Reaching a resource by a route the permission check does not cover does not make the change allowed — do not use one to do what a refusal declined.
4577
+
4578
+ Local work is unaffected: files and local processes are yours. Treat the session as review work — carry the investigation through and produce the complete change (plan, exact commands, cost or impact), stating what would be applied. Ask for read-write only when a specific operation is blocked.`;
4579
+ /**
4580
+ * The text this context contributes for one mode.
4581
+ *
4582
+ * Read-write contributes nothing, and that is the whole point: `''` drops the
4583
+ * contribution from the snapshot, so there is no "you may now write" line to
4584
+ * go stale. Only read-only needs saying.
4585
+ *
4586
+ * An unknown mode contributes nothing either. Before the first read lands the
4587
+ * mode is genuinely unknown, and announcing read-only then would state a
4588
+ * restriction that may not hold — while the gate, if it is in fact read-only,
4589
+ * refuses precisely anyway.
4590
+ *
4591
+ * @param mode - the mode now in effect, or `undefined` before one is read.
4592
+ * @returns the policy text, or `''` to contribute nothing.
4593
+ */
4594
+ function permissionPolicyText(mode) {
4595
+ return mode === "read_only" ? READ_ONLY_POLICY : "";
4596
+ }
4597
+ /**
4598
+ * Register the policy context, reading the mode through `current` at each
4599
+ * assembly.
4600
+ *
4601
+ * Deferred behind `ctx.inject` rather than declared in this plugin's own
4602
+ * `inject`: the policy is an enhancement, and a deployment without the system
4603
+ * prompt should not lose the tools over it. `current` is a function because the
4604
+ * context provider is synchronous and evaluated per assembly, so the mode is
4605
+ * read from the module state at that moment rather than captured once.
4606
+ *
4607
+ * @param ctx - host context.
4608
+ * @param current - the mode last read or applied, or `undefined` if not yet read.
4609
+ */
4610
+ function registerPermissionPolicyContext(ctx, current$1) {
4611
+ ctx.inject(["systemPrompt"], (scope) => {
4612
+ scope.systemPrompt.context({
4613
+ name: PERMISSION_CONTEXT_NAME,
4614
+ order: scope.systemPrompt.getContextOrder("APPROVAL_POLICY"),
4615
+ text: () => permissionPolicyText(current$1())
4616
+ });
4617
+ });
4618
+ }
4619
+
4620
+ //#endregion
4621
+ //#region src/prompt.ts
4622
+ /** Name this contribution registers under; unique across the assembled prompt. */
4623
+ const WORKFLOW_SECTION_NAME = "aishell:deploy-workflow";
4624
+ /**
4625
+ * What the model reads.
4626
+ *
4627
+ * Written in English like every other host-side string in this repo — prompt
4628
+ * sections are host text, and the browser half owns localized copy. The model
4629
+ * relays the answer in the user's language; the instructions do not need to
4630
+ * change language to do that.
4631
+ *
4632
+ * Every tool name appears as the model sees it, `aishell__<name>`, so a model
4633
+ * can copy it straight into a call.
4634
+ */
4635
+ const DEPLOY_WORKFLOW = `Huawei Cloud work goes through the aishell__ tools below, not through shell commands. They carry the safety gates (a plaintext-credential scan, a cost-hash check, a networking check) that a bare \`terraform\` invocation bypasses.
4636
+
4637
+ ## Deployment flow
4638
+
4639
+ Steps marked ★ require the user's explicit agreement before you continue.
4640
+
4641
+ 1. aishell__auth — verify the account and list its projects. Each project's \`name\` is a region; a region-scoped API (one whose path contains \`{project_id}\`) needs the project id from here.
4642
+ 2. aishell__create_deployment — create or reuse the deployment workspace.
4643
+ 3. aishell__apiexplorer — look up API definitions. With no arguments it lists every service; with a product it lists that service's APIs; with an API name it returns the contract (\`compact: true\` for the condensed form, \`regions: true\` for available regions and project ids).
4644
+ aishell__terraform_examples_export — write \`.tf\` examples to a directory. That directory is a reference target, not the deployment workspace.
4645
+ 4. aishell__update_networking — design the topology: VPC, subnets, routes, security groups, plus the EIP/NAT/ELB objects and the component list.
4646
+ ★ Show the topology to the user and get explicit agreement before writing it. Include VPC, subnet CIDRs, security-group rules and how the network objects connect; prefer rendering it as HTML. If the user asks for changes, revise until they accept, then call the tool again. Do not start any later step before that.
4647
+ ★ Opening SSH to 0.0.0.0/0 is a risk. Tell the user to restrict the source range.
4648
+ 5. aishell__list_existing_resources — inventory what already exists that could be reused. The response also carries a balance summary (balance and vouchers).
4649
+ 6. Decide per component: reuse or create.
4650
+ - Reuse: the spec and charging are fixed by the existing resource. Write the resource block, then aishell__terraform_import to bring it into state.
4651
+ - Create: choose a spec and a charging mode, querying available flavors and images with aishell__openapi_request.
4652
+ 7. aishell__openapi_request("GET", <BSS price API>) — fetch the real price for the new resources. Use the \`fields\` parameter to keep large responses out of context.
4653
+ 8. aishell__update_cost — write \`cost.json\`: spec, charging, price, and whether each item is reused or new.
4654
+ ★ Show the cost breakdown before continuing: what is reused, what is bought, each item's spec and charging mode, and the new monthly total.
4655
+ 9. Report the balance summary from step 5: balance and vouchers. Vouchers are applied automatically at the account level (voucher, then cash coupon, then balance) with nothing to configure in \`.tf\`. If vouchers exist, say the actual monthly increase may come in below the \`cost.json\` estimate. Check each voucher's \`expire_time\` and warn about any nearing expiry.
4656
+ 10. Write the \`.tf\` files from \`cost.json\` and \`networking.json\`. Credentials come from the environment; never write \`access_key\`, \`secret_key\` or \`security_token\` into a \`.tf\` file.
4657
+ 11. aishell__terraform_init — the gate here scans for plaintext credentials and refuses if it finds any.
4658
+ 12. aishell__provider_schema — the argument contract for a resource type, when you need it.
4659
+ 13. aishell__terraform_plan — preview the change.
4660
+ ★ Show the plan summary (what will be created, changed and destroyed) and the security-group rules before applying.
4661
+ 14. aishell__terraform_apply — run it. Four gates run first: \`networking.json\` exists, \`cost.json\` exists, its \`tf_hash\` still matches the \`.tf\` files, and no plaintext credential is present.
4662
+
4663
+ ## Destroying and resynchronising
4664
+
4665
+ - aishell__terraform_destroy removes everything terraform manages in that deployment. It refuses a non-empty tfstate only after the credential scan passes.
4666
+ ★ List the resources that will be destroyed and get explicit agreement first. Destruction cannot be undone.
4667
+ If the deployment also imported existing resources, destroy only what this deployment created with \`target: [...]\` and leave the imported ones. Call aishell__terraform_state first to list the addresses and let the user choose.
4668
+ - aishell__terraform_refresh — when the cloud changed outside terraform (edited in the console, a resource deleted by hand), refresh state and then plan to see the difference.
4669
+ - aishell__terraform_state — read state: resource addresses, attributes, security-group rules.
4670
+
4671
+ ## Hard lines
4672
+
4673
+ - Cloud resources are created and destroyed **only** through aishell__terraform_apply and aishell__terraform_destroy. Do not use \`POST\`/\`PUT\`/\`DELETE\` on aishell__openapi_request to create or destroy resources unless the user explicitly asks for the API route and understands the consequences: it skips the cost gate, never enters tfstate, and leaves no trace.
4674
+ - Before applying or destroying, name the resources involved and get the user's explicit agreement. Never run these silently.
4675
+ - A \`.tf\` file must never contain a plaintext \`access_key\`, \`secret_key\` or \`security_token\`. The scan runs before init and apply and refuses the run.
4676
+ - \`cost.json\` must exist and its \`tf_hash\` must match before apply. Editing a \`.tf\` file invalidates it; recompute the cost.
4677
+ - Other \`POST\`/\`DELETE\` calls (issuing a voucher, adjusting a quota — not resource lifecycle) do run, and return a warning. Pass that warning to the user.
4678
+
4679
+ ## Mainland region filing
4680
+
4681
+ In mainland regions (cn-north-1, cn-north-4, cn-east-3 and others), serving web traffic on ports 80/443 requires ICP filing. Traffic is blocked without it. If the user wants a web port, ask about their filing status first.
4682
+
4683
+ ## Typical requests
4684
+
4685
+ - "How many ECS instances do I have?" → aishell__list_existing_resources with \`service: "ecs"\`
4686
+ - "What did I spend this month?" → aishell__openapi_request("GET", <BSS bill API>)
4687
+ - "How many vouchers do I have?" → the \`balance_summary\` field of aishell__list_existing_resources
4688
+ - "What arguments does this resource take?" → aishell__provider_schema(deployment, "huaweicloud_compute_instance")
4689
+ - "Tear this deployment down" → aishell__terraform_destroy, after listing the resources for confirmation
4690
+ - "The cloud changed, resync" → aishell__terraform_refresh, then aishell__terraform_plan for the difference
4691
+ - "What is deployed right now?" → aishell__terraform_state
4692
+ - "Bring this existing instance under management" → write the resource block, then aishell__terraform_import
4693
+
4694
+ ## Product documentation
4695
+
4696
+ For what a Huawei Cloud product *is* — features, quotas, limits, charging models — read the index at https://support.huaweicloud.com/llms.txt. It lists every product's documentation entry point by category; read it to locate the product, then that product's own \`llms.txt\` for detail.
4697
+
4698
+ Do not answer questions about a product's feature boundaries, quotas or charging rules from memory — they change between releases. For API contracts use aishell__apiexplorer; for what exists in the account use aishell__list_existing_resources; this index is for "what is this product and what are its limits".`;
4699
+ /**
4700
+ * Register the workflow section.
4701
+ *
4702
+ * Deferred behind `ctx.inject` rather than declared in this plugin's own
4703
+ * `inject`: the workflow is an enhancement, and a deployment without a system
4704
+ * prompt should lose the guidance rather than fail to mount.
4705
+ *
4706
+ * @param ctx - host context.
4707
+ */
4708
+ function registerDeployWorkflow(ctx) {
4709
+ ctx.inject(["systemPrompt"], (scope) => {
4710
+ scope.systemPrompt.section({
4711
+ name: WORKFLOW_SECTION_NAME,
4712
+ order: scope.systemPrompt.getSectionOrder("MCP_SERVERS"),
4713
+ interpolate: false,
4714
+ text: ({ scope: renderScope }) => ctx.tools.get("aishell__terraform_apply", renderScope) === void 0 ? "" : DEPLOY_WORKFLOW
4715
+ });
4716
+ });
4717
+ }
4718
+
4719
+ //#endregion
4720
+ //#region src/index.ts
4721
+ /** Default Huawei Cloud region when the plugin config names none. */
4722
+ const DEFAULT_REGION = "cn-north-4";
4723
+ /** Default per-call timeout for one tool. */
4724
+ const DEFAULT_TOOL_CALL_TIMEOUT_MS = 6e4;
4725
+ /**
4726
+ * Settings schema.
4727
+ *
4728
+ * Every field is Volatile: each is a deployment fact that may differ between
4729
+ * profiles, and a change should apply to the next call rather than require a
4730
+ * restart. The bridge reads them through thunks for that reason.
4731
+ */
4732
+ const Config = Schema.object({
4733
+ defaultRegion: Schema.string().default(DEFAULT_REGION).volatile(),
4734
+ toolCallTimeoutMs: Schema.number().step(1).min(1).default(DEFAULT_TOOL_CALL_TIMEOUT_MS).volatile()
4735
+ });
4736
+ const name = "aishell-deploy";
4737
+ /**
4738
+ * Required services.
4739
+ *
4740
+ * `tools` is required: the whole point of this plugin is registering its tools.
4741
+ * `connection` is required because the permission route registers on the host's
4742
+ * authenticated fetch registry, and a plugin that silently lost its permission
4743
+ * switch would leave every mutation at the default.
4744
+ */
4745
+ const inject = ["tools", "connection"];
4746
+ function apply(ctx, config) {
4747
+ const log = ctx.logger("aishell-deploy");
4748
+ const store = createCredentialsStore();
4749
+ configureCredentials({
4750
+ store,
4751
+ get region() {
4752
+ return config.defaultRegion.get();
4753
+ }
4754
+ });
4755
+ const { registrar, captured } = createRegistrar();
4756
+ registerAllTools(registrar);
4757
+ const disposers = captured.map((tool) => {
4758
+ const definition = toToolDefinition(tool, config.toolCallTimeoutMs.get());
4759
+ return ctx.tools.register(definition);
4760
+ });
4761
+ ctx.effect(() => () => {
4762
+ for (const dispose of disposers) dispose();
4763
+ }, "aishell-deploy: tools");
4764
+ log.info(`registered ${disposers.length} Huawei Cloud tool(s)`);
4765
+ log.info(`permission mode: ${getMode$1()}`);
4766
+ const routes = createPermissionRoutes({
4767
+ read: () => ({
4768
+ mode: getMode$1(),
4769
+ default: defaultMode(),
4770
+ writable: writesAllowed()
4771
+ }),
4772
+ write: (next) => {
4773
+ const previous = setMode$1(next);
4774
+ return {
4775
+ mode: getMode$1(),
4776
+ previous,
4777
+ changed: previous !== next
4778
+ };
4779
+ }
4780
+ });
4781
+ ctx.effect(() => ctx.connection.fetch.register({
4782
+ path: PERMISSION_PATH,
4783
+ methods: ["GET", "POST"],
4784
+ requestBody: "buffered",
4785
+ fetch: (request) => request.method === "GET" ? routes.get() : routes.set(request)
4786
+ }), "aishell-deploy: permission route");
4787
+ registerPermissionPolicyContext(ctx, () => getMode$1());
4788
+ registerDeployWorkflow(ctx);
4789
+ ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
4790
+ forgetAccount();
4791
+ }), "aishell-deploy: credential cache");
4792
+ }
4793
+
4794
+ //#endregion
4795
+ export { Config, apply, inject, name };
4796
+ //# sourceMappingURL=index.js.map