@huaweidevtools/aishell-dsh-deploy 0.0.16 → 0.0.17

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/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,9 +945,10 @@ 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
+ function toToolDefinition(tool, timeoutMs, workingDirectory) {
951
952
  const name$1 = publicToolName(tool.name);
952
953
  const description = tool.config.description ?? "";
953
954
  const parameters = toJsonSchema(tool.config.inputSchema, tool.name);
@@ -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.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
- * Empty today: nothing the tool modules read lives on the harness context.
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
- * @param _exec - the harness execution context.
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(_exec) {
1015
- return {};
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,13 +1629,46 @@ 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
@@ -1967,7 +2042,7 @@ function forgetAccount() {
1967
2042
  * Throws if no binary can be found.
1968
2043
  */
1969
2044
  async function resolveTerraformEnv(deployment, extraEnv = []) {
1970
- const binary = await resolveBinary(deployment);
2045
+ const binary = await resolveBinary();
1971
2046
  const env = {};
1972
2047
  await resolveTerraformrc(deployment, env);
1973
2048
  await resolvePluginCache(env);
@@ -1997,7 +2072,7 @@ async function resolveTerraformEnv(deployment, extraEnv = []) {
1997
2072
  * environment variable set by the operator still wins over it — the same
1998
2073
  * precedence the rest of this module gives to explicit configuration.
1999
2074
  */
2000
- async function resolveBinary(deployment) {
2075
+ async function resolveBinary() {
2001
2076
  const envPath = process.env["HW_TERRAFORM_PATH"];
2002
2077
  if (envPath && await fileExists(envPath)) return envPath;
2003
2078
  const pathBinary = await findInPath("terraform");
@@ -2006,8 +2081,8 @@ async function resolveBinary(deployment) {
2006
2081
  if (recorded !== void 0 && await fileExists(recorded)) return recorded;
2007
2082
  const globalBin = await findGlobalCacheBinary();
2008
2083
  if (globalBin) return globalBin;
2009
- const depBin = join(deployment, ".terraform", "bin", "terraform");
2010
- if (await fileExists(depBin)) return depBin;
2084
+ const temporaryBin = await findTemporaryCacheBinary();
2085
+ if (temporaryBin) return temporaryBin;
2011
2086
  throw new Error("terraform not found — call terraform_install first");
2012
2087
  }
2013
2088
  /**
@@ -2041,14 +2116,39 @@ async function recordedBinaryPath() {
2041
2116
  return void 0;
2042
2117
  }
2043
2118
  }
2044
- /** .terraformrc resolution: deployment file > user env > user home > none. */
2119
+ /**
2120
+ * Where terraform's CLI configuration comes from: deployment file > user env >
2121
+ * user home > none.
2122
+ *
2123
+ * ## Why the deployment file is absolute
2124
+ *
2125
+ * The subprocess runs with `cwd` set to the deployment, and `TF_CLI_CONFIG_FILE`
2126
+ * is resolved by terraform against THAT directory, not against the process that
2127
+ * spawned it. A deployment given as a relative path therefore produced
2128
+ * `<deployment>/<deployment>/.terraformrc`: a file that cannot exist, a warning
2129
+ * on every run, and — the part that matters — a provider mirror that silently
2130
+ * never applied.
2131
+ *
2132
+ * `resolve(deployment)` is what makes the value mean the same thing to both
2133
+ * processes. The caller may hand this module a relative path; nothing
2134
+ * downstream can.
2135
+ *
2136
+ * @param deployment - the deployment directory, relative or absolute.
2137
+ * @param env - the subprocess env being assembled.
2138
+ */
2045
2139
  async function resolveTerraformrc(deployment, env) {
2046
- const depRc = join(deployment, ".terraformrc");
2047
- if (await fileExists(depRc)) {
2048
- env["TF_CLI_CONFIG_FILE"] = depRc;
2140
+ if (deployment !== void 0) {
2141
+ const depRc = join(resolve(deployment), ".terraformrc");
2142
+ if (await fileExists(depRc)) {
2143
+ env["TF_CLI_CONFIG_FILE"] = depRc;
2144
+ return;
2145
+ }
2146
+ }
2147
+ const fromEnv = process.env["TF_CLI_CONFIG_FILE"];
2148
+ if (fromEnv !== void 0 && fromEnv !== "") {
2149
+ env["TF_CLI_CONFIG_FILE"] = resolve(fromEnv);
2049
2150
  return;
2050
2151
  }
2051
- if (process.env["TF_CLI_CONFIG_FILE"]) return;
2052
2152
  const homeRc = join(homedir(), ".terraformrc");
2053
2153
  if (await fileExists(homeRc)) return;
2054
2154
  }
@@ -2064,19 +2164,16 @@ async function resolvePluginCache(env) {
2064
2164
  /**
2065
2165
  * Find terraform in PATH by running `terraform version`.
2066
2166
  *
2067
- * This is the only reliable way to confirm the binary is actually usable —
2068
- * `which`/`where` only confirm the file exists on PATH, not that it's a
2069
- * working terraform binary (could be a same-named empty file, a corrupt
2070
- * binary, or an architecture mismatch). `terraform version` succeeding
2071
- * means the binary genuinely runs.
2167
+ * This is the only reliable probe. `which`/`where` confirm a file exists on
2168
+ * PATH, not that it is a working terraform binary: a same-named empty file, a
2169
+ * corrupt download and an architecture mismatch all pass those and fail this.
2170
+ * `which` has portability problems of its own too — Alpine lacks it by default,
2171
+ * busybox's behaves differently, and Windows `where` emits several lines.
2172
+ * `terraform version` succeeding means the binary genuinely runs.
2072
2173
  *
2073
2174
  * The extra spawn is negligible: each terraform tool call already spawns a
2074
2175
  * subprocess that runs for seconds-to-minutes (init/plan/apply); a
2075
2176
  * `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
2177
  */
2081
2178
  async function findInPath(_name) {
2082
2179
  return new Promise((resolve$1) => {
@@ -2090,6 +2187,34 @@ async function findInPath(_name) {
2090
2187
  });
2091
2188
  }
2092
2189
  /** Find a cached binary in `<DSH_HOME>/terraform/bin` (terraform-<ver>). */
2190
+ /**
2191
+ * Find a binary downloaded into the temporary cache.
2192
+ *
2193
+ * This is where `terraform_install` puts one when the host's data directory is
2194
+ * read-only — a container with a read-only home, a sandboxed runner. The
2195
+ * search order has to know about it or the install would report success and
2196
+ * every later call would report no terraform.
2197
+ *
2198
+ * @returns the binary's path, or `null` when there is none.
2199
+ */
2200
+ async function findTemporaryCacheBinary() {
2201
+ try {
2202
+ const { readdir: readdir$1 } = await import("node:fs/promises");
2203
+ const dir = join(tmpdir(), "aishell-terraform");
2204
+ const entries = await readdir$1(dir);
2205
+ const versioned = entries.filter((entry) => entry.startsWith("terraform-"));
2206
+ if (versioned.length > 0) {
2207
+ versioned.sort().reverse();
2208
+ const path = join(dir, versioned[0]);
2209
+ if (await fileExists(path)) return path;
2210
+ }
2211
+ const plain = join(dir, "terraform");
2212
+ if (await fileExists(plain)) return plain;
2213
+ return null;
2214
+ } catch {
2215
+ return null;
2216
+ }
2217
+ }
2093
2218
  async function findGlobalCacheBinary() {
2094
2219
  try {
2095
2220
  const { readdir: readdir$1 } = await import("node:fs/promises");
@@ -3144,6 +3269,37 @@ async function assertDestroyPreviewed(directory, readState, hashConfiguration, t
3144
3269
  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
3270
  }
3146
3271
 
3272
+ //#endregion
3273
+ //#region src/projects.ts
3274
+ /**
3275
+ * Every project the account has, keyed by region name.
3276
+ *
3277
+ * @param credentials - the pair to sign with.
3278
+ * @returns region name → project id.
3279
+ * @throws when IAM cannot answer, with its own reason.
3280
+ */
3281
+ async function projectMap(credentials) {
3282
+ const response = await signedHttp("GET", new URL("https://iam.myhuaweicloud.com/v3/projects"), "", {}, credentials);
3283
+ if (response.status !== 200) throw new Error(`could not read the project list from IAM (HTTP ${response.status}): ${response.body.slice(0, 300)}`);
3284
+ const parsed = JSON.parse(response.body);
3285
+ const byRegion = new Map();
3286
+ for (const project of parsed.projects ?? []) if (typeof project.name === "string" && typeof project.id === "string") byRegion.set(project.name, project.id);
3287
+ return byRegion;
3288
+ }
3289
+ /**
3290
+ * The project id for one region, or a message naming what the account does have.
3291
+ *
3292
+ * @param projects - the map from {@link projectMap}.
3293
+ * @param region - the region a request is going to.
3294
+ * @returns the project id.
3295
+ * @throws when the account has no project there, listing the regions it does.
3296
+ */
3297
+ function projectIn(projects, region) {
3298
+ const known = projects.get(region);
3299
+ if (known !== void 0) return known;
3300
+ throw new Error(`the account has no project in ${region}. Its projects are in: ${[...projects.keys()].sort().join(", ")}.`);
3301
+ }
3302
+
3147
3303
  //#endregion
3148
3304
  //#region src/rating-map.ts
3149
3305
  /**
@@ -4131,30 +4287,6 @@ async function imagePlatforms(region, credentials) {
4131
4287
  }
4132
4288
  return platforms;
4133
4289
  }
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
4290
  /** Round to the cent, which is what a price is quoted in. */
4159
4291
  function round(amount) {
4160
4292
  return Math.round(amount * 100) / 100;
@@ -4381,27 +4513,6 @@ function imsHost(region) {
4381
4513
  /** How many catalogue entries one response may carry. */
4382
4514
  const CATALOGUE_LIMIT = 500;
4383
4515
  /**
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
4516
  * Every flavour the region sells in one availability zone.
4406
4517
  *
4407
4518
  * Scoped to an AZ because that is how availability works: a flavour exists in
@@ -4463,7 +4574,12 @@ function registerSpecsTool(registrar) {
4463
4574
  async function handleLookup(availabilityZone, region, deployment) {
4464
4575
  const resolvedRegion = region;
4465
4576
  try {
4466
- const project = await resolveProject(resolvedRegion);
4577
+ const credentials = await loadCredentials();
4578
+ const projects = await projectMap(credentials);
4579
+ const project = {
4580
+ id: projectIn(projects, resolvedRegion),
4581
+ region: resolvedRegion
4582
+ };
4467
4583
  const [flavors, images] = await Promise.all([listFlavors(project, availabilityZone), listImages(project)]);
4468
4584
  const engines = deployment === void 0 ? [] : await databaseEngines(deployment);
4469
4585
  const databaseFlavors = new Map();
@@ -4736,7 +4852,9 @@ async function listDatabaseFlavors(project, engine) {
4736
4852
  */
4737
4853
  const ExistingResourceSchema = z.object({
4738
4854
  id: z.string().min(1).describe("The cloud resource ID."),
4739
- type: z.string().min(1).describe("Resource type, either the terraform type (huaweicloud_vpc) or the short name RMS reports (vpc, ecs, rds)."),
4855
+ 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."),
4856
+ 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."),
4857
+ 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
4858
  name: z.string().optional().describe("Display name, when the cloud id is not the name."),
4741
4859
  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
4860
  cidr: z.string().optional().describe("Address range, for a VPC or subnet."),
@@ -4745,19 +4863,27 @@ const ExistingResourceSchema = z.object({
4745
4863
  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
4864
  });
4747
4865
  /**
4748
- * Short names and terraform types, mapped to the node kinds the diagram has.
4866
+ * Terraform types, mapped to the node kinds a design diagram has.
4749
4867
  *
4750
- * Both spellings are needed for the reason in {@link ExistingResourceSchema}:
4751
- * RMS answers `vpc`, terraform answers `huaweicloud_vpc`, and a caller may have
4752
- * either.
4868
+ * One vocabulary only, and that matters: this table answers for a `.tf` block.
4869
+ * RMS answers with its own plurals (`vpcs`, `cloudservers`, `securityGroups`),
4870
+ * which are a different vocabulary and are resolved by
4871
+ * {@link resolveRmsType} from the provider/type pair instead. Mixing the two
4872
+ * here produced entries that could never match anything the inventory sends.
4873
+ *
4874
+ * Terraform types lose the `huaweicloud_` prefix and any `_vN` suffix before
4875
+ * lookup. Spelled out rather than assumed: `huaweicloud_vpc_subnet` reduces to
4876
+ * `vpc_subnet`, not `subnet`, and a table written from the service names alone
4877
+ * silently fails on every subnet.
4753
4878
  *
4754
4879
  * ## Why this table is small, and why that is not a coverage problem
4755
4880
  *
4756
- * The provider has 1874 resource types; this lists the ones a network topology
4757
- * is made of. Measured against the provider's own example corpus — 1368
4758
- * resource instances of 438 distinct types — these kinds are 46% of the
4759
- * instances, and what they leave out is mostly resources the picture is not
4760
- * about: alarm rules, backups, parameter templates, key pairs, subscriptions.
4881
+ * The provider has over a thousand resource types; this lists the ones a
4882
+ * network topology is made of. Measured against the provider's own example
4883
+ * corpus — 1368 resource instances of 438 distinct types — these kinds are 46%
4884
+ * of the instances, and what they leave out is mostly resources the picture is
4885
+ * not about: alarm rules, backups, parameter templates, key pairs,
4886
+ * subscriptions.
4761
4887
  *
4762
4888
  * A wider table would draw those too. That is the trade this table refuses: a
4763
4889
  * diagram is read by comparing boxes, and a box that represents nothing the
@@ -4766,19 +4892,10 @@ const ExistingResourceSchema = z.object({
4766
4892
  */
4767
4893
  const KIND_BY_SHORT_NAME = {
4768
4894
  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
4895
  vpc_subnet: "subnet",
4780
4896
  networking_secgroup: "security-group",
4781
4897
  networking_secgroup_rule: "security-group-rule",
4898
+ compute_secgroup: "security-group",
4782
4899
  compute_instance: "compute",
4783
4900
  rds_instance: "database",
4784
4901
  dcs_instance: "database",
@@ -4802,20 +4919,86 @@ const KIND_BY_SHORT_NAME = {
4802
4919
  evs_volume: "database"
4803
4920
  };
4804
4921
  /**
4805
- * The kind one resource takes, when the topology has one for it.
4922
+ * What one configured resource is.
4806
4923
  *
4807
- * The terraform spelling is normalised by dropping the `huaweicloud_` prefix,
4808
- * and a few types carry a `_v2`/`_v1` suffix that is the same resource. That
4809
- * leaves one table rather than two that can disagree.
4924
+ * This answers for a `.tf` block, whose type is the provider's own spelling. An
4925
+ * account's resources do not come through here: the inventory already knows
4926
+ * what each one is, and a table of its vocabulary would grow with every service
4927
+ * — see `existing-topology.ts` for how that case is derived instead.
4810
4928
  *
4811
- * @param type - either spelling the caller sent.
4812
- * @returns the node kind, or `undefined` when this resource is not part of the
4813
- * picture — see the note on the table.
4929
+ * @param type - a terraform type (`huaweicloud_vpc`) or the short name the
4930
+ * provider's own docs use (`vpc`).
4931
+ * @returns the node kind, or `undefined` when the picture has none for it.
4814
4932
  */
4815
4933
  function kindOfExisting(type) {
4816
4934
  const stripped = type.replace(/^huaweicloud_/, "").replace(/_v\d+$/, "");
4817
4935
  return KIND_BY_SHORT_NAME[stripped];
4818
4936
  }
4937
+ /** Every kind a node may take. */
4938
+ const KINDS = new Set([
4939
+ "vpc",
4940
+ "subnet",
4941
+ "security-group",
4942
+ "security-group-rule",
4943
+ "gateway",
4944
+ "load-balancer",
4945
+ "compute",
4946
+ "database"
4947
+ ]);
4948
+ /**
4949
+ * What one described resource is.
4950
+ *
4951
+ * `type` is resolved on its own, which is the whole answer for a caller that
4952
+ * sent a terraform type. A caller that copied an RMS `type` has a plural
4953
+ * vocabulary ("vpcs", "cloudservers") that says nothing about what the resource
4954
+ * IS — and `instances` is both a database and an API gateway, depending on the
4955
+ * provider. So when `provider` is present it is used to disambiguate, and when
4956
+ * the pair resolves to nothing the answer is `undefined`: the resource is real
4957
+ * but this picture has no box for it.
4958
+ *
4959
+ * @param resource - the described resource.
4960
+ * @returns the kind, or `undefined` when the picture has none for it.
4961
+ */
4962
+ function kindOfResource(resource) {
4963
+ const stripped = resource.type.replace(/^huaweicloud_/, "").replace(/_v\d+$/, "");
4964
+ const direct = KIND_BY_SHORT_NAME[stripped] ?? resolveRmsType(resource.provider, stripped);
4965
+ return direct !== void 0 && KINDS.has(direct) ? direct : void 0;
4966
+ }
4967
+ /**
4968
+ * The kind an RMS plural type takes, given the provider that reported it.
4969
+ *
4970
+ * RMS names resources in the plural and per service, which is a second
4971
+ * vocabulary — not a translation of the first, and not derivable from it. It
4972
+ * exists because the inventory is the likeliest thing a caller has to hand, and
4973
+ * a caller should not have to translate what it was given.
4974
+ *
4975
+ * The provider is what makes it unambiguous: `instances` is an RDS database and
4976
+ * an APIG gateway, and the same word means neither thing on its own. That is
4977
+ * the reason the pair is required rather than either half.
4978
+ *
4979
+ * A service absent from this table draws nothing, which is the correct failure:
4980
+ * the caller is told the resource is outside the picture rather than shown a
4981
+ * box whose shape was guessed.
4982
+ *
4983
+ * @param provider - the RMS provider, or undefined when the caller omitted it.
4984
+ * @param type - the RMS type with the terraform prefix already stripped.
4985
+ * @returns the kind, or `undefined` when the pair has no box.
4986
+ */
4987
+ function resolveRmsType(provider, type) {
4988
+ if (provider === void 0) return void 0;
4989
+ switch (`${provider}/${type}`) {
4990
+ case "vpc/vpcs": return "vpc";
4991
+ case "vpc/subnets": return "subnet";
4992
+ case "vpc/securityGroups": return "security-group";
4993
+ case "ecs/cloudservers": return "compute";
4994
+ case "elb/loadbalancers": return "load-balancer";
4995
+ case "nat/natGateways": return "gateway";
4996
+ case "cce/clusters": return "compute";
4997
+ case "cce/nodes": return "compute";
4998
+ case "rds/instances": return "database";
4999
+ default: return void 0;
5000
+ }
5001
+ }
4819
5002
 
4820
5003
  //#endregion
4821
5004
  //#region src/network-checks.ts
@@ -4922,7 +5105,7 @@ function findProblems(blocks, byAddress, existing = []) {
4922
5105
  function existingSubnets(existing) {
4923
5106
  const placed = [];
4924
5107
  for (const resource of existing) {
4925
- if (kindOfExisting(resource.type) !== "subnet") continue;
5108
+ if (kindOfResource(resource) !== "subnet") continue;
4926
5109
  const cidr = resource.cidr === void 0 ? void 0 : parseCidr(resource.cidr);
4927
5110
  if (cidr === void 0) continue;
4928
5111
  placed.push({
@@ -4944,7 +5127,7 @@ function checkSubnets(blocks, byAddress, existing = []) {
4944
5127
  */
4945
5128
  const existingVpcByAddress = new Map();
4946
5129
  for (const resource of existing) {
4947
- if (kindOfExisting(resource.type) !== "vpc" || resource.address === void 0) continue;
5130
+ if (kindOfResource(resource) !== "vpc" || resource.address === void 0) continue;
4948
5131
  existingVpcByAddress.set(resource.address, resource.id);
4949
5132
  }
4950
5133
  const findings = [];
@@ -4956,7 +5139,7 @@ function checkSubnets(blocks, byAddress, existing = []) {
4956
5139
  if (parsed !== void 0) vpcCidr.set(`${block.type}.${block.name}`, parsed);
4957
5140
  }
4958
5141
  for (const resource of existing) {
4959
- if (kindOfExisting(resource.type) !== "vpc" || resource.cidr === void 0) continue;
5142
+ if (kindOfResource(resource) !== "vpc" || resource.cidr === void 0) continue;
4960
5143
  const parsed = parseCidr(resource.cidr);
4961
5144
  if (parsed === void 0) continue;
4962
5145
  for (const key of [resource.address, resource.id]) if (key !== void 0) vpcCidr.set(key, parsed);
@@ -5330,7 +5513,7 @@ function deriveTopology(blocks, existing = []) {
5330
5513
  order.push(node);
5331
5514
  }
5332
5515
  for (const resource of existing) {
5333
- const kind = kindOfExisting(resource.type);
5516
+ const kind = kindOfResource(resource);
5334
5517
  if (kind === void 0) {
5335
5518
  omittedCounts.set(resource.type, (omittedCounts.get(resource.type) ?? 0) + 1);
5336
5519
  continue;
@@ -5446,7 +5629,7 @@ function existingFacts(resource) {
5446
5629
  function matchExistingTarget(value, expectedKind, existing, byAddress) {
5447
5630
  const byTerraformAddress = new Map();
5448
5631
  for (const resource of existing) {
5449
- if (kindOfExisting(resource.type) !== expectedKind) continue;
5632
+ if (kindOfResource(resource) !== expectedKind) continue;
5450
5633
  if (resource.address === void 0) continue;
5451
5634
  if (!byTerraformAddress.has(resource.address)) byTerraformAddress.set(resource.address, resource.id);
5452
5635
  }
@@ -5613,7 +5796,240 @@ function edgesOf(blocks, topology) {
5613
5796
  }
5614
5797
 
5615
5798
  //#endregion
5616
- //#region src/d2-render.ts
5799
+ //#region src/existing-topology.ts
5800
+ /** Facts worth showing on a box, by the attribute name that holds them. */
5801
+ const LABEL_ATTRIBUTES = [
5802
+ "name",
5803
+ "cidr",
5804
+ "publicIpAddress",
5805
+ "ipAddress",
5806
+ "vip_address",
5807
+ "flavor",
5808
+ "flavorCode",
5809
+ "spec",
5810
+ "nodeFlavor",
5811
+ "clusterFlavor",
5812
+ "size",
5813
+ "engineName",
5814
+ "engineVersion",
5815
+ "status",
5816
+ "instanceStatus",
5817
+ "clusterStatus",
5818
+ "provisioning_status",
5819
+ "availability_zone",
5820
+ "az"
5821
+ ];
5822
+ /**
5823
+ * Every scalar the properties contain, keyed by its dotted path.
5824
+ *
5825
+ * Nested objects and arrays are flattened because the inventory nests ids
5826
+ * arbitrarily deep (`vnic.vpcId`, `bandwidth.id`,
5827
+ * `security_group_rules[].remote_group_id`), and a rule that only looked at the
5828
+ * top level would miss most of the relationships.
5829
+ *
5830
+ * A JSON-encoded value is also opened, because the inventory sometimes ships one
5831
+ * as a string. RDS is the case that was measured: it reports `vpcId` as
5832
+ * `"[\"73e76381-…\"]"` and `networkId` as its subnet — a real reference, present
5833
+ * and correct, that a plain string comparison never matches. Left closed, the
5834
+ * RDS instance floats at the root of the picture with its VPC in plain sight in
5835
+ * its own properties.
5836
+ *
5837
+ * @param value - any property value.
5838
+ * @returns path → scalar, for every leaf.
5839
+ */
5840
+ function flattenProperties(value) {
5841
+ const found = new Map();
5842
+ const walk = (node, path) => {
5843
+ if (typeof node === "string") {
5844
+ if (isJsonEncoded(node)) try {
5845
+ walk(JSON.parse(node), path);
5846
+ return;
5847
+ } catch {}
5848
+ found.set(path, node);
5849
+ return;
5850
+ }
5851
+ if (typeof node === "number" || typeof node === "boolean") {
5852
+ found.set(path, String(node));
5853
+ return;
5854
+ }
5855
+ if (Array.isArray(node)) {
5856
+ for (const entry of node) walk(entry, path);
5857
+ return;
5858
+ }
5859
+ if (node !== null && typeof node === "object") for (const [key, inner] of Object.entries(node)) walk(inner, path === "" ? key : `${path}.${key}`);
5860
+ };
5861
+ walk(value, "");
5862
+ return found;
5863
+ }
5864
+ /**
5865
+ * Whether a string holds a JSON array or object worth opening.
5866
+ *
5867
+ * The check is deliberately narrow: an id is a plain string and must stay one,
5868
+ * so only a leading `{` or `[` that parses is opened. A quoted string inside a
5869
+ * range or a name that happens to start with a bracket would fail to parse and
5870
+ * be kept verbatim.
5871
+ *
5872
+ * @param text - the property value.
5873
+ * @returns whether it is worth attempting to parse.
5874
+ */
5875
+ function isJsonEncoded(text) {
5876
+ const first = text.trimStart()[0];
5877
+ return first === "[" || first === "{";
5878
+ }
5879
+ /** The kinds a box can be drawn inside, and how specific each is. */
5880
+ const LOCATION_KINDS = [{
5881
+ nouns: ["vpc"],
5882
+ rank: 1
5883
+ }, {
5884
+ nouns: ["subnet", "network"],
5885
+ rank: 2
5886
+ }];
5887
+ /**
5888
+ * How specific a location an attribute names, 0 when it names none.
5889
+ *
5890
+ * The tail of the path is what counts: `vnic.vpcId` and `metadata.vpcId` both
5891
+ * end in a noun describing the container. Everything before the last dot is the
5892
+ * service's own nesting and says nothing about which container this is.
5893
+ *
5894
+ * The `id`/`uid`/`uuid` suffix is stripped rather than required to be present,
5895
+ * because the provider writes all three (`subnet_id`, `subnetId`,
5896
+ * `virsubnet_id`) and a rule that demanded one spelling would miss the others.
5897
+ * A plural suffix is stripped too: `elb_virsubnet_ids` holds several subnets,
5898
+ * and whether the attribute holds one id or a list does not change what it
5899
+ * names. Suffix matching, not equality, is what makes `virsubnet` and
5900
+ * `subnetwork` land on the same noun.
5901
+ *
5902
+ * @param attribute - a dotted property path.
5903
+ * @returns the rank of the location it names, or 0 for a plain association.
5904
+ */
5905
+ function locationRank(attribute) {
5906
+ const tail = attribute.split(".").pop() ?? attribute;
5907
+ const noun = tail.replace(/(_?ids|_?id|_?uids|_?uid|uuid)$/i, "").replace(/[^a-z]/gi, "").toLowerCase();
5908
+ for (const { nouns, rank } of LOCATION_KINDS) for (const word of nouns) if (noun.endsWith(word)) return rank;
5909
+ return 0;
5910
+ }
5911
+ /**
5912
+ * Derive the picture from what the inventory reported.
5913
+ *
5914
+ * @param resources - every resource the inventory returned.
5915
+ * @returns nodes, edges, and the nesting derived from both.
5916
+ */
5917
+ function deriveInventoryTopology(resources) {
5918
+ const byId = new Map();
5919
+ const duplicates = [];
5920
+ for (const resource of resources) {
5921
+ if (byId.has(resource.id)) {
5922
+ if (!duplicates.includes(resource.id)) duplicates.push(resource.id);
5923
+ continue;
5924
+ }
5925
+ byId.set(resource.id, resource);
5926
+ }
5927
+ const flat = new Map();
5928
+ for (const [id, resource] of byId) flat.set(id, flattenProperties(resource.properties ?? {}));
5929
+ const raw = [];
5930
+ const seen = new Set();
5931
+ for (const [id, properties] of flat) for (const [attribute, value] of properties) {
5932
+ if (value === id) continue;
5933
+ if (!byId.has(value)) continue;
5934
+ const key = `${id}\u0000${value}`;
5935
+ if (seen.has(key)) continue;
5936
+ seen.add(key);
5937
+ raw.push({
5938
+ from: id,
5939
+ to: value,
5940
+ attribute,
5941
+ location: locationRank(attribute)
5942
+ });
5943
+ }
5944
+ const edges = raw.map((entry) => ({
5945
+ from: entry.from,
5946
+ to: entry.to,
5947
+ attribute: entry.attribute,
5948
+ contains: entry.location > 0
5949
+ }));
5950
+ const parentOf = new Map();
5951
+ const parentRank = new Map();
5952
+ for (const entry of raw) {
5953
+ if (entry.location === 0) continue;
5954
+ if (entry.location > (parentRank.get(entry.from) ?? 0)) {
5955
+ parentOf.set(entry.from, entry.to);
5956
+ parentRank.set(entry.from, entry.location);
5957
+ }
5958
+ }
5959
+ for (const [child, parent] of [...parentOf]) {
5960
+ const seenChain = new Set([child]);
5961
+ let cursor = parent;
5962
+ while (cursor !== void 0) {
5963
+ if (seenChain.has(cursor)) {
5964
+ parentOf.delete(child);
5965
+ break;
5966
+ }
5967
+ seenChain.add(cursor);
5968
+ cursor = parentOf.get(cursor);
5969
+ }
5970
+ }
5971
+ const childrenOf = new Map();
5972
+ for (const [child, parent] of parentOf) {
5973
+ const list = childrenOf.get(parent) ?? [];
5974
+ list.push(child);
5975
+ childrenOf.set(parent, list);
5976
+ }
5977
+ const factsOf = (resource) => {
5978
+ const properties = flat.get(resource.id) ?? new Map();
5979
+ const label = resource.name ?? "";
5980
+ const facts = [];
5981
+ for (const key of LABEL_ATTRIBUTES) {
5982
+ const value = properties.get(key);
5983
+ if (value === void 0 || value === "" || value === label) continue;
5984
+ if (facts.some((fact) => fact.value === value)) continue;
5985
+ facts.push({
5986
+ key,
5987
+ value
5988
+ });
5989
+ }
5990
+ return facts;
5991
+ };
5992
+ const ancestorsOf = (id) => {
5993
+ const chain = [];
5994
+ const seenChain = new Set([id]);
5995
+ let cursor = parentOf.get(id);
5996
+ while (cursor !== void 0 && !seenChain.has(cursor)) {
5997
+ seenChain.add(cursor);
5998
+ chain.push(cursor);
5999
+ cursor = parentOf.get(cursor);
6000
+ }
6001
+ return chain;
6002
+ };
6003
+ const build = (id) => {
6004
+ const resource = byId.get(id);
6005
+ return {
6006
+ id,
6007
+ provider: resource.provider,
6008
+ type: resource.type,
6009
+ label: resource.name !== void 0 && resource.name !== "" ? resource.name : `${resource.provider}/${resource.type} ${id.slice(0, 8)}`,
6010
+ facts: factsOf(resource),
6011
+ parent: parentOf.get(id),
6012
+ ancestors: ancestorsOf(id),
6013
+ children: (childrenOf.get(id) ?? []).map(build)
6014
+ };
6015
+ };
6016
+ const rootIds = [...byId.keys()].filter((id) => !parentOf.has(id));
6017
+ const depth = (id) => ancestorsOf(id).length;
6018
+ rootIds.sort((a, b) => {
6019
+ const da = depth(a), db = depth(b);
6020
+ if (da !== db) return db - da;
6021
+ return (byId.get(a).name ?? a).localeCompare(byId.get(b).name ?? b);
6022
+ });
6023
+ return {
6024
+ roots: rootIds.map(build),
6025
+ nodes: [...byId.keys()].map(build),
6026
+ edges,
6027
+ duplicates
6028
+ };
6029
+ }
6030
+
6031
+ //#endregion
6032
+ //#region src/d2-engine.ts
5617
6033
  /**
5618
6034
  * The D2 themes, light and dark.
5619
6035
  *
@@ -5633,6 +6049,212 @@ function edgesOf(blocks, topology) {
5633
6049
  const LIGHT_THEME_ID = 5;
5634
6050
  const DARK_THEME_ID = 201;
5635
6051
  /**
6052
+ * The `vars` block every generated diagram opens with.
6053
+ *
6054
+ * The theme ids are written into the diagram rather than passed to `render`, so
6055
+ * the generated source is the whole description of what was drawn — a reader
6056
+ * feeding it to the D2 CLI gets the same colours.
6057
+ *
6058
+ * @returns the opening lines of a D2 document.
6059
+ */
6060
+ function themePreamble() {
6061
+ return [
6062
+ "direction: down",
6063
+ "",
6064
+ "vars: {",
6065
+ " d2-config: {",
6066
+ ` theme-id: ${LIGHT_THEME_ID}`,
6067
+ ` dark-theme-id: ${DARK_THEME_ID}`,
6068
+ " }",
6069
+ "}",
6070
+ ""
6071
+ ];
6072
+ }
6073
+ /**
6074
+ * Compile D2 source and render it to an SVG.
6075
+ *
6076
+ * @param source - the D2 source text.
6077
+ * @returns the SVG, with no XML declaration.
6078
+ * @throws when the source does not compile. That is a defect in the generator
6079
+ * rather than in the user's configuration — the generator produced the text —
6080
+ * so the caller names the generated fragment in its message.
6081
+ */
6082
+ async function renderD2(source$1) {
6083
+ const d2 = new D2();
6084
+ try {
6085
+ const compiled$1 = await d2.compile(source$1, { options: { layout: "elk" } });
6086
+ return await d2.render(compiled$1.diagram, {
6087
+ ...compiled$1.renderOptions,
6088
+ pad: 20,
6089
+ noXMLTag: true
6090
+ });
6091
+ } finally {
6092
+ await closeD2(d2);
6093
+ }
6094
+ }
6095
+ /**
6096
+ * Terminate the renderer's worker.
6097
+ *
6098
+ * `D2` exposes no disposal API, so the thread is terminated directly. The
6099
+ * failure is swallowed: a render that already produced its SVG must not be
6100
+ * reported as failed because the cleanup raced the worker's own shutdown.
6101
+ *
6102
+ * @param d2 - the renderer whose worker to stop.
6103
+ */
6104
+ async function closeD2(d2) {
6105
+ const worker = d2.worker;
6106
+ try {
6107
+ await worker?.terminate?.();
6108
+ } catch {}
6109
+ }
6110
+ /**
6111
+ * Quote a string for a D2 label.
6112
+ *
6113
+ * @param text - the label.
6114
+ * @returns the text inside double quotes, with its own quotes escaped.
6115
+ */
6116
+ function quote(text) {
6117
+ return `"${text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
6118
+ }
6119
+ /**
6120
+ * The D2 identifier for an address or cloud id.
6121
+ *
6122
+ * A `.` in a D2 key means "member of the block before it", so an unreplaced one
6123
+ * nests the node inside a box named after the part before the dot — inventing a
6124
+ * container that does not exist. Every character D2 reserves is replaced by `_`
6125
+ * for the same reason.
6126
+ *
6127
+ * A collision is possible in principle (`a_b.c` and `a.b_c` both map to
6128
+ * `a_b_c`). It cannot occur inside one provider namespace, where the separator
6129
+ * between resource types and names is always the same `.`, but callers draw
6130
+ * from a map keyed by the original id, so a collision would drop an edge rather
6131
+ * than misplace it.
6132
+ *
6133
+ * @param address - a terraform `type.name` address or a cloud resource id.
6134
+ * @returns an identifier D2 accepts.
6135
+ */
6136
+ function d2Id(address) {
6137
+ return address.replaceAll(".", "_").replaceAll(/[^A-Za-z0-9_]/g, "_");
6138
+ }
6139
+
6140
+ //#endregion
6141
+ //#region src/d2-inventory.ts
6142
+ /**
6143
+ * The D2 palette ramps, one hue each with three lightness steps.
6144
+ *
6145
+ * Four ramps rather than a per-provider table: `hash(provider) % 4` picks one,
6146
+ * so a provider not named anywhere still gets a stable, distinct colour.
6147
+ */
6148
+ const PROVIDER_RAMPS = [
6149
+ [
6150
+ "fill-B5, stroke-B3",
6151
+ "fill-B6, stroke-B4",
6152
+ "fill-B4, stroke-B2"
6153
+ ],
6154
+ [
6155
+ "fill-AA4, stroke-AA2",
6156
+ "fill-AA5, stroke-AA4",
6157
+ "fill-AA3, stroke-AA2"
6158
+ ],
6159
+ [
6160
+ "fill-AB5, stroke-AB4",
6161
+ "fill-AB4, stroke-AB4",
6162
+ "fill-AB6, stroke-AB5"
6163
+ ],
6164
+ [
6165
+ "fill-N7, stroke-N5",
6166
+ "fill-N6, stroke-N4",
6167
+ "fill-N5, stroke-N3"
6168
+ ]
6169
+ ];
6170
+ /** The class an arrow into a resource carries: "traffic flows here". */
6171
+ const CONNECTION_CLASS$1 = "stroke-AB3";
6172
+ /**
6173
+ * How many top-level boxes go in one row of an inventory picture.
6174
+ *
6175
+ * Three. Measured on a live 30-resource account: one row (D2's arrangement for
6176
+ * unconnected roots) is 9.6:1, five columns is 5.8:1, four is 4.8:1 and three is
6177
+ * 3.4:1. Below three the picture grows tall rather than wide, and a wider grid
6178
+ * pushes the strip down a level instead of removing it.
6179
+ */
6180
+ const GRID_COLUMNS = 3;
6181
+ /**
6182
+ * The class for one provider/type pair, stable across runs and pictures.
6183
+ *
6184
+ * @param provider - the service that reported the resource.
6185
+ * @param type - that service's own type name.
6186
+ * @returns a D2 theme class reference.
6187
+ */
6188
+ function inventoryClass(provider, type) {
6189
+ const hash = (text) => {
6190
+ let value = 0;
6191
+ for (const character of text) value = value * 31 + character.charCodeAt(0) >>> 0;
6192
+ return value;
6193
+ };
6194
+ const ramp = PROVIDER_RAMPS[hash(provider) % PROVIDER_RAMPS.length];
6195
+ return ramp[hash(type) % ramp.length];
6196
+ }
6197
+ /**
6198
+ * Draw an inventory-derived topology.
6199
+ *
6200
+ * @param topology - the picture derived from the inventory.
6201
+ * @returns the D2 source and the SVG it renders to.
6202
+ */
6203
+ async function renderInventoryTopology(topology) {
6204
+ const source$1 = inventoryToD2(topology);
6205
+ return {
6206
+ source: source$1,
6207
+ svg: await renderD2(source$1)
6208
+ };
6209
+ }
6210
+ /**
6211
+ * Generate the D2 source for an inventory-derived topology.
6212
+ *
6213
+ * @param topology - the picture.
6214
+ * @returns D2 source text.
6215
+ */
6216
+ function inventoryToD2(topology) {
6217
+ const lines = themePreamble();
6218
+ if (topology.roots.length > GRID_COLUMNS) lines.push(`grid-columns: ${GRID_COLUMNS}`, "");
6219
+ const write$1 = (node, depth) => {
6220
+ const indent = " ".repeat(depth);
6221
+ const label = node.facts.length === 0 ? node.label : `${node.label} ${node.facts.map((fact) => fact.value).join(" · ")}`;
6222
+ const style = `class: [${inventoryClass(node.provider, node.type)}]`;
6223
+ if (node.children.length === 0) {
6224
+ lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} { ${style} }`);
6225
+ return;
6226
+ }
6227
+ lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} {`);
6228
+ lines.push(`${indent} ${style}`);
6229
+ for (const child of node.children) write$1(child, depth + 1);
6230
+ lines.push(`${indent}}`);
6231
+ };
6232
+ for (const root of topology.roots) write$1(root, 0);
6233
+ if (topology.roots.length > 0) lines.push("");
6234
+ const parentOf = new Map(topology.nodes.map((node) => [node.id, node.parent]));
6235
+ for (const edge of topology.edges) {
6236
+ if (parentOf.get(edge.from) === edge.to) continue;
6237
+ lines.push(`${nodeId(edge.from)} -> ${nodeId(edge.to)}: ${quote(edge.attribute)} { class: [${CONNECTION_CLASS$1}] }`);
6238
+ }
6239
+ return lines.join("\n");
6240
+ }
6241
+ /**
6242
+ * The D2 identifier for a cloud id.
6243
+ *
6244
+ * The `r_` prefix is what keeps an id from colliding with D2's own reserved
6245
+ * words, and the base conversion handles every character D2 would otherwise
6246
+ * read as syntax.
6247
+ *
6248
+ * @param id - a cloud resource id.
6249
+ * @returns an identifier D2 accepts.
6250
+ */
6251
+ function nodeId(id) {
6252
+ return d2Id(`r_${id}`);
6253
+ }
6254
+
6255
+ //#endregion
6256
+ //#region src/d2-design.ts
6257
+ /**
5636
6258
  * The D2 palette classes per node kind.
5637
6259
  *
5638
6260
  * These are D2's OWN theme classes (`fill-B4`, `stroke-B1`, …), not custom
@@ -5659,6 +6281,29 @@ const KIND_CLASSES = {
5659
6281
  database: "fill-AB4, stroke-AB4"
5660
6282
  };
5661
6283
  /**
6284
+ * The short noun a node's box is headed with.
6285
+ *
6286
+ * The design vocabulary's names are this module's own (`security-group`), while
6287
+ * the box is read by someone looking at a network diagram and needs the words
6288
+ * the cloud uses.
6289
+ *
6290
+ * `compute` and `database` are the two kinds that cover several provider types,
6291
+ * so their captions are the generic word rather than one product name: a CCE
6292
+ * node is not an ECS instance and a DDS cluster is not RDS, and a box captioned
6293
+ * "ECS" would claim it is. The node's own `name` and terraform type carry the
6294
+ * specific identity.
6295
+ */
6296
+ const KIND_CAPTION = {
6297
+ vpc: "VPC",
6298
+ subnet: "subnet",
6299
+ "security-group": "secgroup",
6300
+ "security-group-rule": "rule",
6301
+ gateway: "gateway",
6302
+ "load-balancer": "ELB",
6303
+ compute: "compute",
6304
+ database: "database"
6305
+ };
6306
+ /**
5662
6307
  * The words on a connection's arrow.
5663
6308
  *
5664
6309
  * The cloud's own term for each, not this module's: a reader who looks at the
@@ -5692,66 +6337,30 @@ const CONNECTION_CLASS = "stroke-AB3";
5692
6337
  */
5693
6338
  async function renderTopology(topology, edges) {
5694
6339
  const source$1 = toD2(topology, edges);
5695
- const d2 = new D2();
5696
- try {
5697
- const compiled$1 = await d2.compile(source$1, { options: { layout: "elk" } });
5698
- const svg = await d2.render(compiled$1.diagram, {
5699
- ...compiled$1.renderOptions,
5700
- pad: 20,
5701
- noXMLTag: true
5702
- });
5703
- return {
5704
- source: source$1,
5705
- svg
5706
- };
5707
- } finally {
5708
- await closeD2(d2);
5709
- }
5710
- }
5711
- /**
5712
- * Terminate the renderer's worker.
5713
- *
5714
- * `D2` exposes no disposal API, so the thread is terminated directly. The
5715
- * failure is swallowed: a render that already produced its SVG must not be
5716
- * reported as failed because the cleanup raced the worker's own shutdown.
5717
- *
5718
- * @param d2 - the renderer whose worker to stop.
5719
- */
5720
- async function closeD2(d2) {
5721
- const worker = d2.worker;
5722
- try {
5723
- await worker?.terminate?.();
5724
- } catch {}
6340
+ return {
6341
+ source: source$1,
6342
+ svg: await renderD2(source$1)
6343
+ };
5725
6344
  }
5726
6345
  /**
5727
6346
  * Generate the D2 source for one topology.
5728
6347
  *
5729
- * The shape of the output is fixed by what D2 accepts, and every choice here
5730
- * comes from something D2 refused:
6348
+ * The shape of the output is fixed by what D2 accepts:
5731
6349
  *
5732
6350
  * - Nothing is written as an attribute child. `cidr: "10.0.0.0/16"` inside a
5733
6351
  * node's block renders as its own box, which would put a stray rectangle
5734
6352
  * in every subnet. Facts go into the node's LABEL instead.
5735
6353
  * - Facts are separated by `·` rather than aligned into columns, because D2
5736
6354
  * treats a leading `|` as a block-string terminator.
5737
- * - No `vars` block: D2 discards everything under it except `d2-config`.
6355
+ * - No `vars` block beyond the theme: D2 discards everything under it except
6356
+ * `d2-config`.
5738
6357
  *
5739
6358
  * @param topology - the derived picture.
5740
6359
  * @param edges - the relationships to draw.
5741
6360
  * @returns D2 source text.
5742
6361
  */
5743
6362
  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
- ];
6363
+ const lines = themePreamble();
5755
6364
  const byAddress = new Map(topology.nodes.map((node) => [node.address, node]));
5756
6365
  for (const root of topology.roots) lines.push(...nodeLines(root, 0));
5757
6366
  if (topology.roots.length > 0) lines.push("");
@@ -5788,7 +6397,7 @@ function nodeLines(node, depth) {
5788
6397
  const classes = KIND_CLASSES[node.kind];
5789
6398
  if (classes === void 0) throw new Error(`no D2 class for node kind "${node.kind}" (${node.address})`);
5790
6399
  const style = `class: [${classes}]`;
5791
- const extra = node.existing ? [" style.stroke-dash: 4"] : [];
6400
+ const extra = node.existing ? ["style.stroke-dash: 4"] : [];
5792
6401
  if (node.children.length === 0) {
5793
6402
  if (extra.length === 0) return [`${indent}${d2Id(node.address)}: ${quote(label)} { ${style} }`];
5794
6403
  return [
@@ -5837,51 +6446,6 @@ function d2Label(node) {
5837
6446
  return shown.length === 0 ? head : `${head} ${shown.join(" · ")}`;
5838
6447
  }
5839
6448
  /**
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
6449
  * The findings block, when there are findings.
5886
6450
  *
5887
6451
  * Written as a markdown block pinned below the diagram, so the problems sit
@@ -5999,7 +6563,7 @@ function registerDesignTool(registrar) {
5999
6563
  annotations: READ_ONLY_LOCAL,
6000
6564
  inputSchema: z.object({
6001
6565
  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. Each needs id and type; parent (the containing resource's cloud ID), name, cidr and flavor make the box readable. They are drawn dashed to mark them as already present.")
6566
+ 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. PASS type AND provider EXACTLY AS THE INVENTORY REPORTED THEM. RMS names resources in its own vocabulary (\"vpcs\", \"securityGroups\", \"instances\"), which is not the terraform type; translating it by hand produces names that do not exist (\"huaweicloud_security_group\" for \"securityGroups\"). The pair is also what disambiguates: \"instances\" under rds is a database, under apig it is not. PASS `properties` TOO, copied verbatim. With no .tf, `properties` is the only input this tool has: the nesting and the connections are derived from ids appearing in it, so a resource without one is drawn as an isolated box and the relationships it has are lost. Each needs id and type; parent (the containing resource's cloud ID), name, cidr and flavor make the box readable. They are drawn dashed to mark them as already present. Passing `existing` with no .tf at all is legitimate: it draws the account as it stands, and validation reports itself as skipped.")
6003
6567
  })
6004
6568
  }, guard(async (args) => handleValidateDesign(args.deployment, args.existing ?? [])));
6005
6569
  }
@@ -6011,7 +6575,8 @@ function registerDesignTool(registrar) {
6011
6575
  */
6012
6576
  async function handleValidateDesign(deployment, existing) {
6013
6577
  const configFiles = await configurationFiles(deployment);
6014
- if (configFiles.length === 0) return fail(`no ${CONFIG_EXTENSION} files in ${deployment}. Write the network design first — VPC, subnets, security groups — then call this tool. A deployment with no configuration has no design to check.`);
6578
+ 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\`.`);
6579
+ if (configFiles.length === 0) return await handleInventoryOnly(deployment, existing);
6015
6580
  const sources = [];
6016
6581
  for (const file of configFiles) try {
6017
6582
  sources.push({
@@ -6032,7 +6597,8 @@ async function handleValidateDesign(deployment, existing) {
6032
6597
  const topology = deriveTopology(blocks, existing);
6033
6598
  if (topology.nodes.length === 0) {
6034
6599
  const types = topology.omitted.slice(0, 8).map((entry) => `${entry.type}${entry.count > 1 ? ` ×${entry.count}` : ""}`).join(", ");
6035
- return fail(`the configuration declares ${blocks.length} resource(s), but none of them is part of a network design — so there is no topology to draw. It declares: ${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. Add the network those resources belong to, or review them without a diagram.`);
6600
+ const supplied = blocks.length + existing.length;
6601
+ 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
6602
  }
6037
6603
  const edges = edgesOf(blocks, topology);
6038
6604
  let svg;
@@ -6198,6 +6764,89 @@ function parseValidateJson(stdout) {
6198
6764
  diagnostics
6199
6765
  };
6200
6766
  }
6767
+ /**
6768
+ * Draw an account that already exists, from the inventory's own shape.
6769
+ *
6770
+ * ## Why this does not go through the design path
6771
+ *
6772
+ * A design is a configuration, and its picture is derived from resource blocks.
6773
+ * An account is a set of resources and the references between them, reported by
6774
+ * the inventory with the properties each service attaches. Those are different
6775
+ * inputs, and reading the second through the first would need a table mapping
6776
+ * every service's vocabulary onto the diagram's — the kind of table that grows
6777
+ * with every service and is wrong the first time one is missing.
6778
+ *
6779
+ * So this path asks the inventory what it saw: ids, types, names, properties.
6780
+ * Relationships come from ids appearing in properties, and containment from the
6781
+ * direction references flow. No service is named anywhere.
6782
+ *
6783
+ * @param deployment - the deployment workspace directory, used only for output.
6784
+ * @param existing - the resources the caller reported.
6785
+ * @returns the tool result.
6786
+ */
6787
+ async function handleInventoryOnly(deployment, existing) {
6788
+ const withProperties = existing.filter((resource) => resource.properties !== void 0 && Object.keys(resource.properties).length > 0);
6789
+ 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.");
6790
+ const topology = deriveInventoryTopology(withProperties.map((resource) => ({
6791
+ id: resource.id,
6792
+ provider: resource.provider ?? "",
6793
+ type: resource.type,
6794
+ ...resource.name === void 0 ? {} : { name: resource.name },
6795
+ ...resource.region === void 0 ? {} : { region: resource.region },
6796
+ properties: resource.properties ?? {}
6797
+ })));
6798
+ let svg;
6799
+ let d2;
6800
+ try {
6801
+ const rendered = await renderInventoryTopology(topology);
6802
+ svg = rendered.svg;
6803
+ d2 = rendered.source;
6804
+ } catch (error) {
6805
+ return fail(`the topology could not be rendered: ${error instanceof Error ? error.message : String(error)}`);
6806
+ }
6807
+ try {
6808
+ await mkdir(deployment, { recursive: true });
6809
+ await writeFile(join(deployment, D2_FILE), d2, "utf8");
6810
+ await writeFile(join(deployment, TOPOLOGY_FILE), svg, "utf8");
6811
+ } catch (error) {
6812
+ return fail(`the diagram could not be written into ${deployment}: ${error instanceof Error ? error.message : String(error)}`);
6813
+ }
6814
+ const diagramPath = resolve(deployment, TOPOLOGY_FILE);
6815
+ const provided = existing.length - withProperties.length;
6816
+ return okJson({
6817
+ deployment,
6818
+ mode: "inventory",
6819
+ diagram: {
6820
+ svg: diagramPath,
6821
+ d2: resolve(deployment, D2_FILE),
6822
+ note: `Show the user the picture by writing this into your reply as a Markdown image: ![topology](${diagramPath})`
6823
+ },
6824
+ validation: {
6825
+ state: "skipped",
6826
+ 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."
6827
+ },
6828
+ resources: topology.nodes.map((node) => ({
6829
+ id: node.id,
6830
+ type: `${node.provider}/${node.type}`,
6831
+ label: node.label,
6832
+ parent: node.parent ?? null
6833
+ })),
6834
+ edges: topology.edges.map((edge) => ({
6835
+ from: edge.from,
6836
+ to: edge.to,
6837
+ attribute: edge.attribute,
6838
+ contains: edge.contains
6839
+ })),
6840
+ summary: {
6841
+ drawn: topology.nodes.length,
6842
+ edges: topology.edges.length,
6843
+ nested: topology.nodes.filter((node) => node.parent !== void 0).length,
6844
+ ...provided === 0 ? {} : { without_properties: provided },
6845
+ validation: "skipped"
6846
+ },
6847
+ 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.`)
6848
+ });
6849
+ }
6201
6850
 
6202
6851
  //#endregion
6203
6852
  //#region src/tools/openapi.ts
@@ -6836,6 +7485,90 @@ async function queryBalanceSummary() {
6836
7485
  };
6837
7486
  }
6838
7487
 
7488
+ //#endregion
7489
+ //#region src/inventory-subnets.ts
7490
+ /** How many pages a region's subnet list may take before giving up. */
7491
+ const MAX_PAGES = 10;
7492
+ /**
7493
+ * Every subnet the account has in one region.
7494
+ *
7495
+ * Best-effort by contract: a caller completes an inventory, and a region whose
7496
+ * subnets could not be read is worse off without its other resources, not
7497
+ * better. So a failure is reported rather than thrown, and the caller decides
7498
+ * what to say about it.
7499
+ *
7500
+ * @param region - the region to list.
7501
+ * @returns the subnets, or the reason they could not be read.
7502
+ */
7503
+ async function subnetsInRegion(region) {
7504
+ let projectId;
7505
+ try {
7506
+ const projects = await projectMap(await loadCredentials());
7507
+ projectId = projectIn(projects, region);
7508
+ } catch (error) {
7509
+ return {
7510
+ subnets: [],
7511
+ failure: error instanceof Error ? error.message : String(error)
7512
+ };
7513
+ }
7514
+ const subnets = [];
7515
+ let marker;
7516
+ for (let page = 0; page < MAX_PAGES; page++) {
7517
+ const url = new URL(`https://vpc.${region}.myhuaweicloud.com/v1/${projectId}/subnets`);
7518
+ if (marker !== void 0) url.searchParams.set("marker", marker);
7519
+ let response;
7520
+ try {
7521
+ response = await signedHttp("GET", url, "");
7522
+ } catch (error) {
7523
+ return {
7524
+ subnets,
7525
+ failure: `the subnet list for ${region} could not be read: ${error instanceof Error ? error.message : String(error)}`
7526
+ };
7527
+ }
7528
+ if (response.status !== 200) return {
7529
+ subnets,
7530
+ failure: `the subnet list for ${region} answered HTTP ${response.status}: ${response.body.slice(0, 200)}`
7531
+ };
7532
+ const parsed = JSON.parse(response.body);
7533
+ for (const subnet of parsed.subnets ?? []) {
7534
+ const mapped = asInventorySubnet(subnet, region);
7535
+ if (mapped !== void 0) subnets.push(mapped);
7536
+ }
7537
+ marker = parsed.page_info?.next_marker;
7538
+ if (marker === void 0 || marker === "") break;
7539
+ }
7540
+ return { subnets };
7541
+ }
7542
+ /**
7543
+ * One VPC API subnet as an inventory resource.
7544
+ *
7545
+ * `properties.vpc_id` is what places it: `locationRank` reads the attribute's
7546
+ * noun, so a subnet with this field lands inside its VPC by the same rule that
7547
+ * puts anything else where it lives. The CIDR and gateway go along because a
7548
+ * reader comparing subnets needs to see the ranges.
7549
+ *
7550
+ * @param subnet - one record from the API.
7551
+ * @param region - the region it came from.
7552
+ * @returns the resource, or `undefined` when it is missing the id every node
7553
+ * needs.
7554
+ */
7555
+ function asInventorySubnet(subnet, region) {
7556
+ if (typeof subnet.id !== "string" || subnet.id === "") return void 0;
7557
+ const properties = {};
7558
+ if (typeof subnet.vpc_id === "string") properties["vpc_id"] = subnet.vpc_id;
7559
+ if (typeof subnet.cidr === "string") properties["cidr"] = subnet.cidr;
7560
+ if (typeof subnet.gateway_ip === "string") properties["gateway_ip"] = subnet.gateway_ip;
7561
+ if (typeof subnet.status === "string") properties["status"] = subnet.status;
7562
+ return {
7563
+ id: subnet.id,
7564
+ name: typeof subnet.name === "string" ? subnet.name : subnet.id.slice(0, 8),
7565
+ provider: "vpc",
7566
+ type: "subnets",
7567
+ region,
7568
+ properties
7569
+ };
7570
+ }
7571
+
6839
7572
  //#endregion
6840
7573
  //#region src/tools/existing_resources.ts
6841
7574
  /**
@@ -6999,13 +7732,24 @@ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker,
6999
7732
  tags: r.tags,
7000
7733
  properties: r.properties
7001
7734
  }));
7735
+ const subnets = { subnets: [] };
7736
+ if (serviceFilter === "vpc") {
7737
+ const regions = regionFilter !== void 0 ? [regionFilter] : [...new Set(collected.filter((r) => r.type === "vpcs").map((r) => r.region_id))];
7738
+ const failures = [];
7739
+ for (const listed of await listSubnets(regions)) {
7740
+ subnets.subnets.push(...listed.subnets);
7741
+ if (listed.failure !== void 0) failures.push(listed.failure);
7742
+ }
7743
+ if (failures.length > 0) process.stderr.write(`list_existing_resources: ${failures.join("; ")}\n`);
7744
+ }
7002
7745
  const hitAutoPageLimit = autoAdvance && pagesFetched >= MAX_AUTO_PAGES && !exhausted;
7003
7746
  return okJson({
7004
7747
  mode: "detail",
7005
- resources: normalized,
7006
- count: normalized.length,
7748
+ resources: [...normalized, ...subnets.subnets],
7749
+ count: normalized.length + subnets.subnets.length,
7007
7750
  region: regionFilter ?? "(all regions)",
7008
7751
  ...serviceFilter ? { service_filter: serviceFilter } : {},
7752
+ ...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
7753
  ...nextMarker && !exhausted ? {
7010
7754
  next_marker: nextMarker,
7011
7755
  has_more: true,
@@ -7015,6 +7759,21 @@ async function detailStage(domainId, serviceFilter, regionFilter, limit, marker,
7015
7759
  balance_summary: balanceSummary
7016
7760
  });
7017
7761
  }
7762
+ /**
7763
+ * Read the subnets of several regions, sequentially.
7764
+ *
7765
+ * Sequential rather than concurrent for the same reason the catalogue lookup
7766
+ * is: these are a handful of calls against the same signed client, and flooding
7767
+ * one host buys nothing a short wait does not.
7768
+ *
7769
+ * @param regions - the regions to list.
7770
+ * @returns one result per region, each carrying its own failure if it has one.
7771
+ */
7772
+ async function listSubnets(regions) {
7773
+ const results = [];
7774
+ for (const region of regions) results.push(await subnetsInRegion(region));
7775
+ return results;
7776
+ }
7018
7777
 
7019
7778
  //#endregion
7020
7779
  //#region src/tools/provider_schema.ts
@@ -7607,17 +8366,16 @@ const envParam = z.array(z.string()).optional().describe("Extra env vars for the
7607
8366
  function registerInstall(registrar) {
7608
8367
  registrar.registerTool("terraform_install", {
7609
8368
  title: "Install terraform",
7610
- description: "Ensure a terraform binary is available. Only installs the binary — provider plugins are pulled by terraform_init. Priority: terraform_path param > PATH > the host cache ($DSH_HOME/terraform/bin) > download from binary_mirrors. Download falls back to <deployment>/.terraform/bin/ when that is not writable.",
8369
+ 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
8370
  annotations: CLOUD_WRITE,
7612
8371
  inputSchema: z.object({
7613
- deployment: deploymentParam.describe("Used only as download fallback when HOME is not writable."),
7614
8372
  terraform_path: z.string().optional().describe("Explicit path to a terraform binary."),
7615
8373
  binary_mirrors: z.array(z.string()).optional().describe("Binary download mirror URLs, tried in order."),
7616
8374
  env: envParam
7617
8375
  })
7618
- }, guard(async (args) => handleInstall(args.deployment, args.terraform_path, args.binary_mirrors, args.env ?? [])));
8376
+ }, guard(async (args) => handleInstall(args.terraform_path, args.binary_mirrors, args.env ?? [])));
7619
8377
  }
7620
- async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv = []) {
8378
+ async function handleInstall(terraformPath, binaryMirrors, extraEnv = []) {
7621
8379
  if (terraformPath) {
7622
8380
  const { stat: stat$1 } = await import("node:fs/promises");
7623
8381
  try {
@@ -7633,11 +8391,11 @@ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv
7633
8391
  source: "parameter",
7634
8392
  cached: true,
7635
8393
  recorded,
7636
- ...recorded ? {} : { warning: "the path could not be recorded, so later tool calls will look for terraform on PATH, in the host cache, then in the deployment directory" }
8394
+ ...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
8395
  });
7638
8396
  }
7639
8397
  try {
7640
- const { binary } = await resolveTerraformEnv(deployment, extraEnv);
8398
+ const { binary } = await resolveTerraformEnv(void 0, extraEnv);
7641
8399
  const ver = await getTerraformVersion(binary);
7642
8400
  return okJson({
7643
8401
  terraform: ver,
@@ -7648,7 +8406,7 @@ async function handleInstall(deployment, terraformPath, binaryMirrors, extraEnv
7648
8406
  } catch {}
7649
8407
  const mirrors = binaryMirrors ?? DEFAULT_BINARY_MIRRORS;
7650
8408
  const { version, arch, platform } = detectPlatform();
7651
- const destDir = await resolveDownloadDir(deployment);
8409
+ const destDir = await resolveDownloadDir();
7652
8410
  const binPath = join(destDir, `terraform${version ? "-" + version : ""}`);
7653
8411
  return runOperation(async () => {
7654
8412
  const failures = [];
@@ -8162,20 +8920,66 @@ function detectPlatform() {
8162
8920
  platform
8163
8921
  };
8164
8922
  }
8165
- /** Resolve download dir: the host cache preferred, deployment fallback. */
8166
- async function resolveDownloadDir(deployment) {
8923
+ /**
8924
+ * Where a downloaded terraform binary goes.
8925
+ *
8926
+ * The host cache first, because one binary serves every deployment: a machine
8927
+ * runs `terraform_init` on several workspaces and downloading per workspace
8928
+ * would be a copy each.
8929
+ *
8930
+ * ## Why the fallback is the temp directory, not a deployment
8931
+ *
8932
+ * The cache lives under the host's data directory, and that is unwritable in
8933
+ * some environments — a container with a read-only home, a sandboxed runner. A
8934
+ * download still has to land somewhere.
8935
+ *
8936
+ * A deployment directory is the wrong place for it, in two ways. A binary is not
8937
+ * a deployment asset: putting it inside one makes it invisible to every other
8938
+ * deployment, so each workspace downloads its own copy. And it puts an
8939
+ * executable inside a directory the user treats as their own content, which is
8940
+ * not where a tool should write things it will not clean up.
8941
+ *
8942
+ * The temp directory is the standard answer to "no persistent location
8943
+ * available": shared by every deployment in this process, and rebuilt on the
8944
+ * next run if the system clears it. A cache that can be rebuilt is the right
8945
+ * loss here; a polluted workspace is not.
8946
+ *
8947
+ * @returns the directory to download into.
8948
+ * @throws when neither location exists, naming what to fix.
8949
+ */
8950
+ async function resolveDownloadDir() {
8167
8951
  const globalDir = terraformBinDir();
8952
+ const failure = await writableDirectory(globalDir);
8953
+ if (failure === void 0) return globalDir;
8954
+ const temporary = join(tmpdir(), "aishell-terraform");
8955
+ const temporaryFailure = await writableDirectory(temporary);
8956
+ if (temporaryFailure === void 0) {
8957
+ process.stderr.write(`terraform_install: the host cache at ${globalDir} is not writable (${failure}); using ${temporary}, which will not survive a reboot.\n`);
8958
+ return temporary;
8959
+ }
8960
+ 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\`.`);
8961
+ }
8962
+ /**
8963
+ * Create a directory and confirm it accepts a write.
8964
+ *
8965
+ * A directory that exists is not the same as one this process can write into:
8966
+ * a root-owned cache is present and read-only. The probe is a real file rather
8967
+ * than an access check, because what matters is whether a download will
8968
+ * succeed, not whether the mode bits look permissive.
8969
+ *
8970
+ * @param dir - the directory to test, created when absent.
8971
+ * @returns the reason it cannot be used, or `undefined` when it can.
8972
+ */
8973
+ async function writableDirectory(dir) {
8168
8974
  try {
8169
- await mkdir(globalDir, { recursive: true });
8170
- const testFile = join(globalDir, ".write-test");
8171
- await writeFile(testFile, "");
8975
+ await mkdir(dir, { recursive: true });
8976
+ const probe = join(dir, ".write-test");
8977
+ await writeFile(probe, "");
8172
8978
  const { unlink } = await import("node:fs/promises");
8173
- await unlink(testFile);
8174
- return globalDir;
8175
- } catch {
8176
- const depDir = join(deployment, ".terraform", "bin");
8177
- await mkdir(depDir, { recursive: true });
8178
- return depDir;
8979
+ await unlink(probe);
8980
+ return void 0;
8981
+ } catch (error) {
8982
+ return error instanceof Error ? error.message : String(error);
8179
8983
  }
8180
8984
  }
8181
8985
  function downloadError(kind, message) {
@@ -8643,8 +9447,9 @@ function apply(ctx, config) {
8643
9447
  });
8644
9448
  const { registrar, captured } = createRegistrar();
8645
9449
  registerAllTools(registrar);
9450
+ const workingDirectory = () => ctx.get("workingDirectory");
8646
9451
  const disposers = captured.map((tool) => {
8647
- const definition = toToolDefinition(tool, config.toolCallTimeoutMs.get());
9452
+ const definition = toToolDefinition(tool, config.toolCallTimeoutMs.get(), { ensure: (agent, signal) => requireSessionDirectories(workingDirectory()).ensure(agent, signal) });
8648
9453
  return ctx.tools.register(definition);
8649
9454
  });
8650
9455
  ctx.effect(() => () => {
@@ -8679,6 +9484,21 @@ function apply(ctx, config) {
8679
9484
  forgetAccount();
8680
9485
  }), "aishell-deploy: credential cache");
8681
9486
  }
9487
+ /**
9488
+ * The service when mounted, or one that reports its absence.
9489
+ *
9490
+ * `toToolDefinition` is built once, when the plugin activates, so a service
9491
+ * mounted later would never be seen if the value were captured. Returning a
9492
+ * wrapper keeps the lookup live: each call asks the context, which is the only
9493
+ * thing that knows what is mounted *now*.
9494
+ *
9495
+ * @param service - the service as it stands at this moment.
9496
+ * @returns the service, or a stand-in whose `ensure` refuses.
9497
+ */
9498
+ function requireSessionDirectories(service) {
9499
+ if (service !== void 0) return service;
9500
+ return { ensure: () => Promise.reject(new Error("the host offers no working-directory service")) };
9501
+ }
8682
9502
 
8683
9503
  //#endregion
8684
9504
  export { Config, apply, inject, name };