harnesstap 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +33 -16
  2. package/dist/apply-QSS4242W.js +67 -0
  3. package/dist/apply-QSS4242W.js.map +1 -0
  4. package/dist/approve-CNYQY6DC.js +181 -0
  5. package/dist/approve-CNYQY6DC.js.map +1 -0
  6. package/dist/audit-V4SUV7KA.js +434 -0
  7. package/dist/audit-V4SUV7KA.js.map +1 -0
  8. package/dist/auth-63FOHIQ3.js +220 -0
  9. package/dist/auth-63FOHIQ3.js.map +1 -0
  10. package/dist/bin.js +166 -0
  11. package/dist/bin.js.map +1 -0
  12. package/dist/chunk-2H7UOFLK.js +11 -0
  13. package/dist/chunk-2H7UOFLK.js.map +1 -0
  14. package/dist/chunk-2NE3QYMP.js +103 -0
  15. package/dist/chunk-2NE3QYMP.js.map +1 -0
  16. package/dist/chunk-2P2EOYEW.js +1140 -0
  17. package/dist/chunk-2P2EOYEW.js.map +1 -0
  18. package/dist/chunk-37E5M4JX.js +34 -0
  19. package/dist/chunk-37E5M4JX.js.map +1 -0
  20. package/dist/chunk-37LQQWMF.js +496 -0
  21. package/dist/chunk-37LQQWMF.js.map +1 -0
  22. package/dist/chunk-3FIWOI3H.js +98 -0
  23. package/dist/chunk-3FIWOI3H.js.map +1 -0
  24. package/dist/chunk-3PGC6OA3.js +540 -0
  25. package/dist/chunk-3PGC6OA3.js.map +1 -0
  26. package/dist/chunk-4IHKBIY3.js +118 -0
  27. package/dist/chunk-4IHKBIY3.js.map +1 -0
  28. package/dist/chunk-4ZUBRLSP.js +17 -0
  29. package/dist/chunk-4ZUBRLSP.js.map +1 -0
  30. package/dist/chunk-5F3LNDZG.js +9 -0
  31. package/dist/chunk-5F3LNDZG.js.map +1 -0
  32. package/dist/chunk-5TXI6BI2.js +1359 -0
  33. package/dist/chunk-5TXI6BI2.js.map +1 -0
  34. package/dist/chunk-6P5IO4BX.js +235 -0
  35. package/dist/chunk-6P5IO4BX.js.map +1 -0
  36. package/dist/chunk-ABXUKHAU.js +571 -0
  37. package/dist/chunk-ABXUKHAU.js.map +1 -0
  38. package/dist/chunk-AOUDSNRK.js +1357 -0
  39. package/dist/chunk-AOUDSNRK.js.map +1 -0
  40. package/dist/chunk-BNDJJAEI.js +311 -0
  41. package/dist/chunk-BNDJJAEI.js.map +1 -0
  42. package/dist/chunk-C2IWSFF5.js +818 -0
  43. package/dist/chunk-C2IWSFF5.js.map +1 -0
  44. package/dist/chunk-CHQGE2HF.js +283 -0
  45. package/dist/chunk-CHQGE2HF.js.map +1 -0
  46. package/dist/chunk-DEJLP7QJ.js +681 -0
  47. package/dist/chunk-DEJLP7QJ.js.map +1 -0
  48. package/dist/chunk-DJ6FN6EW.js +532 -0
  49. package/dist/chunk-DJ6FN6EW.js.map +1 -0
  50. package/dist/chunk-E4WRTRMH.js +1173 -0
  51. package/dist/chunk-E4WRTRMH.js.map +1 -0
  52. package/dist/chunk-E5QXNU3K.js +238 -0
  53. package/dist/chunk-E5QXNU3K.js.map +1 -0
  54. package/dist/chunk-EMTBGOR3.js +2959 -0
  55. package/dist/chunk-EMTBGOR3.js.map +1 -0
  56. package/dist/chunk-FFWYIGQ4.js +18 -0
  57. package/dist/chunk-FFWYIGQ4.js.map +1 -0
  58. package/dist/chunk-I6XFZLTJ.js +9 -0
  59. package/dist/chunk-I6XFZLTJ.js.map +1 -0
  60. package/dist/chunk-IHWAOIAU.js +172 -0
  61. package/dist/chunk-IHWAOIAU.js.map +1 -0
  62. package/dist/chunk-IHZUYG66.js +583 -0
  63. package/dist/chunk-IHZUYG66.js.map +1 -0
  64. package/dist/chunk-JQOKQKQT.js +158 -0
  65. package/dist/chunk-JQOKQKQT.js.map +1 -0
  66. package/dist/chunk-JRFUTIEH.js +426 -0
  67. package/dist/chunk-JRFUTIEH.js.map +1 -0
  68. package/dist/chunk-KCBI6JQC.js +115 -0
  69. package/dist/chunk-KCBI6JQC.js.map +1 -0
  70. package/dist/chunk-KDUQMINL.js +60 -0
  71. package/dist/chunk-KDUQMINL.js.map +1 -0
  72. package/dist/chunk-KLR2DURP.js +656 -0
  73. package/dist/chunk-KLR2DURP.js.map +1 -0
  74. package/dist/chunk-KRI4R7EM.js +25 -0
  75. package/dist/chunk-KRI4R7EM.js.map +1 -0
  76. package/dist/chunk-LYQMK6SV.js +87 -0
  77. package/dist/chunk-LYQMK6SV.js.map +1 -0
  78. package/dist/chunk-MK3Q37ZN.js +183 -0
  79. package/dist/chunk-MK3Q37ZN.js.map +1 -0
  80. package/dist/chunk-MSGAGV7B.js +346 -0
  81. package/dist/chunk-MSGAGV7B.js.map +1 -0
  82. package/dist/chunk-MZQRSERO.js +430 -0
  83. package/dist/chunk-MZQRSERO.js.map +1 -0
  84. package/dist/chunk-N3WIJXXM.js +691 -0
  85. package/dist/chunk-N3WIJXXM.js.map +1 -0
  86. package/dist/chunk-NAGAJ5UM.js +145 -0
  87. package/dist/chunk-NAGAJ5UM.js.map +1 -0
  88. package/dist/chunk-NFYPBTKO.js +302 -0
  89. package/dist/chunk-NFYPBTKO.js.map +1 -0
  90. package/dist/chunk-NPO2IG6G.js +491 -0
  91. package/dist/chunk-NPO2IG6G.js.map +1 -0
  92. package/dist/chunk-OS6NUIBJ.js +38 -0
  93. package/dist/chunk-OS6NUIBJ.js.map +1 -0
  94. package/dist/chunk-PFUK3HJ4.js +296 -0
  95. package/dist/chunk-PFUK3HJ4.js.map +1 -0
  96. package/dist/chunk-PMQ55GDB.js +115 -0
  97. package/dist/chunk-PMQ55GDB.js.map +1 -0
  98. package/dist/chunk-QIVE2YFJ.js +514 -0
  99. package/dist/chunk-QIVE2YFJ.js.map +1 -0
  100. package/dist/chunk-QKXD3EUF.js +691 -0
  101. package/dist/chunk-QKXD3EUF.js.map +1 -0
  102. package/dist/chunk-RNQYUWF6.js +32 -0
  103. package/dist/chunk-RNQYUWF6.js.map +1 -0
  104. package/dist/chunk-S2E4SSQV.js +41 -0
  105. package/dist/chunk-S2E4SSQV.js.map +1 -0
  106. package/dist/chunk-SN4BXX3B.js +186 -0
  107. package/dist/chunk-SN4BXX3B.js.map +1 -0
  108. package/dist/chunk-SNVAMWB7.js +40 -0
  109. package/dist/chunk-SNVAMWB7.js.map +1 -0
  110. package/dist/chunk-T5VRREN4.js +696 -0
  111. package/dist/chunk-T5VRREN4.js.map +1 -0
  112. package/dist/chunk-TKBMHZTS.js +10945 -0
  113. package/dist/chunk-TKBMHZTS.js.map +1 -0
  114. package/dist/chunk-TNJPTUE4.js +35 -0
  115. package/dist/chunk-TNJPTUE4.js.map +1 -0
  116. package/dist/chunk-TQ2NA4Z4.js +24 -0
  117. package/dist/chunk-TQ2NA4Z4.js.map +1 -0
  118. package/dist/chunk-TXXDMDPN.js +998 -0
  119. package/dist/chunk-TXXDMDPN.js.map +1 -0
  120. package/dist/chunk-UWXUBU7V.js +184 -0
  121. package/dist/chunk-UWXUBU7V.js.map +1 -0
  122. package/dist/chunk-UYRK2H24.js +141 -0
  123. package/dist/chunk-UYRK2H24.js.map +1 -0
  124. package/dist/chunk-V4IXIM3C.js +806 -0
  125. package/dist/chunk-V4IXIM3C.js.map +1 -0
  126. package/dist/chunk-VFHVXXP4.js +6438 -0
  127. package/dist/chunk-VFHVXXP4.js.map +1 -0
  128. package/dist/chunk-VQVUJYYY.js +244 -0
  129. package/dist/chunk-VQVUJYYY.js.map +1 -0
  130. package/dist/chunk-VZQG2JDV.js +9 -0
  131. package/dist/chunk-VZQG2JDV.js.map +1 -0
  132. package/dist/chunk-W7HQ5X3S.js +610 -0
  133. package/dist/chunk-W7HQ5X3S.js.map +1 -0
  134. package/dist/chunk-WMSQAFK5.js +65 -0
  135. package/dist/chunk-WMSQAFK5.js.map +1 -0
  136. package/dist/chunk-WMYTBJPB.js +364 -0
  137. package/dist/chunk-WMYTBJPB.js.map +1 -0
  138. package/dist/chunk-WNLFNCOH.js +7795 -0
  139. package/dist/chunk-WNLFNCOH.js.map +1 -0
  140. package/dist/chunk-WRX7CB2M.js +6448 -0
  141. package/dist/chunk-WRX7CB2M.js.map +1 -0
  142. package/dist/chunk-XGTTOO4R.js +84 -0
  143. package/dist/chunk-XGTTOO4R.js.map +1 -0
  144. package/dist/chunk-YSXRBUR4.js +682 -0
  145. package/dist/chunk-YSXRBUR4.js.map +1 -0
  146. package/dist/chunk-YTC2EG64.js +1759 -0
  147. package/dist/chunk-YTC2EG64.js.map +1 -0
  148. package/dist/compile-J3UGQSS3.js +161 -0
  149. package/dist/compile-J3UGQSS3.js.map +1 -0
  150. package/dist/config-5BPSZND3.js +438 -0
  151. package/dist/config-5BPSZND3.js.map +1 -0
  152. package/dist/doctor-BVFKLJVO.js +111 -0
  153. package/dist/doctor-BVFKLJVO.js.map +1 -0
  154. package/dist/environment-3RI5H32O.js +2745 -0
  155. package/dist/environment-3RI5H32O.js.map +1 -0
  156. package/dist/github-YFJQVH5K.js +114 -0
  157. package/dist/github-YFJQVH5K.js.map +1 -0
  158. package/dist/harness-ECGHPEKA.js +746 -0
  159. package/dist/harness-ECGHPEKA.js.map +1 -0
  160. package/dist/help-ELPNPPEM.js +2079 -0
  161. package/dist/help-ELPNPPEM.js.map +1 -0
  162. package/dist/help-UL5XLY3I.js +1892 -0
  163. package/dist/help-UL5XLY3I.js.map +1 -0
  164. package/dist/index.d.ts +164 -1
  165. package/dist/index.js +50 -54362
  166. package/dist/index.js.map +1 -1
  167. package/dist/init-UJQTDHW7.js +873 -0
  168. package/dist/init-UJQTDHW7.js.map +1 -0
  169. package/dist/lock-XUMJ63NZ.js +455 -0
  170. package/dist/lock-XUMJ63NZ.js.map +1 -0
  171. package/dist/marketplace-ZUMOLVXE.js +495 -0
  172. package/dist/marketplace-ZUMOLVXE.js.map +1 -0
  173. package/dist/mcp-RZA5O2ND.js +202 -0
  174. package/dist/mcp-RZA5O2ND.js.map +1 -0
  175. package/dist/migrate-CYQI2FH6.js +1043 -0
  176. package/dist/migrate-CYQI2FH6.js.map +1 -0
  177. package/dist/open-AWOAWLKO.js +32 -0
  178. package/dist/open-AWOAWLKO.js.map +1 -0
  179. package/dist/pack-2QD5ZUIO.js +99 -0
  180. package/dist/pack-2QD5ZUIO.js.map +1 -0
  181. package/dist/plugin-GQSSSFX4.js +64 -0
  182. package/dist/plugin-GQSSSFX4.js.map +1 -0
  183. package/dist/plugin-from-project-SIQUFYIO.js +16 -0
  184. package/dist/plugin-from-project-SIQUFYIO.js.map +1 -0
  185. package/dist/policy-CT4JRCJI.js +105 -0
  186. package/dist/policy-CT4JRCJI.js.map +1 -0
  187. package/dist/profile-4JQ6LECP.js +1886 -0
  188. package/dist/profile-4JQ6LECP.js.map +1 -0
  189. package/dist/project-JG7QWXRG.js +1392 -0
  190. package/dist/project-JG7QWXRG.js.map +1 -0
  191. package/dist/resource-QRMR6CSD.js +555 -0
  192. package/dist/resource-QRMR6CSD.js.map +1 -0
  193. package/dist/version-LZ5POOXY.js +17 -0
  194. package/dist/version-LZ5POOXY.js.map +1 -0
  195. package/package.json +25 -14
  196. package/schemas/ap-package.v1.json +36 -0
  197. package/schemas/fixtures/catalog-missing-schema.ap.json +13 -0
  198. package/schemas/fixtures/confidence.ap.json +13 -0
  199. package/schemas/fixtures/context7.ap.json +13 -0
  200. package/schemas/fixtures/minimal-with-schema.ap.json +13 -0
  201. package/schemas/fixtures/superpowers.ap.json +13 -0
  202. package/schemas/fixtures/third-party-skills.ap.json +13 -0
@@ -0,0 +1,2745 @@
1
+ import {
2
+ buildFilterListHelpActions,
3
+ mapFilterTableBrowserResult
4
+ } from "./chunk-OS6NUIBJ.js";
5
+ import {
6
+ resolvePluginGraph
7
+ } from "./chunk-4IHKBIY3.js";
8
+ import {
9
+ toPluginChoices
10
+ } from "./chunk-4ZUBRLSP.js";
11
+ import {
12
+ createTableBrowserPrompt
13
+ } from "./chunk-DJ6FN6EW.js";
14
+ import {
15
+ matchesListSearchQuery,
16
+ parseListSearchQuery
17
+ } from "./chunk-KRI4R7EM.js";
18
+ import "./chunk-S2E4SSQV.js";
19
+ import {
20
+ VIEWPORT_CHROME_LINES,
21
+ computeMaxVisibleRows,
22
+ computeMaxVisibleTableRows,
23
+ renderFoldedHintLine,
24
+ resolveSectionViewport
25
+ } from "./chunk-XGTTOO4R.js";
26
+ import {
27
+ promptForSearchableMultiSelect
28
+ } from "./chunk-JQOKQKQT.js";
29
+ import {
30
+ buildHelpLine
31
+ } from "./chunk-3FIWOI3H.js";
32
+ import {
33
+ renderCliError
34
+ } from "./chunk-37LQQWMF.js";
35
+ import {
36
+ createEnvironmentCommand,
37
+ deleteEnvironmentCommand,
38
+ fragmentFromEnvironmentId,
39
+ getEffectiveActiveEnvironmentName,
40
+ getGlobalActiveEnvironmentName,
41
+ getLocalActiveEnvironmentName,
42
+ listEnvironmentsCommand,
43
+ loadPluginDefaultFragments,
44
+ resolveEnvironmentCascade,
45
+ resolveSecretRefsBestEffort,
46
+ setEnvironmentModelConfigCommand,
47
+ setEnvironmentPermissionCommand,
48
+ setEnvironmentSecretCommand,
49
+ setEnvironmentVarCommand,
50
+ showEnvironmentCommand,
51
+ unsetEnvironmentModelConfigCommand,
52
+ unsetEnvironmentPermissionCommand,
53
+ unsetEnvironmentSecretCommand,
54
+ unsetEnvironmentVarCommand,
55
+ useEnvironmentCommand
56
+ } from "./chunk-WNLFNCOH.js";
57
+ import {
58
+ resolveEnvironmentOrThrow
59
+ } from "./chunk-E5QXNU3K.js";
60
+ import {
61
+ isPromptBackError,
62
+ isPromptCancellationError,
63
+ promptForChoice,
64
+ promptForConfirmation,
65
+ promptForSearchableChoice,
66
+ promptForValue,
67
+ resolveOrPrompt,
68
+ shouldUseWizard,
69
+ withPromptBack
70
+ } from "./chunk-NAGAJ5UM.js";
71
+ import {
72
+ initializeSchema
73
+ } from "./chunk-N3WIJXXM.js";
74
+ import "./chunk-TNJPTUE4.js";
75
+ import "./chunk-KDUQMINL.js";
76
+ import "./chunk-JRFUTIEH.js";
77
+ import {
78
+ getHarnessPreference,
79
+ getProjectByLocalPath,
80
+ getProjectConfiguredPlugins,
81
+ getProjectHarnessConfig
82
+ } from "./chunk-PFUK3HJ4.js";
83
+ import {
84
+ detectPlatforms,
85
+ scanPlatform
86
+ } from "./chunk-WRX7CB2M.js";
87
+ import "./chunk-MZQRSERO.js";
88
+ import "./chunk-DEJLP7QJ.js";
89
+ import {
90
+ addSecretRefToEnvironment,
91
+ collectEnvironmentVarPlaceholders,
92
+ createEnvironment,
93
+ getEnvironment,
94
+ getEnvironmentByName,
95
+ getEnvironmentResources,
96
+ getEnvironmentSecretRefs,
97
+ getPlugin,
98
+ getPluginById,
99
+ getPluginResources,
100
+ listEnvironmentReferences,
101
+ listEnvironments,
102
+ listPlugins,
103
+ listResources,
104
+ resolvePluginSelector,
105
+ setPluginDefaultEnvironment,
106
+ upsertEnvironmentEnvVar,
107
+ upsertEnvironmentModelConfig,
108
+ upsertEnvironmentPermission
109
+ } from "./chunk-TKBMHZTS.js";
110
+ import "./chunk-TXXDMDPN.js";
111
+ import "./chunk-C2IWSFF5.js";
112
+ import "./chunk-NPO2IG6G.js";
113
+ import {
114
+ configureCommandGroup
115
+ } from "./chunk-5TXI6BI2.js";
116
+ import {
117
+ parseOutputFormat,
118
+ printJson
119
+ } from "./chunk-TQ2NA4Z4.js";
120
+ import {
121
+ collectRepeatedOption,
122
+ fail,
123
+ failCaught,
124
+ formatCommand,
125
+ missingRequiredArg
126
+ } from "./chunk-NFYPBTKO.js";
127
+ import {
128
+ renderPanel,
129
+ renderSubheader,
130
+ renderTable,
131
+ resolveTableMaxWidth,
132
+ styleResourceType,
133
+ terminalColumns,
134
+ theme,
135
+ ui
136
+ } from "./chunk-ABXUKHAU.js";
137
+ import "./chunk-2P2EOYEW.js";
138
+ import "./chunk-VQVUJYYY.js";
139
+ import {
140
+ CLI_ERRORS,
141
+ CLI_HINTS,
142
+ getDb
143
+ } from "./chunk-KLR2DURP.js";
144
+
145
+ // src/cli/commands/environment.ts
146
+ import { resolve as resolve2 } from "path";
147
+
148
+ // src/services/environment-requirements.ts
149
+ var NOISE_ENV_KEY_PATTERNS = [
150
+ "PATH",
151
+ "HOME",
152
+ "USER",
153
+ "SHELL",
154
+ "PWD",
155
+ /^npm_/i,
156
+ /^NODE_/i
157
+ ];
158
+ function unique(values) {
159
+ return [...new Set(values)];
160
+ }
161
+ function isNoiseEnvKey(key) {
162
+ return NOISE_ENV_KEY_PATTERNS.some(
163
+ (pattern) => typeof pattern === "string" ? key === pattern : pattern.test(key)
164
+ );
165
+ }
166
+ function resolveScopedPluginIds(configuredPluginIds) {
167
+ const graph = resolvePluginGraph(configuredPluginIds);
168
+ return unique(graph.resolved.map((plugin) => plugin.id));
169
+ }
170
+ function collectRequirementsFromPlugins(pluginIds) {
171
+ const requiredKeys = /* @__PURE__ */ new Set();
172
+ const requiredModels = /* @__PURE__ */ new Map();
173
+ const keySources = /* @__PURE__ */ new Map();
174
+ const rememberKey = (key, source) => {
175
+ if (!key) return;
176
+ requiredKeys.add(key);
177
+ const current = keySources.get(key) ?? /* @__PURE__ */ new Set();
178
+ current.add(source);
179
+ keySources.set(key, current);
180
+ };
181
+ for (const pluginId of pluginIds) {
182
+ const plugin = getPlugin(pluginId);
183
+ if (!plugin) continue;
184
+ for (const need of plugin.needs ?? []) {
185
+ rememberKey(need, "plugin_needs");
186
+ }
187
+ for (const resource of getPluginResources(pluginId)) {
188
+ if (resource.type === "mcp_server") {
189
+ const metadata = resource.metadata;
190
+ for (const key of Object.keys(metadata.env ?? {})) {
191
+ rememberKey(key, "mcp_env");
192
+ }
193
+ for (const value of Object.values(metadata.headers ?? {})) {
194
+ for (const key of collectEnvironmentVarPlaceholders(value)) {
195
+ rememberKey(key, "mcp_env");
196
+ }
197
+ }
198
+ }
199
+ if (resource.type === "agent") {
200
+ const metadata = resource.metadata;
201
+ if (metadata.model) {
202
+ requiredModels.set(resource.name, {
203
+ name: resource.name,
204
+ model: metadata.model
205
+ });
206
+ }
207
+ }
208
+ }
209
+ }
210
+ return {
211
+ configured_plugin_ids: [],
212
+ plugin_ids: pluginIds,
213
+ required_keys: [...requiredKeys].sort(),
214
+ required_models: [...requiredModels.values()].sort(
215
+ (a, b) => a.name.localeCompare(b.name)
216
+ ),
217
+ key_sources: Object.fromEntries(
218
+ [...keySources.entries()].map(([key, sources]) => [key, [...sources].sort()])
219
+ )
220
+ };
221
+ }
222
+ function collectPluginRequirements(pluginSelectors) {
223
+ const configuredPluginIds = pluginSelectors.map((selector) => {
224
+ const configuredPlugin = resolvePluginSelector(selector);
225
+ if (!configuredPlugin) {
226
+ throw new Error(`Configured plugin not found: ${selector}`);
227
+ }
228
+ return configuredPlugin.id;
229
+ });
230
+ const pluginIds = resolveScopedPluginIds(configuredPluginIds);
231
+ const requirements = collectRequirementsFromPlugins(pluginIds);
232
+ requirements.configured_plugin_ids = configuredPluginIds;
233
+ return requirements;
234
+ }
235
+ function analyzeEnvironmentGaps(environmentId, pluginSelector) {
236
+ const requirements = collectPluginRequirements([pluginSelector]);
237
+ const envVarKeys = new Set(
238
+ getEnvironmentResources(environmentId).filter((resource) => resource.type === "env_var").map((resource) => resource.metadata.key)
239
+ );
240
+ const secretRefKeys = new Set(
241
+ getEnvironmentSecretRefs(environmentId).map((ref) => ref.key)
242
+ );
243
+ return requirements.required_keys.map((key) => {
244
+ const satisfied = envVarKeys.has(key) || secretRefKeys.has(key);
245
+ return {
246
+ key,
247
+ sources: requirements.key_sources[key] ?? [],
248
+ status: satisfied ? "satisfied" : "missing"
249
+ };
250
+ });
251
+ }
252
+ function suggestProcessEnvKeys(requiredKeys, options) {
253
+ const processEnv = options?.processEnv ?? process.env;
254
+ const processKeys = Object.keys(processEnv);
255
+ const requiredSet = new Set(requiredKeys);
256
+ const exact = requiredKeys.filter((key) => processEnv[key] !== void 0).sort();
257
+ const noise = processKeys.filter(isNoiseEnvKey).sort();
258
+ const fuzzyMatches = /* @__PURE__ */ new Set();
259
+ for (const requiredKey of requiredKeys) {
260
+ if (requiredSet.has(requiredKey) && processEnv[requiredKey] !== void 0) {
261
+ continue;
262
+ }
263
+ for (const processKey of processKeys) {
264
+ if (processKey === requiredKey) continue;
265
+ if (isNoiseEnvKey(processKey)) continue;
266
+ if (processKey.includes(requiredKey) || requiredKey.includes(processKey)) {
267
+ fuzzyMatches.add(processKey);
268
+ }
269
+ }
270
+ }
271
+ return {
272
+ exact,
273
+ fuzzy: [...fuzzyMatches].sort(),
274
+ noise
275
+ };
276
+ }
277
+
278
+ // src/services/environment-capture.ts
279
+ var PROCESS_ENV_SECRET_PATTERNS = [
280
+ /_TOKEN$/i,
281
+ /_SECRET$/i,
282
+ /_KEY$/i,
283
+ /_PASSWORD$/i
284
+ ];
285
+ function unique2(values) {
286
+ return [...new Set(values)];
287
+ }
288
+ function resolveScanHarness(projectRoot) {
289
+ const project = getProjectByLocalPath(projectRoot);
290
+ if (project) {
291
+ const projectHarness = getProjectHarnessConfig(project.id);
292
+ const [first2] = projectHarness?.registered_harnesses ?? [];
293
+ if (first2) return first2;
294
+ }
295
+ const globalHarness = getHarnessPreference();
296
+ const [globalFirst] = globalHarness?.registered_harnesses ?? [];
297
+ if (globalFirst) return globalFirst;
298
+ const detected = detectPlatforms(projectRoot);
299
+ const [first] = detected;
300
+ if (first) {
301
+ return first;
302
+ }
303
+ throw new Error(`No harness detected for project: ${projectRoot}`);
304
+ }
305
+ function resolveScopedConfiguredPluginIds(projectRoot, pluginSelectors) {
306
+ if (pluginSelectors && pluginSelectors.length > 0) {
307
+ return pluginSelectors.map((selector) => {
308
+ const configuredPlugin = resolvePluginSelector(selector);
309
+ if (!configuredPlugin) {
310
+ throw new Error(`Configured plugin not found: ${selector}`);
311
+ }
312
+ return configuredPlugin.id;
313
+ });
314
+ }
315
+ const project = getProjectByLocalPath(projectRoot);
316
+ if (!project) {
317
+ throw new Error(
318
+ `No tracked project found at ${projectRoot}; pass --plugins explicitly`
319
+ );
320
+ }
321
+ const applied = getProjectConfiguredPlugins(project.id);
322
+ const configuredPluginIds = unique2(applied.map((row) => row.plugin_id));
323
+ if (configuredPluginIds.length === 0) {
324
+ throw new Error(
325
+ `Project ${projectRoot} has no applied configured plugins; pass --plugins explicitly`
326
+ );
327
+ }
328
+ return configuredPluginIds;
329
+ }
330
+ function resolveScopedPluginIds2(configuredPluginIds) {
331
+ const graph = resolvePluginGraph(configuredPluginIds);
332
+ return unique2(graph.resolved.map((plugin) => plugin.id));
333
+ }
334
+ function valueFromScannedResources(resources, key) {
335
+ const match = resources.find((resource) => {
336
+ if (resource.type !== "env_var") return false;
337
+ const metadata2 = resource.metadata;
338
+ return metadata2.key === key;
339
+ });
340
+ if (!match) return void 0;
341
+ const metadata = match.metadata;
342
+ return metadata.value;
343
+ }
344
+ function valueFromLibraryResources(key) {
345
+ const match = listResources({ type: "env_var" }).find((resource) => {
346
+ const metadata2 = resource.metadata;
347
+ return metadata2.key === key;
348
+ });
349
+ if (!match) return void 0;
350
+ const metadata = match.metadata;
351
+ return metadata.value;
352
+ }
353
+ function isSecretKey(key) {
354
+ return PROCESS_ENV_SECRET_PATTERNS.some((pattern) => pattern.test(key));
355
+ }
356
+ function collectPermissionsFromScan(resources) {
357
+ return resources.filter((resource) => resource.type === "permission").map((resource) => {
358
+ const metadata = resource.metadata;
359
+ return {
360
+ action: metadata.action,
361
+ pattern: metadata.pattern,
362
+ name: resource.name
363
+ };
364
+ });
365
+ }
366
+ function collectModelConfigsFromRequirements(requirements) {
367
+ const libraryModels = listResources({ type: "model_config" });
368
+ const byName = /* @__PURE__ */ new Map();
369
+ for (const requirement of requirements.required_models) {
370
+ const libraryMatch = libraryModels.find((resource) => resource.name === requirement.name);
371
+ if (libraryMatch) {
372
+ const metadata = libraryMatch.metadata;
373
+ if (metadata.model) {
374
+ byName.set(requirement.name, { name: requirement.name, model: metadata.model });
375
+ continue;
376
+ }
377
+ }
378
+ byName.set(requirement.name, requirement);
379
+ }
380
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
381
+ }
382
+ async function previewEnvironmentCapture(input) {
383
+ const configuredPluginIds = resolveScopedConfiguredPluginIds(
384
+ input.projectRoot,
385
+ input.pluginSelectors
386
+ );
387
+ const pluginIds = resolveScopedPluginIds2(configuredPluginIds);
388
+ const requirements = collectRequirementsFromPlugins(pluginIds);
389
+ requirements.configured_plugin_ids = configuredPluginIds;
390
+ const scanHarness = resolveScanHarness(input.projectRoot);
391
+ const scanResult = await scanPlatform(scanHarness, input.projectRoot);
392
+ const scannedResources = scanResult.resources.map(
393
+ (resource) => ({
394
+ id: `scan:${resource.type}:${resource.name}`,
395
+ type: resource.type,
396
+ name: resource.name,
397
+ description: resource.description,
398
+ content: resource.content,
399
+ metadata: resource.metadata,
400
+ source: resource.source,
401
+ namespace: "",
402
+ origin_kind: "manual",
403
+ origin_ref: "",
404
+ content_hash: "",
405
+ content_blob_ref: "",
406
+ created_at: "",
407
+ updated_at: ""
408
+ })
409
+ );
410
+ const values = {};
411
+ const secretRefs = {};
412
+ const missingKeys = [];
413
+ const warnings = [];
414
+ for (const key of requirements.required_keys) {
415
+ const fromScan = valueFromScannedResources(scannedResources, key);
416
+ if (fromScan !== void 0) {
417
+ values[key] = fromScan;
418
+ continue;
419
+ }
420
+ const fromLibrary = valueFromLibraryResources(key);
421
+ if (fromLibrary !== void 0) {
422
+ values[key] = fromLibrary;
423
+ continue;
424
+ }
425
+ const fromProcess = process.env[key];
426
+ if (fromProcess !== void 0) {
427
+ const keySources = requirements.key_sources[key] ?? [];
428
+ const requireSecretRef = isSecretKey(key) || keySources.includes("plugin_needs");
429
+ if (requireSecretRef) {
430
+ secretRefs[key] = { provider: "env", ref: key };
431
+ } else {
432
+ values[key] = fromProcess;
433
+ }
434
+ continue;
435
+ }
436
+ const missing = {
437
+ key,
438
+ sources: requirements.key_sources[key] ?? [],
439
+ mode: input.strict ? "strict" : "warn"
440
+ };
441
+ missingKeys.push(missing);
442
+ warnings.push(`Missing required key: ${key}`);
443
+ }
444
+ const permissions = input.includePermissions ? collectPermissionsFromScan(scannedResources) : [];
445
+ const modelConfigs = collectModelConfigsFromRequirements(requirements);
446
+ const strictFailed = Boolean(input.strict && missingKeys.length > 0);
447
+ return {
448
+ mode: input.mode,
449
+ environment_name: input.environmentName,
450
+ configured_plugin_ids: configuredPluginIds,
451
+ harness: scanHarness,
452
+ requirements,
453
+ values,
454
+ secret_refs: secretRefs,
455
+ model_configs: modelConfigs,
456
+ permissions,
457
+ missing_keys: missingKeys,
458
+ warnings,
459
+ strict_failed: strictFailed
460
+ };
461
+ }
462
+ function ensureEnvironmentForCapture(environmentName, mode) {
463
+ const existing = getEnvironmentByName(environmentName);
464
+ if (mode === "capture") {
465
+ if (existing) return existing;
466
+ return createEnvironment({
467
+ name: environmentName,
468
+ description: `captured environment ${environmentName}`
469
+ });
470
+ }
471
+ if (!existing) {
472
+ throw new Error(`Environment not found for refresh: ${environmentName}`);
473
+ }
474
+ return existing;
475
+ }
476
+ async function captureOrRefreshEnvironment(input) {
477
+ const preview = await previewEnvironmentCapture(input);
478
+ if (preview.strict_failed) {
479
+ return {
480
+ ...preview,
481
+ persisted: false
482
+ };
483
+ }
484
+ if (input.dryRun) {
485
+ return {
486
+ ...preview,
487
+ persisted: false
488
+ };
489
+ }
490
+ const environment = ensureEnvironmentForCapture(input.environmentName, input.mode);
491
+ for (const [key, value] of Object.entries(preview.values)) {
492
+ upsertEnvironmentEnvVar(environment.id, key, value);
493
+ }
494
+ for (const [key, secretRef] of Object.entries(preview.secret_refs)) {
495
+ addSecretRefToEnvironment(
496
+ environment.id,
497
+ key,
498
+ secretRef.provider,
499
+ secretRef.ref
500
+ );
501
+ }
502
+ for (const modelConfig of preview.model_configs) {
503
+ upsertEnvironmentModelConfig(environment.id, {
504
+ name: modelConfig.name,
505
+ model: modelConfig.model
506
+ });
507
+ }
508
+ for (const permission of preview.permissions) {
509
+ upsertEnvironmentPermission(environment.id, permission);
510
+ }
511
+ return {
512
+ ...preview,
513
+ persisted: true,
514
+ environment_id: environment.id
515
+ };
516
+ }
517
+
518
+ // src/services/environment-create.ts
519
+ function normalizePluginSelectors(selectors) {
520
+ const raw = Array.isArray(selectors) ? selectors : [selectors];
521
+ return raw.flatMap((entry) => entry.split(",")).map((entry) => entry.trim()).filter(Boolean);
522
+ }
523
+ function resolveCreateMode(input) {
524
+ const modes = [];
525
+ if (input.blank) modes.push("blank");
526
+ if (input.fromProject) modes.push("from-project");
527
+ if (input.fromPlugin !== void 0) modes.push("from-plugin");
528
+ if (modes.length > 1) {
529
+ throw new Error(
530
+ "Specify exactly one of --blank, --from-project, or --from-plugin."
531
+ );
532
+ }
533
+ if (modes.length === 0) {
534
+ return "blank";
535
+ }
536
+ const [mode] = modes;
537
+ if (!mode) {
538
+ return "blank";
539
+ }
540
+ return mode;
541
+ }
542
+ function resolveFromPluginKeyMaterial(input) {
543
+ const values = { ...input.resolved?.values ?? {} };
544
+ const secretRefs = {
545
+ ...input.resolved?.secret_refs ?? {}
546
+ };
547
+ const missingKeys = [];
548
+ const resolvedKeys = /* @__PURE__ */ new Set([
549
+ ...Object.keys(values),
550
+ ...Object.keys(secretRefs)
551
+ ]);
552
+ for (const key of input.requirements.required_keys) {
553
+ if (resolvedKeys.has(key)) {
554
+ continue;
555
+ }
556
+ const fromProcess = process.env[key];
557
+ if (fromProcess !== void 0) {
558
+ const keySources = input.requirements.key_sources[key] ?? [];
559
+ const requireSecretRef = isSecretKey(key) || keySources.includes("plugin_needs");
560
+ if (requireSecretRef) {
561
+ secretRefs[key] = { provider: "env", ref: key };
562
+ } else {
563
+ values[key] = fromProcess;
564
+ }
565
+ continue;
566
+ }
567
+ missingKeys.push({
568
+ key,
569
+ sources: input.requirements.key_sources[key] ?? [],
570
+ mode: input.strict ? "strict" : "warn"
571
+ });
572
+ }
573
+ return { values, secretRefs, missingKeys };
574
+ }
575
+ async function runFromPluginCreate(input) {
576
+ const pluginSelectors = normalizePluginSelectors(input.fromPlugin);
577
+ if (pluginSelectors.length === 0) {
578
+ throw new Error("--from-plugin requires at least one configured plugin selector.");
579
+ }
580
+ const requirements = collectPluginRequirements(pluginSelectors);
581
+ const { values, secretRefs, missingKeys } = resolveFromPluginKeyMaterial({
582
+ requirements,
583
+ strict: input.strict,
584
+ resolved: input.resolved
585
+ });
586
+ const modelConfigs = collectModelConfigsFromRequirements(requirements);
587
+ const strictFailed = Boolean(input.strict && missingKeys.length > 0);
588
+ const preview = {
589
+ mode: "from-plugin",
590
+ environment_name: input.name,
591
+ configured_plugin_ids: requirements.configured_plugin_ids,
592
+ values,
593
+ secret_refs: secretRefs,
594
+ model_configs: modelConfigs,
595
+ missing_keys: missingKeys,
596
+ strict_failed: strictFailed,
597
+ bound_plugin_ids: []
598
+ };
599
+ if (strictFailed || input.dryRun) {
600
+ const existing = getEnvironmentByName(input.name);
601
+ const payload = existing ? showEnvironmentCommand(existing.id) : {
602
+ environment: {
603
+ id: "",
604
+ name: input.name,
605
+ description: input.description ?? "",
606
+ created_at: "",
607
+ updated_at: ""
608
+ },
609
+ values: { env_vars: {}, model_configs: [], permissions: [] },
610
+ secret_refs: {},
611
+ references: { plugins: [] }
612
+ };
613
+ return {
614
+ mode: "from-plugin",
615
+ payload,
616
+ preview,
617
+ persisted: false
618
+ };
619
+ }
620
+ let environment = getEnvironmentByName(input.name);
621
+ if (!environment) {
622
+ environment = input.description ? createEnvironment({ name: input.name, description: input.description }) : createEnvironmentCommand({ name: input.name });
623
+ }
624
+ for (const [key, value] of Object.entries(values)) {
625
+ upsertEnvironmentEnvVar(environment.id, key, value);
626
+ }
627
+ for (const [key, secretRef] of Object.entries(secretRefs)) {
628
+ addSecretRefToEnvironment(
629
+ environment.id,
630
+ key,
631
+ secretRef.provider,
632
+ secretRef.ref
633
+ );
634
+ }
635
+ for (const modelConfig of modelConfigs) {
636
+ upsertEnvironmentModelConfig(environment.id, {
637
+ name: modelConfig.name,
638
+ model: modelConfig.model
639
+ });
640
+ }
641
+ if (input.bind) {
642
+ for (const pluginSelector of pluginSelectors) {
643
+ const configuredPlugin = resolvePluginSelector(pluginSelector);
644
+ if (!configuredPlugin) {
645
+ throw new Error(`Configured plugin not found: ${pluginSelector}`);
646
+ }
647
+ setPluginDefaultEnvironment(configuredPlugin.id, environment.id);
648
+ preview.bound_plugin_ids.push(configuredPlugin.id);
649
+ }
650
+ }
651
+ return {
652
+ mode: "from-plugin",
653
+ payload: showEnvironmentCommand(environment.id),
654
+ preview,
655
+ persisted: true
656
+ };
657
+ }
658
+ async function runEnvironmentCreate(input) {
659
+ const mode = resolveCreateMode(input);
660
+ if (mode === "blank") {
661
+ const created = input.description ? createEnvironmentCommand({ name: input.name, description: input.description }) : createEnvironmentCommand({ name: input.name });
662
+ return {
663
+ mode: "blank",
664
+ payload: showEnvironmentCommand(created.id)
665
+ };
666
+ }
667
+ if (mode === "from-project") {
668
+ const projectRoot = input.fromProject;
669
+ if (!projectRoot) {
670
+ throw new Error("Missing --from-project path.");
671
+ }
672
+ const captureMode = input.refresh ? "refresh" : "capture";
673
+ const result = await captureOrRefreshEnvironment({
674
+ mode: captureMode,
675
+ environmentName: input.name,
676
+ projectRoot,
677
+ pluginSelectors: input.plugins,
678
+ includePermissions: input.includePermissions,
679
+ dryRun: input.dryRun,
680
+ strict: input.strict
681
+ });
682
+ return {
683
+ mode: "from-project",
684
+ result
685
+ };
686
+ }
687
+ const fromPlugin = input.fromPlugin;
688
+ if (fromPlugin === void 0) {
689
+ throw new Error("Missing --from-plugin selector.");
690
+ }
691
+ return runFromPluginCreate({
692
+ name: input.name,
693
+ fromPlugin,
694
+ bind: input.bind,
695
+ strict: input.strict,
696
+ dryRun: input.dryRun,
697
+ description: input.description,
698
+ resolved: input.fromPluginResolved
699
+ });
700
+ }
701
+
702
+ // src/services/environment-edit.ts
703
+ var KIND_ORDER = [
704
+ "env_var",
705
+ "secret_ref",
706
+ "model_config",
707
+ "permission"
708
+ ];
709
+ function kindSortIndex(kind) {
710
+ const index = KIND_ORDER.indexOf(kind);
711
+ return index === -1 ? KIND_ORDER.length : index;
712
+ }
713
+ function compareEnvironmentEditRows(left, right) {
714
+ const kindDelta = kindSortIndex(left.kind) - kindSortIndex(right.kind);
715
+ if (kindDelta !== 0) {
716
+ return kindDelta;
717
+ }
718
+ switch (left.kind) {
719
+ case "env_var":
720
+ return left.key.localeCompare(
721
+ right.kind === "env_var" ? right.key : ""
722
+ );
723
+ case "secret_ref":
724
+ return left.key.localeCompare(
725
+ right.kind === "secret_ref" ? right.key : ""
726
+ );
727
+ case "model_config":
728
+ return left.name.localeCompare(
729
+ right.kind === "model_config" ? right.name : ""
730
+ );
731
+ case "permission":
732
+ return left.name.localeCompare(
733
+ right.kind === "permission" ? right.name : ""
734
+ );
735
+ default: {
736
+ const neverRow = left;
737
+ throw new Error(`Unsupported row kind: ${String(neverRow)}`);
738
+ }
739
+ }
740
+ }
741
+ function buildEnvironmentEditRows(environmentId) {
742
+ const rows = [];
743
+ for (const resource of getEnvironmentResources(environmentId)) {
744
+ if (resource.type === "env_var") {
745
+ const metadata = resource.metadata;
746
+ rows.push({
747
+ kind: "env_var",
748
+ key: metadata.key,
749
+ value: metadata.value
750
+ });
751
+ continue;
752
+ }
753
+ if (resource.type === "model_config") {
754
+ const metadata = resource.metadata;
755
+ rows.push({
756
+ kind: "model_config",
757
+ name: resource.name,
758
+ model: metadata.model,
759
+ ...metadata.provider ? { provider: metadata.provider } : {}
760
+ });
761
+ continue;
762
+ }
763
+ if (resource.type === "permission") {
764
+ const metadata = resource.metadata;
765
+ rows.push({
766
+ kind: "permission",
767
+ name: resource.name,
768
+ action: metadata.action,
769
+ pattern: metadata.pattern
770
+ });
771
+ }
772
+ }
773
+ for (const secretRef of getEnvironmentSecretRefs(environmentId)) {
774
+ rows.push({
775
+ kind: "secret_ref",
776
+ key: secretRef.key,
777
+ provider: secretRef.provider,
778
+ ref: secretRef.ref
779
+ });
780
+ }
781
+ return rows.sort(compareEnvironmentEditRows);
782
+ }
783
+
784
+ // src/services/environment-status.ts
785
+ function activeEnvironmentFragment(name) {
786
+ if (!name) {
787
+ return void 0;
788
+ }
789
+ const environment = getEnvironmentByName(name);
790
+ if (!environment) {
791
+ return void 0;
792
+ }
793
+ return fragmentFromEnvironmentId(environment.id);
794
+ }
795
+ function buildPluginDefaultSummary(configuredPluginIds) {
796
+ return configuredPluginIds.map((pluginId) => {
797
+ const plugin = getPluginById(pluginId);
798
+ const environmentId = plugin?.default_environment_id;
799
+ const environment = environmentId ? getEnvironment(environmentId) : void 0;
800
+ return {
801
+ plugin_id: pluginId,
802
+ environment_name: environment?.name ?? null
803
+ };
804
+ });
805
+ }
806
+ function detectVarDrift(expectedVars) {
807
+ const drift = [];
808
+ for (const [key, expected] of Object.entries(expectedVars).sort(
809
+ ([left], [right]) => left.localeCompare(right)
810
+ )) {
811
+ const actual = process.env[key] ?? null;
812
+ if (actual === null) {
813
+ drift.push({ key, expected, actual, kind: "missing" });
814
+ continue;
815
+ }
816
+ if (actual !== expected) {
817
+ drift.push({ key, expected, actual, kind: "mismatch" });
818
+ }
819
+ }
820
+ return drift;
821
+ }
822
+ function detectEnvironmentStatus(input = {}) {
823
+ const globalEnvironment = getGlobalActiveEnvironmentName() ?? null;
824
+ const localEnvironment = getLocalActiveEnvironmentName() ?? null;
825
+ const effectiveEnvironment = getEffectiveActiveEnvironmentName() ?? null;
826
+ const configuredPluginIds = input.configuredPluginIds ?? [];
827
+ const resolved = resolveEnvironmentCascade({
828
+ home: activeEnvironmentFragment(effectiveEnvironment ?? void 0),
829
+ pluginDefaults: loadPluginDefaultFragments(configuredPluginIds)
830
+ });
831
+ const { resolved: resolvedSecrets, warnings: secretWarnings } = resolveSecretRefsBestEffort(
832
+ resolved.secretRefs
833
+ );
834
+ const expectedVars = { ...resolved.vars, ...resolvedSecrets };
835
+ const drift = detectVarDrift(expectedVars);
836
+ return {
837
+ global_environment: globalEnvironment,
838
+ local_environment: localEnvironment,
839
+ effective_environment: effectiveEnvironment,
840
+ plugin_defaults: buildPluginDefaultSummary(configuredPluginIds),
841
+ resolved,
842
+ secret_warnings: secretWarnings,
843
+ has_drift: drift.length > 0,
844
+ drift
845
+ };
846
+ }
847
+
848
+ // src/services/environment-show-render.ts
849
+ function formatPluginLabel(plugin) {
850
+ return `${plugin.name}@${plugin.version}`;
851
+ }
852
+ function renderEnvironmentShow(payload, opts) {
853
+ const sections = [
854
+ renderPanel({
855
+ title: ["ENVIRONMENT", payload.environment.name],
856
+ rows: [
857
+ ["Description", payload.environment.description || ": "],
858
+ ["Env vars", `${Object.keys(payload.values.env_vars).length}`],
859
+ ["Model configs", `${payload.values.model_configs.length}`],
860
+ ["Permissions", `${payload.values.permissions.length}`],
861
+ ["Secret refs", `${Object.keys(payload.secret_refs).length}`]
862
+ ]
863
+ })
864
+ ];
865
+ if (Object.keys(payload.values.env_vars).length > 0) {
866
+ sections.push(
867
+ renderSubheader("ENV VARS"),
868
+ renderTable({
869
+ columns: [
870
+ { key: "key", header: "KEY", width: 28 },
871
+ { key: "value", header: "VALUE", width: 60 }
872
+ ],
873
+ rows: Object.entries(payload.values.env_vars).map(([key, value]) => ({ key, value }))
874
+ })
875
+ );
876
+ }
877
+ if (payload.values.model_configs.length > 0) {
878
+ sections.push(
879
+ renderSubheader("MODEL CONFIGS"),
880
+ renderTable({
881
+ columns: [
882
+ { key: "name", header: "NAME", width: 24 },
883
+ { key: "model", header: "MODEL", width: 28 },
884
+ { key: "provider", header: "PROVIDER", width: 20 }
885
+ ],
886
+ rows: payload.values.model_configs.map((entry) => ({
887
+ ...entry,
888
+ provider: entry.provider ?? ": "
889
+ }))
890
+ })
891
+ );
892
+ }
893
+ if (payload.values.permissions.length > 0) {
894
+ sections.push(
895
+ renderSubheader("PERMISSIONS"),
896
+ renderTable({
897
+ columns: [
898
+ { key: "name", header: "NAME", width: 30 },
899
+ { key: "action", header: "ACTION", width: 10 },
900
+ { key: "pattern", header: "PATTERN", width: 38 }
901
+ ],
902
+ rows: payload.values.permissions
903
+ })
904
+ );
905
+ }
906
+ if (Object.keys(payload.secret_refs).length > 0) {
907
+ sections.push(
908
+ renderSubheader("SECRET REFS"),
909
+ renderTable({
910
+ columns: [
911
+ { key: "key", header: "KEY", width: 24 },
912
+ { key: "provider", header: "PROVIDER", width: 12 },
913
+ { key: "ref", header: "REF", width: 40 }
914
+ ],
915
+ rows: Object.entries(payload.secret_refs).map(([key, value]) => ({
916
+ key,
917
+ provider: value.provider,
918
+ ref: value.ref
919
+ }))
920
+ })
921
+ );
922
+ }
923
+ if (payload.references.plugins.length > 0) {
924
+ sections.push(
925
+ renderSubheader("REFERENCES"),
926
+ renderTable({
927
+ columns: [
928
+ { key: "plugin", header: "PLUGIN", width: 40 }
929
+ ],
930
+ rows: payload.references.plugins.map((ref) => {
931
+ const plugin = getPluginById(ref.id);
932
+ return {
933
+ plugin: plugin ? formatPluginLabel(plugin) : ref.name
934
+ };
935
+ })
936
+ })
937
+ );
938
+ }
939
+ const requirementGaps = opts?.requirementGaps;
940
+ if (requirementGaps !== void 0) {
941
+ sections.push(
942
+ renderSubheader("REQUIREMENT GAPS"),
943
+ renderTable({
944
+ columns: [
945
+ { key: "key", header: "KEY", width: 28 },
946
+ { key: "sources", header: "SOURCES", width: 24 },
947
+ { key: "status", header: "STATUS", width: 12 }
948
+ ],
949
+ rows: requirementGaps.map((gap) => ({
950
+ key: gap.key,
951
+ sources: gap.sources.join(", "),
952
+ status: gap.status
953
+ })),
954
+ empty: "No requirement gaps found."
955
+ })
956
+ );
957
+ }
958
+ return sections.join("\n");
959
+ }
960
+
961
+ // src/services/wizards/environment-create-project-scope.ts
962
+ import { resolve } from "path";
963
+ function formatPluginSelector(pluginId) {
964
+ const plugin = getPluginById(pluginId);
965
+ if (!plugin) {
966
+ return void 0;
967
+ }
968
+ return `${plugin.name}@${plugin.version}`;
969
+ }
970
+ function inspectProjectPluginScope(projectRoot) {
971
+ const resolvedRoot = resolve(projectRoot);
972
+ const project = getProjectByLocalPath(resolvedRoot);
973
+ if (!project) {
974
+ return { kind: "untracked", projectRoot: resolvedRoot };
975
+ }
976
+ const applied = getProjectConfiguredPlugins(project.id);
977
+ const selectors = [];
978
+ const labels = [];
979
+ for (const row of applied) {
980
+ const selector = formatPluginSelector(row.plugin_id);
981
+ if (!selector) {
982
+ continue;
983
+ }
984
+ selectors.push(selector);
985
+ labels.push(selector);
986
+ }
987
+ if (selectors.length === 0) {
988
+ return { kind: "no_applied_plugins", projectRoot: resolvedRoot };
989
+ }
990
+ return {
991
+ kind: "applied",
992
+ projectRoot: resolvedRoot,
993
+ selectors,
994
+ labels
995
+ };
996
+ }
997
+ function explainMissingProjectPlugins(inspection) {
998
+ console.log("");
999
+ if (inspection.kind === "untracked") {
1000
+ console.log(
1001
+ `No HarnessTap project is tracked at ${inspection.projectRoot}.`
1002
+ );
1003
+ console.log(
1004
+ "Run `ht plugin apply` in that directory first, or pick plugins from your library to define which env vars are required."
1005
+ );
1006
+ return;
1007
+ }
1008
+ console.log(
1009
+ `Project ${inspection.projectRoot} is tracked, but no plugins have been applied yet.`
1010
+ );
1011
+ console.log(
1012
+ "Run `ht plugin apply` there, or pick plugins from your library to define which env vars are required."
1013
+ );
1014
+ }
1015
+ async function promptMissingScopeAction() {
1016
+ return withPromptBack(
1017
+ () => promptForChoice({
1018
+ message: "How do you want to continue?",
1019
+ choices: [
1020
+ {
1021
+ name: "Pick plugins from library",
1022
+ value: "pick_plugins",
1023
+ description: "Choose which plugins define required env vars"
1024
+ },
1025
+ {
1026
+ name: "Try another project directory",
1027
+ value: "change_directory",
1028
+ description: "Look for a tracked project with applied plugins"
1029
+ },
1030
+ {
1031
+ name: "Cancel",
1032
+ value: "cancel",
1033
+ description: "Abort environment create"
1034
+ }
1035
+ ],
1036
+ default: "pick_plugins"
1037
+ })
1038
+ );
1039
+ }
1040
+ async function promptPluginSelectorsFromLibrary() {
1041
+ const pluginChoices = toPluginChoices();
1042
+ if (pluginChoices.length === 0) {
1043
+ console.log("");
1044
+ console.log("No plugins found in your HarnessTap library.");
1045
+ console.log("Create a plugin first with `ht plugin create`, then retry.");
1046
+ return [];
1047
+ }
1048
+ try {
1049
+ const selected = await promptForSearchableMultiSelect({
1050
+ message: "Plugins that define required environment variables",
1051
+ choices: pluginChoices.map((choice) => ({
1052
+ name: choice.name,
1053
+ value: choice.value,
1054
+ description: choice.description
1055
+ }))
1056
+ });
1057
+ if (selected.length === 0) {
1058
+ console.log("");
1059
+ console.log("Select at least one plugin to continue.");
1060
+ return [];
1061
+ }
1062
+ return selected;
1063
+ } catch (error) {
1064
+ if (isPromptBackError(error)) {
1065
+ return "back";
1066
+ }
1067
+ throw error;
1068
+ }
1069
+ }
1070
+ async function promptAppliedPluginSelectors(input) {
1071
+ if (input.selectors.length === 1) {
1072
+ console.log("");
1073
+ console.log(`Using applied plugin: ${input.labels[0]}`);
1074
+ return input.selectors;
1075
+ }
1076
+ console.log("");
1077
+ console.log("Applied plugins at this project:");
1078
+ for (const label of input.labels) {
1079
+ console.log(` - ${label}`);
1080
+ }
1081
+ try {
1082
+ const selected = await promptForSearchableMultiSelect({
1083
+ message: "Plugins to derive required environment variables from",
1084
+ choices: input.selectors.map((selector, index) => ({
1085
+ name: input.labels[index] ?? selector,
1086
+ value: selector
1087
+ })),
1088
+ default: input.selectors
1089
+ });
1090
+ if (selected.length === 0) {
1091
+ console.log("");
1092
+ console.log("Select at least one plugin to continue.");
1093
+ return [];
1094
+ }
1095
+ return selected;
1096
+ } catch (error) {
1097
+ if (isPromptBackError(error)) {
1098
+ return "back";
1099
+ }
1100
+ throw error;
1101
+ }
1102
+ }
1103
+ async function promptProjectDirectory(defaultPath = ".") {
1104
+ return resolve(
1105
+ await withPromptBack(
1106
+ () => promptForValue({
1107
+ message: "Project directory to scan for harness configuration",
1108
+ default: defaultPath
1109
+ })
1110
+ )
1111
+ );
1112
+ }
1113
+ async function promptForProjectPluginScope(input) {
1114
+ let projectRoot = input?.initialProjectRoot ? resolve(input.initialProjectRoot) : void 0;
1115
+ while (true) {
1116
+ if (!projectRoot) {
1117
+ try {
1118
+ projectRoot = await promptProjectDirectory();
1119
+ } catch (error) {
1120
+ if (isPromptBackError(error)) {
1121
+ throw error;
1122
+ }
1123
+ throw error;
1124
+ }
1125
+ }
1126
+ while (true) {
1127
+ const inspection = inspectProjectPluginScope(projectRoot);
1128
+ if (inspection.kind === "applied") {
1129
+ const pluginSelection2 = await promptAppliedPluginSelectors({
1130
+ labels: inspection.labels,
1131
+ selectors: inspection.selectors
1132
+ });
1133
+ if (pluginSelection2 === "back") {
1134
+ projectRoot = void 0;
1135
+ break;
1136
+ }
1137
+ if (pluginSelection2.length === 0) {
1138
+ continue;
1139
+ }
1140
+ return {
1141
+ projectRoot: inspection.projectRoot,
1142
+ pluginSelectors: pluginSelection2
1143
+ };
1144
+ }
1145
+ explainMissingProjectPlugins(inspection);
1146
+ let action;
1147
+ try {
1148
+ action = await promptMissingScopeAction();
1149
+ } catch (error) {
1150
+ if (isPromptBackError(error)) {
1151
+ projectRoot = void 0;
1152
+ break;
1153
+ }
1154
+ throw error;
1155
+ }
1156
+ if (action === "cancel") {
1157
+ return void 0;
1158
+ }
1159
+ if (action === "change_directory") {
1160
+ projectRoot = void 0;
1161
+ break;
1162
+ }
1163
+ const pluginSelection = await promptPluginSelectorsFromLibrary();
1164
+ if (pluginSelection === "back") {
1165
+ continue;
1166
+ }
1167
+ if (pluginSelection.length === 0) {
1168
+ continue;
1169
+ }
1170
+ return {
1171
+ projectRoot: inspection.projectRoot,
1172
+ pluginSelectors: pluginSelection
1173
+ };
1174
+ }
1175
+ }
1176
+ }
1177
+ var ENVIRONMENT_CREATE_SOURCE_CHOICES = [
1178
+ {
1179
+ name: "From project",
1180
+ value: "from-project",
1181
+ description: "Scan harness files and import required env vars for applied plugins"
1182
+ },
1183
+ {
1184
+ name: "From plugin requirements",
1185
+ value: "from-plugin",
1186
+ description: "Fill keys a plugin needs without scanning a project directory"
1187
+ },
1188
+ {
1189
+ name: "Blank environment",
1190
+ value: "blank",
1191
+ description: "Create an empty record and add values in environment edit"
1192
+ }
1193
+ ];
1194
+
1195
+ // src/services/wizards/environment-create.ts
1196
+ function buildEnvSuggestionChoices(requiredKeys, processEnv = process.env) {
1197
+ const suggestions = suggestProcessEnvKeys(requiredKeys, { processEnv });
1198
+ const choices = [];
1199
+ for (const key of suggestions.exact) {
1200
+ choices.push({
1201
+ name: `${key} (exact match)`,
1202
+ value: key,
1203
+ description: `process.env.${key}`,
1204
+ defaultSelected: true
1205
+ });
1206
+ }
1207
+ for (const key of suggestions.fuzzy) {
1208
+ choices.push({
1209
+ name: `${key} (fuzzy match)`,
1210
+ value: key,
1211
+ description: `process.env.${key}`,
1212
+ defaultSelected: false
1213
+ });
1214
+ }
1215
+ return choices;
1216
+ }
1217
+ function resolveRequiredKeyForProcessKey(processKey, requiredKeys) {
1218
+ if (requiredKeys.includes(processKey)) {
1219
+ return processKey;
1220
+ }
1221
+ const matches = requiredKeys.filter(
1222
+ (requiredKey) => processKey.includes(requiredKey) || requiredKey.includes(processKey)
1223
+ );
1224
+ if (matches.length === 0) {
1225
+ return void 0;
1226
+ }
1227
+ return matches.sort((left, right) => right.length - left.length)[0];
1228
+ }
1229
+ function requiresSecretRef(key, sources) {
1230
+ return isSecretKey(key) || sources.includes("plugin_needs");
1231
+ }
1232
+ async function resolveSecretKeyPolicy(input) {
1233
+ if (!requiresSecretRef(input.key, input.sources)) {
1234
+ input.resolved.values[input.key] = input.value;
1235
+ return;
1236
+ }
1237
+ const useLiteral = await promptForConfirmation({
1238
+ message: `Store ${input.key} as a literal value? (default is secret reference)`,
1239
+ default: false
1240
+ });
1241
+ if (useLiteral) {
1242
+ const confirmed = await promptForConfirmation({
1243
+ message: `Warning: storing ${input.key} as a literal secret in the environment record. Continue?`,
1244
+ default: false
1245
+ });
1246
+ if (!confirmed) {
1247
+ input.resolved.secret_refs[input.key] = {
1248
+ provider: "env",
1249
+ ref: input.key
1250
+ };
1251
+ return;
1252
+ }
1253
+ input.resolved.values[input.key] = input.value;
1254
+ return;
1255
+ }
1256
+ input.resolved.secret_refs[input.key] = {
1257
+ provider: "env",
1258
+ ref: input.key
1259
+ };
1260
+ }
1261
+ async function collectFromPluginResolutions(input) {
1262
+ const processEnv = input.processEnv ?? process.env;
1263
+ const requirements = collectPluginRequirements([input.pluginSelector]);
1264
+ const resolved = {
1265
+ values: {},
1266
+ secret_refs: {}
1267
+ };
1268
+ const coveredKeys = /* @__PURE__ */ new Set();
1269
+ const suggestionChoices = buildEnvSuggestionChoices(
1270
+ requirements.required_keys,
1271
+ processEnv
1272
+ );
1273
+ if (suggestionChoices.length > 0) {
1274
+ let selectedProcessKeys;
1275
+ try {
1276
+ selectedProcessKeys = await promptForSearchableMultiSelect({
1277
+ message: "Import matching process environment variables?",
1278
+ choices: suggestionChoices.map((choice) => ({
1279
+ name: choice.name,
1280
+ value: choice.value,
1281
+ description: choice.description
1282
+ })),
1283
+ default: suggestionChoices.filter((choice) => choice.defaultSelected).map((choice) => choice.value)
1284
+ });
1285
+ } catch (error) {
1286
+ if (isPromptBackError(error)) {
1287
+ throw error;
1288
+ }
1289
+ throw error;
1290
+ }
1291
+ for (const processKey of selectedProcessKeys) {
1292
+ const requiredKey = resolveRequiredKeyForProcessKey(
1293
+ processKey,
1294
+ requirements.required_keys
1295
+ );
1296
+ if (!requiredKey || coveredKeys.has(requiredKey)) {
1297
+ continue;
1298
+ }
1299
+ const value = processEnv[processKey];
1300
+ if (value === void 0) {
1301
+ continue;
1302
+ }
1303
+ coveredKeys.add(requiredKey);
1304
+ const sources = requirements.key_sources[requiredKey] ?? [];
1305
+ if (requiresSecretRef(requiredKey, sources)) {
1306
+ resolved.secret_refs[requiredKey] = {
1307
+ provider: "env",
1308
+ ref: processKey
1309
+ };
1310
+ } else {
1311
+ resolved.values[requiredKey] = value;
1312
+ }
1313
+ }
1314
+ }
1315
+ for (const key of requirements.required_keys) {
1316
+ if (coveredKeys.has(key)) {
1317
+ continue;
1318
+ }
1319
+ const sources = requirements.key_sources[key] ?? [];
1320
+ const fromProcess = processEnv[key];
1321
+ if (fromProcess !== void 0) {
1322
+ coveredKeys.add(key);
1323
+ await resolveSecretKeyPolicy({
1324
+ key,
1325
+ value: fromProcess,
1326
+ sources,
1327
+ resolved
1328
+ });
1329
+ continue;
1330
+ }
1331
+ const manualValue = await promptForValue({
1332
+ message: `Value for ${key}`
1333
+ });
1334
+ coveredKeys.add(key);
1335
+ await resolveSecretKeyPolicy({
1336
+ key,
1337
+ value: manualValue,
1338
+ sources,
1339
+ resolved
1340
+ });
1341
+ }
1342
+ return resolved;
1343
+ }
1344
+ async function promptOptionalDescription(description) {
1345
+ if (description) {
1346
+ return description;
1347
+ }
1348
+ const addDescription = await promptForConfirmation({
1349
+ message: "Add a description?",
1350
+ default: false
1351
+ });
1352
+ if (!addDescription) {
1353
+ return void 0;
1354
+ }
1355
+ return promptForValue({ message: "Description" });
1356
+ }
1357
+ function printFromProjectPreviewSummary(preview) {
1358
+ console.log("");
1359
+ console.log(`Environment: ${preview.environment_name}`);
1360
+ console.log(`Project harness: ${preview.harness}`);
1361
+ console.log(`Configured plugins: ${preview.configured_plugin_ids.length}`);
1362
+ console.log(`Imported values: ${Object.keys(preview.values).length}`);
1363
+ console.log(`Secret refs: ${Object.keys(preview.secret_refs).length}`);
1364
+ console.log(`Missing keys: ${preview.missing_keys.length}`);
1365
+ console.log("");
1366
+ }
1367
+ function printFromPluginPreviewSummary(input) {
1368
+ console.log("");
1369
+ console.log(`Environment: ${input.name}`);
1370
+ console.log(`Plugin: ${input.pluginSelector}`);
1371
+ console.log(`Literal values: ${Object.keys(input.resolved.values).length}`);
1372
+ console.log(`Secret refs: ${Object.keys(input.resolved.secret_refs).length}`);
1373
+ console.log(`Bind as default: ${input.bind ? "yes" : "no"}`);
1374
+ console.log("");
1375
+ }
1376
+ async function runEnvironmentCreateWizard(input) {
1377
+ while (true) {
1378
+ const source = await promptForChoice({
1379
+ message: "How should this environment be created?",
1380
+ choices: ENVIRONMENT_CREATE_SOURCE_CHOICES,
1381
+ default: "from-project"
1382
+ });
1383
+ if (source === "blank") {
1384
+ const description = await promptOptionalDescription(input.description);
1385
+ const confirmed2 = await promptForConfirmation({
1386
+ message: `Create blank environment ${input.name}?`,
1387
+ default: true
1388
+ });
1389
+ if (!confirmed2) {
1390
+ continue;
1391
+ }
1392
+ const result2 = await runEnvironmentCreate({
1393
+ name: input.name,
1394
+ blank: true,
1395
+ description
1396
+ });
1397
+ return { status: "confirmed", result: result2 };
1398
+ }
1399
+ if (source === "from-project") {
1400
+ let scope;
1401
+ try {
1402
+ scope = await promptForProjectPluginScope();
1403
+ } catch (error) {
1404
+ if (isPromptBackError(error)) {
1405
+ continue;
1406
+ }
1407
+ throw error;
1408
+ }
1409
+ if (!scope) {
1410
+ continue;
1411
+ }
1412
+ const { projectRoot, pluginSelectors } = scope;
1413
+ const preview = await previewEnvironmentCapture({
1414
+ mode: "capture",
1415
+ environmentName: input.name,
1416
+ projectRoot,
1417
+ pluginSelectors
1418
+ });
1419
+ printFromProjectPreviewSummary(preview);
1420
+ const confirmed2 = await promptForConfirmation({
1421
+ message: "Create environment from this project preview?",
1422
+ default: true
1423
+ });
1424
+ if (!confirmed2) {
1425
+ continue;
1426
+ }
1427
+ const result2 = await runEnvironmentCreate({
1428
+ name: input.name,
1429
+ fromProject: projectRoot,
1430
+ plugins: pluginSelectors,
1431
+ description: input.description
1432
+ });
1433
+ return { status: "confirmed", result: result2 };
1434
+ }
1435
+ const plugins = listPlugins();
1436
+ if (plugins.length === 0) {
1437
+ throw new Error("No configured plugins found.");
1438
+ }
1439
+ let pluginSelector;
1440
+ let resolved;
1441
+ while (true) {
1442
+ try {
1443
+ pluginSelector = await withPromptBack(
1444
+ () => promptForSearchableChoice({
1445
+ message: "Plugin whose requirements should seed this environment",
1446
+ choices: toPluginChoices()
1447
+ })
1448
+ );
1449
+ } catch (error) {
1450
+ if (isPromptBackError(error)) {
1451
+ pluginSelector = void 0;
1452
+ break;
1453
+ }
1454
+ throw error;
1455
+ }
1456
+ try {
1457
+ resolved = await collectFromPluginResolutions({ pluginSelector });
1458
+ break;
1459
+ } catch (error) {
1460
+ if (isPromptBackError(error)) {
1461
+ continue;
1462
+ }
1463
+ throw error;
1464
+ }
1465
+ }
1466
+ if (!pluginSelector || !resolved) {
1467
+ continue;
1468
+ }
1469
+ const bind = await promptForConfirmation({
1470
+ message: "Set as default environment for this plugin?",
1471
+ default: true
1472
+ });
1473
+ printFromPluginPreviewSummary({
1474
+ name: input.name,
1475
+ pluginSelector,
1476
+ resolved,
1477
+ bind
1478
+ });
1479
+ const confirmed = await promptForConfirmation({
1480
+ message: "Create environment from this configuration?",
1481
+ default: true
1482
+ });
1483
+ if (!confirmed) {
1484
+ continue;
1485
+ }
1486
+ const result = await runEnvironmentCreate({
1487
+ name: input.name,
1488
+ fromPlugin: pluginSelector,
1489
+ bind,
1490
+ description: input.description,
1491
+ fromPluginResolved: resolved
1492
+ });
1493
+ return { status: "confirmed", result };
1494
+ }
1495
+ }
1496
+
1497
+ // src/ui/environment-list-render.ts
1498
+ var ENVIRONMENT_SEARCH_SECTIONS = ["name", "desc", "description"];
1499
+ function isEnvironmentSearchSection(section) {
1500
+ return ENVIRONMENT_SEARCH_SECTIONS.includes(section);
1501
+ }
1502
+ function formatEnvironmentListName(row, opts) {
1503
+ const cursor = opts?.selected ? ">" : " ";
1504
+ return `${cursor} ${row.environment.name}`;
1505
+ }
1506
+ function filterEnvironmentsBySearch(rows, search) {
1507
+ const parsed = parseListSearchQuery(search);
1508
+ if (parsed.raw.length === 0) {
1509
+ return rows;
1510
+ }
1511
+ const sectionIsKnown = parsed.section !== void 0 && isEnvironmentSearchSection(parsed.section);
1512
+ const textQuery = sectionIsKnown ? parsed : parsed.section !== void 0 ? { section: void 0, text: parsed.raw, raw: parsed.raw } : parsed;
1513
+ return rows.filter((row) => {
1514
+ if (sectionIsKnown && parsed.section === "name") {
1515
+ return matchesListSearchQuery(row.environment.name, textQuery);
1516
+ }
1517
+ if (sectionIsKnown && (parsed.section === "desc" || parsed.section === "description")) {
1518
+ return matchesListSearchQuery(row.environment.description, textQuery);
1519
+ }
1520
+ const haystack = `${row.environment.name} ${row.environment.description}`;
1521
+ return matchesListSearchQuery(haystack, textQuery);
1522
+ });
1523
+ }
1524
+ function clampIndex(index, length) {
1525
+ if (length === 0) return 0;
1526
+ return Math.max(0, Math.min(index, length - 1));
1527
+ }
1528
+ function buildEnvironmentViewportHintSegments(viewport, total) {
1529
+ const segments = [];
1530
+ if (viewport.start > 0) {
1531
+ segments.push(`\u2191 ${viewport.start} above`);
1532
+ }
1533
+ if (viewport.end < total) {
1534
+ segments.push(`\u2193 ${total - viewport.end} more`);
1535
+ }
1536
+ return segments;
1537
+ }
1538
+ function renderViewportOverflowHints(viewport, total, maxWidth) {
1539
+ const folded = renderFoldedHintLine(
1540
+ buildEnvironmentViewportHintSegments(viewport, total),
1541
+ maxWidth
1542
+ );
1543
+ return folded.length > 0 ? theme.muted(folded) : "";
1544
+ }
1545
+ function makeEnvironmentListColumns(highlightSelection) {
1546
+ return [
1547
+ {
1548
+ key: "name",
1549
+ header: "NAME",
1550
+ width: 24,
1551
+ style: highlightSelection ? (value) => value.startsWith(">") ? theme.accent(value) : value : void 0
1552
+ },
1553
+ { key: "value_count", header: "VALUES", width: 8 },
1554
+ { key: "secret_ref_count", header: "SECRETS", width: 8 },
1555
+ { key: "reference_count", header: "REFS", width: 8 }
1556
+ ];
1557
+ }
1558
+ function toTableRows(rows, selectedName) {
1559
+ return rows.map((row) => ({
1560
+ name: formatEnvironmentListName(row, {
1561
+ selected: row.environment.name === selectedName
1562
+ }),
1563
+ value_count: row.value_count,
1564
+ secret_ref_count: row.secret_ref_count,
1565
+ reference_count: row.reference_count
1566
+ }));
1567
+ }
1568
+ function tableLayout(maxWidth) {
1569
+ return {
1570
+ maxWidth: resolveTableMaxWidth(maxWidth),
1571
+ wordWrap: true
1572
+ };
1573
+ }
1574
+ function renderEnvironmentListViewport(opts) {
1575
+ if (opts.navigable.length === 0) {
1576
+ return theme.muted("No environments found.");
1577
+ }
1578
+ const maxWidth = resolveTableMaxWidth(opts.maxWidth);
1579
+ const maxVisibleRows = computeMaxVisibleTableRows(
1580
+ opts.terminalRows,
1581
+ VIEWPORT_CHROME_LINES.environmentList
1582
+ );
1583
+ const activeIndex = clampIndex(opts.activeIndex, opts.navigable.length);
1584
+ const viewport = resolveSectionViewport(
1585
+ opts.navigable.length,
1586
+ activeIndex,
1587
+ maxVisibleRows
1588
+ );
1589
+ const visibleRows = opts.navigable.slice(viewport.start, viewport.end);
1590
+ const selectedName = opts.navigable[activeIndex]?.environment.name;
1591
+ return [
1592
+ renderTable({
1593
+ columns: makeEnvironmentListColumns(true),
1594
+ rows: toTableRows(visibleRows, selectedName),
1595
+ ...tableLayout(opts.maxWidth)
1596
+ }),
1597
+ renderViewportOverflowHints(viewport, opts.navigable.length, maxWidth)
1598
+ ].filter((line) => line.length > 0).join("\n");
1599
+ }
1600
+ function renderEnvironmentListTable(rows, opts) {
1601
+ if (rows.length === 0) {
1602
+ return theme.muted("No environments found.");
1603
+ }
1604
+ return renderTable({
1605
+ columns: makeEnvironmentListColumns(false),
1606
+ rows: toTableRows(rows),
1607
+ ...tableLayout(opts?.maxWidth)
1608
+ });
1609
+ }
1610
+ function renderEnvironmentListShow(row) {
1611
+ return renderPanel({
1612
+ title: ["ENVIRONMENT", row.environment.name],
1613
+ rows: [
1614
+ ["Description", row.environment.description || ": "],
1615
+ ["Values", `${row.value_count}`],
1616
+ ["Secret refs", `${row.secret_ref_count}`],
1617
+ ["Plugin references", `${row.reference_count}`]
1618
+ ]
1619
+ });
1620
+ }
1621
+
1622
+ // src/services/wizards/adapters/environment-table-browser.ts
1623
+ function createEnvironmentTableBrowserAdapter(config) {
1624
+ return {
1625
+ resolveItems: (query) => {
1626
+ const filtered = filterEnvironmentsBySearch(config.environments, query);
1627
+ return { filtered, navigable: filtered };
1628
+ },
1629
+ renderViewport: (args) => renderEnvironmentListViewport({
1630
+ activeIndex: args.active,
1631
+ navigable: args.navigable,
1632
+ terminalRows: args.terminalRows,
1633
+ maxWidth: args.terminalWidth
1634
+ }),
1635
+ renderShow: (row) => renderEnvironmentListShow(row),
1636
+ onPick: (row) => row.environment.name,
1637
+ onEdit: (row) => row.environment.name,
1638
+ formatDeleteConfirm: (row) => `Delete environment "${row.environment.name}"?`,
1639
+ helpActions: buildFilterListHelpActions({ edit: true, delete: true })
1640
+ };
1641
+ }
1642
+
1643
+ // src/services/wizards/environment-delete.ts
1644
+ async function runEnvironmentDeleteWizard(input, context) {
1645
+ const environments = listEnvironmentsCommand();
1646
+ const filtered = input?.search ? filterEnvironmentsBySearch(environments, input.search) : environments;
1647
+ if (filtered.length > 0) {
1648
+ const result = await createTableBrowserPrompt({
1649
+ message: "Which environment do you want to delete?",
1650
+ initialQuery: input?.search,
1651
+ intent: { kind: "pick-one", action: "delete" },
1652
+ adapter: {
1653
+ ...createEnvironmentTableBrowserAdapter({ environments: filtered }),
1654
+ onPick: (row) => row.environment.name,
1655
+ helpActions: [
1656
+ ["\u2191\u2193", "select"],
1657
+ ["type", "search"],
1658
+ ["\u23CE", "delete"],
1659
+ ["esc", "cancel"]
1660
+ ]
1661
+ }
1662
+ }, context);
1663
+ if (result.kind === "pick-one") {
1664
+ return [result.value];
1665
+ }
1666
+ return [];
1667
+ }
1668
+ const selector = await promptForValue({
1669
+ message: "Environment name or ID to delete",
1670
+ default: input?.search
1671
+ });
1672
+ return selector.length > 0 ? [selector] : [];
1673
+ }
1674
+
1675
+ // src/ui/environment-edit-render.ts
1676
+ var ENVIRONMENT_EDIT_KINDS = [
1677
+ "env_var",
1678
+ "secret_ref",
1679
+ "model_config",
1680
+ "permission"
1681
+ ];
1682
+ var ENVIRONMENT_EDIT_KIND_LABELS = {
1683
+ env_var: "ENV VARS",
1684
+ secret_ref: "SECRET REFS",
1685
+ model_config: "MODEL CONFIGS",
1686
+ permission: "PERMISSIONS"
1687
+ };
1688
+ function formatEnvironmentEditRowLabel(row) {
1689
+ switch (row.kind) {
1690
+ case "env_var":
1691
+ return `${row.key}=${row.value}`;
1692
+ case "secret_ref":
1693
+ return `${row.key} (${row.provider}:${row.ref})`;
1694
+ case "model_config":
1695
+ return row.provider ? `${row.name}: ${row.model} @ ${row.provider}` : `${row.name}: ${row.model}`;
1696
+ case "permission":
1697
+ return `${row.name}: ${row.action}:${row.pattern}`;
1698
+ default: {
1699
+ const neverRow = row;
1700
+ throw new Error(`Unsupported row kind: ${String(neverRow)}`);
1701
+ }
1702
+ }
1703
+ }
1704
+ function listNavigableEnvironmentEditRows(rows) {
1705
+ const ordered = [];
1706
+ for (const kind of ENVIRONMENT_EDIT_KINDS) {
1707
+ ordered.push(...rows.filter((row) => row.kind === kind));
1708
+ }
1709
+ return ordered;
1710
+ }
1711
+ function sectionCount(navigable, kind) {
1712
+ return navigable.filter((row) => row.kind === kind).length;
1713
+ }
1714
+ function resolveEnvironmentActiveSectionContext(navigable, active) {
1715
+ const selected = navigable[active];
1716
+ if (!selected) {
1717
+ return { kind: "env_var", indexInSection: 0, sectionRows: [] };
1718
+ }
1719
+ const kind = selected.kind;
1720
+ const sectionRows = navigable.filter((row) => row.kind === kind);
1721
+ const indexInSection = sectionRows.indexOf(selected);
1722
+ const kindIndex = ENVIRONMENT_EDIT_KINDS.indexOf(kind);
1723
+ const prevSection = ENVIRONMENT_EDIT_KINDS.slice(0, kindIndex).reverse().map((sectionKind) => ({
1724
+ kind: sectionKind,
1725
+ count: sectionCount(navigable, sectionKind)
1726
+ })).find((section) => section.count > 0);
1727
+ const nextSection = ENVIRONMENT_EDIT_KINDS.slice(kindIndex + 1).map((sectionKind) => ({
1728
+ kind: sectionKind,
1729
+ count: sectionCount(navigable, sectionKind)
1730
+ })).find((section) => section.count > 0);
1731
+ return { kind, indexInSection, sectionRows, prevSection, nextSection };
1732
+ }
1733
+ function buildEnvironmentEditViewportHintSegments(ctx, viewport) {
1734
+ const segments = [];
1735
+ const hiddenBelow = ctx.sectionRows.length - viewport.end;
1736
+ const hiddenAbove = viewport.start;
1737
+ if (hiddenAbove > 0) {
1738
+ segments.push(`\u2191 ${hiddenAbove} above`);
1739
+ }
1740
+ if (hiddenBelow > 0) {
1741
+ segments.push(`\u2193 ${hiddenBelow} more in ${ENVIRONMENT_EDIT_KIND_LABELS[ctx.kind]}`);
1742
+ }
1743
+ if (ctx.nextSection) {
1744
+ segments.push(`${ENVIRONMENT_EDIT_KIND_LABELS[ctx.nextSection.kind]} (${ctx.nextSection.count})`);
1745
+ segments.push("\u2193 next section");
1746
+ }
1747
+ if (viewport.start === 0 && ctx.prevSection) {
1748
+ segments.push(`${ENVIRONMENT_EDIT_KIND_LABELS[ctx.prevSection.kind]} (${ctx.prevSection.count})`);
1749
+ segments.push("\u2191 prev section");
1750
+ }
1751
+ return segments;
1752
+ }
1753
+ function renderEnvironmentViewportOverflowHints(ctx, viewport, maxWidth) {
1754
+ const folded = renderFoldedHintLine(
1755
+ buildEnvironmentEditViewportHintSegments(ctx, viewport),
1756
+ maxWidth
1757
+ );
1758
+ return folded.length > 0 ? theme.muted(folded) : "";
1759
+ }
1760
+ function renderGroupedEnvironmentEditViewport(rows, opts) {
1761
+ if (rows.length === 0) {
1762
+ return theme.muted("No matching rows.");
1763
+ }
1764
+ const ctx = resolveEnvironmentActiveSectionContext(opts.navigable, opts.activeIndex);
1765
+ if (ctx.sectionRows.length === 0) {
1766
+ return theme.muted("No matching rows.");
1767
+ }
1768
+ const maxVisibleRows = computeMaxVisibleRows(
1769
+ opts.terminalRows,
1770
+ VIEWPORT_CHROME_LINES.environmentEdit,
1771
+ 3
1772
+ );
1773
+ const viewport = resolveSectionViewport(
1774
+ ctx.sectionRows.length,
1775
+ ctx.indexInSection,
1776
+ maxVisibleRows
1777
+ );
1778
+ const visibleRows = ctx.sectionRows.slice(viewport.start, viewport.end);
1779
+ const activeRow = opts.navigable[opts.activeIndex];
1780
+ const maxWidth = opts.maxWidth ?? terminalColumns();
1781
+ const body = [
1782
+ styleResourceType(ctx.kind),
1783
+ ENVIRONMENT_EDIT_KIND_LABELS[ctx.kind],
1784
+ ...visibleRows.map((row) => {
1785
+ const marker = row === activeRow ? theme.accent(">") : " ";
1786
+ return `${marker} ${formatEnvironmentEditRowLabel(row)}`;
1787
+ }),
1788
+ renderEnvironmentViewportOverflowHints(ctx, viewport, maxWidth)
1789
+ ];
1790
+ return body.filter((line) => line.length > 0).join("\n");
1791
+ }
1792
+
1793
+ // src/services/wizards/prompts/create-action-list-prompt.ts
1794
+ function mapManageAction(action) {
1795
+ switch (action.type) {
1796
+ case "quit":
1797
+ case "cancel":
1798
+ case "add":
1799
+ return action;
1800
+ case "edit":
1801
+ case "delete":
1802
+ return action;
1803
+ default: {
1804
+ const _exhaustive = action;
1805
+ return _exhaustive;
1806
+ }
1807
+ }
1808
+ }
1809
+ function createActionListPrompt(config, context) {
1810
+ const prompt = createTableBrowserPrompt(
1811
+ {
1812
+ message: config.message,
1813
+ initialQuery: config.initialQuery,
1814
+ intent: { kind: "manage" },
1815
+ manageSourceRows: config.rows,
1816
+ adapter: {
1817
+ resolveItems: (query) => {
1818
+ const filtered = config.filterRows(config.rows, query);
1819
+ return { filtered, navigable: filtered };
1820
+ },
1821
+ renderViewport: (args) => config.renderBrowse({
1822
+ prefix: args.prefix,
1823
+ styledMessage: args.styledMessage,
1824
+ query: args.query,
1825
+ filteredRows: args.navigable,
1826
+ activeRow: args.selectedItem,
1827
+ active: args.active,
1828
+ terminalWidth: args.terminalWidth,
1829
+ terminalRows: args.terminalRows
1830
+ }),
1831
+ helpActions: []
1832
+ }
1833
+ },
1834
+ context
1835
+ );
1836
+ const mapped = prompt.then((result) => {
1837
+ if (result.kind === "manage") {
1838
+ return mapManageAction(result.action);
1839
+ }
1840
+ throw new Error(`Unexpected table browser result: ${result.kind}`);
1841
+ });
1842
+ mapped.cancel = prompt.cancel;
1843
+ return mapped;
1844
+ }
1845
+
1846
+ // src/services/wizards/interactive-environment-edit.ts
1847
+ function filterEnvironmentEditRows(rows, query) {
1848
+ const normalized = query.trim().toLowerCase();
1849
+ const filtered = normalized.length === 0 ? rows : rows.filter(
1850
+ (row) => formatEnvironmentEditRowLabel(row).toLowerCase().includes(normalized)
1851
+ );
1852
+ return listNavigableEnvironmentEditRows(filtered);
1853
+ }
1854
+ var promptForInteractiveEnvironmentEdit = (config, context) => createActionListPrompt(
1855
+ {
1856
+ message: config.message,
1857
+ rows: config.rows,
1858
+ initialQuery: config.initialQuery,
1859
+ filterRows: filterEnvironmentEditRows,
1860
+ renderBrowse: ({
1861
+ prefix,
1862
+ styledMessage,
1863
+ query,
1864
+ filteredRows,
1865
+ active,
1866
+ terminalWidth,
1867
+ terminalRows
1868
+ }) => {
1869
+ const tables = renderGroupedEnvironmentEditViewport(filteredRows, {
1870
+ activeIndex: active,
1871
+ navigable: filteredRows,
1872
+ terminalRows,
1873
+ maxWidth: terminalWidth
1874
+ });
1875
+ const helpLine = buildHelpLine([
1876
+ ["\u2191\u2193", "navigate"],
1877
+ ["type", "search"],
1878
+ ["\u232B", "erase"],
1879
+ ["\u23CE", "edit"],
1880
+ ["a", "add env var"],
1881
+ ["d", "delete"],
1882
+ ["q", "quit"],
1883
+ ["esc", "cancel"]
1884
+ ]);
1885
+ return [
1886
+ `${prefix} ${styledMessage}`,
1887
+ `${theme.label("Search:")} ${query ? theme.entity(query) : theme.muted("(type to filter)")}`,
1888
+ "",
1889
+ tables,
1890
+ "",
1891
+ helpLine
1892
+ ].join("\n");
1893
+ }
1894
+ },
1895
+ context
1896
+ );
1897
+
1898
+ // src/services/wizards/environment-edit.ts
1899
+ function parsePermissionEditValue(raw) {
1900
+ const idx = raw.indexOf(":");
1901
+ if (idx <= 0 || idx >= raw.length - 1) {
1902
+ throw new Error(`Invalid permission "${raw}". Expected action:pattern.`);
1903
+ }
1904
+ const action = raw.slice(0, idx);
1905
+ if (!["allow", "deny", "ask"].includes(action)) {
1906
+ throw new Error(`Invalid permission action "${action}". Use allow, deny, or ask.`);
1907
+ }
1908
+ return {
1909
+ action,
1910
+ pattern: raw.slice(idx + 1)
1911
+ };
1912
+ }
1913
+ async function editEnvironmentRow(selector, row) {
1914
+ switch (row.kind) {
1915
+ case "env_var": {
1916
+ const value = await promptForValue({
1917
+ message: `New value for ${row.key}`,
1918
+ default: row.value
1919
+ });
1920
+ setEnvironmentVarCommand(selector, row.key, value);
1921
+ return;
1922
+ }
1923
+ case "secret_ref": {
1924
+ const ref = await promptForValue({
1925
+ message: `New ref for ${row.key}`,
1926
+ default: row.ref
1927
+ });
1928
+ setEnvironmentSecretCommand(selector, {
1929
+ key: row.key,
1930
+ provider: row.provider,
1931
+ ref
1932
+ });
1933
+ return;
1934
+ }
1935
+ case "model_config": {
1936
+ const model = await promptForValue({
1937
+ message: `New model for ${row.name}`,
1938
+ default: row.model
1939
+ });
1940
+ setEnvironmentModelConfigCommand(selector, {
1941
+ name: row.name,
1942
+ model,
1943
+ ...row.provider ? { provider: row.provider } : {}
1944
+ });
1945
+ return;
1946
+ }
1947
+ case "permission": {
1948
+ const pattern = await promptForValue({
1949
+ message: `New action:pattern for ${row.name}`,
1950
+ default: `${row.action}:${row.pattern}`
1951
+ });
1952
+ const parsed = parsePermissionEditValue(pattern);
1953
+ setEnvironmentPermissionCommand(selector, {
1954
+ name: row.name,
1955
+ ...parsed
1956
+ });
1957
+ return;
1958
+ }
1959
+ default: {
1960
+ const neverRow = row;
1961
+ throw new Error(`Unsupported row kind: ${String(neverRow)}`);
1962
+ }
1963
+ }
1964
+ }
1965
+ async function deleteEnvironmentRow(selector, row) {
1966
+ switch (row.kind) {
1967
+ case "env_var":
1968
+ unsetEnvironmentVarCommand(selector, row.key);
1969
+ return;
1970
+ case "secret_ref":
1971
+ unsetEnvironmentSecretCommand(selector, row.key);
1972
+ return;
1973
+ case "model_config":
1974
+ unsetEnvironmentModelConfigCommand(selector, row.name);
1975
+ return;
1976
+ case "permission":
1977
+ unsetEnvironmentPermissionCommand(selector, {
1978
+ name: row.name,
1979
+ action: row.action,
1980
+ pattern: row.pattern
1981
+ });
1982
+ return;
1983
+ default: {
1984
+ const neverRow = row;
1985
+ throw new Error(`Unsupported row kind: ${String(neverRow)}`);
1986
+ }
1987
+ }
1988
+ }
1989
+ function formatEnvironmentLabel(environment) {
1990
+ return environment.name;
1991
+ }
1992
+ async function runEnvironmentEditWizard(input) {
1993
+ const selector = input.environment.name;
1994
+ while (true) {
1995
+ const rows = buildEnvironmentEditRows(input.environment.id);
1996
+ const action = await promptForInteractiveEnvironmentEdit({
1997
+ message: `Edit environment ${formatEnvironmentLabel(input.environment)}`,
1998
+ rows
1999
+ });
2000
+ if (action.type === "cancel") {
2001
+ return void 0;
2002
+ }
2003
+ if (action.type === "quit") {
2004
+ return buildEnvironmentEditRows(input.environment.id);
2005
+ }
2006
+ if (action.type === "add") {
2007
+ const key = await promptForValue({ message: "Env var key" });
2008
+ const value = await promptForValue({ message: `Value for ${key}` });
2009
+ setEnvironmentVarCommand(selector, key, value);
2010
+ continue;
2011
+ }
2012
+ const row = rows[action.rowIndex];
2013
+ if (!row) {
2014
+ continue;
2015
+ }
2016
+ if (action.type === "edit") {
2017
+ await editEnvironmentRow(selector, row);
2018
+ continue;
2019
+ }
2020
+ const confirmed = await promptForConfirmation({
2021
+ message: `Delete ${row.kind} ${formatEnvironmentEditRowSummary(row)}?`,
2022
+ default: false
2023
+ });
2024
+ if (confirmed) {
2025
+ await deleteEnvironmentRow(selector, row);
2026
+ }
2027
+ }
2028
+ }
2029
+ function formatEnvironmentEditRowSummary(row) {
2030
+ switch (row.kind) {
2031
+ case "env_var":
2032
+ return row.key;
2033
+ case "secret_ref":
2034
+ return row.key;
2035
+ case "model_config":
2036
+ return row.name;
2037
+ case "permission":
2038
+ return row.name;
2039
+ default: {
2040
+ const neverRow = row;
2041
+ throw new Error(`Unsupported row kind: ${String(neverRow)}`);
2042
+ }
2043
+ }
2044
+ }
2045
+
2046
+ // src/services/wizards/environment-show.ts
2047
+ async function runEnvironmentShowWizard(input, context) {
2048
+ const environments = listEnvironmentsCommand();
2049
+ const filtered = input?.search ? filterEnvironmentsBySearch(environments, input.search) : environments;
2050
+ if (filtered.length === 0) {
2051
+ return void 0;
2052
+ }
2053
+ const result = await createTableBrowserPrompt({
2054
+ message: "Which environment do you want to show?",
2055
+ initialQuery: input?.search,
2056
+ intent: { kind: "pick-one", action: "show" },
2057
+ adapter: {
2058
+ ...createEnvironmentTableBrowserAdapter({ environments: filtered }),
2059
+ onPick: (row) => row.environment.name,
2060
+ helpActions: [
2061
+ ["\u2191\u2193", "select"],
2062
+ ["type", "search"],
2063
+ ["\u23CE", "show"],
2064
+ ["esc", "cancel"]
2065
+ ]
2066
+ }
2067
+ }, context);
2068
+ if (result.kind === "pick-one") {
2069
+ return result.value;
2070
+ }
2071
+ return void 0;
2072
+ }
2073
+
2074
+ // src/services/wizards/interactive-environment-list.ts
2075
+ var promptForInteractiveEnvironmentList = async (config, context) => {
2076
+ const result = await createTableBrowserPrompt(
2077
+ {
2078
+ message: config.message,
2079
+ initialQuery: config.initialQuery,
2080
+ intent: { kind: "filter" },
2081
+ adapter: createEnvironmentTableBrowserAdapter({
2082
+ environments: config.environments
2083
+ })
2084
+ },
2085
+ context
2086
+ );
2087
+ return mapFilterTableBrowserResult(result);
2088
+ };
2089
+
2090
+ // src/services/wizards/environment-list.ts
2091
+ async function runEnvironmentListWizard(input) {
2092
+ const environments = listEnvironmentsCommand();
2093
+ if (environments.length === 0) {
2094
+ return input?.search ? { action: "filter", query: input.search } : void 0;
2095
+ }
2096
+ return promptForInteractiveEnvironmentList({
2097
+ message: "Filter environments",
2098
+ environments,
2099
+ initialQuery: input?.search
2100
+ });
2101
+ }
2102
+ function filterEnvironmentListRows(rows, search) {
2103
+ if (!search) {
2104
+ return rows;
2105
+ }
2106
+ return filterEnvironmentsBySearch(rows, search);
2107
+ }
2108
+
2109
+ // src/cli/commands/environment.ts
2110
+ function formatPluginLabel2(plugin) {
2111
+ return `${plugin.name}@${plugin.version}`;
2112
+ }
2113
+ function parseVarAssignment(raw) {
2114
+ const idx = raw.indexOf("=");
2115
+ if (idx <= 0) {
2116
+ throw new Error(`Invalid --var entry "${raw}". Expected KEY=VALUE.`);
2117
+ }
2118
+ return {
2119
+ key: raw.slice(0, idx),
2120
+ value: raw.slice(idx + 1)
2121
+ };
2122
+ }
2123
+ function parsePermissionPattern(raw) {
2124
+ const idx = raw.indexOf(":");
2125
+ if (idx <= 0 || idx >= raw.length - 1) {
2126
+ throw new Error(`Invalid permission "${raw}". Expected action:pattern.`);
2127
+ }
2128
+ const action = raw.slice(0, idx);
2129
+ if (!["allow", "deny", "ask"].includes(action)) {
2130
+ throw new Error(`Invalid permission action "${action}". Use allow, deny, or ask.`);
2131
+ }
2132
+ return {
2133
+ action,
2134
+ pattern: raw.slice(idx + 1)
2135
+ };
2136
+ }
2137
+ function parsePermissionUnsetSelector(raw) {
2138
+ try {
2139
+ const parsed = parsePermissionPattern(raw);
2140
+ return parsed;
2141
+ } catch {
2142
+ return { name: raw };
2143
+ }
2144
+ }
2145
+ function renderEnvironmentShowHuman(payload, requirementGaps) {
2146
+ console.log(renderEnvironmentShow(payload, { requirementGaps }));
2147
+ }
2148
+ function printEnvironmentMutationResult(payload, format) {
2149
+ if (format === "json") {
2150
+ printJson(payload);
2151
+ return;
2152
+ }
2153
+ renderEnvironmentShowHuman(payload);
2154
+ }
2155
+ function shouldUseInteractiveEnvironmentEdit(input) {
2156
+ return shouldUseWizard({
2157
+ interactive: true,
2158
+ noInteractive: input.noInteractive,
2159
+ format: parseOutputFormat(input.format),
2160
+ missingRequiredArgs: true
2161
+ });
2162
+ }
2163
+ function shouldUseInteractiveEnvironmentList(input) {
2164
+ if (input.search) {
2165
+ return false;
2166
+ }
2167
+ return shouldUseWizard({
2168
+ interactive: true,
2169
+ noInteractive: input.noInteractive,
2170
+ format: parseOutputFormat(input.format),
2171
+ missingRequiredArgs: true
2172
+ });
2173
+ }
2174
+ async function handleEnvironmentListCommand(opts) {
2175
+ const db = getDb();
2176
+ initializeSchema(db);
2177
+ const format = parseOutputFormat(opts.format);
2178
+ let search = opts.search;
2179
+ if (shouldUseInteractiveEnvironmentList(opts)) {
2180
+ try {
2181
+ while (true) {
2182
+ const wizardResult = await runEnvironmentListWizard({ search });
2183
+ if (!wizardResult) {
2184
+ break;
2185
+ }
2186
+ switch (wizardResult.action) {
2187
+ case "edit":
2188
+ await handleEnvironmentEditCommand(wizardResult.name, {
2189
+ format: opts.format,
2190
+ interactive: true
2191
+ });
2192
+ search = void 0;
2193
+ continue;
2194
+ case "delete":
2195
+ await handleEnvironmentDeleteCommand(wizardResult.name, {
2196
+ format: opts.format,
2197
+ interactive: true
2198
+ });
2199
+ search = void 0;
2200
+ continue;
2201
+ case "filter":
2202
+ search = wizardResult.query.length > 0 ? wizardResult.query : void 0;
2203
+ break;
2204
+ default: {
2205
+ const _exhaustive = wizardResult;
2206
+ throw _exhaustive;
2207
+ }
2208
+ }
2209
+ break;
2210
+ }
2211
+ } catch (error) {
2212
+ if (isPromptCancellationError(error)) {
2213
+ process.exitCode = 1;
2214
+ return;
2215
+ }
2216
+ throw error;
2217
+ }
2218
+ }
2219
+ const environments = filterEnvironmentListRows(listEnvironmentsCommand(), search);
2220
+ if (format === "json") {
2221
+ printJson(environments);
2222
+ return;
2223
+ }
2224
+ if (environments.length === 0) {
2225
+ console.log(
2226
+ `No environments found.
2227
+ \u2192 Run \`${formatCommand("environment create <name>")}\` to add one.`
2228
+ );
2229
+ return;
2230
+ }
2231
+ console.log(renderEnvironmentListTable(environments));
2232
+ }
2233
+ async function resolveEnvironmentMutationTarget(input) {
2234
+ const format = parseOutputFormat(input.format);
2235
+ const choices = listEnvironments().map((environment) => ({
2236
+ name: environment.name,
2237
+ value: environment.name
2238
+ }));
2239
+ return resolveOrPrompt({
2240
+ value: input.environmentName,
2241
+ shouldPrompt: shouldUseWizard({
2242
+ interactive: input.interactive,
2243
+ noInteractive: input.noInteractive,
2244
+ format,
2245
+ missingRequiredArgs: !input.environmentName
2246
+ }),
2247
+ prompt: async () => {
2248
+ if (choices.length === 0) {
2249
+ return void 0;
2250
+ }
2251
+ return promptForSearchableChoice({
2252
+ message: input.message,
2253
+ choices
2254
+ });
2255
+ }
2256
+ });
2257
+ }
2258
+ function printEnvironmentEditJsonSnapshot(environment, rows) {
2259
+ printJson({
2260
+ environment: {
2261
+ id: environment.id,
2262
+ name: environment.name
2263
+ },
2264
+ rows
2265
+ });
2266
+ }
2267
+ async function handleEnvironmentEditCommand(name, opts) {
2268
+ const db = getDb();
2269
+ initializeSchema(db);
2270
+ const format = parseOutputFormat(opts.format);
2271
+ const noInteractive = opts.yes;
2272
+ const secretEntries = (opts.secret ?? []).map((entry) => {
2273
+ const parts = entry.split(":");
2274
+ if (parts.length < 3) {
2275
+ throw new Error(`Invalid --secret entry "${entry}". Expected KEY:provider:ref.`);
2276
+ }
2277
+ const [key, provider, ...refParts] = parts;
2278
+ if (!key || !provider) {
2279
+ throw new Error(`Invalid --secret entry "${entry}". Expected KEY:provider:ref.`);
2280
+ }
2281
+ const providerValue = provider;
2282
+ if (!["keychain", "env", "file"].includes(providerValue)) {
2283
+ throw new Error(`Invalid secret provider "${provider}". Use keychain, env, or file.`);
2284
+ }
2285
+ return {
2286
+ key,
2287
+ provider: providerValue,
2288
+ ref: refParts.join(":")
2289
+ };
2290
+ });
2291
+ const scripting = (opts.var?.length ?? 0) > 0 || (opts.unsetVar?.length ?? 0) > 0 || opts.model !== void 0 || opts.unsetModel !== void 0 || (opts.permission?.length ?? 0) > 0 || (opts.unsetPermission?.length ?? 0) > 0 || secretEntries.length > 0 || (opts.unsetSecret?.length ?? 0) > 0;
2292
+ const resolvedName = name ?? (scripting ? void 0 : await resolveEnvironmentMutationTarget({
2293
+ environmentName: name,
2294
+ interactive: opts.interactive,
2295
+ noInteractive,
2296
+ format: opts.format,
2297
+ message: "Which environment do you want to edit?"
2298
+ }));
2299
+ if (!resolvedName) {
2300
+ process.exitCode = 1;
2301
+ fail(
2302
+ scripting || listEnvironments().length > 0 ? "error: missing required argument 'name'" : `No environments found. Create one with \`${formatCommand("environment create <name>")}\` first.`
2303
+ );
2304
+ return;
2305
+ }
2306
+ const environment = resolveEnvironmentOrThrow(resolvedName);
2307
+ if (scripting) {
2308
+ let lastPayload;
2309
+ for (const entry of opts.var ?? []) {
2310
+ const parsed = parseVarAssignment(entry);
2311
+ lastPayload = setEnvironmentVarCommand(resolvedName, parsed.key, parsed.value);
2312
+ }
2313
+ for (const key of opts.unsetVar ?? []) {
2314
+ lastPayload = unsetEnvironmentVarCommand(resolvedName, key);
2315
+ }
2316
+ if (opts.model) {
2317
+ lastPayload = setEnvironmentModelConfigCommand(resolvedName, {
2318
+ model: opts.model,
2319
+ ...opts.modelProvider ? { provider: opts.modelProvider } : {}
2320
+ });
2321
+ }
2322
+ if (opts.unsetModel !== void 0) {
2323
+ const modelName = typeof opts.unsetModel === "string" && opts.unsetModel.length > 0 ? opts.unsetModel : "default";
2324
+ lastPayload = unsetEnvironmentModelConfigCommand(resolvedName, modelName);
2325
+ }
2326
+ for (const entry of opts.permission ?? []) {
2327
+ lastPayload = setEnvironmentPermissionCommand(resolvedName, parsePermissionPattern(entry));
2328
+ }
2329
+ for (const entry of opts.unsetPermission ?? []) {
2330
+ lastPayload = unsetEnvironmentPermissionCommand(
2331
+ resolvedName,
2332
+ parsePermissionUnsetSelector(entry)
2333
+ );
2334
+ }
2335
+ for (const secret of secretEntries) {
2336
+ lastPayload = setEnvironmentSecretCommand(resolvedName, secret);
2337
+ }
2338
+ for (const key of opts.unsetSecret ?? []) {
2339
+ lastPayload = unsetEnvironmentSecretCommand(resolvedName, key);
2340
+ }
2341
+ const payload = lastPayload ?? showEnvironmentCommand(resolvedName);
2342
+ printEnvironmentMutationResult(payload, format);
2343
+ return;
2344
+ }
2345
+ const rows = buildEnvironmentEditRows(environment.id);
2346
+ if (format === "json" && !shouldUseInteractiveEnvironmentEdit({ noInteractive, format: opts.format })) {
2347
+ printEnvironmentEditJsonSnapshot(environment, rows);
2348
+ return;
2349
+ }
2350
+ if (!shouldUseInteractiveEnvironmentEdit({ noInteractive, format: opts.format })) {
2351
+ process.exitCode = 1;
2352
+ fail(
2353
+ `environment edit requires an interactive terminal. Use scripting flags such as \`${formatCommand("environment edit <name> --var KEY=VALUE")}\` or \`${formatCommand("environment edit <name> --format json")}\` for a snapshot.`
2354
+ );
2355
+ return;
2356
+ }
2357
+ try {
2358
+ const result = await runEnvironmentEditWizard({ environment });
2359
+ if (!result) {
2360
+ ui.info("Operation cancelled.");
2361
+ return;
2362
+ }
2363
+ ui.success(`Updated environment ${ui.theme.accent(environment.name)}`);
2364
+ } catch (error) {
2365
+ if (isPromptCancellationError(error)) {
2366
+ ui.info("Operation cancelled.");
2367
+ return;
2368
+ }
2369
+ throw error;
2370
+ }
2371
+ }
2372
+ function renderEnvironmentDeleteReferences(references) {
2373
+ if (references.plugins.length === 0) {
2374
+ return;
2375
+ }
2376
+ ui.subheader("REFERENCES");
2377
+ ui.table.print({
2378
+ columns: [
2379
+ { key: "plugin", header: "PLUGIN", width: 40 }
2380
+ ],
2381
+ rows: references.plugins.map((ref) => {
2382
+ const plugin = getPluginById(ref.id);
2383
+ return {
2384
+ plugin: plugin ? formatPluginLabel2(plugin) : ref.name
2385
+ };
2386
+ })
2387
+ });
2388
+ }
2389
+ async function handleEnvironmentDeleteCommand(name, opts) {
2390
+ const db = getDb();
2391
+ initializeSchema(db);
2392
+ const format = parseOutputFormat(opts.format);
2393
+ const useWizard = shouldUseWizard({
2394
+ interactive: opts.interactive,
2395
+ noInteractive: opts.yes,
2396
+ format,
2397
+ missingRequiredArgs: !name
2398
+ });
2399
+ const selectors = name ? [name] : useWizard ? await runEnvironmentDeleteWizard({ search: opts.search }) : [];
2400
+ const resolvedName = selectors[0];
2401
+ if (!resolvedName) {
2402
+ throw !name && useWizard ? new Error("No environment selected for deletion") : missingRequiredArg("name", "environment delete");
2403
+ }
2404
+ const environment = resolveEnvironmentOrThrow(resolvedName);
2405
+ const references = listEnvironmentReferences(environment.id);
2406
+ let confirmedWithReferences = false;
2407
+ if (useWizard && !opts.force) {
2408
+ renderEnvironmentDeleteReferences(references);
2409
+ const confirmed = await promptForConfirmation({
2410
+ message: references.plugins.length > 0 ? `Delete environment "${environment.name}" even though it is referenced?` : `Delete environment "${environment.name}"?`,
2411
+ default: false
2412
+ });
2413
+ if (!confirmed) {
2414
+ ui.info("Operation cancelled.");
2415
+ return;
2416
+ }
2417
+ confirmedWithReferences = references.plugins.length > 0;
2418
+ }
2419
+ const result = deleteEnvironmentCommand(resolvedName, {
2420
+ force: Boolean(opts.force || confirmedWithReferences)
2421
+ });
2422
+ if (format === "json") {
2423
+ printJson(result);
2424
+ return;
2425
+ }
2426
+ ui.success(`Deleted environment ${ui.theme.accent(environment.name)}`);
2427
+ }
2428
+ function hasExplicitCreateMode(opts) {
2429
+ return Boolean(
2430
+ opts.blank || opts.fromProject || opts.fromPlugin && opts.fromPlugin.length > 0
2431
+ );
2432
+ }
2433
+ function printEnvironmentCreateResult(result, opts) {
2434
+ if (result.mode === "blank") {
2435
+ if (opts.format === "json") {
2436
+ printJson(result.payload.environment);
2437
+ return;
2438
+ }
2439
+ ui.success(`Created environment ${ui.theme.accent(result.payload.environment.name)}`);
2440
+ return;
2441
+ }
2442
+ if (result.mode === "from-project") {
2443
+ const captureResult = result.result;
2444
+ if (opts.format === "json") {
2445
+ printJson(captureResult);
2446
+ } else {
2447
+ const action = opts.refresh ? "refresh" : "create";
2448
+ ui.panel({
2449
+ title: ["ENVIRONMENT", `${action} ${opts.name}`],
2450
+ rows: [
2451
+ ["Project", opts.fromProject ? resolve2(opts.fromProject) : ": "],
2452
+ ["Harness", captureResult.harness],
2453
+ ["Configured plugins", `${captureResult.configured_plugin_ids.length}`],
2454
+ ["Persisted", captureResult.persisted ? "yes" : "no"],
2455
+ ["Missing keys", `${captureResult.missing_keys.length}`]
2456
+ ]
2457
+ });
2458
+ if (captureResult.missing_keys.length > 0) {
2459
+ ui.subheader("MISSING KEYS");
2460
+ for (const missing of captureResult.missing_keys) {
2461
+ const sources = missing.sources.length > 0 ? missing.sources.join(", ") : "unknown";
2462
+ ui.warn(`${missing.key} (${sources})`);
2463
+ }
2464
+ }
2465
+ }
2466
+ if (captureResult.strict_failed) {
2467
+ process.exitCode = 1;
2468
+ if (opts.format === "human") {
2469
+ fail("Strict mode failed: missing required environment keys.");
2470
+ }
2471
+ }
2472
+ return;
2473
+ }
2474
+ const fromPluginResult = result.preview;
2475
+ if (opts.format === "json") {
2476
+ printJson({
2477
+ ...fromPluginResult,
2478
+ environment: result.payload.environment,
2479
+ persisted: result.persisted
2480
+ });
2481
+ } else {
2482
+ ui.panel({
2483
+ title: ["ENVIRONMENT", `create ${opts.name} from plugin`],
2484
+ rows: [
2485
+ ["Configured plugins", `${fromPluginResult.configured_plugin_ids.length}`],
2486
+ ["Persisted", result.persisted ? "yes" : "no"],
2487
+ ["Missing keys", `${fromPluginResult.missing_keys.length}`],
2488
+ ["Bound plugins", `${fromPluginResult.bound_plugin_ids.length}`]
2489
+ ]
2490
+ });
2491
+ if (fromPluginResult.missing_keys.length > 0) {
2492
+ ui.subheader("MISSING KEYS");
2493
+ for (const missing of fromPluginResult.missing_keys) {
2494
+ const sources = missing.sources.length > 0 ? missing.sources.join(", ") : "unknown";
2495
+ ui.warn(`${missing.key} (${sources})`);
2496
+ }
2497
+ }
2498
+ if (result.persisted) {
2499
+ ui.success(`Created environment ${ui.theme.accent(opts.name)}`);
2500
+ }
2501
+ }
2502
+ if (fromPluginResult.strict_failed) {
2503
+ process.exitCode = 1;
2504
+ if (opts.format === "human") {
2505
+ fail("Strict mode failed: missing required environment keys.");
2506
+ }
2507
+ }
2508
+ }
2509
+ async function handleEnvironmentCreateCommand(name, opts) {
2510
+ const db = getDb();
2511
+ initializeSchema(db);
2512
+ const format = parseOutputFormat(opts.format);
2513
+ if (!opts.refresh && !opts.dryRun && getEnvironmentByName(name)) {
2514
+ fail(CLI_ERRORS.environmentAlreadyExists(name), {
2515
+ hint: CLI_HINTS.onConflictReplace
2516
+ });
2517
+ return;
2518
+ }
2519
+ const useWizard = shouldUseWizard({
2520
+ interactive: opts.interactive,
2521
+ noInteractive: opts.yes,
2522
+ format: opts.format,
2523
+ missingRequiredArgs: !hasExplicitCreateMode(opts)
2524
+ });
2525
+ if (useWizard) {
2526
+ try {
2527
+ const wizardOutcome = await runEnvironmentCreateWizard({
2528
+ name,
2529
+ description: opts.description
2530
+ });
2531
+ printEnvironmentCreateResult(wizardOutcome.result, {
2532
+ name,
2533
+ fromProject: opts.fromProject,
2534
+ refresh: opts.refresh,
2535
+ format
2536
+ });
2537
+ } catch (error) {
2538
+ if (isPromptCancellationError(error)) {
2539
+ ui.info("Operation cancelled.");
2540
+ return;
2541
+ }
2542
+ throw error;
2543
+ }
2544
+ return;
2545
+ }
2546
+ const fromPlugin = opts.fromPlugin?.length ? opts.fromPlugin.flatMap(
2547
+ (entry) => entry.split(",").map((part) => part.trim()).filter(Boolean)
2548
+ ) : void 0;
2549
+ const result = await runEnvironmentCreate({
2550
+ name,
2551
+ ...opts.blank ? { blank: true } : {},
2552
+ ...opts.fromProject ? { fromProject: resolve2(opts.fromProject) } : {},
2553
+ ...fromPlugin ? { fromPlugin } : {},
2554
+ refresh: opts.refresh,
2555
+ bind: opts.bind,
2556
+ plugins: opts.plugins,
2557
+ strict: opts.strict,
2558
+ dryRun: opts.dryRun,
2559
+ includePermissions: opts.includePermissions,
2560
+ description: opts.description
2561
+ });
2562
+ printEnvironmentCreateResult(result, {
2563
+ name,
2564
+ fromProject: opts.fromProject,
2565
+ refresh: opts.refresh,
2566
+ format
2567
+ });
2568
+ }
2569
+ async function handleEnvironmentUseCommand(name, opts) {
2570
+ const db = getDb();
2571
+ initializeSchema(db);
2572
+ const format = parseOutputFormat(opts.format);
2573
+ const payload = useEnvironmentCommand(name, { local: opts.local });
2574
+ if (format === "json") {
2575
+ printJson(payload);
2576
+ return;
2577
+ }
2578
+ const scopeLabel = payload.scope === "local" ? "local session" : "global";
2579
+ ui.success(
2580
+ `Set ${scopeLabel} environment ${ui.theme.accent(payload.environment_name)}`
2581
+ );
2582
+ if (payload.scope === "local") {
2583
+ ui.hint(
2584
+ `Session override is active for this terminal. Global environment remains ${ui.theme.muted("unchanged")}.`
2585
+ );
2586
+ }
2587
+ }
2588
+ async function handleEnvironmentStatusCommand(opts) {
2589
+ const db = getDb();
2590
+ initializeSchema(db);
2591
+ const format = parseOutputFormat(opts.format);
2592
+ const configuredPluginIds = opts.plugins?.map((selector) => {
2593
+ const configuredPlugin = resolvePluginSelector(selector);
2594
+ if (!configuredPlugin) {
2595
+ throw new Error(`Configured plugin not found: ${selector}`);
2596
+ }
2597
+ return configuredPlugin.id;
2598
+ }) ?? [];
2599
+ try {
2600
+ const status = detectEnvironmentStatus({ configuredPluginIds });
2601
+ if (format === "json") {
2602
+ printJson(status);
2603
+ } else {
2604
+ for (const warning of status.secret_warnings) {
2605
+ ui.warn(`${warning.key}: ${warning.message}`);
2606
+ }
2607
+ if (!status.effective_environment) {
2608
+ ui.info("No active environment set.");
2609
+ ui.hint(`Run ${formatCommand("environment use <name>")} to select one globally.`);
2610
+ } else if (!status.has_drift) {
2611
+ ui.success(
2612
+ `Terminal environment is in sync with ${ui.theme.accent(status.effective_environment)}.`
2613
+ );
2614
+ if (status.local_environment) {
2615
+ ui.dim(`Local session override: ${status.local_environment}`);
2616
+ }
2617
+ } else {
2618
+ ui.warn(
2619
+ `Terminal environment is out of sync with ${ui.theme.accent(status.effective_environment)}.`
2620
+ );
2621
+ if (status.local_environment) {
2622
+ ui.dim(`Local session override: ${status.local_environment}`);
2623
+ }
2624
+ ui.table.print({
2625
+ columns: [
2626
+ { key: "key", header: "KEY", width: 24 },
2627
+ { key: "kind", header: "KIND", width: 10 },
2628
+ { key: "expected", header: "EXPECTED", width: 28 },
2629
+ { key: "actual", header: "ACTUAL", width: 28 }
2630
+ ],
2631
+ rows: status.drift.map((entry) => ({
2632
+ key: entry.key,
2633
+ kind: entry.kind,
2634
+ expected: entry.expected,
2635
+ actual: entry.actual ?? "(unset)"
2636
+ })),
2637
+ empty: "No drift detected."
2638
+ });
2639
+ ui.hint(
2640
+ `Export expected values in your shell or run ${formatCommand(["environment", "use", status.effective_environment])} after updating process env.`
2641
+ );
2642
+ }
2643
+ }
2644
+ if (opts.check && status.has_drift) {
2645
+ process.exitCode = 1;
2646
+ }
2647
+ } catch (err) {
2648
+ process.exitCode = 1;
2649
+ fail(err instanceof Error ? err.message : String(err));
2650
+ }
2651
+ }
2652
+ function registerEnvironmentCommands(root) {
2653
+ const environmentCmd = configureCommandGroup(
2654
+ root.command("environment").alias("e").description("Manage reusable environments and plugin environment cascade")
2655
+ );
2656
+ environmentCmd.command("create").argument("<name>", "Environment name").option("--blank", "Create an empty environment").option("--from-project <path>", "Create from project harness configuration").option(
2657
+ "--from-plugin <plugin>",
2658
+ "Create from configured plugin requirements (repeatable or comma-separated)",
2659
+ collectRepeatedOption,
2660
+ []
2661
+ ).option("--refresh", "Refresh an existing environment (--from-project only)").option("--bind", "Bind environment as plugin default (--from-plugin only)").option("--plugins <plugins...>", "Configured plugin selectors for --from-project").option("--strict", "Fail when required keys are missing").option("--dry-run", "Preview without persisting").option("--include-permissions", "Include scanned permission resources").option("--description <text>", "Environment description").option("--interactive", "Prompt instead of relying on explicit flags").option("-y, --yes", "Skip interactive prompts").option("--format <mode>", "Output format: human or json", "human").description("Create a blank, project-scoped, or plugin-derived environment").action(async (name, opts) => {
2662
+ try {
2663
+ await handleEnvironmentCreateCommand(name, opts);
2664
+ } catch (error) {
2665
+ if (isPromptCancellationError(error)) {
2666
+ ui.info("Operation cancelled.");
2667
+ return;
2668
+ }
2669
+ failCaught(error);
2670
+ }
2671
+ });
2672
+ environmentCmd.command("edit").argument("[name]", "Environment name or ID").option("--var <keyValue>", "Set env var KEY=VALUE (scripting mode)", (value, previous = []) => [...previous, value], []).option("--unset-var <key>", "Unset env var key (scripting mode)", (value, previous = []) => [...previous, value], []).option("--model <name>", "Set default model name (scripting mode)").option("--model-provider <provider>", "Provider for --model").option("--unset-model [name]", "Unset model config (scripting mode)").option("--permission <actionPattern>", "Set permission action:pattern (scripting mode)", (value, previous = []) => [...previous, value], []).option("--unset-permission <selector>", "Unset permission action:pattern or name (scripting mode)", (value, previous = []) => [...previous, value], []).option("--secret <keyProviderRef>", "Set secret ref KEY:provider:ref (scripting mode)", (value, previous = []) => [...previous, value], []).option("--unset-secret <key>", "Unset secret ref key (scripting mode)", (value, previous = []) => [...previous, value], []).option("--interactive", "Prompt instead of relying on explicit flags").option("-y, --yes", "Skip interactive prompts").option("--format <mode>", "Output format: human or json", "human").description("Edit environment values interactively or via scripting flags").action(async (name, opts) => {
2673
+ try {
2674
+ await handleEnvironmentEditCommand(name, opts);
2675
+ } catch (error) {
2676
+ if (isPromptCancellationError(error)) {
2677
+ ui.info("Operation cancelled.");
2678
+ return;
2679
+ }
2680
+ process.exitCode = 1;
2681
+ renderCliError(error);
2682
+ }
2683
+ });
2684
+ environmentCmd.command("list").alias("ls").option("-s, --search <query>", "Search by name or description (skips interactive filter)").option("--format <mode>", "Output format: human or json", "human").description("List local environments with value and reference counts").action(async (opts) => {
2685
+ try {
2686
+ await handleEnvironmentListCommand(opts);
2687
+ } catch (error) {
2688
+ process.exitCode = 1;
2689
+ renderCliError(error);
2690
+ }
2691
+ });
2692
+ environmentCmd.command("show").argument("[name]", "Environment name or ID").option("--plugin <selector>", "Analyze requirement gaps for a configured plugin").option("--format <mode>", "Output format: human or json", "human").option("--interactive", "Prompt instead of relying on explicit flags").option("--no-interactive", "Disable interactive wizards").description("Show environment values, secret refs, and plugin references").action(async (name, opts) => {
2693
+ const db = getDb();
2694
+ initializeSchema(db);
2695
+ const format = parseOutputFormat(opts.format);
2696
+ const resolvedName = await resolveOrPrompt({
2697
+ value: name,
2698
+ shouldPrompt: shouldUseWizard({
2699
+ interactive: opts.interactive,
2700
+ noInteractive: opts.noInteractive,
2701
+ format,
2702
+ missingRequiredArgs: !name
2703
+ }),
2704
+ prompt: async () => runEnvironmentShowWizard()
2705
+ });
2706
+ if (!resolvedName) {
2707
+ process.exitCode = 1;
2708
+ fail(
2709
+ listEnvironments().length > 0 ? "error: missing required argument 'name'" : `No environments found. Create one with \`${formatCommand("environment create <name>")}\` first.`
2710
+ );
2711
+ return;
2712
+ }
2713
+ const payload = showEnvironmentCommand(resolvedName);
2714
+ const requirementGaps = opts.plugin ? analyzeEnvironmentGaps(payload.environment.id, opts.plugin) : void 0;
2715
+ if (format === "json") {
2716
+ printJson(
2717
+ requirementGaps !== void 0 ? { ...payload, requirement_gaps: requirementGaps } : payload
2718
+ );
2719
+ return;
2720
+ }
2721
+ renderEnvironmentShowHuman(payload, requirementGaps);
2722
+ });
2723
+ environmentCmd.command("delete").argument("[name]", "Environment name or ID").option("-s, --search <query>", "Filter environments in the delete wizard").option("--force", "Delete even if references exist").option("--interactive", "Prompt instead of relying on explicit flags").option("-y, --yes", "Skip interactive prompts").option("--format <mode>", "Output format: human or json", "human").description("Delete an environment (blocked when referenced unless --force)").action(async (name, opts) => {
2724
+ try {
2725
+ await handleEnvironmentDeleteCommand(name, opts);
2726
+ } catch (error) {
2727
+ if (isPromptCancellationError(error)) {
2728
+ ui.info("Operation cancelled.");
2729
+ return;
2730
+ }
2731
+ process.exitCode = 1;
2732
+ renderCliError(error);
2733
+ }
2734
+ });
2735
+ environmentCmd.command("use").argument("<name>", "Environment name or ID").option("--local", "Apply only to this terminal session without changing the global active environment").option("--format <mode>", "Output format: human or json", "human").description("Set the global or local (session) active environment").action(async (name, opts) => {
2736
+ await handleEnvironmentUseCommand(name, opts);
2737
+ });
2738
+ environmentCmd.command("status").option("--plugins <plugins...>", "Configured plugin selectors to include plugin default environments").option("--check", "Exit with code 1 when the terminal environment is out of sync").option("--format <mode>", "Output format: human or json", "human").description("Show the active environment and whether terminal env vars match expected values").action(async (opts) => {
2739
+ await handleEnvironmentStatusCommand(opts);
2740
+ });
2741
+ }
2742
+ export {
2743
+ registerEnvironmentCommands
2744
+ };
2745
+ //# sourceMappingURL=environment-3RI5H32O.js.map