@huaweidevtools/aishell-dsh-deploy 0.0.16 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/lib/index.js +1394 -361
- package/lib/types/bridge.d.ts +16 -1
- package/lib/types/d2-design.d.ts +60 -0
- package/lib/types/d2-engine.d.ts +111 -0
- package/lib/types/d2-inventory.d.ts +82 -0
- package/lib/types/existing-topology.d.ts +154 -0
- package/lib/types/existing.d.ts +28 -7
- package/lib/types/gates/terraform_env.d.ts +1 -1
- package/lib/types/inventory-subnets.d.ts +78 -0
- package/lib/types/paths.d.ts +51 -0
- package/lib/types/projects.d.ts +40 -0
- package/lib/types/prompt.d.ts +52 -25
- package/lib/types/types.d.ts +28 -3
- package/lib/types/version.d.ts +8 -4
- package/package.json +3 -3
- package/lib/types/d2-render.d.ts +0 -74
package/lib/index.js
CHANGED
|
@@ -2,11 +2,11 @@ import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { access, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
|
-
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { dshHome } from "@huaweidevtools/aishell-dsh-credentials-store/paths";
|
|
8
8
|
import { spawn } from "node:child_process";
|
|
9
|
-
import { homedir } from "node:os";
|
|
9
|
+
import { homedir, tmpdir } from "node:os";
|
|
10
10
|
import { readStoredPair } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
|
|
11
11
|
import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
|
|
12
12
|
import { createHash, createHmac } from "node:crypto";
|
|
@@ -945,13 +945,14 @@ function publicToolName(rawName) {
|
|
|
945
945
|
*
|
|
946
946
|
* @param tool - the captured registration.
|
|
947
947
|
* @param timeoutMs - per-call budget handed to the harness.
|
|
948
|
+
* @param workingDirectory - the host's session-directory service, when mounted.
|
|
948
949
|
* @returns the definition to hand to `ctx.tools.register`.
|
|
949
950
|
*/
|
|
950
|
-
function toToolDefinition(tool, timeoutMs) {
|
|
951
|
-
const name$1 = publicToolName(tool.name);
|
|
952
|
-
const description = tool.config.description ?? "";
|
|
953
|
-
const parameters = toJsonSchema(tool.config.inputSchema, tool.name);
|
|
954
|
-
const validate = argumentValidator(tool.config.inputSchema);
|
|
951
|
+
function toToolDefinition(tool$1, timeoutMs, workingDirectory) {
|
|
952
|
+
const name$1 = publicToolName(tool$1.name);
|
|
953
|
+
const description = tool$1.config.description ?? "";
|
|
954
|
+
const parameters = toJsonSchema(tool$1.config.inputSchema, tool$1.name);
|
|
955
|
+
const validate = argumentValidator(tool$1.config.inputSchema);
|
|
955
956
|
return {
|
|
956
957
|
name: name$1,
|
|
957
958
|
description,
|
|
@@ -973,7 +974,7 @@ function toToolDefinition(tool, timeoutMs) {
|
|
|
973
974
|
async execute(args, exec) {
|
|
974
975
|
const violations = validate(args);
|
|
975
976
|
if (violations.length > 0) throw new Error(`aishell-deploy: ${name$1}: ${violations.join("; ")}`);
|
|
976
|
-
const result = await tool.handler(args, contextFor(exec));
|
|
977
|
+
const result = await tool$1.handler(args, await contextFor(exec, workingDirectory));
|
|
977
978
|
return unwrapOrThrow(result);
|
|
978
979
|
}
|
|
979
980
|
};
|
|
@@ -1003,16 +1004,38 @@ function argumentValidator(schema) {
|
|
|
1003
1004
|
/**
|
|
1004
1005
|
* The handler context for one execution.
|
|
1005
1006
|
*
|
|
1006
|
-
*
|
|
1007
|
-
* It stays a function so the next handler that needs the caller's session or
|
|
1008
|
-
* signal has one obvious place to take it from, rather than reaching into the
|
|
1009
|
-
* harness from a tool module.
|
|
1007
|
+
* ## Why this resolves a directory
|
|
1010
1008
|
*
|
|
1011
|
-
*
|
|
1009
|
+
* The tools take a `deployment` path that the model may give relatively, and a
|
|
1010
|
+
* relative path means nothing until something anchors it. Node would anchor it
|
|
1011
|
+
* at `process.cwd()` — the directory the host was launched from, which has
|
|
1012
|
+
* nothing to do with the session a person is working in. Every filesystem tool
|
|
1013
|
+
* in the product anchors at the session, so a relative path means the same
|
|
1014
|
+
* thing here as it does there.
|
|
1015
|
+
*
|
|
1016
|
+
* `ensure` rather than `get`: it returns an absolute directory and validates
|
|
1017
|
+
* that it still exists. `get` is cheaper but is a pure read, so a deleted
|
|
1018
|
+
* directory would be handed back and every operation under it would fail with
|
|
1019
|
+
* the wrong reason.
|
|
1020
|
+
*
|
|
1021
|
+
* The service may be absent — a deployment without it, or a call outside an
|
|
1022
|
+
* agent. That is not permission to fall back to `process.cwd()`: the context
|
|
1023
|
+
* then carries no directory, and a tool that needs one to resolve a relative
|
|
1024
|
+
* path says so rather than writing somewhere nobody chose.
|
|
1025
|
+
*
|
|
1026
|
+
* @param exec - the harness execution context.
|
|
1027
|
+
* @param workingDirectory - the host's service, when mounted.
|
|
1012
1028
|
* @returns the handler context.
|
|
1013
1029
|
*/
|
|
1014
|
-
function contextFor(
|
|
1015
|
-
|
|
1030
|
+
async function contextFor(exec, workingDirectory) {
|
|
1031
|
+
const call = exec;
|
|
1032
|
+
const agent = call?.agent;
|
|
1033
|
+
if (workingDirectory === void 0 || agent === void 0) return {};
|
|
1034
|
+
try {
|
|
1035
|
+
return { sessionDirectory: await workingDirectory.ensure(agent, call?.signal) };
|
|
1036
|
+
} catch {
|
|
1037
|
+
return {};
|
|
1038
|
+
}
|
|
1016
1039
|
}
|
|
1017
1040
|
/**
|
|
1018
1041
|
* Turn a handler's return into the canonical value, or throw on failure.
|
|
@@ -1519,6 +1542,25 @@ function denyHttp(method, url) {
|
|
|
1519
1542
|
}
|
|
1520
1543
|
}
|
|
1521
1544
|
|
|
1545
|
+
//#endregion
|
|
1546
|
+
//#region src/paths.ts
|
|
1547
|
+
/**
|
|
1548
|
+
* The absolute directory a directory argument names.
|
|
1549
|
+
*
|
|
1550
|
+
* @param given - the path the caller gave, relative or absolute.
|
|
1551
|
+
* @param context - the call's context, carrying the session directory when the
|
|
1552
|
+
* host provides one.
|
|
1553
|
+
* @returns the absolute path.
|
|
1554
|
+
* @throws when the path is relative and there is no session directory to anchor
|
|
1555
|
+
* it — the caller gets a remedy, not a directory chosen for them.
|
|
1556
|
+
*/
|
|
1557
|
+
function anchorPath(given, context) {
|
|
1558
|
+
if (isAbsolute(given)) return given;
|
|
1559
|
+
const base = context?.sessionDirectory;
|
|
1560
|
+
if (base === void 0) throw new Error(`"${given}" is a relative path, and this call has no session working directory to resolve it against — so it names no directory in particular. Pass an absolute path instead. (Resolving it against the host process's own directory would put the workspace somewhere the session is not.)`);
|
|
1561
|
+
return resolve(base, given);
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1522
1564
|
//#endregion
|
|
1523
1565
|
//#region src/tools/errors.ts
|
|
1524
1566
|
/**
|
|
@@ -1587,22 +1629,59 @@ function guard(fn, toolName) {
|
|
|
1587
1629
|
if (refusal !== void 0) return fail(refusal);
|
|
1588
1630
|
}
|
|
1589
1631
|
try {
|
|
1590
|
-
return await fn(args, ctx);
|
|
1632
|
+
return await fn(withAnchoredPaths(args, ctx), ctx);
|
|
1591
1633
|
} catch (err) {
|
|
1592
1634
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1593
1635
|
return fail(msg);
|
|
1594
1636
|
}
|
|
1595
1637
|
};
|
|
1596
1638
|
}
|
|
1639
|
+
/**
|
|
1640
|
+
* The directory-valued arguments every tool declares.
|
|
1641
|
+
*
|
|
1642
|
+
* Both are the same kind of value and were both relative-path bugs: `deployment`
|
|
1643
|
+
* is the workspace, `dest` is where reference data is exported. Handling only
|
|
1644
|
+
* `deployment` left `terraform_examples_export` resolving its target against the
|
|
1645
|
+
* host's launch directory, which is the same defect one tool over.
|
|
1646
|
+
*/
|
|
1647
|
+
const DIRECTORY_ARGUMENTS = ["deployment", "dest"];
|
|
1648
|
+
/**
|
|
1649
|
+
* The arguments with every directory argument made absolute.
|
|
1650
|
+
*
|
|
1651
|
+
* A handler that takes neither passes through untouched, so this is not a
|
|
1652
|
+
* parameter every tool has to declare. A relative path with no session
|
|
1653
|
+
* directory throws here, inside the guard's `try`, which turns it into the
|
|
1654
|
+
* failure a caller can act on.
|
|
1655
|
+
*
|
|
1656
|
+
* @param args - the call's arguments.
|
|
1657
|
+
* @param ctx - the call's context.
|
|
1658
|
+
* @returns the same arguments, with directory arguments resolved.
|
|
1659
|
+
*/
|
|
1660
|
+
function withAnchoredPaths(args, ctx) {
|
|
1661
|
+
if (args === void 0 || args === null || typeof args !== "object") return args;
|
|
1662
|
+
const candidate = args;
|
|
1663
|
+
let resolved;
|
|
1664
|
+
for (const key of DIRECTORY_ARGUMENTS) {
|
|
1665
|
+
const value = candidate[key];
|
|
1666
|
+
if (typeof value !== "string" || value === "") continue;
|
|
1667
|
+
resolved ??= { ...candidate };
|
|
1668
|
+
resolved[key] = anchorPath(value, ctx);
|
|
1669
|
+
}
|
|
1670
|
+
return resolved ?? candidate;
|
|
1671
|
+
}
|
|
1597
1672
|
|
|
1598
1673
|
//#endregion
|
|
1599
1674
|
//#region src/version.ts
|
|
1600
1675
|
/**
|
|
1601
1676
|
* The version recorded in a deployment's `.deployment.json`.
|
|
1602
1677
|
*
|
|
1603
|
-
*
|
|
1604
|
-
*
|
|
1605
|
-
* value
|
|
1678
|
+
* GENERATED by `scripts/write-deploy-version.mjs` — do not edit. It is
|
|
1679
|
+
* rewritten on every build from the package manifest, so the two cannot
|
|
1680
|
+
* disagree; a hand-written value here would drift from the version that
|
|
1681
|
+
* actually ships, and the field exists to make that traceable.
|
|
1682
|
+
*
|
|
1683
|
+
* A deployment snapshot names the code that wrote it, so an old workspace can be
|
|
1684
|
+
* traced to the release that produced it.
|
|
1606
1685
|
*
|
|
1607
1686
|
* @module @huaweidevtools/aishell-dsh-deploy/version
|
|
1608
1687
|
*/
|
|
@@ -1613,7 +1692,7 @@ function guard(fn, toolName) {
|
|
|
1613
1692
|
* written by earlier releases carry it — so it is kept even though there is no
|
|
1614
1693
|
* server.
|
|
1615
1694
|
*/
|
|
1616
|
-
const SERVER_VERSION = "aishell-deploy 0.
|
|
1695
|
+
const SERVER_VERSION = "aishell-deploy 0.0.18";
|
|
1617
1696
|
|
|
1618
1697
|
//#endregion
|
|
1619
1698
|
//#region src/deployment-state.ts
|
|
@@ -1967,7 +2046,7 @@ function forgetAccount() {
|
|
|
1967
2046
|
* Throws if no binary can be found.
|
|
1968
2047
|
*/
|
|
1969
2048
|
async function resolveTerraformEnv(deployment, extraEnv = []) {
|
|
1970
|
-
const binary = await resolveBinary(
|
|
2049
|
+
const binary = await resolveBinary();
|
|
1971
2050
|
const env = {};
|
|
1972
2051
|
await resolveTerraformrc(deployment, env);
|
|
1973
2052
|
await resolvePluginCache(env);
|
|
@@ -1997,7 +2076,7 @@ async function resolveTerraformEnv(deployment, extraEnv = []) {
|
|
|
1997
2076
|
* environment variable set by the operator still wins over it — the same
|
|
1998
2077
|
* precedence the rest of this module gives to explicit configuration.
|
|
1999
2078
|
*/
|
|
2000
|
-
async function resolveBinary(
|
|
2079
|
+
async function resolveBinary() {
|
|
2001
2080
|
const envPath = process.env["HW_TERRAFORM_PATH"];
|
|
2002
2081
|
if (envPath && await fileExists(envPath)) return envPath;
|
|
2003
2082
|
const pathBinary = await findInPath("terraform");
|
|
@@ -2006,8 +2085,8 @@ async function resolveBinary(deployment) {
|
|
|
2006
2085
|
if (recorded !== void 0 && await fileExists(recorded)) return recorded;
|
|
2007
2086
|
const globalBin = await findGlobalCacheBinary();
|
|
2008
2087
|
if (globalBin) return globalBin;
|
|
2009
|
-
const
|
|
2010
|
-
if (
|
|
2088
|
+
const temporaryBin = await findTemporaryCacheBinary();
|
|
2089
|
+
if (temporaryBin) return temporaryBin;
|
|
2011
2090
|
throw new Error("terraform not found — call terraform_install first");
|
|
2012
2091
|
}
|
|
2013
2092
|
/**
|
|
@@ -2041,14 +2120,39 @@ async function recordedBinaryPath() {
|
|
|
2041
2120
|
return void 0;
|
|
2042
2121
|
}
|
|
2043
2122
|
}
|
|
2044
|
-
/**
|
|
2123
|
+
/**
|
|
2124
|
+
* Where terraform's CLI configuration comes from: deployment file > user env >
|
|
2125
|
+
* user home > none.
|
|
2126
|
+
*
|
|
2127
|
+
* ## Why the deployment file is absolute
|
|
2128
|
+
*
|
|
2129
|
+
* The subprocess runs with `cwd` set to the deployment, and `TF_CLI_CONFIG_FILE`
|
|
2130
|
+
* is resolved by terraform against THAT directory, not against the process that
|
|
2131
|
+
* spawned it. A deployment given as a relative path therefore produced
|
|
2132
|
+
* `<deployment>/<deployment>/.terraformrc`: a file that cannot exist, a warning
|
|
2133
|
+
* on every run, and — the part that matters — a provider mirror that silently
|
|
2134
|
+
* never applied.
|
|
2135
|
+
*
|
|
2136
|
+
* `resolve(deployment)` is what makes the value mean the same thing to both
|
|
2137
|
+
* processes. The caller may hand this module a relative path; nothing
|
|
2138
|
+
* downstream can.
|
|
2139
|
+
*
|
|
2140
|
+
* @param deployment - the deployment directory, relative or absolute.
|
|
2141
|
+
* @param env - the subprocess env being assembled.
|
|
2142
|
+
*/
|
|
2045
2143
|
async function resolveTerraformrc(deployment, env) {
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2144
|
+
if (deployment !== void 0) {
|
|
2145
|
+
const depRc = join(resolve(deployment), ".terraformrc");
|
|
2146
|
+
if (await fileExists(depRc)) {
|
|
2147
|
+
env["TF_CLI_CONFIG_FILE"] = depRc;
|
|
2148
|
+
return;
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
const fromEnv = process.env["TF_CLI_CONFIG_FILE"];
|
|
2152
|
+
if (fromEnv !== void 0 && fromEnv !== "") {
|
|
2153
|
+
env["TF_CLI_CONFIG_FILE"] = resolve(fromEnv);
|
|
2049
2154
|
return;
|
|
2050
2155
|
}
|
|
2051
|
-
if (process.env["TF_CLI_CONFIG_FILE"]) return;
|
|
2052
2156
|
const homeRc = join(homedir(), ".terraformrc");
|
|
2053
2157
|
if (await fileExists(homeRc)) return;
|
|
2054
2158
|
}
|
|
@@ -2064,19 +2168,16 @@ async function resolvePluginCache(env) {
|
|
|
2064
2168
|
/**
|
|
2065
2169
|
* Find terraform in PATH by running `terraform version`.
|
|
2066
2170
|
*
|
|
2067
|
-
* This is the only reliable
|
|
2068
|
-
*
|
|
2069
|
-
*
|
|
2070
|
-
*
|
|
2071
|
-
*
|
|
2171
|
+
* This is the only reliable probe. `which`/`where` confirm a file exists on
|
|
2172
|
+
* PATH, not that it is a working terraform binary: a same-named empty file, a
|
|
2173
|
+
* corrupt download and an architecture mismatch all pass those and fail this.
|
|
2174
|
+
* `which` has portability problems of its own too — Alpine lacks it by default,
|
|
2175
|
+
* busybox's behaves differently, and Windows `where` emits several lines.
|
|
2176
|
+
* `terraform version` succeeding means the binary genuinely runs.
|
|
2072
2177
|
*
|
|
2073
2178
|
* The extra spawn is negligible: each terraform tool call already spawns a
|
|
2074
2179
|
* subprocess that runs for seconds-to-minutes (init/plan/apply); a
|
|
2075
2180
|
* `terraform version` probe takes tens of milliseconds.
|
|
2076
|
-
*
|
|
2077
|
-
* Using `which` was tried and rejected: Alpine Linux lacks `which` by
|
|
2078
|
-
* default, busybox's `which` behaves differently, and Windows `where`
|
|
2079
|
-
* emits multiple lines — all for no real benefit.
|
|
2080
2181
|
*/
|
|
2081
2182
|
async function findInPath(_name) {
|
|
2082
2183
|
return new Promise((resolve$1) => {
|
|
@@ -2090,6 +2191,34 @@ async function findInPath(_name) {
|
|
|
2090
2191
|
});
|
|
2091
2192
|
}
|
|
2092
2193
|
/** Find a cached binary in `<DSH_HOME>/terraform/bin` (terraform-<ver>). */
|
|
2194
|
+
/**
|
|
2195
|
+
* Find a binary downloaded into the temporary cache.
|
|
2196
|
+
*
|
|
2197
|
+
* This is where `terraform_install` puts one when the host's data directory is
|
|
2198
|
+
* read-only — a container with a read-only home, a sandboxed runner. The
|
|
2199
|
+
* search order has to know about it or the install would report success and
|
|
2200
|
+
* every later call would report no terraform.
|
|
2201
|
+
*
|
|
2202
|
+
* @returns the binary's path, or `null` when there is none.
|
|
2203
|
+
*/
|
|
2204
|
+
async function findTemporaryCacheBinary() {
|
|
2205
|
+
try {
|
|
2206
|
+
const { readdir: readdir$1 } = await import("node:fs/promises");
|
|
2207
|
+
const dir = join(tmpdir(), "aishell-terraform");
|
|
2208
|
+
const entries = await readdir$1(dir);
|
|
2209
|
+
const versioned = entries.filter((entry) => entry.startsWith("terraform-"));
|
|
2210
|
+
if (versioned.length > 0) {
|
|
2211
|
+
versioned.sort().reverse();
|
|
2212
|
+
const path = join(dir, versioned[0]);
|
|
2213
|
+
if (await fileExists(path)) return path;
|
|
2214
|
+
}
|
|
2215
|
+
const plain = join(dir, "terraform");
|
|
2216
|
+
if (await fileExists(plain)) return plain;
|
|
2217
|
+
return null;
|
|
2218
|
+
} catch {
|
|
2219
|
+
return null;
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2093
2222
|
async function findGlobalCacheBinary() {
|
|
2094
2223
|
try {
|
|
2095
2224
|
const { readdir: readdir$1 } = await import("node:fs/promises");
|
|
@@ -2240,7 +2369,7 @@ async function runTerraform(cwd, args, extraEnv = []) {
|
|
|
2240
2369
|
function registerDeploymentTools(registrar) {
|
|
2241
2370
|
registrar.registerTool("create_deployment", {
|
|
2242
2371
|
title: "Create deployment",
|
|
2243
|
-
description: "Create or reuse a deployment workspace directory.
|
|
2372
|
+
description: "Create or reuse a deployment workspace directory. The only file it writes is .deployment.json, the state snapshot the gates later read — no .tf, no plan. If the directory already holds a deployment, it returns that snapshot instead of touching it. If the directory is non-empty and is not a deployment, it refuses rather than writing into someone else's files.",
|
|
2244
2373
|
annotations: LOCAL_WRITE,
|
|
2245
2374
|
inputSchema: z.object({ deployment: deploymentParam })
|
|
2246
2375
|
}, guard(async (args) => handleCreate(args.deployment)));
|
|
@@ -3144,6 +3273,37 @@ async function assertDestroyPreviewed(directory, readState, hashConfiguration, t
|
|
|
3144
3273
|
if (current$1 !== record.tf_hash) throw new Error("the .tf files changed after the teardown was previewed. The saved destroy plan describes a different configuration. Call terraform_plan with destroy: true again and show the new list before destroying.");
|
|
3145
3274
|
}
|
|
3146
3275
|
|
|
3276
|
+
//#endregion
|
|
3277
|
+
//#region src/projects.ts
|
|
3278
|
+
/**
|
|
3279
|
+
* Every project the account has, keyed by region name.
|
|
3280
|
+
*
|
|
3281
|
+
* @param credentials - the pair to sign with.
|
|
3282
|
+
* @returns region name → project id.
|
|
3283
|
+
* @throws when IAM cannot answer, with its own reason.
|
|
3284
|
+
*/
|
|
3285
|
+
async function projectMap(credentials) {
|
|
3286
|
+
const response = await signedHttp("GET", new URL("https://iam.myhuaweicloud.com/v3/projects"), "", {}, credentials);
|
|
3287
|
+
if (response.status !== 200) throw new Error(`could not read the project list from IAM (HTTP ${response.status}): ${response.body.slice(0, 300)}`);
|
|
3288
|
+
const parsed = JSON.parse(response.body);
|
|
3289
|
+
const byRegion = new Map();
|
|
3290
|
+
for (const project of parsed.projects ?? []) if (typeof project.name === "string" && typeof project.id === "string") byRegion.set(project.name, project.id);
|
|
3291
|
+
return byRegion;
|
|
3292
|
+
}
|
|
3293
|
+
/**
|
|
3294
|
+
* The project id for one region, or a message naming what the account does have.
|
|
3295
|
+
*
|
|
3296
|
+
* @param projects - the map from {@link projectMap}.
|
|
3297
|
+
* @param region - the region a request is going to.
|
|
3298
|
+
* @returns the project id.
|
|
3299
|
+
* @throws when the account has no project there, listing the regions it does.
|
|
3300
|
+
*/
|
|
3301
|
+
function projectIn(projects, region) {
|
|
3302
|
+
const known = projects.get(region);
|
|
3303
|
+
if (known !== void 0) return known;
|
|
3304
|
+
throw new Error(`the account has no project in ${region}. Its projects are in: ${[...projects.keys()].sort().join(", ")}.`);
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3147
3307
|
//#endregion
|
|
3148
3308
|
//#region src/rating-map.ts
|
|
3149
3309
|
/**
|
|
@@ -3568,7 +3728,7 @@ const COST_FILE$1 = "cost.json";
|
|
|
3568
3728
|
function registerPricingTool(registrar) {
|
|
3569
3729
|
registrar.registerTool("price_resources", {
|
|
3570
3730
|
title: "Price the resources in the saved plan",
|
|
3571
|
-
description: "Read the plan terraform_plan saved and quote each priceable resource against this account's own on-demand prices, then write cost.json. It prices the PLAN, not the .tf: a block with count = 3 is three priced instances, for_each is one per key, and a module's resources are visible — none of which the .tf files show. Each figure is one month (730 hours) of the resource, with the list price it was discounted from and the moment of the inquiry.
|
|
3731
|
+
description: "Read the plan terraform_plan saved and quote each priceable resource against this account's own on-demand prices, then write cost.json. It prices the PLAN, not the .tf: a block with count = 3 is three priced instances, for_each is one per key, and a module's resources are visible — none of which the .tf files show. Each figure is one month (730 hours) of the resource, with the list price it was discounted from and the moment of the inquiry. It prices compute instances (Linux and Windows bill separately), RDS, DCS, EVS volumes, EIPs, NAT gateways, ELB load balancers, APIG instances and VPCEP endpoints. Anything else — a bucket, a resource whose spec came from a variable — is listed as UNPRICED with the reason, never estimated. Read that list rather than assuming a type is covered: a total that silently omits the unpriced ones understates the bill, so say which they are. Each resource is priced in the region its provider block names, so a deployment spanning several regions gets a price for each — but a region written as a variable cannot be read from the plan, and those resources are reported unpriced rather than priced against a guess. Write the region as a literal in the provider block. It reads the saved plan, so a deployment that has not been planned has nothing to price.",
|
|
3572
3732
|
annotations: READ_ONLY_CLOUD,
|
|
3573
3733
|
inputSchema: z.object({ deployment: deploymentParam })
|
|
3574
3734
|
}, guard(async (args) => handlePrice(args.deployment)));
|
|
@@ -4131,30 +4291,6 @@ async function imagePlatforms(region, credentials) {
|
|
|
4131
4291
|
}
|
|
4132
4292
|
return platforms;
|
|
4133
4293
|
}
|
|
4134
|
-
/**
|
|
4135
|
-
* Every region the account has a project in, by region name.
|
|
4136
|
-
*
|
|
4137
|
-
* IAM is global — one endpoint serves every region — so this is one call
|
|
4138
|
-
* rather than one per region. Verified: `iam.myhuaweicloud.com/v3/projects`
|
|
4139
|
-
* returns all 14 projects the account holds, and a regional replica returns
|
|
4140
|
-
* the same list.
|
|
4141
|
-
*
|
|
4142
|
-
* The project id is bound to its region's endpoints: pairing one region's
|
|
4143
|
-
* project with another region's host answers HTTP 400, so the mapping is
|
|
4144
|
-
* carried rather than re-derived per call.
|
|
4145
|
-
*
|
|
4146
|
-
* @param credentials - the pair to sign with.
|
|
4147
|
-
* @returns region name → project id.
|
|
4148
|
-
* @throws when IAM cannot answer, with its own reason.
|
|
4149
|
-
*/
|
|
4150
|
-
async function projectMap(credentials) {
|
|
4151
|
-
const response = await signedHttp("GET", new URL("https://iam.myhuaweicloud.com/v3/projects"), "", {}, credentials);
|
|
4152
|
-
if (response.status !== 200) throw new Error(`could not read the project list from IAM (HTTP ${response.status}): ${response.body.slice(0, 300)}`);
|
|
4153
|
-
const parsed = JSON.parse(response.body);
|
|
4154
|
-
const byRegion = new Map();
|
|
4155
|
-
for (const project of parsed.projects ?? []) if (typeof project.name === "string" && typeof project.id === "string") byRegion.set(project.name, project.id);
|
|
4156
|
-
return byRegion;
|
|
4157
|
-
}
|
|
4158
4294
|
/** Round to the cent, which is what a price is quoted in. */
|
|
4159
4295
|
function round(amount) {
|
|
4160
4296
|
return Math.round(amount * 100) / 100;
|
|
@@ -4381,27 +4517,6 @@ function imsHost(region) {
|
|
|
4381
4517
|
/** How many catalogue entries one response may carry. */
|
|
4382
4518
|
const CATALOGUE_LIMIT = 500;
|
|
4383
4519
|
/**
|
|
4384
|
-
* Resolve the region's project id.
|
|
4385
|
-
*
|
|
4386
|
-
* The path parameter every region-scoped API needs, and it is per region — one
|
|
4387
|
-
* account has a project per region, so this cannot be cached across regions.
|
|
4388
|
-
*
|
|
4389
|
-
* @param region - the region to resolve.
|
|
4390
|
-
* @returns the project reference.
|
|
4391
|
-
* @throws when IAM cannot answer, with its own reason.
|
|
4392
|
-
*/
|
|
4393
|
-
async function resolveProject(region) {
|
|
4394
|
-
const response = await signedHttp("GET", new URL(`https://iam.${region}.myhuaweicloud.com/v3/projects`), "");
|
|
4395
|
-
if (response.status !== 200) throw new Error(`could not read the project list from IAM (HTTP ${response.status}): ${response.body.slice(0, 300)}`);
|
|
4396
|
-
const parsed = JSON.parse(response.body);
|
|
4397
|
-
const match = (parsed.projects ?? []).find((project) => project.name === region);
|
|
4398
|
-
if (match === void 0 || typeof match.id !== "string") throw new Error(`the account has no project in ${region}. Choose a region the account is subscribed to; the project list IAM returned does not contain it.`);
|
|
4399
|
-
return {
|
|
4400
|
-
id: match.id,
|
|
4401
|
-
region
|
|
4402
|
-
};
|
|
4403
|
-
}
|
|
4404
|
-
/**
|
|
4405
4520
|
* Every flavour the region sells in one availability zone.
|
|
4406
4521
|
*
|
|
4407
4522
|
* Scoped to an AZ because that is how availability works: a flavour exists in
|
|
@@ -4443,7 +4558,7 @@ async function listImages(project) {
|
|
|
4443
4558
|
function registerSpecsTool(registrar) {
|
|
4444
4559
|
registrar.registerTool("lookup_specs", {
|
|
4445
4560
|
title: "Look up compute flavours and images, and check a design against them",
|
|
4446
|
-
description: "Two uses. WITHOUT `deployment`: list the compute flavours and images this region offers in one availability zone, with each flavour vCPUs, memory and disk, and each image OS, minimum disk and minimum memory.
|
|
4561
|
+
description: "Two uses. WITHOUT `deployment`: list the compute flavours and images this region offers in one availability zone, with each flavour vCPUs, memory and disk, and each image OS, minimum disk and minimum memory. `flavor_id` and `image_id` are values only the region knows — an invented one passes terraform validate, which checks only that the value is a string, and fails at apply. WITH `deployment`: read the .tf files and check every flavor_id, flavor_name, image_id and image_name they name against the catalogue, reporting any that the region does not offer in that zone, plus images whose minimum disk or memory the chosen flavour cannot meet. terraform validate cannot see any of this: it checks only that the value is a string. The numbers are returned so the user can judge suitability; this tool does not judge it.",
|
|
4447
4562
|
annotations: READ_ONLY_CLOUD,
|
|
4448
4563
|
inputSchema: z.object({
|
|
4449
4564
|
availability_zone: z.string().describe("The zone to ask about, e.g. \"cn-north-4a\". A flavour exists per zone, so this is required — asking without it would report a flavour as available when only another zone carries it."),
|
|
@@ -4463,7 +4578,12 @@ function registerSpecsTool(registrar) {
|
|
|
4463
4578
|
async function handleLookup(availabilityZone, region, deployment) {
|
|
4464
4579
|
const resolvedRegion = region;
|
|
4465
4580
|
try {
|
|
4466
|
-
const
|
|
4581
|
+
const credentials = await loadCredentials();
|
|
4582
|
+
const projects = await projectMap(credentials);
|
|
4583
|
+
const project = {
|
|
4584
|
+
id: projectIn(projects, resolvedRegion),
|
|
4585
|
+
region: resolvedRegion
|
|
4586
|
+
};
|
|
4467
4587
|
const [flavors, images] = await Promise.all([listFlavors(project, availabilityZone), listImages(project)]);
|
|
4468
4588
|
const engines = deployment === void 0 ? [] : await databaseEngines(deployment);
|
|
4469
4589
|
const databaseFlavors = new Map();
|
|
@@ -4736,7 +4856,9 @@ async function listDatabaseFlavors(project, engine) {
|
|
|
4736
4856
|
*/
|
|
4737
4857
|
const ExistingResourceSchema = z.object({
|
|
4738
4858
|
id: z.string().min(1).describe("The cloud resource ID."),
|
|
4739
|
-
type: z.string().min(1).describe("
|
|
4859
|
+
type: z.string().min(1).describe("The resource type as whoever reported it spelled it. From list_existing_resources that is the RMS `type` (\"vpcs\", \"securityGroups\", \"cloudservers\"); from a .tf it is the terraform type (\"huaweicloud_vpc\"). Do not translate between the two vocabularies — pass `provider` alongside an RMS type and this resolves it."),
|
|
4860
|
+
provider: z.string().optional().describe("The RMS provider the resource came from (\"vpc\", \"ecs\", \"rds\"). Needed when `type` is an RMS name and this tool has to resolve it: \"instances\" is a database under rds and an API gateway under apig, and the pair is what tells them apart."),
|
|
4861
|
+
properties: z.record(z.string(), z.unknown()).optional().describe("The `properties` object from list_existing_resources, copied verbatim. This is where the relationships live: when one property holds another resource's id, the two are connected. Pass it and the diagram is derived from the account itself, with no per-service knowledge."),
|
|
4740
4862
|
name: z.string().optional().describe("Display name, when the cloud id is not the name."),
|
|
4741
4863
|
parent: z.string().optional().describe("The containing resource's cloud ID, when known. An ECS's subnet, a subnet's VPC. Resources with no parent are drawn at the root."),
|
|
4742
4864
|
cidr: z.string().optional().describe("Address range, for a VPC or subnet."),
|
|
@@ -4745,19 +4867,27 @@ const ExistingResourceSchema = z.object({
|
|
|
4745
4867
|
address: z.string().optional().describe("The terraform address this resource stands for, when the configuration references it — `huaweicloud_vpc.prod` for a VPC whose `.tf` block is omitted because it already exists. A `.tf` reference resolves only through this: the cloud name and the terraform label are independent, so no rule can derive one from the other.")
|
|
4746
4868
|
});
|
|
4747
4869
|
/**
|
|
4748
|
-
*
|
|
4870
|
+
* Terraform types, mapped to the node kinds a design diagram has.
|
|
4749
4871
|
*
|
|
4750
|
-
*
|
|
4751
|
-
* RMS answers
|
|
4752
|
-
*
|
|
4872
|
+
* One vocabulary only, and that matters: this table answers for a `.tf` block.
|
|
4873
|
+
* RMS answers with its own plurals (`vpcs`, `cloudservers`, `securityGroups`),
|
|
4874
|
+
* which are a different vocabulary and are resolved by
|
|
4875
|
+
* {@link resolveRmsType} from the provider/type pair instead. Mixing the two
|
|
4876
|
+
* here produced entries that could never match anything the inventory sends.
|
|
4877
|
+
*
|
|
4878
|
+
* Terraform types lose the `huaweicloud_` prefix and any `_vN` suffix before
|
|
4879
|
+
* lookup. Spelled out rather than assumed: `huaweicloud_vpc_subnet` reduces to
|
|
4880
|
+
* `vpc_subnet`, not `subnet`, and a table written from the service names alone
|
|
4881
|
+
* silently fails on every subnet.
|
|
4753
4882
|
*
|
|
4754
4883
|
* ## Why this table is small, and why that is not a coverage problem
|
|
4755
4884
|
*
|
|
4756
|
-
* The provider has
|
|
4757
|
-
* is made of. Measured against the provider's own example
|
|
4758
|
-
* resource instances of 438 distinct types — these kinds are 46%
|
|
4759
|
-
* instances, and what they leave out is mostly resources the picture is
|
|
4760
|
-
* about: alarm rules, backups, parameter templates, key pairs,
|
|
4885
|
+
* The provider has over a thousand resource types; this lists the ones a
|
|
4886
|
+
* network topology is made of. Measured against the provider's own example
|
|
4887
|
+
* corpus — 1368 resource instances of 438 distinct types — these kinds are 46%
|
|
4888
|
+
* of the instances, and what they leave out is mostly resources the picture is
|
|
4889
|
+
* not about: alarm rules, backups, parameter templates, key pairs,
|
|
4890
|
+
* subscriptions.
|
|
4761
4891
|
*
|
|
4762
4892
|
* A wider table would draw those too. That is the trade this table refuses: a
|
|
4763
4893
|
* diagram is read by comparing boxes, and a box that represents nothing the
|
|
@@ -4766,19 +4896,10 @@ const ExistingResourceSchema = z.object({
|
|
|
4766
4896
|
*/
|
|
4767
4897
|
const KIND_BY_SHORT_NAME = {
|
|
4768
4898
|
vpc: "vpc",
|
|
4769
|
-
subnet: "subnet",
|
|
4770
|
-
secgroup: "security-group",
|
|
4771
|
-
eip: "gateway",
|
|
4772
|
-
nat: "gateway",
|
|
4773
|
-
elb: "load-balancer",
|
|
4774
|
-
ecs: "compute",
|
|
4775
|
-
rds: "database",
|
|
4776
|
-
dcs: "database",
|
|
4777
|
-
gaussdb: "database",
|
|
4778
|
-
dds: "database",
|
|
4779
4899
|
vpc_subnet: "subnet",
|
|
4780
4900
|
networking_secgroup: "security-group",
|
|
4781
4901
|
networking_secgroup_rule: "security-group-rule",
|
|
4902
|
+
compute_secgroup: "security-group",
|
|
4782
4903
|
compute_instance: "compute",
|
|
4783
4904
|
rds_instance: "database",
|
|
4784
4905
|
dcs_instance: "database",
|
|
@@ -4802,20 +4923,86 @@ const KIND_BY_SHORT_NAME = {
|
|
|
4802
4923
|
evs_volume: "database"
|
|
4803
4924
|
};
|
|
4804
4925
|
/**
|
|
4805
|
-
*
|
|
4926
|
+
* What one configured resource is.
|
|
4806
4927
|
*
|
|
4807
|
-
*
|
|
4808
|
-
*
|
|
4809
|
-
*
|
|
4928
|
+
* This answers for a `.tf` block, whose type is the provider's own spelling. An
|
|
4929
|
+
* account's resources do not come through here: the inventory already knows
|
|
4930
|
+
* what each one is, and a table of its vocabulary would grow with every service
|
|
4931
|
+
* — see `existing-topology.ts` for how that case is derived instead.
|
|
4810
4932
|
*
|
|
4811
|
-
* @param type -
|
|
4812
|
-
*
|
|
4813
|
-
*
|
|
4933
|
+
* @param type - a terraform type (`huaweicloud_vpc`) or the short name the
|
|
4934
|
+
* provider's own docs use (`vpc`).
|
|
4935
|
+
* @returns the node kind, or `undefined` when the picture has none for it.
|
|
4814
4936
|
*/
|
|
4815
4937
|
function kindOfExisting(type) {
|
|
4816
4938
|
const stripped = type.replace(/^huaweicloud_/, "").replace(/_v\d+$/, "");
|
|
4817
4939
|
return KIND_BY_SHORT_NAME[stripped];
|
|
4818
4940
|
}
|
|
4941
|
+
/** Every kind a node may take. */
|
|
4942
|
+
const KINDS = new Set([
|
|
4943
|
+
"vpc",
|
|
4944
|
+
"subnet",
|
|
4945
|
+
"security-group",
|
|
4946
|
+
"security-group-rule",
|
|
4947
|
+
"gateway",
|
|
4948
|
+
"load-balancer",
|
|
4949
|
+
"compute",
|
|
4950
|
+
"database"
|
|
4951
|
+
]);
|
|
4952
|
+
/**
|
|
4953
|
+
* What one described resource is.
|
|
4954
|
+
*
|
|
4955
|
+
* `type` is resolved on its own, which is the whole answer for a caller that
|
|
4956
|
+
* sent a terraform type. A caller that copied an RMS `type` has a plural
|
|
4957
|
+
* vocabulary ("vpcs", "cloudservers") that says nothing about what the resource
|
|
4958
|
+
* IS — and `instances` is both a database and an API gateway, depending on the
|
|
4959
|
+
* provider. So when `provider` is present it is used to disambiguate, and when
|
|
4960
|
+
* the pair resolves to nothing the answer is `undefined`: the resource is real
|
|
4961
|
+
* but this picture has no box for it.
|
|
4962
|
+
*
|
|
4963
|
+
* @param resource - the described resource.
|
|
4964
|
+
* @returns the kind, or `undefined` when the picture has none for it.
|
|
4965
|
+
*/
|
|
4966
|
+
function kindOfResource(resource) {
|
|
4967
|
+
const stripped = resource.type.replace(/^huaweicloud_/, "").replace(/_v\d+$/, "");
|
|
4968
|
+
const direct = KIND_BY_SHORT_NAME[stripped] ?? resolveRmsType(resource.provider, stripped);
|
|
4969
|
+
return direct !== void 0 && KINDS.has(direct) ? direct : void 0;
|
|
4970
|
+
}
|
|
4971
|
+
/**
|
|
4972
|
+
* The kind an RMS plural type takes, given the provider that reported it.
|
|
4973
|
+
*
|
|
4974
|
+
* RMS names resources in the plural and per service, which is a second
|
|
4975
|
+
* vocabulary — not a translation of the first, and not derivable from it. It
|
|
4976
|
+
* exists because the inventory is the likeliest thing a caller has to hand, and
|
|
4977
|
+
* a caller should not have to translate what it was given.
|
|
4978
|
+
*
|
|
4979
|
+
* The provider is what makes it unambiguous: `instances` is an RDS database and
|
|
4980
|
+
* an APIG gateway, and the same word means neither thing on its own. That is
|
|
4981
|
+
* the reason the pair is required rather than either half.
|
|
4982
|
+
*
|
|
4983
|
+
* A service absent from this table draws nothing, which is the correct failure:
|
|
4984
|
+
* the caller is told the resource is outside the picture rather than shown a
|
|
4985
|
+
* box whose shape was guessed.
|
|
4986
|
+
*
|
|
4987
|
+
* @param provider - the RMS provider, or undefined when the caller omitted it.
|
|
4988
|
+
* @param type - the RMS type with the terraform prefix already stripped.
|
|
4989
|
+
* @returns the kind, or `undefined` when the pair has no box.
|
|
4990
|
+
*/
|
|
4991
|
+
function resolveRmsType(provider, type) {
|
|
4992
|
+
if (provider === void 0) return void 0;
|
|
4993
|
+
switch (`${provider}/${type}`) {
|
|
4994
|
+
case "vpc/vpcs": return "vpc";
|
|
4995
|
+
case "vpc/subnets": return "subnet";
|
|
4996
|
+
case "vpc/securityGroups": return "security-group";
|
|
4997
|
+
case "ecs/cloudservers": return "compute";
|
|
4998
|
+
case "elb/loadbalancers": return "load-balancer";
|
|
4999
|
+
case "nat/natGateways": return "gateway";
|
|
5000
|
+
case "cce/clusters": return "compute";
|
|
5001
|
+
case "cce/nodes": return "compute";
|
|
5002
|
+
case "rds/instances": return "database";
|
|
5003
|
+
default: return void 0;
|
|
5004
|
+
}
|
|
5005
|
+
}
|
|
4819
5006
|
|
|
4820
5007
|
//#endregion
|
|
4821
5008
|
//#region src/network-checks.ts
|
|
@@ -4922,7 +5109,7 @@ function findProblems(blocks, byAddress, existing = []) {
|
|
|
4922
5109
|
function existingSubnets(existing) {
|
|
4923
5110
|
const placed = [];
|
|
4924
5111
|
for (const resource of existing) {
|
|
4925
|
-
if (
|
|
5112
|
+
if (kindOfResource(resource) !== "subnet") continue;
|
|
4926
5113
|
const cidr = resource.cidr === void 0 ? void 0 : parseCidr(resource.cidr);
|
|
4927
5114
|
if (cidr === void 0) continue;
|
|
4928
5115
|
placed.push({
|
|
@@ -4944,7 +5131,7 @@ function checkSubnets(blocks, byAddress, existing = []) {
|
|
|
4944
5131
|
*/
|
|
4945
5132
|
const existingVpcByAddress = new Map();
|
|
4946
5133
|
for (const resource of existing) {
|
|
4947
|
-
if (
|
|
5134
|
+
if (kindOfResource(resource) !== "vpc" || resource.address === void 0) continue;
|
|
4948
5135
|
existingVpcByAddress.set(resource.address, resource.id);
|
|
4949
5136
|
}
|
|
4950
5137
|
const findings = [];
|
|
@@ -4956,7 +5143,7 @@ function checkSubnets(blocks, byAddress, existing = []) {
|
|
|
4956
5143
|
if (parsed !== void 0) vpcCidr.set(`${block.type}.${block.name}`, parsed);
|
|
4957
5144
|
}
|
|
4958
5145
|
for (const resource of existing) {
|
|
4959
|
-
if (
|
|
5146
|
+
if (kindOfResource(resource) !== "vpc" || resource.cidr === void 0) continue;
|
|
4960
5147
|
const parsed = parseCidr(resource.cidr);
|
|
4961
5148
|
if (parsed === void 0) continue;
|
|
4962
5149
|
for (const key of [resource.address, resource.id]) if (key !== void 0) vpcCidr.set(key, parsed);
|
|
@@ -5330,7 +5517,7 @@ function deriveTopology(blocks, existing = []) {
|
|
|
5330
5517
|
order.push(node);
|
|
5331
5518
|
}
|
|
5332
5519
|
for (const resource of existing) {
|
|
5333
|
-
const kind =
|
|
5520
|
+
const kind = kindOfResource(resource);
|
|
5334
5521
|
if (kind === void 0) {
|
|
5335
5522
|
omittedCounts.set(resource.type, (omittedCounts.get(resource.type) ?? 0) + 1);
|
|
5336
5523
|
continue;
|
|
@@ -5446,7 +5633,7 @@ function existingFacts(resource) {
|
|
|
5446
5633
|
function matchExistingTarget(value, expectedKind, existing, byAddress) {
|
|
5447
5634
|
const byTerraformAddress = new Map();
|
|
5448
5635
|
for (const resource of existing) {
|
|
5449
|
-
if (
|
|
5636
|
+
if (kindOfResource(resource) !== expectedKind) continue;
|
|
5450
5637
|
if (resource.address === void 0) continue;
|
|
5451
5638
|
if (!byTerraformAddress.has(resource.address)) byTerraformAddress.set(resource.address, resource.id);
|
|
5452
5639
|
}
|
|
@@ -5613,7 +5800,240 @@ function edgesOf(blocks, topology) {
|
|
|
5613
5800
|
}
|
|
5614
5801
|
|
|
5615
5802
|
//#endregion
|
|
5616
|
-
//#region src/
|
|
5803
|
+
//#region src/existing-topology.ts
|
|
5804
|
+
/** Facts worth showing on a box, by the attribute name that holds them. */
|
|
5805
|
+
const LABEL_ATTRIBUTES = [
|
|
5806
|
+
"name",
|
|
5807
|
+
"cidr",
|
|
5808
|
+
"publicIpAddress",
|
|
5809
|
+
"ipAddress",
|
|
5810
|
+
"vip_address",
|
|
5811
|
+
"flavor",
|
|
5812
|
+
"flavorCode",
|
|
5813
|
+
"spec",
|
|
5814
|
+
"nodeFlavor",
|
|
5815
|
+
"clusterFlavor",
|
|
5816
|
+
"size",
|
|
5817
|
+
"engineName",
|
|
5818
|
+
"engineVersion",
|
|
5819
|
+
"status",
|
|
5820
|
+
"instanceStatus",
|
|
5821
|
+
"clusterStatus",
|
|
5822
|
+
"provisioning_status",
|
|
5823
|
+
"availability_zone",
|
|
5824
|
+
"az"
|
|
5825
|
+
];
|
|
5826
|
+
/**
|
|
5827
|
+
* Every scalar the properties contain, keyed by its dotted path.
|
|
5828
|
+
*
|
|
5829
|
+
* Nested objects and arrays are flattened because the inventory nests ids
|
|
5830
|
+
* arbitrarily deep (`vnic.vpcId`, `bandwidth.id`,
|
|
5831
|
+
* `security_group_rules[].remote_group_id`), and a rule that only looked at the
|
|
5832
|
+
* top level would miss most of the relationships.
|
|
5833
|
+
*
|
|
5834
|
+
* A JSON-encoded value is also opened, because the inventory sometimes ships one
|
|
5835
|
+
* as a string. RDS is the case that was measured: it reports `vpcId` as
|
|
5836
|
+
* `"[\"73e76381-…\"]"` and `networkId` as its subnet — a real reference, present
|
|
5837
|
+
* and correct, that a plain string comparison never matches. Left closed, the
|
|
5838
|
+
* RDS instance floats at the root of the picture with its VPC in plain sight in
|
|
5839
|
+
* its own properties.
|
|
5840
|
+
*
|
|
5841
|
+
* @param value - any property value.
|
|
5842
|
+
* @returns path → scalar, for every leaf.
|
|
5843
|
+
*/
|
|
5844
|
+
function flattenProperties(value) {
|
|
5845
|
+
const found = new Map();
|
|
5846
|
+
const walk = (node, path) => {
|
|
5847
|
+
if (typeof node === "string") {
|
|
5848
|
+
if (isJsonEncoded(node)) try {
|
|
5849
|
+
walk(JSON.parse(node), path);
|
|
5850
|
+
return;
|
|
5851
|
+
} catch {}
|
|
5852
|
+
found.set(path, node);
|
|
5853
|
+
return;
|
|
5854
|
+
}
|
|
5855
|
+
if (typeof node === "number" || typeof node === "boolean") {
|
|
5856
|
+
found.set(path, String(node));
|
|
5857
|
+
return;
|
|
5858
|
+
}
|
|
5859
|
+
if (Array.isArray(node)) {
|
|
5860
|
+
for (const entry of node) walk(entry, path);
|
|
5861
|
+
return;
|
|
5862
|
+
}
|
|
5863
|
+
if (node !== null && typeof node === "object") for (const [key, inner] of Object.entries(node)) walk(inner, path === "" ? key : `${path}.${key}`);
|
|
5864
|
+
};
|
|
5865
|
+
walk(value, "");
|
|
5866
|
+
return found;
|
|
5867
|
+
}
|
|
5868
|
+
/**
|
|
5869
|
+
* Whether a string holds a JSON array or object worth opening.
|
|
5870
|
+
*
|
|
5871
|
+
* The check is deliberately narrow: an id is a plain string and must stay one,
|
|
5872
|
+
* so only a leading `{` or `[` that parses is opened. A quoted string inside a
|
|
5873
|
+
* range or a name that happens to start with a bracket would fail to parse and
|
|
5874
|
+
* be kept verbatim.
|
|
5875
|
+
*
|
|
5876
|
+
* @param text - the property value.
|
|
5877
|
+
* @returns whether it is worth attempting to parse.
|
|
5878
|
+
*/
|
|
5879
|
+
function isJsonEncoded(text) {
|
|
5880
|
+
const first = text.trimStart()[0];
|
|
5881
|
+
return first === "[" || first === "{";
|
|
5882
|
+
}
|
|
5883
|
+
/** The kinds a box can be drawn inside, and how specific each is. */
|
|
5884
|
+
const LOCATION_KINDS = [{
|
|
5885
|
+
nouns: ["vpc"],
|
|
5886
|
+
rank: 1
|
|
5887
|
+
}, {
|
|
5888
|
+
nouns: ["subnet", "network"],
|
|
5889
|
+
rank: 2
|
|
5890
|
+
}];
|
|
5891
|
+
/**
|
|
5892
|
+
* How specific a location an attribute names, 0 when it names none.
|
|
5893
|
+
*
|
|
5894
|
+
* The tail of the path is what counts: `vnic.vpcId` and `metadata.vpcId` both
|
|
5895
|
+
* end in a noun describing the container. Everything before the last dot is the
|
|
5896
|
+
* service's own nesting and says nothing about which container this is.
|
|
5897
|
+
*
|
|
5898
|
+
* The `id`/`uid`/`uuid` suffix is stripped rather than required to be present,
|
|
5899
|
+
* because the provider writes all three (`subnet_id`, `subnetId`,
|
|
5900
|
+
* `virsubnet_id`) and a rule that demanded one spelling would miss the others.
|
|
5901
|
+
* A plural suffix is stripped too: `elb_virsubnet_ids` holds several subnets,
|
|
5902
|
+
* and whether the attribute holds one id or a list does not change what it
|
|
5903
|
+
* names. Suffix matching, not equality, is what makes `virsubnet` and
|
|
5904
|
+
* `subnetwork` land on the same noun.
|
|
5905
|
+
*
|
|
5906
|
+
* @param attribute - a dotted property path.
|
|
5907
|
+
* @returns the rank of the location it names, or 0 for a plain association.
|
|
5908
|
+
*/
|
|
5909
|
+
function locationRank(attribute) {
|
|
5910
|
+
const tail = attribute.split(".").pop() ?? attribute;
|
|
5911
|
+
const noun = tail.replace(/(_?ids|_?id|_?uids|_?uid|uuid)$/i, "").replace(/[^a-z]/gi, "").toLowerCase();
|
|
5912
|
+
for (const { nouns, rank } of LOCATION_KINDS) for (const word of nouns) if (noun.endsWith(word)) return rank;
|
|
5913
|
+
return 0;
|
|
5914
|
+
}
|
|
5915
|
+
/**
|
|
5916
|
+
* Derive the picture from what the inventory reported.
|
|
5917
|
+
*
|
|
5918
|
+
* @param resources - every resource the inventory returned.
|
|
5919
|
+
* @returns nodes, edges, and the nesting derived from both.
|
|
5920
|
+
*/
|
|
5921
|
+
function deriveInventoryTopology(resources) {
|
|
5922
|
+
const byId = new Map();
|
|
5923
|
+
const duplicates = [];
|
|
5924
|
+
for (const resource of resources) {
|
|
5925
|
+
if (byId.has(resource.id)) {
|
|
5926
|
+
if (!duplicates.includes(resource.id)) duplicates.push(resource.id);
|
|
5927
|
+
continue;
|
|
5928
|
+
}
|
|
5929
|
+
byId.set(resource.id, resource);
|
|
5930
|
+
}
|
|
5931
|
+
const flat = new Map();
|
|
5932
|
+
for (const [id, resource] of byId) flat.set(id, flattenProperties(resource.properties ?? {}));
|
|
5933
|
+
const raw = [];
|
|
5934
|
+
const seen = new Set();
|
|
5935
|
+
for (const [id, properties] of flat) for (const [attribute, value] of properties) {
|
|
5936
|
+
if (value === id) continue;
|
|
5937
|
+
if (!byId.has(value)) continue;
|
|
5938
|
+
const key = `${id}\u0000${value}`;
|
|
5939
|
+
if (seen.has(key)) continue;
|
|
5940
|
+
seen.add(key);
|
|
5941
|
+
raw.push({
|
|
5942
|
+
from: id,
|
|
5943
|
+
to: value,
|
|
5944
|
+
attribute,
|
|
5945
|
+
location: locationRank(attribute)
|
|
5946
|
+
});
|
|
5947
|
+
}
|
|
5948
|
+
const edges = raw.map((entry) => ({
|
|
5949
|
+
from: entry.from,
|
|
5950
|
+
to: entry.to,
|
|
5951
|
+
attribute: entry.attribute,
|
|
5952
|
+
contains: entry.location > 0
|
|
5953
|
+
}));
|
|
5954
|
+
const parentOf = new Map();
|
|
5955
|
+
const parentRank = new Map();
|
|
5956
|
+
for (const entry of raw) {
|
|
5957
|
+
if (entry.location === 0) continue;
|
|
5958
|
+
if (entry.location > (parentRank.get(entry.from) ?? 0)) {
|
|
5959
|
+
parentOf.set(entry.from, entry.to);
|
|
5960
|
+
parentRank.set(entry.from, entry.location);
|
|
5961
|
+
}
|
|
5962
|
+
}
|
|
5963
|
+
for (const [child, parent] of [...parentOf]) {
|
|
5964
|
+
const seenChain = new Set([child]);
|
|
5965
|
+
let cursor = parent;
|
|
5966
|
+
while (cursor !== void 0) {
|
|
5967
|
+
if (seenChain.has(cursor)) {
|
|
5968
|
+
parentOf.delete(child);
|
|
5969
|
+
break;
|
|
5970
|
+
}
|
|
5971
|
+
seenChain.add(cursor);
|
|
5972
|
+
cursor = parentOf.get(cursor);
|
|
5973
|
+
}
|
|
5974
|
+
}
|
|
5975
|
+
const childrenOf = new Map();
|
|
5976
|
+
for (const [child, parent] of parentOf) {
|
|
5977
|
+
const list = childrenOf.get(parent) ?? [];
|
|
5978
|
+
list.push(child);
|
|
5979
|
+
childrenOf.set(parent, list);
|
|
5980
|
+
}
|
|
5981
|
+
const factsOf = (resource) => {
|
|
5982
|
+
const properties = flat.get(resource.id) ?? new Map();
|
|
5983
|
+
const label = resource.name ?? "";
|
|
5984
|
+
const facts = [];
|
|
5985
|
+
for (const key of LABEL_ATTRIBUTES) {
|
|
5986
|
+
const value = properties.get(key);
|
|
5987
|
+
if (value === void 0 || value === "" || value === label) continue;
|
|
5988
|
+
if (facts.some((fact) => fact.value === value)) continue;
|
|
5989
|
+
facts.push({
|
|
5990
|
+
key,
|
|
5991
|
+
value
|
|
5992
|
+
});
|
|
5993
|
+
}
|
|
5994
|
+
return facts;
|
|
5995
|
+
};
|
|
5996
|
+
const ancestorsOf = (id) => {
|
|
5997
|
+
const chain = [];
|
|
5998
|
+
const seenChain = new Set([id]);
|
|
5999
|
+
let cursor = parentOf.get(id);
|
|
6000
|
+
while (cursor !== void 0 && !seenChain.has(cursor)) {
|
|
6001
|
+
seenChain.add(cursor);
|
|
6002
|
+
chain.push(cursor);
|
|
6003
|
+
cursor = parentOf.get(cursor);
|
|
6004
|
+
}
|
|
6005
|
+
return chain;
|
|
6006
|
+
};
|
|
6007
|
+
const build = (id) => {
|
|
6008
|
+
const resource = byId.get(id);
|
|
6009
|
+
return {
|
|
6010
|
+
id,
|
|
6011
|
+
provider: resource.provider,
|
|
6012
|
+
type: resource.type,
|
|
6013
|
+
label: resource.name !== void 0 && resource.name !== "" ? resource.name : `${resource.provider}/${resource.type} ${id.slice(0, 8)}`,
|
|
6014
|
+
facts: factsOf(resource),
|
|
6015
|
+
parent: parentOf.get(id),
|
|
6016
|
+
ancestors: ancestorsOf(id),
|
|
6017
|
+
children: (childrenOf.get(id) ?? []).map(build)
|
|
6018
|
+
};
|
|
6019
|
+
};
|
|
6020
|
+
const rootIds = [...byId.keys()].filter((id) => !parentOf.has(id));
|
|
6021
|
+
const depth = (id) => ancestorsOf(id).length;
|
|
6022
|
+
rootIds.sort((a, b) => {
|
|
6023
|
+
const da = depth(a), db = depth(b);
|
|
6024
|
+
if (da !== db) return db - da;
|
|
6025
|
+
return (byId.get(a).name ?? a).localeCompare(byId.get(b).name ?? b);
|
|
6026
|
+
});
|
|
6027
|
+
return {
|
|
6028
|
+
roots: rootIds.map(build),
|
|
6029
|
+
nodes: [...byId.keys()].map(build),
|
|
6030
|
+
edges,
|
|
6031
|
+
duplicates
|
|
6032
|
+
};
|
|
6033
|
+
}
|
|
6034
|
+
|
|
6035
|
+
//#endregion
|
|
6036
|
+
//#region src/d2-engine.ts
|
|
5617
6037
|
/**
|
|
5618
6038
|
* The D2 themes, light and dark.
|
|
5619
6039
|
*
|
|
@@ -5633,77 +6053,45 @@ function edgesOf(blocks, topology) {
|
|
|
5633
6053
|
const LIGHT_THEME_ID = 5;
|
|
5634
6054
|
const DARK_THEME_ID = 201;
|
|
5635
6055
|
/**
|
|
5636
|
-
* The
|
|
5637
|
-
*
|
|
5638
|
-
* These are D2's OWN theme classes (`fill-B4`, `stroke-B1`, …), not custom
|
|
5639
|
-
* colours, and that is the whole reason for using them. A custom
|
|
5640
|
-
* `classes: { vpc: { style: { fill: "#EEF4FF" } } }` is emitted as a
|
|
5641
|
-
* hard-coded `fill="#EEF4FF"` on the element, so it stays light-blue on a dark
|
|
5642
|
-
* ground and the diagram becomes unreadable. The built-in classes are emitted
|
|
5643
|
-
* as class REFERENCES, and D2 writes both palettes into the SVG with the dark
|
|
5644
|
-
* half behind `@media (prefers-color-scheme: dark)` — so one file follows the
|
|
5645
|
-
* viewer's theme with no JavaScript.
|
|
5646
|
-
*
|
|
5647
|
-
* The hues are D2's accent ramps: `B` (blue) for network structure, `AA` (red)
|
|
5648
|
-
* for the one kind that is a warning by nature, and `N` (neutral) for anything
|
|
5649
|
-
* unrecognised. Lightness steps apart so a subnet reads as inside its VPC.
|
|
5650
|
-
*/
|
|
5651
|
-
const KIND_CLASSES = {
|
|
5652
|
-
vpc: "fill-B5, stroke-B3",
|
|
5653
|
-
subnet: "fill-B6, stroke-B4",
|
|
5654
|
-
"security-group": "fill-AA4, stroke-AA2",
|
|
5655
|
-
"security-group-rule": "fill-AA5, stroke-AA4",
|
|
5656
|
-
gateway: "fill-N6, stroke-N4",
|
|
5657
|
-
"load-balancer": "fill-B4, stroke-B2",
|
|
5658
|
-
compute: "fill-AB5, stroke-AB4",
|
|
5659
|
-
database: "fill-AB4, stroke-AB4"
|
|
5660
|
-
};
|
|
5661
|
-
/**
|
|
5662
|
-
* The words on a connection's arrow.
|
|
6056
|
+
* The `vars` block every generated diagram opens with.
|
|
5663
6057
|
*
|
|
5664
|
-
* The
|
|
5665
|
-
*
|
|
5666
|
-
*
|
|
5667
|
-
*/
|
|
5668
|
-
const CONNECTION_LABEL = {
|
|
5669
|
-
peering: "peering",
|
|
5670
|
-
endpoint: "VPCEP",
|
|
5671
|
-
route: "route"
|
|
5672
|
-
};
|
|
5673
|
-
/**
|
|
5674
|
-
* The D2 class an edge carries.
|
|
6058
|
+
* The theme ids are written into the diagram rather than passed to `render`, so
|
|
6059
|
+
* the generated source is the whole description of what was drawn — a reader
|
|
6060
|
+
* feeding it to the D2 CLI gets the same colours.
|
|
5675
6061
|
*
|
|
5676
|
-
*
|
|
5677
|
-
* connection uses the accent that reads as "traffic flows here" rather than the
|
|
5678
|
-
* neutral a plain reference gets. It is a theme class, not a literal colour, so
|
|
5679
|
-
* the dark palette follows.
|
|
6062
|
+
* @returns the opening lines of a D2 document.
|
|
5680
6063
|
*/
|
|
5681
|
-
|
|
6064
|
+
function themePreamble() {
|
|
6065
|
+
return [
|
|
6066
|
+
"direction: down",
|
|
6067
|
+
"",
|
|
6068
|
+
"vars: {",
|
|
6069
|
+
" d2-config: {",
|
|
6070
|
+
` theme-id: ${LIGHT_THEME_ID}`,
|
|
6071
|
+
` dark-theme-id: ${DARK_THEME_ID}`,
|
|
6072
|
+
" }",
|
|
6073
|
+
"}",
|
|
6074
|
+
""
|
|
6075
|
+
];
|
|
6076
|
+
}
|
|
5682
6077
|
/**
|
|
5683
|
-
*
|
|
6078
|
+
* Compile D2 source and render it to an SVG.
|
|
5684
6079
|
*
|
|
5685
|
-
* @param
|
|
5686
|
-
* @
|
|
5687
|
-
*
|
|
5688
|
-
*
|
|
5689
|
-
*
|
|
5690
|
-
* this module rather than in the user's configuration — the generator is
|
|
5691
|
-
* what produced the text — so the message names the generated fragment.
|
|
6080
|
+
* @param source - the D2 source text.
|
|
6081
|
+
* @returns the SVG, with no XML declaration.
|
|
6082
|
+
* @throws when the source does not compile. That is a defect in the generator
|
|
6083
|
+
* rather than in the user's configuration — the generator produced the text —
|
|
6084
|
+
* so the caller names the generated fragment in its message.
|
|
5692
6085
|
*/
|
|
5693
|
-
async function
|
|
5694
|
-
const source$1 = toD2(topology, edges);
|
|
6086
|
+
async function renderD2(source$1) {
|
|
5695
6087
|
const d2 = new D2();
|
|
5696
6088
|
try {
|
|
5697
6089
|
const compiled$1 = await d2.compile(source$1, { options: { layout: "elk" } });
|
|
5698
|
-
|
|
6090
|
+
return await d2.render(compiled$1.diagram, {
|
|
5699
6091
|
...compiled$1.renderOptions,
|
|
5700
6092
|
pad: 20,
|
|
5701
6093
|
noXMLTag: true
|
|
5702
6094
|
});
|
|
5703
|
-
return {
|
|
5704
|
-
source: source$1,
|
|
5705
|
-
svg
|
|
5706
|
-
};
|
|
5707
6095
|
} finally {
|
|
5708
6096
|
await closeD2(d2);
|
|
5709
6097
|
}
|
|
@@ -5724,34 +6112,297 @@ async function closeD2(d2) {
|
|
|
5724
6112
|
} catch {}
|
|
5725
6113
|
}
|
|
5726
6114
|
/**
|
|
5727
|
-
*
|
|
6115
|
+
* Quote a string for a D2 label.
|
|
5728
6116
|
*
|
|
5729
|
-
*
|
|
5730
|
-
*
|
|
6117
|
+
* @param text - the label.
|
|
6118
|
+
* @returns the text inside double quotes, with its own quotes escaped.
|
|
6119
|
+
*/
|
|
6120
|
+
function quote(text) {
|
|
6121
|
+
return `"${text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
|
|
6122
|
+
}
|
|
6123
|
+
/**
|
|
6124
|
+
* The D2 identifier for an address or cloud id.
|
|
5731
6125
|
*
|
|
5732
|
-
*
|
|
5733
|
-
*
|
|
5734
|
-
*
|
|
5735
|
-
*
|
|
5736
|
-
* treats a leading `|` as a block-string terminator.
|
|
5737
|
-
* - No `vars` block: D2 discards everything under it except `d2-config`.
|
|
6126
|
+
* A `.` in a D2 key means "member of the block before it", so an unreplaced one
|
|
6127
|
+
* nests the node inside a box named after the part before the dot — inventing a
|
|
6128
|
+
* container that does not exist. Every character D2 reserves is replaced by `_`
|
|
6129
|
+
* for the same reason.
|
|
5738
6130
|
*
|
|
5739
|
-
*
|
|
5740
|
-
*
|
|
5741
|
-
*
|
|
5742
|
-
|
|
6131
|
+
* A collision is possible in principle (`a_b.c` and `a.b_c` both map to
|
|
6132
|
+
* `a_b_c`). It cannot occur inside one provider namespace, where the separator
|
|
6133
|
+
* between resource types and names is always the same `.`, but callers draw
|
|
6134
|
+
* from a map keyed by the original id, so a collision would drop an edge rather
|
|
6135
|
+
* than misplace it.
|
|
6136
|
+
*
|
|
6137
|
+
* @param address - a terraform `type.name` address or a cloud resource id.
|
|
6138
|
+
* @returns an identifier D2 accepts.
|
|
6139
|
+
*/
|
|
6140
|
+
function d2Id(address) {
|
|
6141
|
+
return address.replaceAll(".", "_").replaceAll(/[^A-Za-z0-9_]/g, "_");
|
|
6142
|
+
}
|
|
6143
|
+
|
|
6144
|
+
//#endregion
|
|
6145
|
+
//#region src/d2-inventory.ts
|
|
6146
|
+
/**
|
|
6147
|
+
* The D2 palette ramps, one hue each with three lightness steps.
|
|
6148
|
+
*
|
|
6149
|
+
* Four ramps rather than a per-provider table: `hash(provider) % 4` picks one,
|
|
6150
|
+
* so a provider not named anywhere still gets a stable, distinct colour.
|
|
6151
|
+
*/
|
|
6152
|
+
const PROVIDER_RAMPS = [
|
|
6153
|
+
[
|
|
6154
|
+
"fill-B5, stroke-B3",
|
|
6155
|
+
"fill-B6, stroke-B4",
|
|
6156
|
+
"fill-B4, stroke-B2"
|
|
6157
|
+
],
|
|
6158
|
+
[
|
|
6159
|
+
"fill-AA4, stroke-AA2",
|
|
6160
|
+
"fill-AA5, stroke-AA4",
|
|
6161
|
+
"fill-AA3, stroke-AA2"
|
|
6162
|
+
],
|
|
6163
|
+
[
|
|
6164
|
+
"fill-AB5, stroke-AB4",
|
|
6165
|
+
"fill-AB4, stroke-AB4",
|
|
6166
|
+
"fill-AB6, stroke-AB5"
|
|
6167
|
+
],
|
|
6168
|
+
[
|
|
6169
|
+
"fill-N7, stroke-N5",
|
|
6170
|
+
"fill-N6, stroke-N4",
|
|
6171
|
+
"fill-N5, stroke-N3"
|
|
6172
|
+
]
|
|
6173
|
+
];
|
|
6174
|
+
/** The class an arrow into a resource carries: "traffic flows here". */
|
|
6175
|
+
const CONNECTION_CLASS$1 = "stroke-AB3";
|
|
6176
|
+
/**
|
|
6177
|
+
* How many top-level boxes go in one row of an inventory picture.
|
|
6178
|
+
*
|
|
6179
|
+
* Three. Measured on a live 30-resource account: one row (D2's arrangement for
|
|
6180
|
+
* unconnected roots) is 9.6:1, five columns is 5.8:1, four is 4.8:1 and three is
|
|
6181
|
+
* 3.4:1. Below three the picture grows tall rather than wide, and a wider grid
|
|
6182
|
+
* pushes the strip down a level instead of removing it.
|
|
6183
|
+
*/
|
|
6184
|
+
const GRID_COLUMNS = 3;
|
|
6185
|
+
/**
|
|
6186
|
+
* The class for one provider/type pair, stable across runs and pictures.
|
|
6187
|
+
*
|
|
6188
|
+
* @param provider - the service that reported the resource.
|
|
6189
|
+
* @param type - that service's own type name.
|
|
6190
|
+
* @returns a D2 theme class reference.
|
|
6191
|
+
*/
|
|
6192
|
+
function inventoryClass(provider, type) {
|
|
6193
|
+
const hash = (text) => {
|
|
6194
|
+
let value = 0;
|
|
6195
|
+
for (const character of text) value = value * 31 + character.charCodeAt(0) >>> 0;
|
|
6196
|
+
return value;
|
|
6197
|
+
};
|
|
6198
|
+
const ramp = PROVIDER_RAMPS[hash(provider) % PROVIDER_RAMPS.length];
|
|
6199
|
+
return ramp[hash(type) % ramp.length];
|
|
6200
|
+
}
|
|
6201
|
+
/**
|
|
6202
|
+
* Draw an inventory-derived topology.
|
|
6203
|
+
*
|
|
6204
|
+
* @param topology - the picture derived from the inventory.
|
|
6205
|
+
* @returns the D2 source and the SVG it renders to.
|
|
6206
|
+
*/
|
|
6207
|
+
async function renderInventoryTopology(topology) {
|
|
6208
|
+
const source$1 = inventoryToD2(topology);
|
|
6209
|
+
return {
|
|
6210
|
+
source: source$1,
|
|
6211
|
+
svg: await renderD2(source$1)
|
|
6212
|
+
};
|
|
6213
|
+
}
|
|
6214
|
+
/**
|
|
6215
|
+
* Generate the D2 source for an inventory-derived topology.
|
|
6216
|
+
*
|
|
6217
|
+
* @param topology - the picture.
|
|
6218
|
+
* @returns D2 source text.
|
|
6219
|
+
*/
|
|
6220
|
+
function inventoryToD2(topology) {
|
|
6221
|
+
const lines = themePreamble();
|
|
6222
|
+
if (topology.roots.length > GRID_COLUMNS) lines.push(`grid-columns: ${GRID_COLUMNS}`, "");
|
|
6223
|
+
const write$1 = (node, depth) => {
|
|
6224
|
+
const indent = " ".repeat(depth);
|
|
6225
|
+
const label = node.facts.length === 0 ? node.label : `${node.label} ${node.facts.map((fact) => fact.value).join(" · ")}`;
|
|
6226
|
+
const style = `class: [${inventoryClass(node.provider, node.type)}]`;
|
|
6227
|
+
if (node.children.length === 0) {
|
|
6228
|
+
lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} { ${style} }`);
|
|
6229
|
+
return;
|
|
6230
|
+
}
|
|
6231
|
+
lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} {`);
|
|
6232
|
+
lines.push(`${indent} ${style}`);
|
|
6233
|
+
for (const child of node.children) write$1(child, depth + 1);
|
|
6234
|
+
lines.push(`${indent}}`);
|
|
6235
|
+
};
|
|
6236
|
+
for (const root of topology.roots) write$1(root, 0);
|
|
6237
|
+
if (topology.roots.length > 0) lines.push("");
|
|
6238
|
+
for (const edge of drawnEdges(topology)) lines.push(`${nodeId(edge.from)} -> ${nodeId(edge.to)}: ${quote(edge.attribute)} { class: [${CONNECTION_CLASS$1}] }`);
|
|
6239
|
+
return lines.join("\n");
|
|
6240
|
+
}
|
|
6241
|
+
/**
|
|
6242
|
+
* The relationships worth drawing as an arrow.
|
|
6243
|
+
*
|
|
6244
|
+
* Three kinds of association are dropped, each for a reason that shows up on a
|
|
6245
|
+
* real account rather than being a preference:
|
|
6246
|
+
*
|
|
6247
|
+
* 1. **Containment.** A parent/child edge is already said by the nesting, and
|
|
6248
|
+
* an arrow beside it draws the same fact twice — the line leaves the box
|
|
6249
|
+
* it never left.
|
|
6250
|
+
* 2. **The reverse of another edge.** The inventory reports both ends of a
|
|
6251
|
+
* relationship: an EIP names its bandwidth and the bandwidth names the
|
|
6252
|
+
* EIP, a server names its volumes and each volume names the server. Both
|
|
6253
|
+
* are true, but one arrow per pair says as much and does not put two
|
|
6254
|
+
* lines on top of each other. Measured on a live 49-resource account:
|
|
6255
|
+
* 40 associations, 32 distinct pairs.
|
|
6256
|
+
* 3. **A reference that points at an ancestor.** The VPC a resource sits in
|
|
6257
|
+
* is visible from where the resource is drawn; a line from inside the
|
|
6258
|
+
* container out to it adds no fact and crosses the container's border to
|
|
6259
|
+
* say nothing. Five of those on the same account, all of them `vpc_id`.
|
|
6260
|
+
*
|
|
6261
|
+
* What is left is a genuine cross-container reference: a resource here naming
|
|
6262
|
+
* a resource there. Those are the ones a reader has to follow, so they are the
|
|
6263
|
+
* ones that get a line.
|
|
6264
|
+
*
|
|
6265
|
+
* @param topology - the derived picture.
|
|
6266
|
+
* @returns the edges to draw, deduplicated and without the ones nesting implies.
|
|
6267
|
+
*/
|
|
6268
|
+
function drawnEdges(topology) {
|
|
6269
|
+
const parentOf = new Map(topology.nodes.map((node) => [node.id, node.parent]));
|
|
6270
|
+
const ancestorsOf = new Map(topology.nodes.map((node) => [node.id, node.ancestors]));
|
|
6271
|
+
const seenPairs = new Set();
|
|
6272
|
+
const drawn = [];
|
|
6273
|
+
for (const edge of topology.edges) {
|
|
6274
|
+
if (parentOf.get(edge.from) === edge.to) continue;
|
|
6275
|
+
if ((ancestorsOf.get(edge.from) ?? []).includes(edge.to)) continue;
|
|
6276
|
+
const pair = [edge.from, edge.to].sort().join("\0");
|
|
6277
|
+
if (seenPairs.has(pair)) continue;
|
|
6278
|
+
seenPairs.add(pair);
|
|
6279
|
+
drawn.push(edge);
|
|
6280
|
+
}
|
|
6281
|
+
return drawn;
|
|
6282
|
+
}
|
|
6283
|
+
/**
|
|
6284
|
+
* The D2 identifier for a cloud id.
|
|
6285
|
+
*
|
|
6286
|
+
* The `r_` prefix is what keeps an id from colliding with D2's own reserved
|
|
6287
|
+
* words, and the base conversion handles every character D2 would otherwise
|
|
6288
|
+
* read as syntax.
|
|
6289
|
+
*
|
|
6290
|
+
* @param id - a cloud resource id.
|
|
6291
|
+
* @returns an identifier D2 accepts.
|
|
6292
|
+
*/
|
|
6293
|
+
function nodeId(id) {
|
|
6294
|
+
return d2Id(`r_${id}`);
|
|
6295
|
+
}
|
|
6296
|
+
|
|
6297
|
+
//#endregion
|
|
6298
|
+
//#region src/d2-design.ts
|
|
6299
|
+
/**
|
|
6300
|
+
* The D2 palette classes per node kind.
|
|
6301
|
+
*
|
|
6302
|
+
* These are D2's OWN theme classes (`fill-B4`, `stroke-B1`, …), not custom
|
|
6303
|
+
* colours, and that is the whole reason for using them. A custom
|
|
6304
|
+
* `classes: { vpc: { style: { fill: "#EEF4FF" } } }` is emitted as a
|
|
6305
|
+
* hard-coded `fill="#EEF4FF"` on the element, so it stays light-blue on a dark
|
|
6306
|
+
* ground and the diagram becomes unreadable. The built-in classes are emitted
|
|
6307
|
+
* as class REFERENCES, and D2 writes both palettes into the SVG with the dark
|
|
6308
|
+
* half behind `@media (prefers-color-scheme: dark)` — so one file follows the
|
|
6309
|
+
* viewer's theme with no JavaScript.
|
|
6310
|
+
*
|
|
6311
|
+
* The hues are D2's accent ramps: `B` (blue) for network structure, `AA` (red)
|
|
6312
|
+
* for the one kind that is a warning by nature, and `N` (neutral) for anything
|
|
6313
|
+
* unrecognised. Lightness steps apart so a subnet reads as inside its VPC.
|
|
6314
|
+
*/
|
|
6315
|
+
const KIND_CLASSES = {
|
|
6316
|
+
vpc: "fill-B5, stroke-B3",
|
|
6317
|
+
subnet: "fill-B6, stroke-B4",
|
|
6318
|
+
"security-group": "fill-AA4, stroke-AA2",
|
|
6319
|
+
"security-group-rule": "fill-AA5, stroke-AA4",
|
|
6320
|
+
gateway: "fill-N6, stroke-N4",
|
|
6321
|
+
"load-balancer": "fill-B4, stroke-B2",
|
|
6322
|
+
compute: "fill-AB5, stroke-AB4",
|
|
6323
|
+
database: "fill-AB4, stroke-AB4"
|
|
6324
|
+
};
|
|
6325
|
+
/**
|
|
6326
|
+
* The short noun a node's box is headed with.
|
|
6327
|
+
*
|
|
6328
|
+
* The design vocabulary's names are this module's own (`security-group`), while
|
|
6329
|
+
* the box is read by someone looking at a network diagram and needs the words
|
|
6330
|
+
* the cloud uses.
|
|
6331
|
+
*
|
|
6332
|
+
* `compute` and `database` are the two kinds that cover several provider types,
|
|
6333
|
+
* so their captions are the generic word rather than one product name: a CCE
|
|
6334
|
+
* node is not an ECS instance and a DDS cluster is not RDS, and a box captioned
|
|
6335
|
+
* "ECS" would claim it is. The node's own `name` and terraform type carry the
|
|
6336
|
+
* specific identity.
|
|
6337
|
+
*/
|
|
6338
|
+
const KIND_CAPTION = {
|
|
6339
|
+
vpc: "VPC",
|
|
6340
|
+
subnet: "subnet",
|
|
6341
|
+
"security-group": "secgroup",
|
|
6342
|
+
"security-group-rule": "rule",
|
|
6343
|
+
gateway: "gateway",
|
|
6344
|
+
"load-balancer": "ELB",
|
|
6345
|
+
compute: "compute",
|
|
6346
|
+
database: "database"
|
|
6347
|
+
};
|
|
6348
|
+
/**
|
|
6349
|
+
* The words on a connection's arrow.
|
|
6350
|
+
*
|
|
6351
|
+
* The cloud's own term for each, not this module's: a reader who looks at the
|
|
6352
|
+
* console finds "对等连接", "终端节点" and "路由" — and a diagram that renamed
|
|
6353
|
+
* them would need a translation step nobody asked for.
|
|
6354
|
+
*/
|
|
6355
|
+
const CONNECTION_LABEL = {
|
|
6356
|
+
peering: "peering",
|
|
6357
|
+
endpoint: "VPCEP",
|
|
6358
|
+
route: "route"
|
|
6359
|
+
};
|
|
6360
|
+
/**
|
|
6361
|
+
* The D2 class an edge carries.
|
|
6362
|
+
*
|
|
6363
|
+
* D2's connection classes take the same palette vocabulary as shapes, so the
|
|
6364
|
+
* connection uses the accent that reads as "traffic flows here" rather than the
|
|
6365
|
+
* neutral a plain reference gets. It is a theme class, not a literal colour, so
|
|
6366
|
+
* the dark palette follows.
|
|
6367
|
+
*/
|
|
6368
|
+
const CONNECTION_CLASS = "stroke-AB3";
|
|
6369
|
+
/**
|
|
6370
|
+
* Draw the topology.
|
|
6371
|
+
*
|
|
6372
|
+
* @param topology - the derived picture.
|
|
6373
|
+
* @param edges - the relationships to draw, from `<from-address>` to
|
|
6374
|
+
* `<to-address>`. Only addresses the topology knows are drawn.
|
|
6375
|
+
* @returns the D2 source and the SVG it renders to.
|
|
6376
|
+
* @throws when the generated D2 source does not compile. That is a defect in
|
|
6377
|
+
* this module rather than in the user's configuration — the generator is
|
|
6378
|
+
* what produced the text — so the message names the generated fragment.
|
|
6379
|
+
*/
|
|
6380
|
+
async function renderTopology(topology, edges) {
|
|
6381
|
+
const source$1 = toD2(topology, edges);
|
|
6382
|
+
return {
|
|
6383
|
+
source: source$1,
|
|
6384
|
+
svg: await renderD2(source$1)
|
|
6385
|
+
};
|
|
6386
|
+
}
|
|
6387
|
+
/**
|
|
6388
|
+
* Generate the D2 source for one topology.
|
|
6389
|
+
*
|
|
6390
|
+
* The shape of the output is fixed by what D2 accepts:
|
|
6391
|
+
*
|
|
6392
|
+
* - Nothing is written as an attribute child. `cidr: "10.0.0.0/16"` inside a
|
|
6393
|
+
* node's block renders as its own box, which would put a stray rectangle
|
|
6394
|
+
* in every subnet. Facts go into the node's LABEL instead.
|
|
6395
|
+
* - Facts are separated by `·` rather than aligned into columns, because D2
|
|
6396
|
+
* treats a leading `|` as a block-string terminator.
|
|
6397
|
+
* - No `vars` block beyond the theme: D2 discards everything under it except
|
|
6398
|
+
* `d2-config`.
|
|
6399
|
+
*
|
|
6400
|
+
* @param topology - the derived picture.
|
|
6401
|
+
* @param edges - the relationships to draw.
|
|
6402
|
+
* @returns D2 source text.
|
|
6403
|
+
*/
|
|
5743
6404
|
function toD2(topology, edges) {
|
|
5744
|
-
const lines =
|
|
5745
|
-
"direction: down",
|
|
5746
|
-
"",
|
|
5747
|
-
"vars: {",
|
|
5748
|
-
" d2-config: {",
|
|
5749
|
-
` theme-id: ${LIGHT_THEME_ID}`,
|
|
5750
|
-
` dark-theme-id: ${DARK_THEME_ID}`,
|
|
5751
|
-
" }",
|
|
5752
|
-
"}",
|
|
5753
|
-
""
|
|
5754
|
-
];
|
|
6405
|
+
const lines = themePreamble();
|
|
5755
6406
|
const byAddress = new Map(topology.nodes.map((node) => [node.address, node]));
|
|
5756
6407
|
for (const root of topology.roots) lines.push(...nodeLines(root, 0));
|
|
5757
6408
|
if (topology.roots.length > 0) lines.push("");
|
|
@@ -5788,7 +6439,7 @@ function nodeLines(node, depth) {
|
|
|
5788
6439
|
const classes = KIND_CLASSES[node.kind];
|
|
5789
6440
|
if (classes === void 0) throw new Error(`no D2 class for node kind "${node.kind}" (${node.address})`);
|
|
5790
6441
|
const style = `class: [${classes}]`;
|
|
5791
|
-
const extra = node.existing ? ["
|
|
6442
|
+
const extra = node.existing ? ["style.stroke-dash: 4"] : [];
|
|
5792
6443
|
if (node.children.length === 0) {
|
|
5793
6444
|
if (extra.length === 0) return [`${indent}${d2Id(node.address)}: ${quote(label)} { ${style} }`];
|
|
5794
6445
|
return [
|
|
@@ -5837,51 +6488,6 @@ function d2Label(node) {
|
|
|
5837
6488
|
return shown.length === 0 ? head : `${head} ${shown.join(" · ")}`;
|
|
5838
6489
|
}
|
|
5839
6490
|
/**
|
|
5840
|
-
* The short noun a node's box is headed with.
|
|
5841
|
-
*
|
|
5842
|
-
* Written out rather than derived from `NodeKind` because the kind is this
|
|
5843
|
-
* module's vocabulary (`security-group`), while the box is read by someone
|
|
5844
|
-
* looking at a network diagram and needs the words the cloud uses.
|
|
5845
|
-
*/
|
|
5846
|
-
const KIND_CAPTION = {
|
|
5847
|
-
vpc: "VPC",
|
|
5848
|
-
subnet: "subnet",
|
|
5849
|
-
"security-group": "secgroup",
|
|
5850
|
-
gateway: "gateway",
|
|
5851
|
-
"load-balancer": "ELB",
|
|
5852
|
-
compute: "ECS",
|
|
5853
|
-
database: "database"
|
|
5854
|
-
};
|
|
5855
|
-
/**
|
|
5856
|
-
* Quote a string for a D2 label.
|
|
5857
|
-
*
|
|
5858
|
-
* @param text - the label.
|
|
5859
|
-
* @returns the text inside double quotes, with its own quotes escaped.
|
|
5860
|
-
*/
|
|
5861
|
-
function quote(text) {
|
|
5862
|
-
return `"${text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
|
|
5863
|
-
}
|
|
5864
|
-
/**
|
|
5865
|
-
* The D2 identifier for a terraform address.
|
|
5866
|
-
*
|
|
5867
|
-
* `huaweicloud_vpc_subnet.web` becomes `huaweicloud_vpc_subnet_web`, because a
|
|
5868
|
-
* `.` in a D2 key means "member of the block before it" — an unescaped one
|
|
5869
|
-
* would nest the subnet inside a node named `huaweicloud_vpc_subnet`, inventing
|
|
5870
|
-
* a container that does not exist.
|
|
5871
|
-
*
|
|
5872
|
-
* A collision is possible in principle (`a_b.c` and `a.b_c` both map to
|
|
5873
|
-
* `a_b_c`). It cannot occur inside one provider namespace, where the separator
|
|
5874
|
-
* between resource types and names is always the same `.`, but the caller
|
|
5875
|
-
* draws from a map keyed by address, so a collision would drop an edge rather
|
|
5876
|
-
* than misplace it.
|
|
5877
|
-
*
|
|
5878
|
-
* @param address - a `type.name` address.
|
|
5879
|
-
* @returns an identifier D2 accepts.
|
|
5880
|
-
*/
|
|
5881
|
-
function d2Id(address) {
|
|
5882
|
-
return address.replaceAll(".", "_");
|
|
5883
|
-
}
|
|
5884
|
-
/**
|
|
5885
6491
|
* The findings block, when there are findings.
|
|
5886
6492
|
*
|
|
5887
6493
|
* Written as a markdown block pinned below the diagram, so the problems sit
|
|
@@ -5995,11 +6601,11 @@ const CONFIG_EXTENSION = ".tf";
|
|
|
5995
6601
|
function registerDesignTool(registrar) {
|
|
5996
6602
|
registrar.registerTool("validate_design", {
|
|
5997
6603
|
title: "Validate the network design and draw it",
|
|
5998
|
-
description: "Check the
|
|
6604
|
+
description: "Check the network design this deployment declares (.tf: VPCs, subnets, security groups and rules, gateways, load balancers, compute and managed databases) and draw it. It runs `terraform validate` when the provider is installed — the authoritative check on attribute names, required arguments and references — then the checks terraform cannot do: subnet CIDRs overlapping, a subnet outside its VPC, a gateway_ip outside its subnet, and security-group rules open to 0.0.0.0/0 on administrative or database ports. Findings are REPORTED, not enforced: a design with findings still gets its diagram. Writes topology.svg and topology.d2 into the deployment and returns their absolute paths. No cloud credentials are needed and no resource is created. The drawing is a VIEW, not an inventory. Resources outside a network picture — alarm rules, log groups, backups, key pairs, parameter templates — come back counted under `omitted` by type and are not drawn; a configuration declaring only those gets a refusal naming them rather than an empty picture. Connections between VPCs (a peering, a VPCEP endpoint, a route) are labelled EDGES rather than boxes, listed under `connections` with `unresolved` when the far network is not declared here. A local module (`source = \"./...\"`) is part of the design and is read, drawn and hashed like the workspace files. A downloaded module is not — it is a dependency. Module paths come from terraform's own record, so a design written inside one is read after `terraform_init` and not before. With `existing` and no .tf at all it draws the account as it stands instead, and reports validation as skipped. See the `existing` parameter for what those have to carry.",
|
|
5999
6605
|
annotations: READ_ONLY_LOCAL,
|
|
6000
6606
|
inputSchema: z.object({
|
|
6001
6607
|
deployment: deploymentParam,
|
|
6002
|
-
existing: z.array(ExistingResourceSchema).optional().describe("Cloud resources that already exist and that this design reuses or works around, as reported by list_existing_resources. Pass only the ones the design is about — the whole account is usually the wrong picture.
|
|
6608
|
+
existing: z.array(ExistingResourceSchema).optional().describe("Cloud resources that already exist and that this design reuses or works around, as reported by list_existing_resources. Pass only the ones the design is about — the whole account is usually the wrong picture. Copy `id`, `type`, `provider`, `properties` and `name` verbatim from the inventory; do not translate its vocabulary into terraform type names, which produces names that do not exist. `properties` is what carries the relationships — with no .tf it is this tool's only input, and a resource without one is drawn as an isolated box. An existing resource the .tf references without declaring it (a subnet cut from a VPC that already exists) also needs `address`, the terraform address the reference resolves to. Passing `existing` with no .tf at all draws the account as it stands, and validation reports itself as skipped.")
|
|
6003
6609
|
})
|
|
6004
6610
|
}, guard(async (args) => handleValidateDesign(args.deployment, args.existing ?? [])));
|
|
6005
6611
|
}
|
|
@@ -6011,7 +6617,8 @@ function registerDesignTool(registrar) {
|
|
|
6011
6617
|
*/
|
|
6012
6618
|
async function handleValidateDesign(deployment, existing) {
|
|
6013
6619
|
const configFiles = await configurationFiles(deployment);
|
|
6014
|
-
if (configFiles.length === 0) return fail(`no ${CONFIG_EXTENSION} files in ${deployment}.
|
|
6620
|
+
if (configFiles.length === 0 && existing.length === 0) return fail(`no ${CONFIG_EXTENSION} files in ${deployment}, and no \`existing\` resources were passed. There is nothing to draw. Either write the network design — VPC, subnets, security groups — or, to picture an account as it already stands, call list_existing_resources first and pass what it returns as \`existing\`.`);
|
|
6621
|
+
if (configFiles.length === 0) return await handleInventoryOnly(deployment, existing);
|
|
6015
6622
|
const sources = [];
|
|
6016
6623
|
for (const file of configFiles) try {
|
|
6017
6624
|
sources.push({
|
|
@@ -6032,7 +6639,8 @@ async function handleValidateDesign(deployment, existing) {
|
|
|
6032
6639
|
const topology = deriveTopology(blocks, existing);
|
|
6033
6640
|
if (topology.nodes.length === 0) {
|
|
6034
6641
|
const types = topology.omitted.slice(0, 8).map((entry) => `${entry.type}${entry.count > 1 ? ` ×${entry.count}` : ""}`).join(", ");
|
|
6035
|
-
|
|
6642
|
+
const supplied = blocks.length + existing.length;
|
|
6643
|
+
return fail(`all ${supplied} resource(s) supplied are outside the network picture, so there is no topology to draw. They are: ${types}${topology.omitted.length > 8 ? ", and others" : ""}. The picture shows the network and what it carries: VPCs, subnets, security groups and their rules, gateways, load balancers, compute instances and managed databases.`);
|
|
6036
6644
|
}
|
|
6037
6645
|
const edges = edgesOf(blocks, topology);
|
|
6038
6646
|
let svg;
|
|
@@ -6198,6 +6806,89 @@ function parseValidateJson(stdout) {
|
|
|
6198
6806
|
diagnostics
|
|
6199
6807
|
};
|
|
6200
6808
|
}
|
|
6809
|
+
/**
|
|
6810
|
+
* Draw an account that already exists, from the inventory's own shape.
|
|
6811
|
+
*
|
|
6812
|
+
* ## Why this does not go through the design path
|
|
6813
|
+
*
|
|
6814
|
+
* A design is a configuration, and its picture is derived from resource blocks.
|
|
6815
|
+
* An account is a set of resources and the references between them, reported by
|
|
6816
|
+
* the inventory with the properties each service attaches. Those are different
|
|
6817
|
+
* inputs, and reading the second through the first would need a table mapping
|
|
6818
|
+
* every service's vocabulary onto the diagram's — the kind of table that grows
|
|
6819
|
+
* with every service and is wrong the first time one is missing.
|
|
6820
|
+
*
|
|
6821
|
+
* So this path asks the inventory what it saw: ids, types, names, properties.
|
|
6822
|
+
* Relationships come from ids appearing in properties, and containment from the
|
|
6823
|
+
* direction references flow. No service is named anywhere.
|
|
6824
|
+
*
|
|
6825
|
+
* @param deployment - the deployment workspace directory, used only for output.
|
|
6826
|
+
* @param existing - the resources the caller reported.
|
|
6827
|
+
* @returns the tool result.
|
|
6828
|
+
*/
|
|
6829
|
+
async function handleInventoryOnly(deployment, existing) {
|
|
6830
|
+
const withProperties = existing.filter((resource) => resource.properties !== void 0 && Object.keys(resource.properties).length > 0);
|
|
6831
|
+
if (withProperties.length === 0) return fail("none of the `existing` resources carried a `properties` object, so there are no relationships to derive — the diagram would be a list of unconnected boxes. Pass each resource's `properties` from list_existing_resources verbatim; that is where the ids that connect resources live.");
|
|
6832
|
+
const topology = deriveInventoryTopology(withProperties.map((resource) => ({
|
|
6833
|
+
id: resource.id,
|
|
6834
|
+
provider: resource.provider ?? "",
|
|
6835
|
+
type: resource.type,
|
|
6836
|
+
...resource.name === void 0 ? {} : { name: resource.name },
|
|
6837
|
+
...resource.region === void 0 ? {} : { region: resource.region },
|
|
6838
|
+
properties: resource.properties ?? {}
|
|
6839
|
+
})));
|
|
6840
|
+
let svg;
|
|
6841
|
+
let d2;
|
|
6842
|
+
try {
|
|
6843
|
+
const rendered = await renderInventoryTopology(topology);
|
|
6844
|
+
svg = rendered.svg;
|
|
6845
|
+
d2 = rendered.source;
|
|
6846
|
+
} catch (error) {
|
|
6847
|
+
return fail(`the topology could not be rendered: ${error instanceof Error ? error.message : String(error)}`);
|
|
6848
|
+
}
|
|
6849
|
+
try {
|
|
6850
|
+
await mkdir(deployment, { recursive: true });
|
|
6851
|
+
await writeFile(join(deployment, D2_FILE), d2, "utf8");
|
|
6852
|
+
await writeFile(join(deployment, TOPOLOGY_FILE), svg, "utf8");
|
|
6853
|
+
} catch (error) {
|
|
6854
|
+
return fail(`the diagram could not be written into ${deployment}: ${error instanceof Error ? error.message : String(error)}`);
|
|
6855
|
+
}
|
|
6856
|
+
const diagramPath = resolve(deployment, TOPOLOGY_FILE);
|
|
6857
|
+
const provided = existing.length - withProperties.length;
|
|
6858
|
+
return okJson({
|
|
6859
|
+
deployment,
|
|
6860
|
+
mode: "inventory",
|
|
6861
|
+
diagram: {
|
|
6862
|
+
svg: diagramPath,
|
|
6863
|
+
d2: resolve(deployment, D2_FILE),
|
|
6864
|
+
note: `Show the user the picture by writing this into your reply as a Markdown image: `
|
|
6865
|
+
},
|
|
6866
|
+
validation: {
|
|
6867
|
+
state: "skipped",
|
|
6868
|
+
detail: "There is no configuration to validate — this picture is of resources that already exist. Write a network .tf and call this tool again to have it checked."
|
|
6869
|
+
},
|
|
6870
|
+
resources: topology.nodes.map((node) => ({
|
|
6871
|
+
id: node.id,
|
|
6872
|
+
type: `${node.provider}/${node.type}`,
|
|
6873
|
+
label: node.label,
|
|
6874
|
+
parent: node.parent ?? null
|
|
6875
|
+
})),
|
|
6876
|
+
edges: topology.edges.map((edge) => ({
|
|
6877
|
+
from: edge.from,
|
|
6878
|
+
to: edge.to,
|
|
6879
|
+
attribute: edge.attribute,
|
|
6880
|
+
contains: edge.contains
|
|
6881
|
+
})),
|
|
6882
|
+
summary: {
|
|
6883
|
+
drawn: topology.nodes.length,
|
|
6884
|
+
edges: topology.edges.length,
|
|
6885
|
+
nested: topology.nodes.filter((node) => node.parent !== void 0).length,
|
|
6886
|
+
...provided === 0 ? {} : { without_properties: provided },
|
|
6887
|
+
validation: "skipped"
|
|
6888
|
+
},
|
|
6889
|
+
next: "Show the diagram and name what it shows: the VPCs, what sits inside them, and the connections between resources. The nesting comes from references between ids, so a resource at the root is one nothing in the account names as its container." + (provided === 0 ? "" : ` ${provided} resource(s) carried no properties and are not in the picture — say so rather than presenting the diagram as the whole account.`)
|
|
6890
|
+
});
|
|
6891
|
+
}
|
|
6201
6892
|
|
|
6202
6893
|
//#endregion
|
|
6203
6894
|
//#region src/tools/openapi.ts
|
|
@@ -6243,7 +6934,7 @@ function registerOpenApiTools(registrar) {
|
|
|
6243
6934
|
}, guard(async (args) => handleApiExplorer(args.productshort, args.api_name, args.compact, args.regions, args.endpoints, args.limit, args.offset)));
|
|
6244
6935
|
registrar.registerTool("openapi_request", {
|
|
6245
6936
|
title: "Call HuaweiCloud API",
|
|
6246
|
-
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.
|
|
6937
|
+
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. This is the route for READING a service the other tools do not cover; creating or destroying resources belongs to terraform_apply and terraform_destroy, which carry the cost and design gates this call skips. GET is safe. POST/PUT/DELETE execute, and the response carries a warning naming the consequence — pass that warning to the user. Pass `fields` with JSONPath expressions rather than reading a large body into the conversation: one ECS list can be hundreds of KB, and the few values you need come back as {path, value} pairs. Both plain dot paths and full JSONPath work. A body over 4 MB is truncated and says so.",
|
|
6247
6938
|
annotations: CLOUD_MUTABLE_API,
|
|
6248
6939
|
inputSchema: z.object({
|
|
6249
6940
|
method: z.enum([
|
|
@@ -6836,6 +7527,90 @@ async function queryBalanceSummary() {
|
|
|
6836
7527
|
};
|
|
6837
7528
|
}
|
|
6838
7529
|
|
|
7530
|
+
//#endregion
|
|
7531
|
+
//#region src/inventory-subnets.ts
|
|
7532
|
+
/** How many pages a region's subnet list may take before giving up. */
|
|
7533
|
+
const MAX_PAGES = 10;
|
|
7534
|
+
/**
|
|
7535
|
+
* Every subnet the account has in one region.
|
|
7536
|
+
*
|
|
7537
|
+
* Best-effort by contract: a caller completes an inventory, and a region whose
|
|
7538
|
+
* subnets could not be read is worse off without its other resources, not
|
|
7539
|
+
* better. So a failure is reported rather than thrown, and the caller decides
|
|
7540
|
+
* what to say about it.
|
|
7541
|
+
*
|
|
7542
|
+
* @param region - the region to list.
|
|
7543
|
+
* @returns the subnets, or the reason they could not be read.
|
|
7544
|
+
*/
|
|
7545
|
+
async function subnetsInRegion(region) {
|
|
7546
|
+
let projectId;
|
|
7547
|
+
try {
|
|
7548
|
+
const projects = await projectMap(await loadCredentials());
|
|
7549
|
+
projectId = projectIn(projects, region);
|
|
7550
|
+
} catch (error) {
|
|
7551
|
+
return {
|
|
7552
|
+
subnets: [],
|
|
7553
|
+
failure: error instanceof Error ? error.message : String(error)
|
|
7554
|
+
};
|
|
7555
|
+
}
|
|
7556
|
+
const subnets = [];
|
|
7557
|
+
let marker;
|
|
7558
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
7559
|
+
const url = new URL(`https://vpc.${region}.myhuaweicloud.com/v1/${projectId}/subnets`);
|
|
7560
|
+
if (marker !== void 0) url.searchParams.set("marker", marker);
|
|
7561
|
+
let response;
|
|
7562
|
+
try {
|
|
7563
|
+
response = await signedHttp("GET", url, "");
|
|
7564
|
+
} catch (error) {
|
|
7565
|
+
return {
|
|
7566
|
+
subnets,
|
|
7567
|
+
failure: `the subnet list for ${region} could not be read: ${error instanceof Error ? error.message : String(error)}`
|
|
7568
|
+
};
|
|
7569
|
+
}
|
|
7570
|
+
if (response.status !== 200) return {
|
|
7571
|
+
subnets,
|
|
7572
|
+
failure: `the subnet list for ${region} answered HTTP ${response.status}: ${response.body.slice(0, 200)}`
|
|
7573
|
+
};
|
|
7574
|
+
const parsed = JSON.parse(response.body);
|
|
7575
|
+
for (const subnet of parsed.subnets ?? []) {
|
|
7576
|
+
const mapped = asInventorySubnet(subnet, region);
|
|
7577
|
+
if (mapped !== void 0) subnets.push(mapped);
|
|
7578
|
+
}
|
|
7579
|
+
marker = parsed.page_info?.next_marker;
|
|
7580
|
+
if (marker === void 0 || marker === "") break;
|
|
7581
|
+
}
|
|
7582
|
+
return { subnets };
|
|
7583
|
+
}
|
|
7584
|
+
/**
|
|
7585
|
+
* One VPC API subnet as an inventory resource.
|
|
7586
|
+
*
|
|
7587
|
+
* `properties.vpc_id` is what places it: `locationRank` reads the attribute's
|
|
7588
|
+
* noun, so a subnet with this field lands inside its VPC by the same rule that
|
|
7589
|
+
* puts anything else where it lives. The CIDR and gateway go along because a
|
|
7590
|
+
* reader comparing subnets needs to see the ranges.
|
|
7591
|
+
*
|
|
7592
|
+
* @param subnet - one record from the API.
|
|
7593
|
+
* @param region - the region it came from.
|
|
7594
|
+
* @returns the resource, or `undefined` when it is missing the id every node
|
|
7595
|
+
* needs.
|
|
7596
|
+
*/
|
|
7597
|
+
function asInventorySubnet(subnet, region) {
|
|
7598
|
+
if (typeof subnet.id !== "string" || subnet.id === "") return void 0;
|
|
7599
|
+
const properties = {};
|
|
7600
|
+
if (typeof subnet.vpc_id === "string") properties["vpc_id"] = subnet.vpc_id;
|
|
7601
|
+
if (typeof subnet.cidr === "string") properties["cidr"] = subnet.cidr;
|
|
7602
|
+
if (typeof subnet.gateway_ip === "string") properties["gateway_ip"] = subnet.gateway_ip;
|
|
7603
|
+
if (typeof subnet.status === "string") properties["status"] = subnet.status;
|
|
7604
|
+
return {
|
|
7605
|
+
id: subnet.id,
|
|
7606
|
+
name: typeof subnet.name === "string" ? subnet.name : subnet.id.slice(0, 8),
|
|
7607
|
+
provider: "vpc",
|
|
7608
|
+
type: "subnets",
|
|
7609
|
+
region,
|
|
7610
|
+
properties
|
|
7611
|
+
};
|
|
7612
|
+
}
|
|
7613
|
+
|
|
6839
7614
|
//#endregion
|
|
6840
7615
|
//#region src/tools/existing_resources.ts
|
|
6841
7616
|
/**
|
|
@@ -6867,7 +7642,7 @@ async function queryBalanceSummary() {
|
|
|
6867
7642
|
function registerExistingResourcesTool(registrar) {
|
|
6868
7643
|
registrar.registerTool("list_existing_resources", {
|
|
6869
7644
|
title: "List existing cloud resources",
|
|
6870
|
-
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).
|
|
7645
|
+
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). What the account already has decides what a design can reuse and what it must not collide with, and nothing in a configuration can tell you that. 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.",
|
|
6871
7646
|
annotations: READ_ONLY_CLOUD,
|
|
6872
7647
|
inputSchema: z.object({
|
|
6873
7648
|
service: z.string().optional().describe("Filter by RMS provider in detail mode: \"vpc\"|\"ecs\"|\"rds\"|\"elb\"|..."),
|
|
@@ -6999,13 +7774,24 @@ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker,
|
|
|
6999
7774
|
tags: r.tags,
|
|
7000
7775
|
properties: r.properties
|
|
7001
7776
|
}));
|
|
7777
|
+
const subnets = { subnets: [] };
|
|
7778
|
+
if (serviceFilter === "vpc") {
|
|
7779
|
+
const regions = regionFilter !== void 0 ? [regionFilter] : [...new Set(collected.filter((r) => r.type === "vpcs").map((r) => r.region_id))];
|
|
7780
|
+
const failures = [];
|
|
7781
|
+
for (const listed of await listSubnets(regions)) {
|
|
7782
|
+
subnets.subnets.push(...listed.subnets);
|
|
7783
|
+
if (listed.failure !== void 0) failures.push(listed.failure);
|
|
7784
|
+
}
|
|
7785
|
+
if (failures.length > 0) process.stderr.write(`list_existing_resources: ${failures.join("; ")}\n`);
|
|
7786
|
+
}
|
|
7002
7787
|
const hitAutoPageLimit = autoAdvance && pagesFetched >= MAX_AUTO_PAGES && !exhausted;
|
|
7003
7788
|
return okJson({
|
|
7004
7789
|
mode: "detail",
|
|
7005
|
-
resources: normalized,
|
|
7006
|
-
count: normalized.length,
|
|
7790
|
+
resources: [...normalized, ...subnets.subnets],
|
|
7791
|
+
count: normalized.length + subnets.subnets.length,
|
|
7007
7792
|
region: regionFilter ?? "(all regions)",
|
|
7008
7793
|
...serviceFilter ? { service_filter: serviceFilter } : {},
|
|
7794
|
+
...subnets.subnets.length > 0 ? { subnet_note: `${subnets.subnets.length} subnet(s) were added to this page from the VPC API; RMS does not report them. They are listed with provider "vpc" and type "subnets", the same shape as the rest, and carry \`vpc_id\` in properties, which is what places them inside their VPC.` } : {},
|
|
7009
7795
|
...nextMarker && !exhausted ? {
|
|
7010
7796
|
next_marker: nextMarker,
|
|
7011
7797
|
has_more: true,
|
|
@@ -7015,6 +7801,21 @@ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker,
|
|
|
7015
7801
|
balance_summary: balanceSummary
|
|
7016
7802
|
});
|
|
7017
7803
|
}
|
|
7804
|
+
/**
|
|
7805
|
+
* Read the subnets of several regions, sequentially.
|
|
7806
|
+
*
|
|
7807
|
+
* Sequential rather than concurrent for the same reason the catalogue lookup
|
|
7808
|
+
* is: these are a handful of calls against the same signed client, and flooding
|
|
7809
|
+
* one host buys nothing a short wait does not.
|
|
7810
|
+
*
|
|
7811
|
+
* @param regions - the regions to list.
|
|
7812
|
+
* @returns one result per region, each carrying its own failure if it has one.
|
|
7813
|
+
*/
|
|
7814
|
+
async function listSubnets(regions) {
|
|
7815
|
+
const results = [];
|
|
7816
|
+
for (const region of regions) results.push(await subnetsInRegion(region));
|
|
7817
|
+
return results;
|
|
7818
|
+
}
|
|
7018
7819
|
|
|
7019
7820
|
//#endregion
|
|
7020
7821
|
//#region src/tools/provider_schema.ts
|
|
@@ -7037,7 +7838,7 @@ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker,
|
|
|
7037
7838
|
function registerProviderSchemaTool(registrar) {
|
|
7038
7839
|
registrar.registerTool("provider_schema", {
|
|
7039
7840
|
title: "Extract provider schema",
|
|
7040
|
-
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).
|
|
7841
|
+
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). The schema is read from what terraform installed, so a provider that is not installed yet answers nothing — call terraform_init first.",
|
|
7041
7842
|
annotations: READ_ONLY_LOCAL,
|
|
7042
7843
|
inputSchema: z.object({
|
|
7043
7844
|
deployment: deploymentParam,
|
|
@@ -7607,17 +8408,16 @@ const envParam = z.array(z.string()).optional().describe("Extra env vars for the
|
|
|
7607
8408
|
function registerInstall(registrar) {
|
|
7608
8409
|
registrar.registerTool("terraform_install", {
|
|
7609
8410
|
title: "Install terraform",
|
|
7610
|
-
description: "Ensure a terraform binary is available. Only installs the binary — provider plugins are pulled by terraform_init.
|
|
8411
|
+
description: "Ensure a terraform binary is available. Only installs the binary — provider plugins are pulled by terraform_init. It looks, in order, at: the `terraform_path` you pass, PATH, the path a previous install recorded, and the host's own cache; failing all of those it downloads from `binary_mirrors`. It takes no deployment: the binary is a machine-level tool every deployment shares, and installing it does not depend on any workspace.",
|
|
7611
8412
|
annotations: CLOUD_WRITE,
|
|
7612
8413
|
inputSchema: z.object({
|
|
7613
|
-
deployment: deploymentParam.describe("Used only as download fallback when HOME is not writable."),
|
|
7614
8414
|
terraform_path: z.string().optional().describe("Explicit path to a terraform binary."),
|
|
7615
8415
|
binary_mirrors: z.array(z.string()).optional().describe("Binary download mirror URLs, tried in order."),
|
|
7616
8416
|
env: envParam
|
|
7617
8417
|
})
|
|
7618
|
-
}, guard(async (args) => handleInstall(args.
|
|
8418
|
+
}, guard(async (args) => handleInstall(args.terraform_path, args.binary_mirrors, args.env ?? [])));
|
|
7619
8419
|
}
|
|
7620
|
-
async function handleInstall(
|
|
8420
|
+
async function handleInstall(terraformPath, binaryMirrors, extraEnv = []) {
|
|
7621
8421
|
if (terraformPath) {
|
|
7622
8422
|
const { stat: stat$1 } = await import("node:fs/promises");
|
|
7623
8423
|
try {
|
|
@@ -7633,11 +8433,11 @@ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv
|
|
|
7633
8433
|
source: "parameter",
|
|
7634
8434
|
cached: true,
|
|
7635
8435
|
recorded,
|
|
7636
|
-
...recorded ? {} : { warning: "the path could not be recorded, so later tool calls will look for terraform on PATH
|
|
8436
|
+
...recorded ? {} : { warning: "the path could not be recorded, so later tool calls will look for terraform on PATH and in the host's caches instead" }
|
|
7637
8437
|
});
|
|
7638
8438
|
}
|
|
7639
8439
|
try {
|
|
7640
|
-
const { binary } = await resolveTerraformEnv(
|
|
8440
|
+
const { binary } = await resolveTerraformEnv(void 0, extraEnv);
|
|
7641
8441
|
const ver = await getTerraformVersion(binary);
|
|
7642
8442
|
return okJson({
|
|
7643
8443
|
terraform: ver,
|
|
@@ -7648,7 +8448,7 @@ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv
|
|
|
7648
8448
|
} catch {}
|
|
7649
8449
|
const mirrors = binaryMirrors ?? DEFAULT_BINARY_MIRRORS;
|
|
7650
8450
|
const { version, arch, platform } = detectPlatform();
|
|
7651
|
-
const destDir = await resolveDownloadDir(
|
|
8451
|
+
const destDir = await resolveDownloadDir();
|
|
7652
8452
|
const binPath = join(destDir, `terraform${version ? "-" + version : ""}`);
|
|
7653
8453
|
return runOperation(async () => {
|
|
7654
8454
|
const failures = [];
|
|
@@ -7689,7 +8489,7 @@ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv
|
|
|
7689
8489
|
function registerInit(registrar) {
|
|
7690
8490
|
registrar.registerTool("terraform_init", {
|
|
7691
8491
|
title: "Terraform init",
|
|
7692
|
-
description: "Run `terraform init
|
|
8492
|
+
description: "Run `terraform init` to install the provider plugins. It writes <deployment>/.terraformrc with the provider mirror configuration unless one is already there or `provider_mirrors` is empty, points TF_PLUGIN_CACHE_DIR at the shared provider cache when that directory is writable, and injects the stored credentials into the subprocess environment so the provider can authenticate.",
|
|
7693
8493
|
annotations: CLOUD_WRITE,
|
|
7694
8494
|
inputSchema: z.object({
|
|
7695
8495
|
deployment: deploymentParam,
|
|
@@ -7727,11 +8527,11 @@ async function handleInit(deployment, providerMirrors, extraEnv = []) {
|
|
|
7727
8527
|
function registerPlan(registrar) {
|
|
7728
8528
|
registrar.registerTool("terraform_plan", {
|
|
7729
8529
|
title: "Terraform plan",
|
|
7730
|
-
description: "Run `terraform plan` and save it to plan.tfplan. Returns the CHANGES, not the raw plan document: one entry per resource with its action (create / update / replace / destroy), the attribute names an update touches, and what forces a replacement. Also returns the security-group rules the change would create, so they can be reviewed without opening the plan. terraform_apply runs this saved plan, and records the configuration it was computed from — so any .tf edit after planning requires another call to this tool. With destroy: true it previews the DESTRUCTION instead: the same change list, every entry delete, written to a separate file so the apply plan is untouched.
|
|
8530
|
+
description: "Run `terraform plan` and save it to plan.tfplan. Returns the CHANGES, not the raw plan document: one entry per resource with its action (create / update / replace / destroy), the attribute names an update touches, and what forces a replacement. Also returns the security-group rules the change would create, so they can be reviewed without opening the plan. terraform_apply runs this saved plan, and records the configuration it was computed from — so any .tf edit after planning requires another call to this tool. With destroy: true it previews the DESTRUCTION instead: the same change list, every entry delete, written to a separate file so the apply plan is untouched. The `target` list given here is baked into the saved teardown — terraform_destroy applies THIS saved plan and refuses a target list that differs from it.",
|
|
7731
8531
|
annotations: READ_ONLY_CLOUD,
|
|
7732
8532
|
inputSchema: z.object({
|
|
7733
8533
|
deployment: deploymentParam,
|
|
7734
|
-
destroy: z.boolean().optional().describe("Preview what terraform_destroy would remove instead of what an apply would change.
|
|
8534
|
+
destroy: z.boolean().optional().describe("Preview what terraform_destroy would remove instead of what an apply would change. The plan names every resource that goes away, and terraform_destroy later applies this same saved plan. Writes a separate destroy.plan.tfplan and does not touch the apply plan."),
|
|
7735
8535
|
target: z.array(z.string()).optional().describe("With destroy: true only — the resource addresses to preview removing, e.g. [\"huaweicloud_vpc.main\"]. Omit to preview removing everything the deployment manages. terraform_destroy must be given the same list."),
|
|
7736
8536
|
env: envParam
|
|
7737
8537
|
})
|
|
@@ -7884,11 +8684,11 @@ function registerDestroy(registrar) {
|
|
|
7884
8684
|
"terraform_destroy",
|
|
7885
8685
|
{
|
|
7886
8686
|
title: "Terraform destroy",
|
|
7887
|
-
description: "Run `terraform apply` on the destruction `terraform_plan({ destroy: true })` saved. Permanently deletes cloud resources managed by this deployment — irreversible.
|
|
8687
|
+
description: "Run `terraform apply` on the destruction `terraform_plan({ destroy: true })` saved. Permanently deletes cloud resources managed by this deployment — irreversible. Refuses to run without a saved teardown covering exactly these targets: a destroy that computed its own plan would remove a set of resources nobody previewed. Also refuses when the state is empty (nothing to destroy) or when the .tf files hold plaintext credentials (the same scan init and apply run). 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. `target` must match the list terraform_plan was given with destroy: true, or the gate refuses: the saved teardown is the approval record, and a different target list is a different destruction than the one previewed.",
|
|
7888
8688
|
annotations: CLOUD_DESTRUCTIVE,
|
|
7889
8689
|
inputSchema: z.object({
|
|
7890
8690
|
deployment: deploymentParam,
|
|
7891
|
-
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).
|
|
8691
|
+
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). Must equal the target list given to terraform_plan with destroy: true. Use this to spare imported resources: destroy only newly-created resources, leaving imported ones in state."),
|
|
7892
8692
|
env: envParam
|
|
7893
8693
|
})
|
|
7894
8694
|
},
|
|
@@ -7934,7 +8734,7 @@ function registerDestroy(registrar) {
|
|
|
7934
8734
|
function registerRefresh(registrar) {
|
|
7935
8735
|
registrar.registerTool("terraform_refresh", {
|
|
7936
8736
|
title: "Terraform refresh",
|
|
7937
|
-
description: "
|
|
8737
|
+
description: "Reconcile tfstate with the cloud: runs `terraform apply -refresh-only`, which records what each managed resource looks like now without changing any of them. Use it when something changed outside terraform — edited in the console, deleted by hand — then call terraform_plan to see the difference.",
|
|
7938
8738
|
annotations: READ_ONLY_CLOUD,
|
|
7939
8739
|
inputSchema: z.object({
|
|
7940
8740
|
deployment: deploymentParam,
|
|
@@ -8077,7 +8877,7 @@ function stateInventory(stateJson) {
|
|
|
8077
8877
|
function registerImport(registrar) {
|
|
8078
8878
|
registrar.registerTool("terraform_import", {
|
|
8079
8879
|
title: "Terraform import",
|
|
8080
|
-
description: "Run `terraform import` to bring an existing cloud resource into tfstate without creating it.
|
|
8880
|
+
description: "Run `terraform import` to bring an existing cloud resource into tfstate without creating it. 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>). IMPORT DOES NOT RECONCILE. It records what the CLOUD holds; the resource block in the .tf may say something else, and nothing compares them here. A plan run afterwards shows that difference as a diff — applying it would CHANGE a resource that was meant to be left alone, possibly by replacing it.",
|
|
8081
8881
|
annotations: READ_ONLY_CLOUD,
|
|
8082
8882
|
inputSchema: z.object({
|
|
8083
8883
|
deployment: deploymentParam,
|
|
@@ -8162,20 +8962,66 @@ function detectPlatform() {
|
|
|
8162
8962
|
platform
|
|
8163
8963
|
};
|
|
8164
8964
|
}
|
|
8165
|
-
/**
|
|
8166
|
-
|
|
8965
|
+
/**
|
|
8966
|
+
* Where a downloaded terraform binary goes.
|
|
8967
|
+
*
|
|
8968
|
+
* The host cache first, because one binary serves every deployment: a machine
|
|
8969
|
+
* runs `terraform_init` on several workspaces and downloading per workspace
|
|
8970
|
+
* would be a copy each.
|
|
8971
|
+
*
|
|
8972
|
+
* ## Why the fallback is the temp directory, not a deployment
|
|
8973
|
+
*
|
|
8974
|
+
* The cache lives under the host's data directory, and that is unwritable in
|
|
8975
|
+
* some environments — a container with a read-only home, a sandboxed runner. A
|
|
8976
|
+
* download still has to land somewhere.
|
|
8977
|
+
*
|
|
8978
|
+
* A deployment directory is the wrong place for it, in two ways. A binary is not
|
|
8979
|
+
* a deployment asset: putting it inside one makes it invisible to every other
|
|
8980
|
+
* deployment, so each workspace downloads its own copy. And it puts an
|
|
8981
|
+
* executable inside a directory the user treats as their own content, which is
|
|
8982
|
+
* not where a tool should write things it will not clean up.
|
|
8983
|
+
*
|
|
8984
|
+
* The temp directory is the standard answer to "no persistent location
|
|
8985
|
+
* available": shared by every deployment in this process, and rebuilt on the
|
|
8986
|
+
* next run if the system clears it. A cache that can be rebuilt is the right
|
|
8987
|
+
* loss here; a polluted workspace is not.
|
|
8988
|
+
*
|
|
8989
|
+
* @returns the directory to download into.
|
|
8990
|
+
* @throws when neither location exists, naming what to fix.
|
|
8991
|
+
*/
|
|
8992
|
+
async function resolveDownloadDir() {
|
|
8167
8993
|
const globalDir = terraformBinDir();
|
|
8994
|
+
const failure = await writableDirectory(globalDir);
|
|
8995
|
+
if (failure === void 0) return globalDir;
|
|
8996
|
+
const temporary = join(tmpdir(), "aishell-terraform");
|
|
8997
|
+
const temporaryFailure = await writableDirectory(temporary);
|
|
8998
|
+
if (temporaryFailure === void 0) {
|
|
8999
|
+
process.stderr.write(`terraform_install: the host cache at ${globalDir} is not writable (${failure}); using ${temporary}, which will not survive a reboot.\n`);
|
|
9000
|
+
return temporary;
|
|
9001
|
+
}
|
|
9002
|
+
throw new Error(`terraform has nowhere to be installed: the host cache at ${globalDir} is not writable (${failure}), and neither is ${temporary} (${temporaryFailure}). Grant write access to one of them, or install terraform yourself and pass \`terraform_path\`.`);
|
|
9003
|
+
}
|
|
9004
|
+
/**
|
|
9005
|
+
* Create a directory and confirm it accepts a write.
|
|
9006
|
+
*
|
|
9007
|
+
* A directory that exists is not the same as one this process can write into:
|
|
9008
|
+
* a root-owned cache is present and read-only. The probe is a real file rather
|
|
9009
|
+
* than an access check, because what matters is whether a download will
|
|
9010
|
+
* succeed, not whether the mode bits look permissive.
|
|
9011
|
+
*
|
|
9012
|
+
* @param dir - the directory to test, created when absent.
|
|
9013
|
+
* @returns the reason it cannot be used, or `undefined` when it can.
|
|
9014
|
+
*/
|
|
9015
|
+
async function writableDirectory(dir) {
|
|
8168
9016
|
try {
|
|
8169
|
-
await mkdir(
|
|
8170
|
-
const
|
|
8171
|
-
await writeFile(
|
|
9017
|
+
await mkdir(dir, { recursive: true });
|
|
9018
|
+
const probe = join(dir, ".write-test");
|
|
9019
|
+
await writeFile(probe, "");
|
|
8172
9020
|
const { unlink } = await import("node:fs/promises");
|
|
8173
|
-
await unlink(
|
|
8174
|
-
return
|
|
8175
|
-
} catch {
|
|
8176
|
-
|
|
8177
|
-
await mkdir(depDir, { recursive: true });
|
|
8178
|
-
return depDir;
|
|
9021
|
+
await unlink(probe);
|
|
9022
|
+
return void 0;
|
|
9023
|
+
} catch (error) {
|
|
9024
|
+
return error instanceof Error ? error.message : String(error);
|
|
8179
9025
|
}
|
|
8180
9026
|
}
|
|
8181
9027
|
function downloadError(kind, message) {
|
|
@@ -8475,98 +9321,269 @@ function registerPermissionPolicyContext(ctx, current$1) {
|
|
|
8475
9321
|
/** Name this contribution registers under; unique across the assembled prompt. */
|
|
8476
9322
|
const WORKFLOW_SECTION_NAME = "aishell:deploy-workflow";
|
|
8477
9323
|
/**
|
|
8478
|
-
*
|
|
9324
|
+
* A tool name as the model sees it.
|
|
8479
9325
|
*
|
|
8480
|
-
*
|
|
8481
|
-
*
|
|
8482
|
-
|
|
8483
|
-
|
|
9326
|
+
* @param name - the tool's own name.
|
|
9327
|
+
* @returns the registered name.
|
|
9328
|
+
*/
|
|
9329
|
+
function tool(name$1) {
|
|
9330
|
+
return `aishell__${name$1}`;
|
|
9331
|
+
}
|
|
9332
|
+
/**
|
|
9333
|
+
* The opening paragraph, which needs no particular tool.
|
|
8484
9334
|
*
|
|
8485
|
-
*
|
|
8486
|
-
*
|
|
9335
|
+
* It names the reason to prefer these tools over shell: the gates. That is true
|
|
9336
|
+
* as long as any of them exists.
|
|
8487
9337
|
*/
|
|
8488
|
-
const
|
|
8489
|
-
|
|
8490
|
-
|
|
8491
|
-
|
|
8492
|
-
|
|
8493
|
-
|
|
8494
|
-
|
|
8495
|
-
|
|
8496
|
-
|
|
8497
|
-
|
|
8498
|
-
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
9338
|
+
const PREAMBLE = `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.`;
|
|
9339
|
+
/**
|
|
9340
|
+
* The deployment flow, in the order a deployment is built.
|
|
9341
|
+
*
|
|
9342
|
+
* Each step names the tools it is about. A step whose tools are absent is
|
|
9343
|
+
* dropped and the rest renumber, which is why the text carries `%n` rather than
|
|
9344
|
+
* a number.
|
|
9345
|
+
*/
|
|
9346
|
+
const FLOW = [
|
|
9347
|
+
{
|
|
9348
|
+
requires: ["auth"],
|
|
9349
|
+
text: `%n. ${tool("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.`
|
|
9350
|
+
},
|
|
9351
|
+
{
|
|
9352
|
+
requires: ["list_existing_resources"],
|
|
9353
|
+
text: `%n. ${tool("list_existing_resources")} — what the account already has. This is the first question, not the fifth: a design for an account that already runs a VPC is mostly "what can be reused and what must not collide", and nothing in the .tf can tell you that. Drill into the services the user's request is about (\`service: "vpc"\`, then \`"ecs"\` and so on); the summary alone is counts. On \`service: "vpc"\` the answer also carries the SUBNETS, read from the VPC API because RMS does not report them — pass those on like any other resource.`
|
|
9354
|
+
},
|
|
9355
|
+
{
|
|
9356
|
+
requires: ["create_deployment", "validate_design"],
|
|
9357
|
+
text: ` ${tool("create_deployment")} — create or reuse the deployment workspace. If the user only wants to SEE what is deployed, skip this and pass the inventory straight to ${tool("validate_design")}, which draws the account as it stands.`
|
|
9358
|
+
},
|
|
9359
|
+
{
|
|
9360
|
+
requires: ["terraform_install"],
|
|
9361
|
+
text: `%n. ${tool("terraform_install")} — ensure a terraform binary is available: \`terraform_path\` if the user has one, else PATH, else the host cache, else a download from \`binary_mirrors\`. Idempotent, so calling it when one is already present costs nothing — call it before \`terraform_init\`, not after it fails with "terraform not found".`
|
|
9362
|
+
},
|
|
9363
|
+
{
|
|
9364
|
+
requires: ["terraform_init", "validate_design"],
|
|
9365
|
+
text: ` ${tool("terraform_init")} — install the provider. This comes BEFORE the design check, not after: \`terraform validate\` needs the provider to have an opinion about a configuration, and without it \`validate_design\` reports "not validated" — a design nobody checked against the provider schema. The gate here also scans for plaintext credentials and refuses if it finds any.`
|
|
9366
|
+
},
|
|
9367
|
+
{
|
|
9368
|
+
requires: ["apiexplorer"],
|
|
9369
|
+
text: ` ${tool("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).`
|
|
9370
|
+
},
|
|
9371
|
+
{
|
|
9372
|
+
requires: ["terraform_examples_export"],
|
|
9373
|
+
text: ` ${tool("terraform_examples_export")} — write \`.tf\` examples to a directory. That directory is a reference target, not the deployment workspace.`
|
|
9374
|
+
},
|
|
9375
|
+
{
|
|
9376
|
+
requires: ["validate_design"],
|
|
9377
|
+
text: `%n. Write the network \`.tf\`: the VPC, its subnets, the security groups and their rules, and any gateway or load balancer. This stage needs no flavour, no image and no resource id — the network design is what decides those, not the other way round — so it needs no cloud credentials either.
|
|
8502
9378
|
Write the provider block with the region as a LITERAL: \`provider "huaweicloud" { region = "cn-north-4" }\`. Nothing else carries it. There is no plugin-wide default region, so a provider block without one is a configuration terraform refuses, and a region given as a variable is one the price inquiry cannot read. A deployment may declare several provider blocks with different regions and point resources at each with \`provider = huaweicloud.<alias>\`; the price inquiry prices each resource in its own region.
|
|
8503
|
-
|
|
9379
|
+
${tool("validate_design")} — check that design and draw it. It runs \`terraform validate\` when the provider is installed, then reports what terraform cannot: overlapping subnet CIDRs, a subnet outside its VPC, a gateway_ip outside its subnet, and rules open to 0.0.0.0/0 on administrative or database ports. It writes \`topology.svg\` beside the configuration and returns its absolute path.
|
|
8504
9380
|
The drawing is a VIEW, not an inventory. It shows the network and what it carries; a configuration also declares alarm rules, log groups, backups and key pairs, and those come back counted under \`omitted\` and are not drawn. If \`omitted\` is non-empty, say so — do not let the picture read as the whole file. Connections between VPCs (a peering, a VPCEP endpoint, a route) are drawn as LABELLED EDGES rather than boxes, and listed under \`connections\`; an entry with \`unresolved\` means the far network is not declared here, which is normal for an endpoint service published by another account.
|
|
8505
|
-
Pass the resources from
|
|
9381
|
+
Pass the resources from the inventory that this design is about as \`existing\`, so the picture shows what is already deployed (dashed) next to what would be created. Two things depend on it. An existing subnet is what a new subnet can COLLIDE with, and that collision is invisible to a check that only reads the .tf. And a .tf that reuses a VPC it does not declare (\`vpc_id = huaweicloud_vpc.prod.id\` with no \`huaweicloud_vpc.prod\` block) needs \`address: "huaweicloud_vpc.prod"\` on that existing resource, or the subnet is drawn at the root as if it created a new VPC.
|
|
8506
9382
|
★ Show the diagram and the findings, and get explicit agreement before going further. Put the picture in your reply as \`\`. If the user asks for changes, edit the \`.tf\`, call validate_design again, and show the new picture. Do not start any later step before they accept.
|
|
8507
|
-
★ Opening SSH to 0.0.0.0/0 is a risk. The tool reports it; still raise it in your own words and ask the user to restrict the source range. A finding is information, not permission
|
|
8508
|
-
|
|
8509
|
-
|
|
8510
|
-
|
|
8511
|
-
|
|
8512
|
-
|
|
8513
|
-
|
|
8514
|
-
|
|
8515
|
-
|
|
8516
|
-
|
|
8517
|
-
|
|
8518
|
-
|
|
8519
|
-
|
|
8520
|
-
|
|
8521
|
-
|
|
8522
|
-
|
|
8523
|
-
|
|
8524
|
-
|
|
8525
|
-
|
|
8526
|
-
|
|
8527
|
-
|
|
8528
|
-
|
|
8529
|
-
|
|
8530
|
-
|
|
8531
|
-
|
|
8532
|
-
|
|
8533
|
-
|
|
8534
|
-
|
|
8535
|
-
|
|
8536
|
-
|
|
8537
|
-
|
|
8538
|
-
|
|
8539
|
-
|
|
8540
|
-
|
|
8541
|
-
|
|
9383
|
+
★ Opening SSH to 0.0.0.0/0 is a risk. The tool reports it; still raise it in your own words and ask the user to restrict the source range. A finding is information, not permission.`
|
|
9384
|
+
},
|
|
9385
|
+
{
|
|
9386
|
+
requires: ["list_existing_resources"],
|
|
9387
|
+
text: `%n. Report the balance summary from the inventory: balance and vouchers.`
|
|
9388
|
+
},
|
|
9389
|
+
{
|
|
9390
|
+
requires: [
|
|
9391
|
+
"terraform_import",
|
|
9392
|
+
"terraform_plan",
|
|
9393
|
+
"lookup_specs"
|
|
9394
|
+
],
|
|
9395
|
+
text: `%n. Decide per component: reuse or create.
|
|
9396
|
+
- Reuse: the spec and charging are fixed by the existing resource. Write the resource block, then ${tool("terraform_import")} to bring it into state. This needs the provider installed.
|
|
9397
|
+
★ An import does NOT check that the block you wrote matches the resource that exists — it records what the cloud holds. Call ${tool("terraform_plan")} straight after each import and show the user the diff. A non-empty diff means applying would CHANGE a resource they asked you to leave alone, possibly by replacing it. Fix the block until the plan shows no change, or get explicit agreement that the change is wanted.
|
|
9398
|
+
- Create: ${tool("lookup_specs")} takes \`region\` and \`availability_zone\` and lists the flavours and images that region actually sells there, with each flavour's vCPUs, memory and disk and each image's OS and minimums. Both are required: a flavour exists per zone in a region, and a catalogue listed for one region says nothing about another. Pass the region from the provider block. Call it BEFORE writing the resource block: \`flavor_id\` and \`image_id\` are values only the region knows, and an invented one passes \`terraform validate\` (it checks only that the value is a string) and fails at apply.
|
|
9399
|
+
Pick a flavour and an image whose minimum disk and memory the flavour can meet, and state the choice to the user — this is the decision the price hangs on.`
|
|
9400
|
+
},
|
|
9401
|
+
{
|
|
9402
|
+
requires: ["terraform_plan"],
|
|
9403
|
+
text: `%n. Add the compute, database and other resources to the same \`.tf\` files, from the design agreed above and the flavours chosen. Credentials come from the environment; never write \`access_key\`, \`secret_key\` or \`security_token\` into a \`.tf\` file.
|
|
9404
|
+
${tool("provider_schema")} — the argument contract for a resource type, when you need it.
|
|
9405
|
+
${tool("terraform_plan")} — compute the change and save it to \`plan.tfplan\`. It returns one entry per resource: the action (create / update / **replace** / destroy), the attribute names an update touches, and — for a replace — what forces the rebuild. It also returns the security-group rules the change would create.
|
|
9406
|
+
★ Show the user every resource with its action, and the security-group rules. A **replace** is not an update: terraform destroys the resource and builds it again, so the data on that disk or database is gone. Call it out by name and say what forces it. Do not proceed on "a few things change" — name them. Do not describe the plan as reversible.`
|
|
9407
|
+
},
|
|
9408
|
+
{
|
|
9409
|
+
requires: ["price_resources", "terraform_plan"],
|
|
9410
|
+
text: `%n. ${tool("price_resources")} — read the SAVED PLAN and quote every priceable resource against this account's own on-demand prices, then write \`cost.json\`. Prices come after the plan, not before, because the plan is the real list: a block with \`count = 3\` is three instances, \`for_each\` is one per key, and a module's resources are visible — none of which the .tf files show. Each figure is a month (730 hours), with the list price and the moment of the inquiry.
|
|
9411
|
+
It prices compute instances (Linux and Windows bill separately, from the image), RDS, DCS, EVS volumes, EIPs, NAT gateways, ELB load balancers, APIG instances and VPCEP endpoints. Do NOT walk the .tf yourself to estimate the rest: it reports exactly which resources it could not price and why, and a spec that came from a variable cannot be priced at all. Read that list rather than assuming a type is covered. Say which ones are unpriced — a total that silently omits them understates the bill.`
|
|
9412
|
+
},
|
|
9413
|
+
{
|
|
9414
|
+
requires: ["price_resources"],
|
|
9415
|
+
text: `%n. ★ Report the cost before applying: each resource's spec, its monthly figure, the total, and which resources are unpriced and why, plus the balance and vouchers. Get the user's explicit agreement on the specification and the cost.
|
|
9416
|
+
Vouchers are applied automatically at the account level (voucher, then cash coupon, then balance) with nothing to configure in \`.tf\`. Say so: if vouchers exist, the actual monthly increase may come in below the quoted figure. Check each voucher's \`expire_time\` and warn about any nearing expiry.`
|
|
9417
|
+
},
|
|
9418
|
+
{
|
|
9419
|
+
requires: ["terraform_apply"],
|
|
9420
|
+
text: `%n. ${tool("terraform_apply")} — run it. Five gates run first: the design was checked by ${tool("validate_design")}, the cost was quoted by ${tool("price_resources")}, and ${tool("terraform_plan")} computed the saved plan — each of the three recorded against a digest of the configuration, and each refusing when the \`.tf\` has changed since. The fifth is the credential scan. Then it applies THAT saved plan rather than re-planning, so the changes executed are exactly the ones shown in the plan.
|
|
9421
|
+
A successful apply SPENDS the plan: terraform will not run the same plan file twice, so the tool clears it and its records. What follows is a new change set — plan, price, then apply again. Expect that rather than treating the cleared plan as a failure.
|
|
9422
|
+
A deployment with nothing to charge for — a VPC, subnets, security groups and routes — still gets a cost record saying so. price_resources reports \`nothing_billable\`, and that record satisfies the gate: the absence of a charge is an approval, the absence of a quote is not.`
|
|
9423
|
+
}
|
|
9424
|
+
];
|
|
9425
|
+
/**
|
|
9426
|
+
* Destroying and resynchronising.
|
|
9427
|
+
*
|
|
9428
|
+
* Its own block because it is a different task, reached from a different place
|
|
9429
|
+
* in a conversation, and because each bullet is about a different tool.
|
|
9430
|
+
*/
|
|
9431
|
+
const DESTROYING = [
|
|
9432
|
+
{
|
|
9433
|
+
requires: [
|
|
9434
|
+
"terraform_destroy",
|
|
9435
|
+
"terraform_plan",
|
|
9436
|
+
"terraform_state"
|
|
9437
|
+
],
|
|
9438
|
+
text: `- ${tool("terraform_destroy")} applies the teardown ${tool("terraform_plan")} saved. It refuses when the state is empty, when the .tf holds plaintext credentials, or when the saved teardown covers different targets from the ones this call names.
|
|
9439
|
+
★ Call ${tool("terraform_plan")} with \`destroy: true\` first, passing the SAME \`target\` list you intend to destroy. It returns every resource that would be removed, one entry each — show that list, then call terraform_destroy with the same targets. The saved plan is what destroy runs, so the resources that go away are exactly the ones the user saw. Destruction cannot be undone.
|
|
9440
|
+
If the deployment also imported existing resources, destroy only what this deployment created: pass their addresses as \`target: [...]\` and leave the imported ones in state. ${tool("terraform_state")} lists the addresses; terraform_plan with destroy: true says which ones the deployment would remove.`
|
|
9441
|
+
},
|
|
9442
|
+
{
|
|
9443
|
+
requires: ["terraform_refresh", "terraform_plan"],
|
|
9444
|
+
text: `- ${tool("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.`
|
|
9445
|
+
},
|
|
9446
|
+
{
|
|
9447
|
+
requires: ["terraform_state"],
|
|
9448
|
+
text: `- ${tool("terraform_state")} — read state. Without \`address\` it returns the INVENTORY: one entry per managed resource with its address, type and module. Those addresses are what \`terraform_import\`, \`destroy: true\` and \`target: [...]\` all take. With \`address\` it returns that one resource in full. The attributes of every resource at once are deliberately not returned — a real deployment runs to megabytes of them. Both forms also return the security-group rules the state records.`
|
|
9449
|
+
}
|
|
9450
|
+
];
|
|
9451
|
+
/** The rules that hold whenever the tools are present at all. */
|
|
9452
|
+
const HARD_LINES = `## Hard lines
|
|
8542
9453
|
|
|
8543
9454
|
- 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.
|
|
8544
9455
|
- Before applying or destroying, name the resources involved and get the user's explicit agreement. Never run these silently.
|
|
8545
9456
|
- 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.
|
|
8546
9457
|
- \`cost.json\` must exist and its \`tf_hash\` must match before apply. Editing a \`.tf\` file invalidates it; recompute the cost.
|
|
8547
|
-
- 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
|
|
8548
|
-
|
|
8549
|
-
|
|
9458
|
+
- 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.`;
|
|
9459
|
+
/** Region advice that is independent of which tools are present. */
|
|
9460
|
+
const REGION_FILING = `## Mainland region filing
|
|
8550
9461
|
|
|
8551
|
-
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
|
|
8552
|
-
|
|
8553
|
-
|
|
8554
|
-
|
|
8555
|
-
|
|
8556
|
-
|
|
8557
|
-
|
|
8558
|
-
|
|
8559
|
-
|
|
8560
|
-
|
|
8561
|
-
|
|
8562
|
-
|
|
8563
|
-
|
|
8564
|
-
|
|
9462
|
+
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.`;
|
|
9463
|
+
/** Answers to the questions that map onto one call each. */
|
|
9464
|
+
const TYPICAL_REQUESTS = [
|
|
9465
|
+
{
|
|
9466
|
+
requires: ["list_existing_resources"],
|
|
9467
|
+
text: `- "How many ECS instances do I have?" → aishell__list_existing_resources with \`service: "ecs"\``
|
|
9468
|
+
},
|
|
9469
|
+
{
|
|
9470
|
+
requires: ["openapi_request"],
|
|
9471
|
+
text: `- "What did I spend this month?" → aishell__openapi_request("GET", <BSS bill API>)`
|
|
9472
|
+
},
|
|
9473
|
+
{
|
|
9474
|
+
requires: ["list_existing_resources"],
|
|
9475
|
+
text: `- "How many vouchers do I have?" → the \`balance_summary\` field of aishell__list_existing_resources`
|
|
9476
|
+
},
|
|
9477
|
+
{
|
|
9478
|
+
requires: ["provider_schema"],
|
|
9479
|
+
text: `- "What arguments does this resource take?" → aishell__provider_schema(deployment, "huaweicloud_compute_instance")`
|
|
9480
|
+
},
|
|
9481
|
+
{
|
|
9482
|
+
requires: ["terraform_destroy"],
|
|
9483
|
+
text: `- "Tear this deployment down" → aishell__terraform_destroy, after listing the resources for confirmation`
|
|
9484
|
+
},
|
|
9485
|
+
{
|
|
9486
|
+
requires: ["terraform_refresh", "terraform_plan"],
|
|
9487
|
+
text: `- "The cloud changed, resync" → aishell__terraform_refresh, then aishell__terraform_plan for the difference`
|
|
9488
|
+
},
|
|
9489
|
+
{
|
|
9490
|
+
requires: ["terraform_state"],
|
|
9491
|
+
text: `- "What is deployed right now?" → aishell__terraform_state`
|
|
9492
|
+
},
|
|
9493
|
+
{
|
|
9494
|
+
requires: ["terraform_import"],
|
|
9495
|
+
text: `- "Bring this existing instance under management" → write the resource block, then aishell__terraform_import`
|
|
9496
|
+
}
|
|
9497
|
+
];
|
|
9498
|
+
/** Where to read about a product, and what not to answer from memory. */
|
|
9499
|
+
const PRODUCT_DOCS = `## Product documentation
|
|
8565
9500
|
|
|
8566
9501
|
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.
|
|
8567
9502
|
|
|
8568
9503
|
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".`;
|
|
8569
9504
|
/**
|
|
9505
|
+
* Whether every tool a block names is registered for this render.
|
|
9506
|
+
*
|
|
9507
|
+
* @param requires - the tool names, without the `aishell__` prefix.
|
|
9508
|
+
* @param present - the lookup bound to the current render scope.
|
|
9509
|
+
* @returns whether the block applies.
|
|
9510
|
+
*/
|
|
9511
|
+
function allPresent(requires, present) {
|
|
9512
|
+
return requires.every((name$1) => present(tool(name$1)));
|
|
9513
|
+
}
|
|
9514
|
+
/**
|
|
9515
|
+
* Render an ordered list of steps, numbering only the ones that apply.
|
|
9516
|
+
*
|
|
9517
|
+
* A step whose text begins with indentation is a continuation of the step
|
|
9518
|
+
* before it, and keeps that step's alignment rather than taking a number — the
|
|
9519
|
+
* distinction is carried by the text, because `requires` differs between a
|
|
9520
|
+
* parent step and its continuation.
|
|
9521
|
+
*
|
|
9522
|
+
* @param steps - the steps to consider.
|
|
9523
|
+
* @param present - the lookup bound to the current render scope.
|
|
9524
|
+
* @returns the rendered lines.
|
|
9525
|
+
*/
|
|
9526
|
+
function renderSteps(steps, present) {
|
|
9527
|
+
const lines = [];
|
|
9528
|
+
let number = 0;
|
|
9529
|
+
for (const step of steps) {
|
|
9530
|
+
if (!allPresent(step.requires, present)) continue;
|
|
9531
|
+
if (step.text.startsWith(" ")) {
|
|
9532
|
+
lines.push(step.text);
|
|
9533
|
+
continue;
|
|
9534
|
+
}
|
|
9535
|
+
number += 1;
|
|
9536
|
+
lines.push(step.text.replace("%n", String(number)));
|
|
9537
|
+
}
|
|
9538
|
+
return lines;
|
|
9539
|
+
}
|
|
9540
|
+
/**
|
|
9541
|
+
* The workflow text for one render scope.
|
|
9542
|
+
*
|
|
9543
|
+
* @param present - whether a tool with the given name is registered here.
|
|
9544
|
+
* @returns the section's text, empty when nothing it describes is available.
|
|
9545
|
+
*/
|
|
9546
|
+
function buildDeployWorkflow(present) {
|
|
9547
|
+
const flow = renderSteps(FLOW, present);
|
|
9548
|
+
const destroying = renderSteps(DESTROYING, present);
|
|
9549
|
+
const typical = renderSteps(TYPICAL_REQUESTS, present);
|
|
9550
|
+
const lifecyclePresent = allPresent(["terraform_apply"], present) || allPresent(["terraform_destroy"], present);
|
|
9551
|
+
const docsPresent = allPresent(["apiexplorer"], present) || allPresent(["list_existing_resources"], present);
|
|
9552
|
+
if (flow.length === 0 && destroying.length === 0 && typical.length === 0 && !lifecyclePresent && !docsPresent) return "";
|
|
9553
|
+
const blocks = [PREAMBLE];
|
|
9554
|
+
if (flow.length > 0) blocks.push([
|
|
9555
|
+
"## Deployment flow",
|
|
9556
|
+
"",
|
|
9557
|
+
"Steps marked ★ require the user's explicit agreement before you continue.",
|
|
9558
|
+
"",
|
|
9559
|
+
...flow
|
|
9560
|
+
].join("\n"));
|
|
9561
|
+
if (destroying.length > 0) blocks.push([
|
|
9562
|
+
"## Destroying and resynchronising",
|
|
9563
|
+
"",
|
|
9564
|
+
...destroying
|
|
9565
|
+
].join("\n"));
|
|
9566
|
+
if (lifecyclePresent) blocks.push(HARD_LINES);
|
|
9567
|
+
blocks.push(REGION_FILING);
|
|
9568
|
+
if (typical.length > 0) blocks.push([
|
|
9569
|
+
"## Typical requests",
|
|
9570
|
+
"",
|
|
9571
|
+
...typical
|
|
9572
|
+
].join("\n"));
|
|
9573
|
+
if (docsPresent) blocks.push(PRODUCT_DOCS);
|
|
9574
|
+
return blocks.join("\n\n");
|
|
9575
|
+
}
|
|
9576
|
+
/**
|
|
9577
|
+
* Where this section sits among the assembled prompt's sections.
|
|
9578
|
+
*
|
|
9579
|
+
* DSH concatenates sections in ascending order. The built-in per-tool
|
|
9580
|
+
* narration occupies 1000–3000 and the SDK documentation starts at 5000, so
|
|
9581
|
+
* 3100 is the gap between them. This workflow describes a contributed group of
|
|
9582
|
+
* tools, which is what belongs there: after every built-in tool's narration,
|
|
9583
|
+
* before the SDK reference.
|
|
9584
|
+
*/
|
|
9585
|
+
const WORKFLOW_SECTION_ORDER = 3100;
|
|
9586
|
+
/**
|
|
8570
9587
|
* Register the workflow section.
|
|
8571
9588
|
*
|
|
8572
9589
|
* Deferred behind `ctx.inject` rather than declared in this plugin's own
|
|
@@ -8579,9 +9596,9 @@ function registerDeployWorkflow(ctx) {
|
|
|
8579
9596
|
ctx.inject(["systemPrompt"], (scope) => {
|
|
8580
9597
|
scope.systemPrompt.section({
|
|
8581
9598
|
name: WORKFLOW_SECTION_NAME,
|
|
8582
|
-
order:
|
|
9599
|
+
order: WORKFLOW_SECTION_ORDER,
|
|
8583
9600
|
interpolate: false,
|
|
8584
|
-
text: ({ scope: renderScope }) => ctx.tools.get(
|
|
9601
|
+
text: ({ scope: renderScope }) => buildDeployWorkflow((name$1) => ctx.tools.get(name$1, renderScope) !== void 0)
|
|
8585
9602
|
});
|
|
8586
9603
|
});
|
|
8587
9604
|
}
|
|
@@ -8643,8 +9660,9 @@ function apply(ctx, config) {
|
|
|
8643
9660
|
});
|
|
8644
9661
|
const { registrar, captured } = createRegistrar();
|
|
8645
9662
|
registerAllTools(registrar);
|
|
8646
|
-
const
|
|
8647
|
-
|
|
9663
|
+
const workingDirectory = () => ctx.get("workingDirectory");
|
|
9664
|
+
const disposers = captured.map((tool$1) => {
|
|
9665
|
+
const definition = toToolDefinition(tool$1, config.toolCallTimeoutMs.get(), { ensure: (agent, signal) => requireSessionDirectories(workingDirectory()).ensure(agent, signal) });
|
|
8648
9666
|
return ctx.tools.register(definition);
|
|
8649
9667
|
});
|
|
8650
9668
|
ctx.effect(() => () => {
|
|
@@ -8679,6 +9697,21 @@ function apply(ctx, config) {
|
|
|
8679
9697
|
forgetAccount();
|
|
8680
9698
|
}), "aishell-deploy: credential cache");
|
|
8681
9699
|
}
|
|
9700
|
+
/**
|
|
9701
|
+
* The service when mounted, or one that reports its absence.
|
|
9702
|
+
*
|
|
9703
|
+
* `toToolDefinition` is built once, when the plugin activates, so a service
|
|
9704
|
+
* mounted later would never be seen if the value were captured. Returning a
|
|
9705
|
+
* wrapper keeps the lookup live: each call asks the context, which is the only
|
|
9706
|
+
* thing that knows what is mounted *now*.
|
|
9707
|
+
*
|
|
9708
|
+
* @param service - the service as it stands at this moment.
|
|
9709
|
+
* @returns the service, or a stand-in whose `ensure` refuses.
|
|
9710
|
+
*/
|
|
9711
|
+
function requireSessionDirectories(service) {
|
|
9712
|
+
if (service !== void 0) return service;
|
|
9713
|
+
return { ensure: () => Promise.reject(new Error("the host offers no working-directory service")) };
|
|
9714
|
+
}
|
|
8682
9715
|
|
|
8683
9716
|
//#endregion
|
|
8684
9717
|
export { Config, apply, inject, name };
|