@elementumai/edk 0.9.19 → 0.9.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +146 -6
  2. package/dist-sdk/src/catalog/factories.d.ts +24 -1
  3. package/dist-sdk/src/catalog/factories.js +30 -0
  4. package/dist-sdk/src/catalog/from-authoring.d.ts +13 -8
  5. package/dist-sdk/src/catalog/from-authoring.js +34 -9
  6. package/dist-sdk/src/catalog/index.d.ts +2 -2
  7. package/dist-sdk/src/catalog/index.js +2 -2
  8. package/dist-sdk/src/catalog/render.js +6 -6
  9. package/dist-sdk/src/catalog/token.js +7 -0
  10. package/dist-sdk/src/catalog/types.d.ts +34 -1
  11. package/dist-sdk/src/catalog/types.js +11 -0
  12. package/dist-sdk/src/core/triggers/on-demand.d.ts +39 -3
  13. package/dist-sdk/src/core/triggers/on-demand.js +10 -2
  14. package/dist-sdk/src/engine/build/context.d.ts +1 -1
  15. package/dist-sdk/src/engine/ei/run.d.ts +149 -0
  16. package/dist-sdk/src/engine/ei/run.js +1132 -0
  17. package/dist-sdk/src/engine/logging.d.ts +17 -0
  18. package/dist-sdk/src/engine/logging.js +18 -0
  19. package/dist-sdk/src/engine/pull/ref-only.d.ts +5 -0
  20. package/dist-sdk/src/engine/pull/ref-only.js +10 -7
  21. package/dist-sdk/src/engine/pull/result-output.d.ts +6 -0
  22. package/dist-sdk/src/engine/pull/result-output.js +87 -3
  23. package/dist-sdk/src/engine/tf/expr.js +1 -1
  24. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  25. package/dist-sdk/src/engine/tf/index.js +1 -1
  26. package/dist-sdk/src/engine/tf/labels.d.ts +6 -0
  27. package/dist-sdk/src/engine/tf/labels.js +9 -0
  28. package/dist-sdk/src/engine/tf/model.d.ts +22 -1
  29. package/dist-sdk/src/engine/tf/parse.js +92 -4
  30. package/dist-sdk/src/engine/tf/render.d.ts +4 -2
  31. package/dist-sdk/src/engine/tf/render.js +41 -7
  32. package/dist-sdk/src/engine/validation.d.ts +39 -0
  33. package/dist-sdk/src/engine/validation.js +85 -0
  34. package/dist-sdk/src/entities/access-policy/to-tf.js +5 -2
  35. package/dist-sdk/src/entities/agent/build.d.ts +4 -16
  36. package/dist-sdk/src/entities/agent/build.js +40 -5
  37. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +4 -2
  38. package/dist-sdk/src/entities/agent/to-tf.js +6 -3
  39. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  40. package/dist-sdk/src/entities/agent-tool/from-tf.js +7 -1
  41. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  42. package/dist-sdk/src/entities/agent-tool/to-tf.js +27 -5
  43. package/dist-sdk/src/entities/app/build.d.ts +89 -20
  44. package/dist-sdk/src/entities/app/build.js +51 -6
  45. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +16 -0
  46. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  47. package/dist-sdk/src/entities/app/from-tf.js +7 -2
  48. package/dist-sdk/src/entities/app/index.d.ts +6 -6
  49. package/dist-sdk/src/entities/app/index.js +1 -0
  50. package/dist-sdk/src/entities/app/module.js +5 -2
  51. package/dist-sdk/src/entities/app/to-tf.js +19 -11
  52. package/dist-sdk/src/entities/automation/build.d.ts +47 -5
  53. package/dist-sdk/src/entities/automation/build.js +137 -20
  54. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +24 -1
  55. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +314 -39
  56. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  57. package/dist-sdk/src/entities/automation/from-tf.js +428 -48
  58. package/dist-sdk/src/entities/automation/generated/task-output-contracts.d.ts +33 -0
  59. package/dist-sdk/src/entities/automation/generated/task-output-contracts.js +183 -0
  60. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  61. package/dist-sdk/src/entities/automation/index.js +1 -1
  62. package/dist-sdk/src/entities/automation/module.js +37 -8
  63. package/dist-sdk/src/entities/automation/output-field-types.d.ts +7 -0
  64. package/dist-sdk/src/entities/automation/output-field-types.js +36 -0
  65. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +9 -0
  66. package/dist-sdk/src/entities/automation/output-key-wire-name.js +13 -0
  67. package/dist-sdk/src/entities/automation/script-code.d.ts +17 -0
  68. package/dist-sdk/src/entities/automation/script-code.js +91 -5
  69. package/dist-sdk/src/entities/automation/system-ref-name.js +4 -0
  70. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +2 -0
  71. package/dist-sdk/src/entities/automation/task-output-labels.js +9 -0
  72. package/dist-sdk/src/entities/automation/tasks.d.ts +24 -2
  73. package/dist-sdk/src/entities/automation/tasks.js +38 -9
  74. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  75. package/dist-sdk/src/entities/automation/to-tf.js +489 -83
  76. package/dist-sdk/src/entities/automation/triggers.d.ts +4 -2
  77. package/dist-sdk/src/entities/automation/triggers.js +4 -0
  78. package/dist-sdk/src/entities/chart/to-tf.js +10 -3
  79. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +24 -31
  80. package/dist-sdk/src/entities/element/build.d.ts +25 -13
  81. package/dist-sdk/src/entities/element/build.js +4 -1
  82. package/dist-sdk/src/entities/element/from-tf.d.ts +11 -0
  83. package/dist-sdk/src/entities/element/from-tf.js +58 -1
  84. package/dist-sdk/src/entities/element/index.d.ts +5 -3
  85. package/dist-sdk/src/entities/element/index.js +1 -0
  86. package/dist-sdk/src/entities/element/module.js +9 -3
  87. package/dist-sdk/src/entities/element/to-tf.js +8 -2
  88. package/dist-sdk/src/entities/field/build.d.ts +14 -1
  89. package/dist-sdk/src/entities/field/build.js +3 -0
  90. package/dist-sdk/src/entities/field/from-tf.d.ts +1 -0
  91. package/dist-sdk/src/entities/field/from-tf.js +39 -1
  92. package/dist-sdk/src/entities/field/media-types.d.ts +6 -0
  93. package/dist-sdk/src/entities/field/media-types.js +30 -0
  94. package/dist-sdk/src/entities/field/module.js +1 -0
  95. package/dist-sdk/src/entities/field/to-tf.d.ts +23 -2
  96. package/dist-sdk/src/entities/field/to-tf.js +130 -14
  97. package/dist-sdk/src/entities/file-reader/from-tf.js +14 -5
  98. package/dist-sdk/src/entities/file-reader/module.js +1 -0
  99. package/dist-sdk/src/entities/file-reader/types.d.ts +2 -0
  100. package/dist-sdk/src/entities/file-reader/types.js +1 -1
  101. package/dist-sdk/src/entities/portal/build.d.ts +26 -0
  102. package/dist-sdk/src/entities/portal/build.js +37 -0
  103. package/dist-sdk/src/entities/portal/from-tf.d.ts +27 -0
  104. package/dist-sdk/src/entities/portal/from-tf.js +75 -0
  105. package/dist-sdk/src/entities/portal/index.d.ts +1 -0
  106. package/dist-sdk/src/entities/portal/index.js +1 -0
  107. package/dist-sdk/src/entities/portal/module.d.ts +3 -0
  108. package/dist-sdk/src/entities/portal/module.js +28 -0
  109. package/dist-sdk/src/entities/portal/to-tf.d.ts +12 -0
  110. package/dist-sdk/src/entities/portal/to-tf.js +73 -0
  111. package/dist-sdk/src/entities/portal/types.d.ts +1 -0
  112. package/dist-sdk/src/entities/portal/types.js +1 -0
  113. package/dist-sdk/src/entities/relationship/module.js +2 -0
  114. package/dist-sdk/src/entities/relationship/pair-check.d.ts +7 -0
  115. package/dist-sdk/src/entities/relationship/pair-check.js +68 -0
  116. package/dist-sdk/src/entities/relationship/to-tf.d.ts +2 -0
  117. package/dist-sdk/src/entities/relationship/to-tf.js +12 -3
  118. package/dist-sdk/src/entities/search-table/module.js +1 -0
  119. package/dist-sdk/src/entities/search-table/to-tf.d.ts +1 -0
  120. package/dist-sdk/src/entities/search-table/to-tf.js +1 -1
  121. package/dist-sdk/src/entities/service-account/build.d.ts +15 -2
  122. package/dist-sdk/src/entities/service-account/from-tf.d.ts +2 -4
  123. package/dist-sdk/src/entities/service-account/from-tf.js +17 -5
  124. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +56 -0
  125. package/dist-sdk/src/entities/service-account/role-fidelity.js +243 -0
  126. package/dist-sdk/src/entities/service-account/to-tf.d.ts +14 -0
  127. package/dist-sdk/src/entities/service-account/to-tf.js +17 -0
  128. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +1 -1
  129. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +5 -2
  130. package/dist-sdk/src/entities/shared/filters/ast.d.ts +8 -0
  131. package/dist-sdk/src/entities/shared/filters/index.d.ts +2 -0
  132. package/dist-sdk/src/entities/shared/filters/index.js +14 -4
  133. package/dist-sdk/src/entities/shared/filters/print.js +17 -1
  134. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +2 -0
  135. package/dist-sdk/src/entities/shared/filters/tf-codec.js +5 -1
  136. package/dist-sdk/src/entities/shared/filters/types.d.ts +9 -1
  137. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -5
  138. package/dist-sdk/src/entities/shared/types/field-types.js +4 -0
  139. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +2 -1
  140. package/dist-sdk/src/entities/skill/from-tf.js +66 -13
  141. package/dist-sdk/src/entities/skill/input-coverage.d.ts +7 -0
  142. package/dist-sdk/src/entities/skill/input-coverage.js +11 -0
  143. package/dist-sdk/src/entities/skill/to-tf.js +14 -4
  144. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  145. package/dist-sdk/src/entities/skill-tool/from-tf.js +8 -2
  146. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -2
  147. package/dist-sdk/src/entities/skill-tool/to-tf.js +27 -5
  148. package/dist-sdk/src/entities/table/catalog.d.ts +14 -0
  149. package/dist-sdk/src/entities/table/catalog.js +66 -0
  150. package/dist-sdk/src/entities/table/module.js +2 -1
  151. package/dist-sdk/src/entities/table/to-tf.js +2 -2
  152. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +49 -9
  153. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +71 -18
  154. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +19 -4
  155. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +82 -10
  156. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +53 -23
  157. package/dist-sdk/src/entities/view/agent-view-layout.js +1 -1
  158. package/dist-sdk/src/entities/view/from-tf.d.ts +3 -2
  159. package/dist-sdk/src/entities/view/from-tf.js +124 -12
  160. package/dist-sdk/src/entities/view/module.js +30 -3
  161. package/dist-sdk/src/entities/view/to-tf.d.ts +14 -1
  162. package/dist-sdk/src/entities/view/to-tf.js +67 -10
  163. package/dist-sdk/src/entities/view/types.d.ts +4 -15
  164. package/dist-sdk/src/entities/view/types.js +15 -15
  165. package/dist-sdk/src/entities/widget/build.d.ts +16 -1
  166. package/dist-sdk/src/entities/widget/build.js +11 -1
  167. package/dist-sdk/src/entities/widget/to-tf.js +34 -8
  168. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +16 -5
  169. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  170. package/dist-sdk/src/graph/index.d.ts +11 -0
  171. package/dist-sdk/src/graph/index.js +21 -0
  172. package/dist-sdk/src/graph/modules.js +2 -0
  173. package/dist-sdk/src/graph/types.d.ts +55 -2
  174. package/dist-sdk/src/internal/sdk-package.d.ts +1 -1
  175. package/dist-sdk/src/internal/sdk-package.js +1 -0
  176. package/package.json +10 -1
@@ -0,0 +1,1132 @@
1
+ /**
2
+ * Subprocess rules for the `ei` Go CLI (plan §4.8):
3
+ *
4
+ * - Pass-throughs (plan/apply/list): EDK owns both child streams and routes
5
+ * incoming messages to the output layer. stdio remains the transport to the
6
+ * user, but never bypasses EDK's timing/renderer boundary. One exception: a
7
+ * non-bridge pass-through with no caller-supplied streams, whose stdin and
8
+ * stdout are both a terminal, inherits the terminal so interactive `ei`
9
+ * prompts can draw themselves (#1146). Bridge mode (`plan`'s progress) and
10
+ * captures keep the pipes.
11
+ * - Export calls (file mode, results land in `.tf/in/`): ei's stdout is
12
+ * status text — routed to OUR progress stream (see `engine/progress.ts`), so
13
+ * an Elementum command's stdout stays one pure JSON summary whenever anything
14
+ * is actually reading it.
15
+ * - Capture calls (machine-consumed stdout, e.g. adoption's plan output):
16
+ * stdout captured bounded, stderr routed through EDK's diagnostics sink.
17
+ *
18
+ * ei owns auth (`ei auth login`) — Elementum sets no credentials and never talks
19
+ * to the platform itself.
20
+ */
21
+ import { spawn, spawnSync } from "node:child_process";
22
+ import { accessSync, closeSync, constants as fsConstants, openSync, readSync, statSync } from "node:fs";
23
+ import { homedir } from "node:os";
24
+ import { constants as osConstants } from "node:os";
25
+ import { delimiter, isAbsolute, join, resolve } from "node:path";
26
+ import { applyProgressEvent, incrementProgress, progressStream, resumeProgress, suspendProgress, updateProgress, withProgressBatch, writeProgress, writeTechnicalLog, writeUserOutput, writeUserPayload } from "../progress.js";
27
+ import { createLogWriter, parseBridgeLogEvent, parsePartialReadEvent, parseProgressEvent } from "../logging.js";
28
+ const runtimeLog = createLogWriter();
29
+ /** Shell convention for signal death: 128 + signal number (130 = SIGINT). */
30
+ function exitCodeFor(code, signal) {
31
+ if (code !== null)
32
+ return code;
33
+ if (signal !== null) {
34
+ const num = osConstants.signals[signal];
35
+ if (num !== undefined)
36
+ return 128 + num;
37
+ }
38
+ return 1;
39
+ }
40
+ export class EiRunError extends Error {
41
+ exitCode;
42
+ stderr;
43
+ constructor(message, exitCode, stderr) {
44
+ super(message);
45
+ this.exitCode = exitCode;
46
+ this.stderr = stderr;
47
+ this.name = "EiRunError";
48
+ }
49
+ }
50
+ /** Max captured stdout for export calls. Streams are a few MB at most; far
51
+ * beyond that means something is wrong — fail loudly rather than buffer. */
52
+ const CAPTURE_LIMIT_BYTES = 256 * 1024 * 1024;
53
+ const LOCAL_HELP_CAPTURE_LIMIT_BYTES = 256 * 1024;
54
+ const LOCAL_HELP_TIMEOUT_MS = 1_500;
55
+ let bridgeProfile;
56
+ /** Convert the provider's default tflog text sink into EDK technical logs. */
57
+ const TFLOG_LINE = /^time=(\S+)\s+level=(TRACE|DEBUG|INFO|WARN|ERROR)\s+msg="((?:\\.|[^"])*)"/;
58
+ const TOFU_TRANSIENT_LINE = /^.+: (Reading|Still reading|Read complete after|Preparing import|Importing|Import complete|Import complete after|Refreshing state|Still refreshing|Refresh complete after|Creating|Still creating|Creation complete after|Modifying|Still modifying|Modification complete after|Destroying|Still destroying|Destruction complete after)(?:\.\.\.|\s)/;
59
+ const ANSI_SEQUENCE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
60
+ function withoutAnsi(line) {
61
+ return line.replace(ANSI_SEQUENCE, "");
62
+ }
63
+ function normalizeTofuLogLevel(level, component, message) {
64
+ return component === "tofu" && TOFU_TRANSIENT_LINE.test(message) ? "DEBUG" : level;
65
+ }
66
+ function writeCapturedTechnicalLine(line, component = "provider") {
67
+ const trimmed = line.trimEnd();
68
+ if (trimmed === "")
69
+ return;
70
+ const match = TFLOG_LINE.exec(trimmed);
71
+ if (match !== null) {
72
+ const message = match[3].replace(/\\"/g, '"').replace(/\\\\/g, "\\");
73
+ const level = match[2] === "TRACE" ? "DEBUG" : match[2];
74
+ writeTechnicalLog(normalizeTofuLogLevel(level, component, message), component, message, match[1]);
75
+ return;
76
+ }
77
+ writeTechnicalLog(TOFU_TRANSIENT_LINE.test(trimmed) ? "DEBUG" : "INFO", component, trimmed);
78
+ }
79
+ /** OpenTofu writes its normal CLI transcript to stderr, but that transcript is
80
+ * user-facing output rather than a diagnostic. Keep it out of the structured
81
+ * log stream while still preserving the pull/adoption output boundary. */
82
+ function writeCapturedUserLine(line) {
83
+ const trimmed = line.trimEnd();
84
+ if (trimmed === "") {
85
+ writeUserOutput("\n");
86
+ return;
87
+ }
88
+ if (process.stdout.isTTY === true)
89
+ writeUserOutput(`${trimmed}\n`);
90
+ else
91
+ writeProgress(trimmed);
92
+ }
93
+ function writeCapturedStderrLine(line, component = "provider") {
94
+ if (TFLOG_LINE.test(line.trimEnd()))
95
+ writeCapturedTechnicalLine(line, component);
96
+ else
97
+ writeCapturedUserLine(line);
98
+ }
99
+ export function configureBridgeProfile(profile) {
100
+ bridgeProfile = profile;
101
+ }
102
+ export function configuredBridgeProfile() {
103
+ return bridgeProfile;
104
+ }
105
+ export function managedElementumRoot() {
106
+ return resolve(process.env["ELEMENTUM_HOME"] ?? join(homedir(), ".elementum"));
107
+ }
108
+ function managedEiPath() {
109
+ return join(managedElementumRoot(), "libexec", "elementum", "ei");
110
+ }
111
+ function isExecutableFile(path) {
112
+ try {
113
+ accessSync(path, fsConstants.X_OK);
114
+ return statSync(path).isFile();
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ /** Resolve `name` via PATH (and PATHEXT on Windows). Returns an absolute path. */
121
+ function findOnPath(name) {
122
+ const pathEnv = process.env["PATH"];
123
+ if (pathEnv === undefined || pathEnv === "")
124
+ return undefined;
125
+ const extensions = process.platform === "win32"
126
+ ? (process.env["PATHEXT"] ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((ext) => ext !== "")
127
+ : [];
128
+ for (const dir of pathEnv.split(delimiter)) {
129
+ if (dir === "")
130
+ continue;
131
+ const candidates = [join(dir, name), ...extensions.map((ext) => join(dir, name + ext))];
132
+ for (const candidate of candidates) {
133
+ if (isExecutableFile(candidate))
134
+ return resolve(candidate);
135
+ }
136
+ }
137
+ return undefined;
138
+ }
139
+ /**
140
+ * Resolve the private Go bridge.
141
+ *
142
+ * 1. `ELEMENTUM_BRIDGE_PATH` — explicit pin, always honored (relative paths
143
+ * resolve against cwd). Empty/whitespace is treated as unset.
144
+ * 2. Managed libexec — `~/.elementum/libexec/elementum/ei` (or `$ELEMENTUM_HOME/...`).
145
+ * Installed toolchains keep `ei` here, not on PATH (`~/.elementum/bin` only
146
+ * has `elementum`). Preferring this over PATH keeps the CLI on the
147
+ * version-locked train when a source-built or leftover `ei` is also on PATH.
148
+ * 3. PATH — OS-native lookup for `ei`. Used when there is no managed install
149
+ * (source-built bridge on PATH, no installer).
150
+ */
151
+ export function resolveEiBinary() {
152
+ const override = process.env["ELEMENTUM_BRIDGE_PATH"]?.trim();
153
+ if (override !== undefined && override !== "") {
154
+ return isAbsolute(override) ? override : resolve(override);
155
+ }
156
+ const managed = managedEiPath();
157
+ if (isExecutableFile(managed))
158
+ return managed;
159
+ const fromPath = findOnPath("ei");
160
+ if (fromPath !== undefined)
161
+ return fromPath;
162
+ throw new EiRunError(`Elementum bridge not found: managed binary is missing or not executable at ${managed}, and no \`ei\` on PATH. Add \`ei\` to PATH, set ELEMENTUM_BRIDGE_PATH, or rerun the Elementum installer`, null);
163
+ }
164
+ /**
165
+ * Resolve the OpenTofu binary shipped in the same managed Elementum train.
166
+ * Source development may explicitly select an engine for tests/local work;
167
+ * installed executions never fall back to a globally installed tofu binary.
168
+ */
169
+ export function resolveOpenTofuBinary() {
170
+ const external = process.env["ELEMENTUM_TERRAFORM_COMMAND"];
171
+ if (external !== undefined && external.trim() !== "")
172
+ return external;
173
+ const managed = join(managedElementumRoot(), "libexec", "elementum", "tofu");
174
+ try {
175
+ accessSync(managed, fsConstants.X_OK);
176
+ return managed;
177
+ }
178
+ catch {
179
+ throw new EiRunError(`managed OpenTofu is missing or not executable at ${managed}; rerun the Elementum installer`, null);
180
+ }
181
+ }
182
+ /**
183
+ * Whether the bridge will resolve the plan engine to OpenTofu. OpenTofu is
184
+ * the only supported engine for `-target-file`; keep the adoption fallback
185
+ * conservative when an explicit Terraform command or a PATH-only install is
186
+ * in use.
187
+ */
188
+ export function usesOpenTofuTargetFile() {
189
+ const binary = resolveBridgeOpenTofu();
190
+ if (binary === undefined)
191
+ return false;
192
+ // -target-file was added in OpenTofu 1.10. Do not infer support from the
193
+ // executable name: older OpenTofu installations and wrappers can resolve
194
+ // to a binary that does not implement the option.
195
+ const version = spawnSync(binary, ["version"], {
196
+ encoding: "utf8",
197
+ stdio: ["ignore", "pipe", "ignore"],
198
+ timeout: 1_500,
199
+ windowsHide: true,
200
+ });
201
+ if (version.status !== 0 || typeof version.stdout !== "string")
202
+ return false;
203
+ const match = /OpenTofu\s+v(\d+)\.(\d+)(?:\.(\d+))?/i.exec(version.stdout);
204
+ if (match === null)
205
+ return false;
206
+ const major = Number(match[1]);
207
+ const minor = Number(match[2]);
208
+ return major > 1 || (major === 1 && minor >= 10);
209
+ }
210
+ /**
211
+ * The OpenTofu the bridge plans with: `ELEMENTUM_TERRAFORM_COMMAND`, else the
212
+ * managed OpenTofu, else `tofu` on PATH. Undefined when none is executable.
213
+ */
214
+ export function resolveBridgeOpenTofu() {
215
+ const external = process.env["ELEMENTUM_TERRAFORM_COMMAND"]?.trim();
216
+ if (external !== undefined && external !== "") {
217
+ return isAbsolute(external) ? (isExecutableFile(external) ? external : undefined) : findOnPath(external);
218
+ }
219
+ const managed = join(managedElementumRoot(), "libexec", "elementum", "tofu");
220
+ return isExecutableFile(managed) ? managed : findOnPath("tofu");
221
+ }
222
+ function bridgeArgs(args) {
223
+ return bridgeProfile === undefined ? [...args] : ["--profile", bridgeProfile, ...args];
224
+ }
225
+ function bridgeEnv() {
226
+ const managedBin = join(managedElementumRoot(), "libexec", "elementum");
227
+ const path = process.env["PATH"];
228
+ const env = {
229
+ ...process.env,
230
+ PATH: path === undefined || path === "" ? managedBin : `${managedBin}:${path}`,
231
+ };
232
+ // The child usually writes through a pipe so EDK can arbitrate its output.
233
+ // Preserve the terminal's styling decision for commands such as
234
+ // `elementum list`; otherwise lipgloss sees the pipe and silently strips
235
+ // ANSI sequences.
236
+ if ((process.stdout.isTTY === true || process.stderr.isTTY === true) && env["NO_COLOR"] === undefined) {
237
+ env["CLICOLOR_FORCE"] ??= "1";
238
+ }
239
+ return env;
240
+ }
241
+ /** Forward terminal/process cancellation to the bridge and return its cleanup. */
242
+ function forwardSignalsToChild(child) {
243
+ const forwardSignal = (signal) => {
244
+ child.kill(signal);
245
+ };
246
+ process.once("SIGINT", forwardSignal);
247
+ process.once("SIGTERM", forwardSignal);
248
+ return () => {
249
+ process.off("SIGINT", forwardSignal);
250
+ process.off("SIGTERM", forwardSignal);
251
+ };
252
+ }
253
+ /**
254
+ * Windows has no kernel-level `#!` shebang interpretation (POSIX gets this
255
+ * for free from exec()), so a script-shaped `ELEMENTUM_BRIDGE_PATH`
256
+ * override — a real possibility, since that override is explicitly meant
257
+ * for local development bridges, not just compiled binaries — would fail to
258
+ * spawn there. Sniff the first line and, if it names an interpreter, run
259
+ * that interpreter with the script as its first argument instead. Cheap and
260
+ * a no-op everywhere else: the real managed binary is a PE/ELF/Mach-O file
261
+ * whose first bytes never start with "#!".
262
+ */
263
+ function spawnTarget(binary) {
264
+ const interpreter = process.platform === "win32" ? readShebangInterpreter(binary) : null;
265
+ return interpreter === null ? { command: binary, prefixArgs: [] } : { command: interpreter, prefixArgs: [binary] };
266
+ }
267
+ function readShebangInterpreter(path) {
268
+ let fd;
269
+ try {
270
+ fd = openSync(path, "r");
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ try {
276
+ const buffer = Buffer.alloc(256);
277
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, 0);
278
+ const head = buffer.toString("utf8", 0, bytesRead);
279
+ if (!head.startsWith("#!"))
280
+ return null;
281
+ const newline = head.indexOf("\n");
282
+ const line = (newline === -1 ? head.slice(2) : head.slice(2, newline)).trim();
283
+ const [interpreterPath = "", ...rest] = line.split(/\s+/);
284
+ const base = interpreterPath.split(/[\\/]/).pop() ?? interpreterPath;
285
+ if (base === "")
286
+ return null;
287
+ // "#!/usr/bin/env node" -> "node"; a direct "#!/bin/sh" is POSIX-only
288
+ // and unusable on win32, but resolveEiBinary()'s override is the
289
+ // caller's choice — surface whatever it names rather than guessing.
290
+ return base === "env" && rest[0] !== undefined ? rest[0] : base;
291
+ }
292
+ finally {
293
+ closeSync(fd);
294
+ }
295
+ }
296
+ function spawnBridge(args, options) {
297
+ const target = spawnTarget(resolveEiBinary());
298
+ return spawn(target.command, [...target.prefixArgs, ...bridgeArgs(args)], {
299
+ ...options,
300
+ env: { ...bridgeEnv(), ...(options.env ?? {}) },
301
+ });
302
+ }
303
+ /**
304
+ * Read Cobra's root help without auth/profile resolution. This deliberately
305
+ * bypasses bridgeArgs: root discovery must stay local even when the Elementum
306
+ * invocation includes a global --profile.
307
+ */
308
+ export function runEiLocalHelp() {
309
+ return new Promise((resolvePromise, reject) => {
310
+ let child;
311
+ try {
312
+ const target = spawnTarget(resolveEiBinary());
313
+ child = spawn(target.command, [...target.prefixArgs, "--help"], {
314
+ stdio: ["ignore", "pipe", "pipe"],
315
+ env: bridgeEnv(),
316
+ });
317
+ }
318
+ catch (error) {
319
+ reject(error);
320
+ return;
321
+ }
322
+ const stdout = [];
323
+ const stderr = [];
324
+ let size = 0;
325
+ let settled = false;
326
+ const finish = (result) => {
327
+ if (settled)
328
+ return;
329
+ settled = true;
330
+ clearTimeout(timer);
331
+ if ("error" in result)
332
+ reject(result.error);
333
+ else
334
+ resolvePromise(result.output);
335
+ };
336
+ const onData = (destination) => (chunk) => {
337
+ size += chunk.length;
338
+ if (size > LOCAL_HELP_CAPTURE_LIMIT_BYTES) {
339
+ child.kill();
340
+ finish({
341
+ error: new EiRunError(`ei --help output exceeded ${LOCAL_HELP_CAPTURE_LIMIT_BYTES} bytes`, null),
342
+ });
343
+ return;
344
+ }
345
+ destination.push(chunk);
346
+ };
347
+ const stopForwarding = forwardSignalsToChild(child);
348
+ child.stdout?.on("data", onData(stdout));
349
+ child.stderr?.on("data", onData(stderr));
350
+ child.on("error", (error) => {
351
+ stopForwarding();
352
+ finish({ error: wrapSpawnError(error) });
353
+ });
354
+ child.on("close", (code, signal) => {
355
+ stopForwarding();
356
+ const exit = exitCodeFor(code, signal);
357
+ if (exit !== 0) {
358
+ finish({
359
+ error: new EiRunError(`ei --help exited with code ${exit}`, exit),
360
+ });
361
+ return;
362
+ }
363
+ finish({ output: Buffer.concat(stdout).toString("utf8") });
364
+ });
365
+ const timer = setTimeout(() => {
366
+ child.kill();
367
+ finish({
368
+ error: new EiRunError(`ei --help exceeded the ${LOCAL_HELP_TIMEOUT_MS}ms discovery timeout`, null),
369
+ });
370
+ }, LOCAL_HELP_TIMEOUT_MS);
371
+ timer.unref();
372
+ });
373
+ }
374
+ /**
375
+ * Run a local (no auth, no profile) bridge command that reads `input` on stdin
376
+ * and returns stdout. Non-zero exit rejects with the captured stderr.
377
+ */
378
+ export function runEiLocalWithInput(args, input) {
379
+ return new Promise((resolvePromise, reject) => {
380
+ let child;
381
+ try {
382
+ const target = spawnTarget(resolveEiBinary());
383
+ child = spawn(target.command, [...target.prefixArgs, ...args], {
384
+ stdio: ["pipe", "pipe", "pipe"],
385
+ env: bridgeEnv(),
386
+ });
387
+ }
388
+ catch (error) {
389
+ reject(error);
390
+ return;
391
+ }
392
+ const stdout = [];
393
+ const stderr = [];
394
+ let size = 0;
395
+ let settled = false;
396
+ const finish = (result) => {
397
+ if (settled)
398
+ return;
399
+ settled = true;
400
+ if ("error" in result)
401
+ reject(result.error);
402
+ else
403
+ resolvePromise(result.output);
404
+ };
405
+ const onData = (destination) => (chunk) => {
406
+ size += chunk.length;
407
+ if (size > CAPTURE_LIMIT_BYTES) {
408
+ child.kill();
409
+ finish({ error: new EiRunError(`ei ${args[0] ?? ""} output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null) });
410
+ return;
411
+ }
412
+ destination.push(chunk);
413
+ };
414
+ const stopForwarding = forwardSignalsToChild(child);
415
+ child.stdout?.on("data", onData(stdout));
416
+ child.stderr?.on("data", onData(stderr));
417
+ child.stdin?.on("error", () => undefined);
418
+ child.on("error", (error) => {
419
+ stopForwarding();
420
+ finish({ error: wrapSpawnError(error) });
421
+ });
422
+ child.on("close", (code, signal) => {
423
+ stopForwarding();
424
+ const exit = exitCodeFor(code, signal);
425
+ if (exit !== 0) {
426
+ const message = Buffer.concat(stderr).toString("utf8");
427
+ finish({ error: new EiRunError(`ei ${args.join(" ")} exited with code ${exit}`, exit, message) });
428
+ return;
429
+ }
430
+ finish({ output: Buffer.concat(stdout).toString("utf8") });
431
+ });
432
+ child.stdin?.end(input, "utf8");
433
+ });
434
+ }
435
+ /**
436
+ * A person at a terminal may be answering an interactive `ei` prompt, such
437
+ * as the `auth login` form. Terminal UIs size and redraw themselves from
438
+ * their output terminal, so a pipe breaks them — hand the terminal over.
439
+ * Bridge mode still needs its progress events parsed, and explicit
440
+ * destinations are captures, so both keep EDK's pipes.
441
+ */
442
+ function passthroughNeedsTerminal(opts) {
443
+ return opts?.bridge !== true &&
444
+ opts?.stdout === undefined &&
445
+ opts?.stderr === undefined &&
446
+ process.stdin.isTTY === true &&
447
+ process.stdout.isTTY === true;
448
+ }
449
+ /**
450
+ * Run `ei` with EDK-owned streaming and return its exit code. The caller (a
451
+ * CLI pass-through) should `process.exit(code)` with it. Output is streamed
452
+ * rather than buffered so large OpenTofu plans do not hit a capture limit or
453
+ * deadlock the child. An interactive terminal run hands the child the
454
+ * terminal instead (see {@link passthroughNeedsTerminal}).
455
+ */
456
+ export function runEiPassthrough(args, opts) {
457
+ return new Promise((resolvePromise, reject) => {
458
+ let child;
459
+ try {
460
+ // `ei apply` decides whether it may prompt by inspecting stdin. Keep
461
+ // the parent's stdin attached so a real terminal remains interactive;
462
+ // pipes and redirected input still correctly make it non-interactive.
463
+ const stdio = passthroughNeedsTerminal(opts) ? "inherit" : ["inherit", "pipe", "pipe"];
464
+ child = spawnBridge(opts?.bridge === true ? ["--bridge", ...args] : args, { stdio, cwd: opts?.cwd });
465
+ }
466
+ catch (error) {
467
+ reject(error);
468
+ return;
469
+ }
470
+ const countedTofuProgress = new Set();
471
+ const loggedTofuLines = new Set();
472
+ const logTofuLifecycle = (line) => {
473
+ const plain = withoutAnsi(line).trim();
474
+ if (plain === "" || loggedTofuLines.has(plain))
475
+ return;
476
+ loggedTofuLines.add(plain);
477
+ writeTechnicalLog("DEBUG", "tofu", plain);
478
+ };
479
+ const output = Promise.all([
480
+ routeEiOutput(child.stdout, opts?.stdout ?? process.stdout, opts?.bridge === true ? (line) => {
481
+ const plain = withoutAnsi(line);
482
+ const event = parseProgressEvent(line);
483
+ if (event !== undefined) {
484
+ withProgressBatch(() => {
485
+ applyProgressEvent(withPlanProgressTotal(event, opts?.progressTotal));
486
+ const progressEvent = tofuProgressEvent(event.label);
487
+ if (progressEvent !== undefined)
488
+ countTofuProgress(progressEvent.phase, progressEvent.address, countedTofuProgress);
489
+ });
490
+ return true;
491
+ }
492
+ const log = parseBridgeLogEvent(line);
493
+ if (log !== undefined) {
494
+ if (log.component === "tofu") {
495
+ const key = log.message.trim();
496
+ if (loggedTofuLines.has(key))
497
+ return true;
498
+ loggedTofuLines.add(key);
499
+ }
500
+ writeTechnicalLog(normalizeTofuLogLevel(log.level, log.component, log.message), log.component, log.message, log.timestamp, log.text_effects);
501
+ return true;
502
+ }
503
+ if (TOFU_TRANSIENT_LINE.test(plain)) {
504
+ updateTofuProgress(plain, countedTofuProgress);
505
+ logTofuLifecycle(plain);
506
+ return true;
507
+ }
508
+ if (TFLOG_LINE.test(plain)) {
509
+ writeCapturedTechnicalLine(line);
510
+ return true;
511
+ }
512
+ // A bridge-versioned ei may still emit ordinary user-facing text
513
+ // (for example "Using tofu") on stdout. Preserve it verbatim.
514
+ return false;
515
+ } : undefined, writeUserPayload),
516
+ routeEiOutput(child.stderr, opts?.stderr ?? process.stderr, opts?.bridge === true ? (line) => {
517
+ const plain = withoutAnsi(line);
518
+ const event = parseProgressEvent(line);
519
+ if (event !== undefined) {
520
+ withProgressBatch(() => {
521
+ applyProgressEvent(withPlanProgressTotal(event, opts?.progressTotal));
522
+ const progressEvent = tofuProgressEvent(event.label);
523
+ if (progressEvent !== undefined)
524
+ countTofuProgress(progressEvent.phase, progressEvent.address, countedTofuProgress);
525
+ });
526
+ return true;
527
+ }
528
+ const log = parseBridgeLogEvent(line);
529
+ if (log !== undefined) {
530
+ if (log.component === "tofu") {
531
+ const key = log.message.trim();
532
+ if (loggedTofuLines.has(key))
533
+ return true;
534
+ loggedTofuLines.add(key);
535
+ }
536
+ writeTechnicalLog(normalizeTofuLogLevel(log.level, log.component, log.message), log.component, log.message, log.timestamp, log.text_effects);
537
+ return true;
538
+ }
539
+ if (TOFU_TRANSIENT_LINE.test(plain)) {
540
+ updateTofuProgress(plain, countedTofuProgress);
541
+ logTofuLifecycle(plain);
542
+ return true;
543
+ }
544
+ if (TFLOG_LINE.test(plain)) {
545
+ writeCapturedTechnicalLine(line);
546
+ return true;
547
+ }
548
+ // OpenTofu and ei can write a human-readable transcript to stderr.
549
+ // It is user output, not a protocol failure; move it to EDK stdout
550
+ // without reformatting or inventing an ERROR log.
551
+ // Preserve unrecognized stderr through the writer callback so the
552
+ // caller-selected stderr destination is retained.
553
+ return false;
554
+ } : undefined, writeUserPayload),
555
+ ]);
556
+ const forwardSignal = (signal) => child.kill(signal);
557
+ process.once("SIGINT", forwardSignal);
558
+ process.once("SIGTERM", forwardSignal);
559
+ child.on("error", (e) => reject(wrapSpawnError(e)));
560
+ child.on("close", async (code, signal) => {
561
+ process.off("SIGINT", forwardSignal);
562
+ process.off("SIGTERM", forwardSignal);
563
+ try {
564
+ await output;
565
+ resolvePromise(exitCodeFor(code, signal));
566
+ }
567
+ catch (error) {
568
+ reject(error);
569
+ }
570
+ });
571
+ });
572
+ }
573
+ function withPlanProgressTotal(event, total) {
574
+ if (total === undefined || (event.operation !== "plan" && event.operation !== "tofu_plan") || event.total !== undefined)
575
+ return event;
576
+ // The command knows the number of generated blocks before starting ei.
577
+ // Older bridges announce the plan section without repeating that total;
578
+ // retain a determinate EDK progress bar instead of downgrading to a spinner.
579
+ return { ...event, total };
580
+ }
581
+ /** Partial reads reported by bridge exports since the last take (docs/design/graphql-error-standard.md). */
582
+ const recordedPartialReads = [];
583
+ /** Returns and clears the partial reads reported by `runEiWithStatus` exports. */
584
+ export function takePartialReads() {
585
+ return recordedPartialReads.splice(0);
586
+ }
587
+ /**
588
+ * Run `ei` with EDK-owned streaming: stdout (status text) is routed to OUR
589
+ * progress stream and stderr to the diagnostics sink. For file-mode export
590
+ * calls — the caller's own stdout stays a single JSON summary whenever it is
591
+ * piped.
592
+ */
593
+ export function runEiWithStatus(args, opts) {
594
+ return new Promise((resolvePromise, reject) => {
595
+ // `apply` may own the terminal (and stdin) for prompts. A live status line
596
+ // must give it the terminal back instead of racing its cursor updates.
597
+ if (opts?.bridge !== true)
598
+ suspendProgress();
599
+ let child;
600
+ try {
601
+ child = spawnBridge(opts?.bridge === true ? ["--bridge", ...args] : args, {
602
+ stdio: ["ignore", "pipe", "pipe"],
603
+ cwd: opts?.cwd,
604
+ env: opts?.env,
605
+ });
606
+ }
607
+ catch (error) {
608
+ resumeProgress();
609
+ reject(error);
610
+ return;
611
+ }
612
+ const loggedTofuLines = new Set();
613
+ const countedTofuProgress = new Set();
614
+ const consumeNonBridgeTofuLine = (line) => {
615
+ const plain = withoutAnsi(line);
616
+ const key = plain.trim();
617
+ if (key === "" || loggedTofuLines.has(key))
618
+ return false;
619
+ if (TOFU_TRANSIENT_LINE.test(plain) || TFLOG_LINE.test(plain)) {
620
+ loggedTofuLines.add(key);
621
+ if (TOFU_TRANSIENT_LINE.test(plain))
622
+ updateTofuProgress(plain, countedTofuProgress);
623
+ writeCapturedTechnicalLine(plain, "tofu");
624
+ return true;
625
+ }
626
+ return false;
627
+ };
628
+ const userOutput = opts?.userOutput ?? (process.stdout.isTTY === true ? process.stdout : progressStream());
629
+ const output = Promise.all([
630
+ routeEiOutput(child.stdout, process.stdout, opts?.bridge === true ? (line) => {
631
+ const event = parseProgressEvent(line);
632
+ if (event !== undefined) {
633
+ withProgressBatch(() => {
634
+ applyProgressEvent(event);
635
+ const progressEvent = tofuProgressEvent(event.label);
636
+ if (progressEvent !== undefined)
637
+ countTofuProgress(progressEvent.phase, progressEvent.address, countedTofuProgress);
638
+ });
639
+ opts.onProgress?.(event);
640
+ return true;
641
+ }
642
+ if (!TFLOG_LINE.test(line))
643
+ return false;
644
+ writeCapturedTechnicalLine(line);
645
+ return true;
646
+ } : consumeNonBridgeTofuLine, (text, destination) => writeUserOutput(text, opts?.bridge === true ? userOutput : destination)),
647
+ routeEiOutput(child.stderr, process.stderr, opts?.bridge === true ? (line) => {
648
+ const event = parseProgressEvent(line);
649
+ if (event !== undefined) {
650
+ applyProgressEvent(event);
651
+ opts.onProgress?.(event);
652
+ return true;
653
+ }
654
+ if (TFLOG_LINE.test(line)) {
655
+ writeCapturedTechnicalLine(line);
656
+ return true;
657
+ }
658
+ const partialRead = parsePartialReadEvent(line);
659
+ if (partialRead !== undefined) {
660
+ recordedPartialReads.push(partialRead);
661
+ return true;
662
+ }
663
+ const log = parseBridgeLogEvent(line);
664
+ if (log !== undefined) {
665
+ writeTechnicalLog(normalizeTofuLogLevel(log.level, log.component, log.message), log.component, log.message, log.timestamp, log.text_effects);
666
+ return true;
667
+ }
668
+ writeUserOutput(`${line}\n`, userOutput);
669
+ return true;
670
+ } : consumeNonBridgeTofuLine, (text, destination) => writeUserOutput(text, opts?.bridge === true ? userOutput : destination)),
671
+ ]);
672
+ child.on("error", (e) => {
673
+ resumeProgress();
674
+ reject(wrapSpawnError(e));
675
+ });
676
+ child.on("close", (code, signal) => {
677
+ const exit = exitCodeFor(code, signal);
678
+ void output.then(() => {
679
+ resumeProgress();
680
+ if (exit !== 0) {
681
+ reject(new EiRunError(`ei ${args.join(" ")} exited with code ${exit}`, exit));
682
+ return;
683
+ }
684
+ resolvePromise();
685
+ }, (error) => {
686
+ resumeProgress();
687
+ reject(error);
688
+ });
689
+ });
690
+ });
691
+ }
692
+ /**
693
+ * Run the managed OpenTofu binary while reserving a piped stdout for the
694
+ * Elementum command's single result. Arguments are passed directly, never
695
+ * through a shell, so provider source addresses cannot be reinterpreted.
696
+ */
697
+ export function runOpenTofuWithStatus(args, opts) {
698
+ return new Promise((resolvePromise, reject) => {
699
+ let stderrPending = "";
700
+ let child;
701
+ try {
702
+ child = spawn(resolveOpenTofuBinary(), [...args], {
703
+ stdio: ["ignore", progressStream(), "pipe"],
704
+ cwd: opts?.cwd,
705
+ env: bridgeEnv(),
706
+ });
707
+ }
708
+ catch (error) {
709
+ reject(error);
710
+ return;
711
+ }
712
+ const stopForwarding = forwardSignalsToChild(child);
713
+ child.stderr?.on("data", (chunk) => {
714
+ stderrPending += chunk.toString("utf8");
715
+ const lines = stderrPending.split("\n");
716
+ stderrPending = lines.pop() ?? "";
717
+ for (const line of lines)
718
+ writeCapturedStderrLine(line, "tofu");
719
+ });
720
+ child.on("error", (error) => {
721
+ stopForwarding();
722
+ reject(wrapOpenTofuSpawnError(error));
723
+ });
724
+ child.on("close", (code, signal) => {
725
+ stopForwarding();
726
+ if (stderrPending.trim() !== "")
727
+ writeCapturedStderrLine(stderrPending, "tofu");
728
+ const exit = exitCodeFor(code, signal);
729
+ if (exit !== 0) {
730
+ reject(new EiRunError(`managed OpenTofu exited with code ${exit}`, exit));
731
+ return;
732
+ }
733
+ resolvePromise();
734
+ });
735
+ });
736
+ }
737
+ /** Capture bounded, machine-consumed OpenTofu stdout while preserving stderr. */
738
+ export function runOpenTofuCapture(args, opts) {
739
+ return new Promise((resolvePromise, reject) => {
740
+ let child;
741
+ try {
742
+ child = spawn(opts?.binary ?? resolveOpenTofuBinary(), [...args], {
743
+ stdio: ["ignore", "pipe", "pipe"],
744
+ cwd: opts?.cwd,
745
+ env: bridgeEnv(),
746
+ });
747
+ }
748
+ catch (error) {
749
+ reject(error);
750
+ return;
751
+ }
752
+ const chunks = [];
753
+ const stderrChunks = [];
754
+ let size = 0;
755
+ let settled = false;
756
+ const stopForwarding = forwardSignalsToChild(child);
757
+ const collect = (destination, echo) => (chunk) => {
758
+ if (settled)
759
+ return;
760
+ size += chunk.length;
761
+ if (size > CAPTURE_LIMIT_BYTES) {
762
+ settled = true;
763
+ stopForwarding();
764
+ child.kill();
765
+ reject(new EiRunError(`managed OpenTofu output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null));
766
+ return;
767
+ }
768
+ destination.push(chunk);
769
+ if (echo)
770
+ progressStream().write(chunk);
771
+ };
772
+ child.stdout?.on("data", collect(chunks, false));
773
+ child.stderr?.on("data", collect(stderrChunks, opts?.suppressStderr !== true));
774
+ child.on("error", (error) => {
775
+ stopForwarding();
776
+ if (settled)
777
+ return;
778
+ settled = true;
779
+ reject(wrapOpenTofuSpawnError(error));
780
+ });
781
+ child.on("close", (code, signal) => {
782
+ stopForwarding();
783
+ if (settled)
784
+ return;
785
+ settled = true;
786
+ const exit = exitCodeFor(code, signal);
787
+ const stderr = Buffer.concat(stderrChunks).toString("utf8");
788
+ if (exit !== 0) {
789
+ reject(new EiRunError(`managed OpenTofu exited with code ${exit}`, exit, stderr));
790
+ return;
791
+ }
792
+ resolvePromise(Buffer.concat(chunks).toString("utf8"));
793
+ });
794
+ });
795
+ }
796
+ /**
797
+ * Run `ei` capturing stdout (the machine-consumed stream); stderr is routed by
798
+ * EDK to the diagnostics sink. Non-zero exit rejects — partial output must be
799
+ * discarded.
800
+ *
801
+ * `echoStdout` additionally tees stdout to OUR stderr as it arrives, for long
802
+ * captured commands whose output is also the user's only progress signal
803
+ * (adoption's `ei plan`). It never moves anything onto our stdout, so the
804
+ * caller's single-JSON-summary contract holds.
805
+ */
806
+ export function runEiCapture(args, opts) {
807
+ return new Promise((resolvePromise, reject) => {
808
+ let child;
809
+ try {
810
+ child = spawnBridge(args, {
811
+ stdio: ["ignore", "pipe", "pipe"],
812
+ cwd: opts?.cwd,
813
+ });
814
+ }
815
+ catch (error) {
816
+ reject(error);
817
+ return;
818
+ }
819
+ const chunks = [];
820
+ const stderrChunks = [];
821
+ let size = 0;
822
+ let settled = false;
823
+ let tofuPending = "";
824
+ let stderrPending = "";
825
+ const startedTofuAddresses = new Set();
826
+ const completedTofuAddresses = new Set();
827
+ const countedTofuProgress = new Set();
828
+ const consumeTofuLine = (line) => {
829
+ const event = parseTofuJsonEvent(line);
830
+ if (event.type === "diagnostic") {
831
+ writeTechnicalLog(normalizeTofuLogLevel(event.level, "tofu", event.message), "tofu", event.message);
832
+ return;
833
+ }
834
+ if ((event.type !== "refresh_start" && event.type !== "refresh_complete") ||
835
+ !opts?.tofuJsonProgress?.expectedAddresses.has(event.address))
836
+ return;
837
+ if (event.type === "refresh_start") {
838
+ if (startedTofuAddresses.has(event.address))
839
+ return;
840
+ startedTofuAddresses.add(event.address);
841
+ updateProgress(`Refreshing state: ${event.address}`);
842
+ writeTechnicalLog("DEBUG", "tofu", event.message ?? `${event.address}: Refreshing state...`);
843
+ return;
844
+ }
845
+ if (completedTofuAddresses.has(event.address))
846
+ return;
847
+ completedTofuAddresses.add(event.address);
848
+ incrementProgress();
849
+ };
850
+ const onData = (destination, echoTo) => (chunk) => {
851
+ if (settled)
852
+ return;
853
+ size += chunk.length;
854
+ if (size > CAPTURE_LIMIT_BYTES) {
855
+ settled = true;
856
+ child.kill();
857
+ reject(new EiRunError(`ei ${args[0] ?? ""} output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null));
858
+ return;
859
+ }
860
+ destination.push(chunk);
861
+ if (opts?.tofuJsonProgress !== undefined && destination === chunks) {
862
+ tofuPending += chunk.toString("utf8");
863
+ const lines = tofuPending.split("\n");
864
+ tofuPending = lines.pop() ?? "";
865
+ for (const line of lines)
866
+ consumeTofuLine(line);
867
+ }
868
+ else if (echoTo === "stdout") {
869
+ tofuPending += chunk.toString("utf8");
870
+ const lines = tofuPending.split("\n");
871
+ tofuPending = lines.pop() ?? "";
872
+ for (const line of lines)
873
+ updateTofuProgress(line, countedTofuProgress);
874
+ }
875
+ if (echoTo === "stdout" && opts?.tofuJsonProgress === undefined) {
876
+ if (process.stdout.isTTY === true)
877
+ writeUserOutput(chunk.toString("utf8"));
878
+ else
879
+ progressStream().write(chunk);
880
+ }
881
+ else if (echoTo === "stderr") {
882
+ stderrPending += chunk.toString("utf8");
883
+ const lines = stderrPending.split("\n");
884
+ stderrPending = lines.pop() ?? "";
885
+ for (const line of lines)
886
+ writeCapturedStderrLine(line);
887
+ }
888
+ };
889
+ child.stdout?.on("data", onData(chunks, opts?.echoStdout === true ? "stdout" : undefined));
890
+ child.stderr?.on("data", onData(stderrChunks, opts?.suppressStderr === true ? undefined : "stderr"));
891
+ child.on("error", (e) => {
892
+ if (settled)
893
+ return;
894
+ settled = true;
895
+ reject(wrapSpawnError(e));
896
+ });
897
+ child.on("close", (code, signal) => {
898
+ if (settled)
899
+ return;
900
+ settled = true;
901
+ if (opts?.tofuJsonProgress !== undefined && tofuPending.trim() !== "")
902
+ consumeTofuLine(tofuPending);
903
+ if (stderrPending.trim() !== "")
904
+ writeCapturedStderrLine(stderrPending);
905
+ const exit = exitCodeFor(code, signal);
906
+ const stderr = Buffer.concat(stderrChunks).toString("utf8");
907
+ if (exit !== 0) {
908
+ reject(new EiRunError(`ei ${args.join(" ")} exited with code ${exit} — discarding output`, exit, stderr));
909
+ return;
910
+ }
911
+ resolvePromise(Buffer.concat(chunks).toString("utf8"));
912
+ });
913
+ });
914
+ }
915
+ /** Parse the stable subset of OpenTofu's line-delimited JSON UI used by adoption. */
916
+ export function parseTofuJsonEvent(line) {
917
+ try {
918
+ const value = JSON.parse(line);
919
+ if (typeof value !== "object" || value === null)
920
+ return { type: "other" };
921
+ const event = value;
922
+ if (event.type === "refresh_start" || event.type === "refresh_complete") {
923
+ const hook = event.hook;
924
+ if (typeof hook !== "object" || hook === null)
925
+ return { type: "other" };
926
+ const resource = hook.resource;
927
+ if (typeof resource !== "object" || resource === null)
928
+ return { type: "other" };
929
+ const address = resource.addr;
930
+ if (typeof address !== "string")
931
+ return { type: "other" };
932
+ const message = event["@message"];
933
+ return typeof message === "string" ? { type: event.type, address, message } : { type: event.type, address };
934
+ }
935
+ if (event.type === "diagnostic") {
936
+ const diagnostic = event.diagnostic;
937
+ if (typeof diagnostic !== "object" || diagnostic === null)
938
+ return { type: "other" };
939
+ const fields = diagnostic;
940
+ if (typeof fields.summary !== "string")
941
+ return { type: "other" };
942
+ const detail = typeof fields.detail === "string" && fields.detail !== "" ? `: ${fields.detail}` : "";
943
+ const level = fields.severity === "error" ? "ERROR" : fields.severity === "warning" ? "WARN" : "INFO";
944
+ return { type: "diagnostic", level, message: fields.summary + detail };
945
+ }
946
+ return { type: "other" };
947
+ }
948
+ catch {
949
+ return { type: "other" };
950
+ }
951
+ }
952
+ const TOFU_PROGRESS_LINE = /^(.+?): (Reading|Still reading|Preparing import|Importing|Refreshing state|Still refreshing|Read complete after|Import complete after|Refresh complete after|Creating|Still creating|Creation complete after|Modifying|Still modifying|Modification complete after|Destroying|Still destroying|Destruction complete after)\b/;
953
+ const TOFU_PROGRESS_EVENT_LABEL = /^(Reading|Still reading|Preparing import|Importing|Refreshing state|Still refreshing|Read complete after|Import complete after|Refresh complete after|Creating|Still creating|Creation complete after|Modifying|Still modifying|Modification complete after|Destroying|Still destroying|Destruction complete after):\s+(.+)$/;
954
+ const TOFU_PROGRESS_STARTS = new Set([
955
+ "Reading", "Preparing import", "Importing", "Refreshing state",
956
+ "Creating", "Modifying", "Destroying",
957
+ ]);
958
+ const TOFU_PROGRESS_COMPLETIONS = new Set([
959
+ "Read complete after", "Import complete after", "Refresh complete after",
960
+ "Creation complete after", "Modification complete after", "Destruction complete after",
961
+ ]);
962
+ function tofuProgressEvent(label) {
963
+ if (label === undefined)
964
+ return undefined;
965
+ const match = TOFU_PROGRESS_EVENT_LABEL.exec(label);
966
+ return match === null ? undefined : { phase: match[1], address: match[2] };
967
+ }
968
+ function countTofuProgress(phase, address, counted) {
969
+ if (!TOFU_PROGRESS_STARTS.has(phase) && !TOFU_PROGRESS_COMPLETIONS.has(phase))
970
+ return;
971
+ if (counted.has(address))
972
+ return;
973
+ counted.add(address);
974
+ incrementProgress();
975
+ }
976
+ /** Best-effort adapter for OpenTofu's user-facing progress stream. */
977
+ function updateTofuProgress(line, counted) {
978
+ const clean = line.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim();
979
+ const match = TOFU_PROGRESS_LINE.exec(clean);
980
+ if (match === null)
981
+ return;
982
+ const address = match[1];
983
+ const phase = match[2];
984
+ updateProgress(`${phase}: ${address}`);
985
+ // OpenTofu starts many reads/refreshes concurrently. Count the first start
986
+ // so the bar moves while work is actually being processed; completion is a
987
+ // fallback for a stream that omitted the corresponding start line.
988
+ countTofuProgress(phase, address, counted);
989
+ }
990
+ /** Capture both bridge output streams for small machine-inspection commands. */
991
+ export function runEiCaptureCombined(args, opts) {
992
+ return new Promise((resolvePromise, reject) => {
993
+ let child;
994
+ try {
995
+ child = spawnBridge(args, {
996
+ stdio: ["ignore", "pipe", "pipe"],
997
+ cwd: opts?.cwd,
998
+ });
999
+ }
1000
+ catch (error) {
1001
+ reject(error);
1002
+ return;
1003
+ }
1004
+ const chunks = [];
1005
+ let size = 0;
1006
+ const onData = (chunk) => {
1007
+ size += chunk.length;
1008
+ if (size > CAPTURE_LIMIT_BYTES) {
1009
+ child.kill();
1010
+ reject(new EiRunError(`ei ${args[0] ?? ""} output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null));
1011
+ return;
1012
+ }
1013
+ chunks.push(chunk);
1014
+ };
1015
+ const stopForwarding = forwardSignalsToChild(child);
1016
+ child.stdout?.on("data", onData);
1017
+ child.stderr?.on("data", onData);
1018
+ child.on("error", (e) => {
1019
+ stopForwarding();
1020
+ reject(wrapSpawnError(e));
1021
+ });
1022
+ child.on("close", (code, signal) => {
1023
+ stopForwarding();
1024
+ const exit = exitCodeFor(code, signal);
1025
+ if (exit !== 0) {
1026
+ reject(new EiRunError(`ei ${args.join(" ")} exited with code ${exit}`, exit));
1027
+ return;
1028
+ }
1029
+ resolvePromise(Buffer.concat(chunks).toString("utf8"));
1030
+ });
1031
+ });
1032
+ }
1033
+ function wrapSpawnError(e) {
1034
+ if (e.code === "ENOENT") {
1035
+ return new EiRunError("the Elementum bridge could not be started; add `ei` to PATH, set ELEMENTUM_BRIDGE_PATH, or rerun the Elementum installer", null);
1036
+ }
1037
+ return new EiRunError(`failed to run the Elementum bridge: ${e.message}`, null);
1038
+ }
1039
+ /**
1040
+ * The output boundary owned by EDK. Chunks are written immediately so prompts
1041
+ * without a trailing newline and carriage-return progress remain interactive.
1042
+ * The caller-owned output queue drains the source without applying pipe
1043
+ * backpressure to ei. This keeps the producer independent from a slow
1044
+ * terminal while preserving FIFO order in the output arbiter.
1045
+ */
1046
+ function routeEiOutput(source, destination, consume, write) {
1047
+ if (source === null)
1048
+ return Promise.resolve();
1049
+ const readable = source;
1050
+ return new Promise((resolvePromise, reject) => {
1051
+ let ended = false;
1052
+ let settled = false;
1053
+ let pending = "";
1054
+ const settle = (error) => {
1055
+ if (settled)
1056
+ return;
1057
+ settled = true;
1058
+ destination.removeListener("error", onDestinationError);
1059
+ if (error === undefined)
1060
+ resolvePromise();
1061
+ else
1062
+ reject(error);
1063
+ };
1064
+ const flush = (chunk = "") => {
1065
+ withProgressBatch(() => {
1066
+ pending += chunk;
1067
+ while (true) {
1068
+ const newline = pending.indexOf("\n");
1069
+ if (newline === -1) {
1070
+ if (!ended || pending === "")
1071
+ return;
1072
+ const final = pending;
1073
+ pending = "";
1074
+ if (write !== undefined) {
1075
+ write(final, destination);
1076
+ return;
1077
+ }
1078
+ destination.write(final);
1079
+ return;
1080
+ }
1081
+ const line = pending.slice(0, newline + 1);
1082
+ pending = pending.slice(newline + 1);
1083
+ if (consume?.(line.trimEnd()) === true) {
1084
+ continue;
1085
+ }
1086
+ if (write !== undefined) {
1087
+ write(line, destination);
1088
+ continue;
1089
+ }
1090
+ destination.write(line);
1091
+ }
1092
+ });
1093
+ };
1094
+ const onDestinationError = (error) => {
1095
+ if (error.code === "EPIPE") {
1096
+ // A downstream consumer such as `head` closed early. Drain and let the
1097
+ // child finish without turning the expected closed pipe into a crash.
1098
+ readable.resume();
1099
+ settle();
1100
+ return;
1101
+ }
1102
+ runtimeLog.emit({
1103
+ level: "ERROR",
1104
+ component: "edk",
1105
+ message: "Failed to route bridge output",
1106
+ error,
1107
+ });
1108
+ settle(error);
1109
+ };
1110
+ destination.on("error", onDestinationError);
1111
+ readable.setEncoding?.("utf8");
1112
+ readable.on("data", (chunk) => {
1113
+ flush(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
1114
+ });
1115
+ readable.on("end", () => {
1116
+ ended = true;
1117
+ flush();
1118
+ settle();
1119
+ });
1120
+ readable.on("error", settle);
1121
+ readable.on("close", () => {
1122
+ if (ended)
1123
+ settle();
1124
+ });
1125
+ });
1126
+ }
1127
+ function wrapOpenTofuSpawnError(e) {
1128
+ if (e.code === "ENOENT") {
1129
+ return new EiRunError("managed OpenTofu could not be started; rerun the Elementum installer", null);
1130
+ }
1131
+ return new EiRunError(`failed to run managed OpenTofu: ${e.message}`, null);
1132
+ }