mulesoft-anypoint-cli-agent-fabric-plugin 1.3.0 → 1.3.1-beta

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 (184) hide show
  1. package/README.md +77 -42
  2. package/bin/run +6 -0
  3. package/dist/commands/agent-network/project/agent-console.d.ts +16 -0
  4. package/dist/commands/agent-network/project/agent-console.js +175 -0
  5. package/dist/commands/agent-network/project/agent-console.js.map +1 -0
  6. package/dist/commands/agent-network/project/broker/create.d.ts +10 -0
  7. package/dist/commands/agent-network/project/broker/create.js +192 -0
  8. package/dist/commands/agent-network/project/broker/create.js.map +1 -0
  9. package/dist/commands/agent-network/project/create.d.ts +12 -0
  10. package/dist/commands/agent-network/project/create.js +48 -11
  11. package/dist/commands/agent-network/project/create.js.map +1 -1
  12. package/dist/commands/agent-network/project/deploy.d.ts +24 -14
  13. package/dist/commands/agent-network/project/deploy.js +230 -178
  14. package/dist/commands/agent-network/project/deploy.js.map +1 -1
  15. package/dist/commands/agent-network/project/export-logs.d.ts +11 -0
  16. package/dist/commands/agent-network/project/export-logs.js +38 -0
  17. package/dist/commands/agent-network/project/export-logs.js.map +1 -0
  18. package/dist/commands/agent-network/project/mcp/introspect.js +4 -1
  19. package/dist/commands/agent-network/project/mcp/introspect.js.map +1 -1
  20. package/dist/commands/agent-network/project/publish.js +1 -1
  21. package/dist/commands/agent-network/project/publish.js.map +1 -1
  22. package/dist/commands/agent-network/project/run-local.d.ts +85 -0
  23. package/dist/commands/agent-network/project/run-local.js +825 -0
  24. package/dist/commands/agent-network/project/run-local.js.map +1 -0
  25. package/dist/commands/agent-network/project/secrets.d.ts +21 -0
  26. package/dist/commands/agent-network/project/secrets.js +163 -0
  27. package/dist/commands/agent-network/project/secrets.js.map +1 -0
  28. package/dist/commands/agent-network/project/stop-local.d.ts +11 -0
  29. package/dist/commands/agent-network/project/stop-local.js +38 -0
  30. package/dist/commands/agent-network/project/stop-local.js.map +1 -0
  31. package/dist/commands/agent-network/project/undeploy.js +15 -10
  32. package/dist/commands/agent-network/project/undeploy.js.map +1 -1
  33. package/dist/commands/agent-network/project/unpublish.js +14 -6
  34. package/dist/commands/agent-network/project/unpublish.js.map +1 -1
  35. package/dist/commands/agent-network/setup/gateways.d.ts +3 -0
  36. package/dist/commands/agent-network/setup/gateways.js +66 -3
  37. package/dist/commands/agent-network/setup/gateways.js.map +1 -1
  38. package/dist/errors/error-factory.d.ts +51 -6
  39. package/dist/errors/error-factory.js +246 -15
  40. package/dist/errors/error-factory.js.map +1 -1
  41. package/dist/helpers/proxy-agent.d.ts +2 -0
  42. package/dist/helpers/proxy-agent.js +26 -0
  43. package/dist/helpers/proxy-agent.js.map +1 -0
  44. package/dist/helpers/request-utils.d.ts +2 -1
  45. package/dist/helpers/request-utils.js +2 -2
  46. package/dist/helpers/request-utils.js.map +1 -1
  47. package/dist/helpers/utils.d.ts +1 -0
  48. package/dist/helpers/utils.js +5 -0
  49. package/dist/helpers/utils.js.map +1 -1
  50. package/dist/resources/agent-console.html +478 -0
  51. package/dist/resources/schemas/broker-deployment-settings.schema.json +46 -0
  52. package/dist/types/agent-network-v2.d.ts +4 -0
  53. package/dist/types/agent-network-v2.js.map +1 -1
  54. package/dist/types/types.d.ts +1 -0
  55. package/dist/utils/builders/network-lock.d.ts +1 -0
  56. package/dist/utils/builders/network-lock.js +41 -6
  57. package/dist/utils/builders/network-lock.js.map +1 -1
  58. package/dist/utils/builders/policies-factory.d.ts +5 -1
  59. package/dist/utils/builders/policies-factory.js +10 -2
  60. package/dist/utils/builders/policies-factory.js.map +1 -1
  61. package/dist/utils/builders/project-builder-impl.d.ts +16 -2
  62. package/dist/utils/builders/project-builder-impl.js +29 -1
  63. package/dist/utils/builders/project-builder-impl.js.map +1 -1
  64. package/dist/utils/builders/project-builder.d.ts +29 -2
  65. package/dist/utils/builders/project-builder.js +10 -2
  66. package/dist/utils/builders/project-builder.js.map +1 -1
  67. package/dist/utils/builders/remote-space-resolver.d.ts +2 -2
  68. package/dist/utils/builders/remote-space-resolver.js +27 -11
  69. package/dist/utils/builders/remote-space-resolver.js.map +1 -1
  70. package/dist/utils/builders/space-serializer.js +3 -1
  71. package/dist/utils/builders/space-serializer.js.map +1 -1
  72. package/dist/utils/builders/stage-diagnostics.d.ts +2 -0
  73. package/dist/utils/builders/stage-diagnostics.js +27 -0
  74. package/dist/utils/builders/stage-diagnostics.js.map +1 -0
  75. package/dist/utils/builders/tooling-metadata.d.ts +4 -4
  76. package/dist/utils/builders/tooling-metadata.js +27 -15
  77. package/dist/utils/builders/tooling-metadata.js.map +1 -1
  78. package/dist/utils/builders/v1/network-builder.js +2 -1
  79. package/dist/utils/builders/v1/network-builder.js.map +1 -1
  80. package/dist/utils/builders/v2/broker-builder.d.ts +1 -0
  81. package/dist/utils/builders/v2/broker-builder.js +69 -4
  82. package/dist/utils/builders/v2/broker-builder.js.map +1 -1
  83. package/dist/utils/builders/v2/network-builder.js +1 -1
  84. package/dist/utils/builders/v2/network-builder.js.map +1 -1
  85. package/dist/utils/constants.d.ts +3 -0
  86. package/dist/utils/constants.js +8 -3
  87. package/dist/utils/constants.js.map +1 -1
  88. package/dist/utils/deployment-settings.d.ts +13 -0
  89. package/dist/utils/deployment-settings.js +97 -0
  90. package/dist/utils/deployment-settings.js.map +1 -0
  91. package/dist/utils/facets/abstract-facet.d.ts +1 -0
  92. package/dist/utils/facets/abstract-facet.js +3 -0
  93. package/dist/utils/facets/abstract-facet.js.map +1 -1
  94. package/dist/utils/facets/agent-graph-facet.d.ts +14 -1
  95. package/dist/utils/facets/agent-graph-facet.js +126 -49
  96. package/dist/utils/facets/agent-graph-facet.js.map +1 -1
  97. package/dist/utils/facets/api-instance-facet.d.ts +36 -1
  98. package/dist/utils/facets/api-instance-facet.js +196 -5
  99. package/dist/utils/facets/api-instance-facet.js.map +1 -1
  100. package/dist/utils/facets/connection-facet.d.ts +8 -0
  101. package/dist/utils/facets/connection-facet.js +65 -1
  102. package/dist/utils/facets/connection-facet.js.map +1 -1
  103. package/dist/utils/facets/deployment-helpers.d.ts +18 -1
  104. package/dist/utils/facets/deployment-helpers.js +53 -0
  105. package/dist/utils/facets/deployment-helpers.js.map +1 -1
  106. package/dist/utils/facets/deployment-logs.js +1 -0
  107. package/dist/utils/facets/deployment-logs.js.map +1 -1
  108. package/dist/utils/facets/deployment-runner.js +5 -0
  109. package/dist/utils/facets/deployment-runner.js.map +1 -1
  110. package/dist/utils/facets/facets.d.ts +2 -0
  111. package/dist/utils/facets/facets.js +20 -3
  112. package/dist/utils/facets/facets.js.map +1 -1
  113. package/dist/utils/facets/mule-application-facet.d.ts +1 -1
  114. package/dist/utils/facets/mule-application-facet.js +25 -21
  115. package/dist/utils/facets/mule-application-facet.js.map +1 -1
  116. package/dist/utils/files.d.ts +25 -0
  117. package/dist/utils/files.js +62 -0
  118. package/dist/utils/files.js.map +1 -1
  119. package/dist/utils/gateway.d.ts +6 -2
  120. package/dist/utils/gateway.js +37 -33
  121. package/dist/utils/gateway.js.map +1 -1
  122. package/dist/utils/keychain.d.ts +56 -0
  123. package/dist/utils/keychain.js +488 -0
  124. package/dist/utils/keychain.js.map +1 -0
  125. package/dist/utils/logger.d.ts +1 -0
  126. package/dist/utils/logger.js +3 -0
  127. package/dist/utils/logger.js.map +1 -1
  128. package/dist/utils/mcp/mcp-metadata-mapper.d.ts +8 -0
  129. package/dist/utils/mcp/mcp-metadata-mapper.js +7 -1
  130. package/dist/utils/mcp/mcp-metadata-mapper.js.map +1 -1
  131. package/dist/utils/mcp/project-registrar.js +2 -26
  132. package/dist/utils/mcp/project-registrar.js.map +1 -1
  133. package/dist/utils/naming.d.ts +13 -0
  134. package/dist/utils/naming.js +36 -4
  135. package/dist/utils/naming.js.map +1 -1
  136. package/dist/utils/request-executor.d.ts +5 -5
  137. package/dist/utils/run-local/agent-console-proxy.d.ts +56 -0
  138. package/dist/utils/run-local/agent-console-proxy.js +182 -0
  139. package/dist/utils/run-local/agent-console-proxy.js.map +1 -0
  140. package/dist/utils/run-local/broker-recreate-selector.d.ts +31 -0
  141. package/dist/utils/run-local/broker-recreate-selector.js +82 -0
  142. package/dist/utils/run-local/broker-recreate-selector.js.map +1 -0
  143. package/dist/utils/run-local/build-status.d.ts +73 -0
  144. package/dist/utils/run-local/build-status.js +210 -0
  145. package/dist/utils/run-local/build-status.js.map +1 -0
  146. package/dist/utils/run-local/constants.d.ts +28 -0
  147. package/dist/utils/run-local/constants.js +36 -0
  148. package/dist/utils/run-local/constants.js.map +1 -0
  149. package/dist/utils/run-local/crd-files.d.ts +2 -0
  150. package/dist/utils/run-local/crd-files.js +24 -0
  151. package/dist/utils/run-local/crd-files.js.map +1 -0
  152. package/dist/utils/run-local/index.d.ts +9 -0
  153. package/dist/utils/run-local/index.js +42 -0
  154. package/dist/utils/run-local/index.js.map +1 -0
  155. package/dist/utils/run-local/local-a2a-upstream.d.ts +9 -0
  156. package/dist/utils/run-local/local-a2a-upstream.js +55 -0
  157. package/dist/utils/run-local/local-a2a-upstream.js.map +1 -0
  158. package/dist/utils/run-local/local-deploy-descriptor.d.ts +36 -0
  159. package/dist/utils/run-local/local-deploy-descriptor.js +70 -0
  160. package/dist/utils/run-local/local-deploy-descriptor.js.map +1 -0
  161. package/dist/utils/run-local/local-run-manager.d.ts +51 -0
  162. package/dist/utils/run-local/local-run-manager.js +220 -0
  163. package/dist/utils/run-local/local-run-manager.js.map +1 -0
  164. package/dist/utils/run-local/policy-resolver.d.ts +69 -0
  165. package/dist/utils/run-local/policy-resolver.js +461 -0
  166. package/dist/utils/run-local/policy-resolver.js.map +1 -0
  167. package/dist/utils/run-local/runtime-environment-manager.d.ts +89 -0
  168. package/dist/utils/run-local/runtime-environment-manager.js +313 -0
  169. package/dist/utils/run-local/runtime-environment-manager.js.map +1 -0
  170. package/dist/utils/run-local/secrets-manager.d.ts +66 -0
  171. package/dist/utils/run-local/secrets-manager.js +181 -0
  172. package/dist/utils/run-local/secrets-manager.js.map +1 -0
  173. package/dist/utils/uris.js +4 -0
  174. package/dist/utils/uris.js.map +1 -1
  175. package/dist/utils/variables.d.ts +17 -4
  176. package/dist/utils/variables.js +52 -7
  177. package/dist/utils/variables.js.map +1 -1
  178. package/package.json +3 -1
  179. package/scripts/check-gus-ticket-format.sh +29 -0
  180. package/scripts/resolve-version.sh +161 -52
  181. package/scripts/resolve-version.test.sh +207 -20
  182. package/templates/agent-network/exchange.json.template +1 -0
  183. package/templates/agentic-network/brokers/broker1.agent.template +2 -2
  184. package/templates/agentic-network/exchange.json.template +1 -0
@@ -0,0 +1,825 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RunLocal = exports.COMPOSE_SETTLE_TIMEOUT_MS = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const core_1 = require("@oclif/core");
6
+ const anypoint_cli_command_lib_1 = require("anypoint-cli-command-lib");
7
+ const node_fs_1 = require("node:fs");
8
+ const fs = tslib_1.__importStar(require("fs-extra"));
9
+ const node_net_1 = require("node:net");
10
+ const node_path_1 = require("node:path");
11
+ const error_factory_1 = require("../../../errors/error-factory");
12
+ const space_serializer_1 = require("../../../utils/builders/space-serializer");
13
+ const facets_1 = require("../../../utils/facets/facets");
14
+ const project_builder_1 = require("../../../utils/builders/project-builder");
15
+ const project_builder_impl_1 = require("../../../utils/builders/project-builder-impl");
16
+ const variables_1 = require("../../../utils/variables");
17
+ const utils_1 = require("../../../helpers/utils");
18
+ const constants_1 = require("../../../utils/constants");
19
+ const naming_1 = require("../../../utils/naming");
20
+ const network_lock_1 = require("../../../utils/builders/network-lock");
21
+ const run_local_1 = require("../../../utils/run-local");
22
+ const GITIGNORE_FILE = '.gitignore';
23
+ const LOCAL_RUN_GITIGNORE_ENTRY = `${run_local_1.CHAT_ROOT_DIR}/`;
24
+ const LOCAL_RUN_GITIGNORE_COMMENT = '# .deployment — local render output and remote deploy descriptors; may contain secret material (e.g. the encrypted secrets store)';
25
+ const TARGET_DIR = 'target';
26
+ const VARIABLES_CACHE_FILE = 'variables.json';
27
+ const STORED_SECRET_PLACEHOLDER = '__KEYCHAIN__';
28
+ /**
29
+ * What the masked prompt rejects with on Ctrl+C: raw-mode stdin sees a keystroke, not a signal.
30
+ * The literal is thrown by the `password-prompt` package (`reject(new Error('SIGINT'))`), reached via
31
+ * `@oclif/core`'s CliUx masked prompt through `anypoint-cli-command-lib`'s `Logger.cliPrompt`. oclif's own
32
+ * top-level handler keys on the identical string, making it a de-facto ecosystem contract.
33
+ */
34
+ const RAW_MODE_SIGINT_MESSAGE = 'SIGINT';
35
+ /** How long a shutdown waits for an in-flight `compose` call before tearing down regardless. */
36
+ exports.COMPOSE_SETTLE_TIMEOUT_MS = 30000;
37
+ /** Debounce window collapsing a burst of file-change events into a single rebuild. */
38
+ const WATCH_DEBOUNCE_MS = 500;
39
+ class RunLocal extends anypoint_cli_command_lib_1.AuthenticationBaseCommand {
40
+ constructor() {
41
+ super(...arguments);
42
+ this.secretsManager = (0, run_local_1.createSecretsManager)();
43
+ this.runtimeManager = new run_local_1.DockerComposeEnvironmentManager();
44
+ this.localRunManager = new run_local_1.DefaultLocalRunManager();
45
+ // True while a masked secret prompt is open. password-prompt resets raw mode synchronously before
46
+ // its Ctrl+C rejection surfaces, so this is the only signal the rebuild catch has to tell an
47
+ // interrupted prompt from a genuine failure once the recognized SIGINT literal drifts.
48
+ this.maskedPromptOpen = false;
49
+ }
50
+ async run() {
51
+ var _a;
52
+ const { flags } = await this.parse(RunLocal);
53
+ const cwd = process.cwd();
54
+ const projectPath = (0, node_path_1.resolve)(cwd, flags.path);
55
+ this.buildStatus = new run_local_1.LocalDeploymentStatusWriter((0, node_path_1.join)(projectPath, run_local_1.LOCAL_RUN_DIR));
56
+ this.buildStatus.writeRunning('initializing');
57
+ try {
58
+ if (flags.port !== undefined && (!Number.isInteger(flags.port) || flags.port < 1 || flags.port > 65535)) {
59
+ throw error_factory_1.ErrorFactory.invalidPort(flags.port);
60
+ }
61
+ const dockerPort = (_a = flags.port) !== null && _a !== void 0 ? _a : await RunLocal.findAvailablePort(run_local_1.DEFAULT_INGRESS_PORT);
62
+ if (flags.port === undefined && dockerPort !== run_local_1.DEFAULT_INGRESS_PORT) {
63
+ anypoint_cli_command_lib_1.Logger.info(`Port ${run_local_1.DEFAULT_INGRESS_PORT} is in use; using ${dockerPort} instead.`);
64
+ }
65
+ const options = {
66
+ projectPath,
67
+ targetDir: (0, node_path_1.join)(projectPath, TARGET_DIR),
68
+ localRenderDir: (0, node_path_1.join)(projectPath, run_local_1.LOCAL_RUN_DIR),
69
+ properties: flags.property,
70
+ buildOnly: flags['build-only'],
71
+ watchMode: flags.watch,
72
+ host: flags.host,
73
+ dockerPort,
74
+ };
75
+ if (flags.build) {
76
+ this.buildStatus.writeRunning('building');
77
+ await this.buildProject(projectPath, flags.host);
78
+ }
79
+ await this.render(options);
80
+ if (options.buildOnly && !options.watchMode) {
81
+ this.buildStatus.writeCompleted();
82
+ return;
83
+ }
84
+ await (options.watchMode ? this.runWithWatch(options) : this.startRuntime(options));
85
+ }
86
+ catch (error) {
87
+ if ((error === null || error === void 0 ? void 0 : error.message) === RAW_MODE_SIGINT_MESSAGE || this.maskedPromptOpen) {
88
+ this.buildStatus.writeCancelled();
89
+ }
90
+ else {
91
+ this.buildStatus.writeFailed(error);
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+ async buildProject(projectPath, host) {
97
+ anypoint_cli_command_lib_1.Logger.cliStart('Building project');
98
+ const start = Date.now();
99
+ try {
100
+ // runCommand dispatches in-process; the child re-parses argv and, absent --host, defaults
101
+ // host to prod (the flag has no env binding), which overwrites the shared CredentialsSingleton.
102
+ // Forward --host so the build (and run-local's subsequent Exchange calls) hit the right env.
103
+ await this.config.runCommand('agent-network:project:build', ['--path', projectPath, '--host', host]);
104
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) ✅`);
105
+ }
106
+ catch (error) {
107
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) !`);
108
+ throw error;
109
+ }
110
+ }
111
+ async render(options) {
112
+ var _a, _b;
113
+ const { projectPath, targetDir, localRenderDir, host, dockerPort } = options;
114
+ const totalStart = Date.now();
115
+ (_a = this.buildStatus) === null || _a === void 0 ? void 0 : _a.writeRunning('rendering');
116
+ try {
117
+ this.runtimeManager.checkPrerequisites();
118
+ const space = new space_serializer_1.SpaceSerializer(targetDir).load();
119
+ if (!space) {
120
+ throw error_factory_1.ErrorFactory.invalidOrNotBuiltAgentNetworkProject();
121
+ }
122
+ if (!RunLocal.hasV2Components(space)) {
123
+ throw error_factory_1.ErrorFactory.v1NotSupportedForLocalRun();
124
+ }
125
+ const localVersionVariables = RunLocal.deriveLocalVersionVariables(space);
126
+ (0, network_lock_1.validateNoReservedVersionVariableDeclarations)(Object.keys(variables_1.VariablesHelper.flattenVariables((_b = space.variables) !== null && _b !== void 0 ? _b : {})));
127
+ RunLocal.validateReferencedVariablesDeclared(space, localVersionVariables);
128
+ RunLocal.validateNoSecretInGatewayRoutingFields(space);
129
+ RunLocal.validateNoEnvVarNameCollisions(space, [key => this.secretsManager.toEnvVarName(key), naming_1.toAgentGraphEnvVarName]);
130
+ this.localRunManager.validateExchangeAssets(space, targetDir);
131
+ fs.mkdirpSync(localRenderDir);
132
+ RunLocal.protectLocalRunInGitIgnore(projectPath);
133
+ const collectedProperties = await this.collectVariables(space, options);
134
+ const descriptor = RunLocal.loadDescriptor(projectPath);
135
+ const mainFile = descriptor.main;
136
+ if (!mainFile) {
137
+ throw error_factory_1.ErrorFactory.exchangeJsonMissingMain();
138
+ }
139
+ anypoint_cli_command_lib_1.Logger.cliStart('Setting up local environment');
140
+ const setupStart = Date.now();
141
+ this.localRunManager.setup({ projectPath, targetDir, localRenderDir, space, dockerPort });
142
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - setupStart}ms) ✅`);
143
+ const policyResolver = new run_local_1.ExchangePolicyResolver({ req: this.req, localRenderDir, session: this.session, host });
144
+ const renderVariables = await this.stepRenderFacets(space, collectedProperties, localRenderDir, policyResolver, dockerPort, localVersionVariables);
145
+ await this.stepDownloadPolicies(policyResolver, localRenderDir);
146
+ this.stepWriteRuntimeConfig(localRenderDir, space, mainFile, dockerPort, renderVariables);
147
+ }
148
+ catch (error) {
149
+ anypoint_cli_command_lib_1.Logger.cliEndFailed();
150
+ throw error;
151
+ }
152
+ anypoint_cli_command_lib_1.Logger.print('');
153
+ anypoint_cli_command_lib_1.Logger.info(`Total: ${Date.now() - totalStart}ms`);
154
+ anypoint_cli_command_lib_1.Logger.info(`Output: ${localRenderDir}`);
155
+ }
156
+ async startRuntime(options) {
157
+ var _a, _b, _c, _d;
158
+ const space = this.loadBuiltSpace(options.targetDir);
159
+ RunLocal.validateNoEnvVarNameCollisions(space, [key => this.secretsManager.toEnvVarName(key), naming_1.toAgentGraphEnvVarName]);
160
+ (_a = this.buildStatus) === null || _a === void 0 ? void 0 : _a.writeRunning('deploying');
161
+ this.runtimeManager.assertAgentGraphImage();
162
+ const env = this.runtimeManager.buildEnv(this.secretsManager, options.projectPath, space);
163
+ try {
164
+ await this.runtimeManager.start(options.localRenderDir, env);
165
+ // Attached compose exited cleanly (containers stopped) — treat as graceful stop.
166
+ (_b = this.buildStatus) === null || _b === void 0 ? void 0 : _b.writeCancelled();
167
+ }
168
+ catch (error) {
169
+ if ((0, run_local_1.isComposeSignalExit)(error)) {
170
+ (_c = this.buildStatus) === null || _c === void 0 ? void 0 : _c.writeCancelled();
171
+ }
172
+ else {
173
+ (_d = this.buildStatus) === null || _d === void 0 ? void 0 : _d.writeFailed(error, 'runtime');
174
+ }
175
+ throw error;
176
+ }
177
+ }
178
+ runWithWatch(options) {
179
+ // Extracted into WatchSession so each unit of the watch state machine stays independently
180
+ // readable; the closures previously shared ~10 mutable locals folded into one method.
181
+ return new WatchSession(options, this.runtimeManager, this.secretsManager, (projectPath, host) => this.buildProject(projectPath, host), opts => this.render(opts), targetDir => this.loadBuiltSpace(targetDir), () => this.maskedPromptOpen, (pending, timeoutMs) => RunLocal.settleOrTimeout(pending, timeoutMs), this.buildStatus).run();
182
+ }
183
+ // Never rejects, so teardown can sequence on it unconditionally. Timer unref'd to not hold the loop.
184
+ static settleOrTimeout(pending, timeoutMs) {
185
+ if (!pending) {
186
+ return Promise.resolve();
187
+ }
188
+ return new Promise(settle => {
189
+ var _a;
190
+ const timer = setTimeout(settle, timeoutMs);
191
+ (_a = timer.unref) === null || _a === void 0 ? void 0 : _a.call(timer);
192
+ pending.then(settle, settle).finally(() => clearTimeout(timer));
193
+ });
194
+ }
195
+ loadBuiltSpace(targetDir) {
196
+ const space = new space_serializer_1.SpaceSerializer(targetDir).load();
197
+ if (!space) {
198
+ throw error_factory_1.ErrorFactory.invalidOrNotBuiltAgentNetworkProject();
199
+ }
200
+ return space;
201
+ }
202
+ seedStoredSecretPlaceholders(variables, mergedDefaults, projectPath) {
203
+ const flatVars = variables_1.VariablesHelper.flattenVariables(variables);
204
+ for (const [key, varDef] of Object.entries(flatVars)) {
205
+ if (!variables_1.VariablesHelper.isSecret(varDef)) {
206
+ continue;
207
+ }
208
+ if (mergedDefaults[key]) {
209
+ continue;
210
+ }
211
+ if (this.secretsManager.exists(projectPath, key)) {
212
+ mergedDefaults[key] = STORED_SECRET_PLACEHOLDER;
213
+ }
214
+ }
215
+ }
216
+ hydrateOrPersistSecuredProperties(collectedProperties, projectPath) {
217
+ for (const [key, value] of Object.entries(collectedProperties.securedProperties)) {
218
+ if (value === STORED_SECRET_PLACEHOLDER) {
219
+ // Fail loud rather than write a blank key: a null value means the keychain entry
220
+ // was deleted or the secrets file failed to decrypt.
221
+ const stored = this.secretsManager.retrieve(projectPath, key);
222
+ if (!stored) {
223
+ throw error_factory_1.ErrorFactory.localSecretRetrievalFailed(key);
224
+ }
225
+ collectedProperties.securedProperties[key] = stored;
226
+ }
227
+ else {
228
+ const stored = this.secretsManager.store(projectPath, key, value);
229
+ if (!stored) {
230
+ anypoint_cli_command_lib_1.Logger.warn(`Could not persist secret '${key}' to the secrets backend; ` +
231
+ 'it will be used for this run but will not be available on the next run.');
232
+ }
233
+ }
234
+ }
235
+ }
236
+ async collectVariables(space, options) {
237
+ var _a, _b;
238
+ let collectedProperties = { properties: {}, securedProperties: {} };
239
+ const variables = space.variables;
240
+ if (!variables) {
241
+ return collectedProperties;
242
+ }
243
+ const cachedVars = RunLocal.loadVariablesCache(options.localRenderDir);
244
+ const flagVars = variables_1.VariablesHelper.propertiesArrayToObject(options.properties);
245
+ const mergedDefaults = { ...cachedVars, ...flagVars };
246
+ this.seedStoredSecretPlaceholders(variables, mergedDefaults, options.projectPath);
247
+ const needsPrompts = variables_1.VariablesHelper.checkIfPromptsNeeded(variables, mergedDefaults);
248
+ if (needsPrompts) {
249
+ anypoint_cli_command_lib_1.Logger.print('Please provide values for the following variables:');
250
+ (_a = this.buildStatus) === null || _a === void 0 ? void 0 : _a.writeRunning('waiting_for_input');
251
+ }
252
+ // Only while a prompt is actually open: a throw after a no-prompt collect must be `failed`, not Ctrl+C.
253
+ this.maskedPromptOpen = needsPrompts;
254
+ collectedProperties = await variables_1.VariablesHelper.promptForVariables(variables, mergedDefaults);
255
+ this.maskedPromptOpen = false;
256
+ if (needsPrompts) {
257
+ (_b = this.buildStatus) === null || _b === void 0 ? void 0 : _b.writeRunning('rendering');
258
+ }
259
+ this.hydrateOrPersistSecuredProperties(collectedProperties, options.projectPath);
260
+ RunLocal.saveVariablesCache(options.localRenderDir, collectedProperties);
261
+ return collectedProperties;
262
+ }
263
+ /** Returns the redaction map the facets rendered against. Built after the stage: facets inject variables while it runs. */
264
+ async stepRenderFacets(space, properties, localRenderDir, policyResolver, dockerPort, localVersionVariables = {}) {
265
+ anypoint_cli_command_lib_1.Logger.cliStart('Rendering gateway and agent-graph configuration');
266
+ const start = Date.now();
267
+ const stageContext = new project_builder_impl_1.DefaultStageContextBuilder(this.req)
268
+ .withProperties(properties)
269
+ .withLocalRenderDir(localRenderDir)
270
+ .withPolicyResolver(policyResolver)
271
+ .withDockerPort(dockerPort)
272
+ .build();
273
+ for (const [key, version] of Object.entries(localVersionVariables)) {
274
+ stageContext.stageResultRegistry.withVariable(key, version);
275
+ }
276
+ await facets_1.ProjectFacets.execute(project_builder_1.Stages.LocalRender, space, stageContext);
277
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) ✅`);
278
+ return variables_1.VariablesHelper.buildSecretRedactionMap(space.variables, variables_1.VariablesHelper.getAllVariablesFromContext(stageContext));
279
+ }
280
+ async stepDownloadPolicies(policyResolver, localRenderDir) {
281
+ anypoint_cli_command_lib_1.Logger.cliStart('Downloading custom policies');
282
+ const start = Date.now();
283
+ const downloaded = await policyResolver.downloadAll(localRenderDir);
284
+ if (downloaded === 0) {
285
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) ⏩ all cached`);
286
+ }
287
+ else {
288
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) ✅`);
289
+ }
290
+ }
291
+ stepWriteRuntimeConfig(localRenderDir, space, mainFile, dockerPort, renderVariables) {
292
+ anypoint_cli_command_lib_1.Logger.cliStart('Writing runtime configuration');
293
+ const start = Date.now();
294
+ // Every secret reaches its container through env-var indirection, never baked into on-disk
295
+ // artifacts: the agent-graph reads the bare env var, both gateways read the SECURE_ one.
296
+ // Both interpolate from the host process env (populated by buildEnv) at compose parse time.
297
+ const { agentGraphEnvPassthrough, gatewayEnvPassthrough } = this.buildSecuredEnvPassthrough(space);
298
+ const runtimeManager = new run_local_1.DockerComposeEnvironmentManager();
299
+ runtimeManager.addGateway({
300
+ side: 'ingress',
301
+ port: dockerPort,
302
+ configDir: './ingress/config',
303
+ securedEnvPassthrough: gatewayEnvPassthrough,
304
+ });
305
+ runtimeManager.addGateway({
306
+ side: 'egress',
307
+ port: constants_1.EGRESS_GW_PORT,
308
+ configDir: './egress/config',
309
+ securedEnvPassthrough: gatewayEnvPassthrough,
310
+ });
311
+ runtimeManager.addStaticServer({
312
+ assetsDir: './exchange',
313
+ nginxConfPath: './exchange/nginx.conf',
314
+ });
315
+ for (const component of Object.values(space.components)) {
316
+ for (const agentGraph of Object.values(component.agentGraphs)) {
317
+ runtimeManager.addAgentGraph({
318
+ brokerId: agentGraph.id,
319
+ envFilePath: `./agent-graph/${agentGraph.id}/env`,
320
+ sourceDir: './agent-graph/src',
321
+ mainFile,
322
+ llmPlatforms: RunLocal.resolveLlmPlatforms(space, agentGraph),
323
+ securedEnvPassthrough: agentGraphEnvPassthrough,
324
+ });
325
+ }
326
+ }
327
+ runtimeManager.writeConfiguration(localRenderDir);
328
+ // Advisory: aborting here would leave the gateways on new CRDs while the agent-graphs run old code.
329
+ try {
330
+ (0, run_local_1.writeLocalDeployDescriptor)({ localRenderDir, space, dockerPort, variables: renderVariables });
331
+ }
332
+ catch (error) {
333
+ anypoint_cli_command_lib_1.Logger.warn(`Could not write the local deploy descriptor: ${error.message}`);
334
+ }
335
+ anypoint_cli_command_lib_1.Logger.cliEnd(`(${Date.now() - start}ms) ✅`);
336
+ }
337
+ /**
338
+ * Builds the two compose `${SECURE_*:-}` env maps that carry every declared secret into its
339
+ * container without ever writing the real value to disk. Identical for every agent-graph, so
340
+ * computed once. The agent-graph keys are bare (matching agent-graph-module's env-var convention);
341
+ * the gateway keys are the SECURE_-prefixed names the process env is populated with.
342
+ */
343
+ buildSecuredEnvPassthrough(space) {
344
+ var _a;
345
+ const agentGraphEnvPassthrough = {};
346
+ const gatewayEnvPassthrough = {};
347
+ const flatVars = variables_1.VariablesHelper.flattenVariables((_a = space.variables) !== null && _a !== void 0 ? _a : {});
348
+ for (const [key, varDef] of Object.entries(flatVars)) {
349
+ if (!variables_1.VariablesHelper.isSecret(varDef)) {
350
+ continue;
351
+ }
352
+ const secureName = this.secretsManager.toEnvVarName(key);
353
+ const reference = `\${${secureName}:-}`;
354
+ agentGraphEnvPassthrough[(0, naming_1.toAgentGraphEnvVarName)(key)] = reference;
355
+ gatewayEnvPassthrough[secureName] = reference;
356
+ }
357
+ return { agentGraphEnvPassthrough, gatewayEnvPassthrough };
358
+ }
359
+ /** Platforms (e.g. 'gemini') a broker's LLM connections use, for selecting its placeholder api-key env var. */
360
+ static resolveLlmPlatforms(space, agentGraph) {
361
+ var _a;
362
+ const platforms = new Set();
363
+ for (const connection of agentGraph.connections) {
364
+ if (connection.type !== constants_1.LLM_ASSET_TYPE) {
365
+ continue;
366
+ }
367
+ for (const component of Object.values(space.components)) {
368
+ for (const asset of Object.values(component.assets)) {
369
+ if (asset.type === constants_1.LLM_ASSET_TYPE && asset.assetId === connection.asset.assetId && ((_a = asset.properties) === null || _a === void 0 ? void 0 : _a.platform)) {
370
+ platforms.add(asset.properties.platform);
371
+ }
372
+ }
373
+ }
374
+ }
375
+ return [...platforms];
376
+ }
377
+ /** Ensures `.deployment/` (may hold secret material such as the encrypted secrets file) is gitignored; warns if there's no .gitignore to append to. */
378
+ static protectLocalRunInGitIgnore(projectPath) {
379
+ const gitignorePath = (0, node_path_1.join)(projectPath, GITIGNORE_FILE);
380
+ if (!fs.existsSync(gitignorePath)) {
381
+ anypoint_cli_command_lib_1.Logger.warn(`No .gitignore found at ${projectPath}; the ${run_local_1.CHAT_ROOT_DIR}/ directory ` +
382
+ '(which may hold secret material) will not be excluded from your project repo. ' +
383
+ `Add a .gitignore with a "${LOCAL_RUN_GITIGNORE_ENTRY}" entry to protect it.`);
384
+ return;
385
+ }
386
+ try {
387
+ const content = fs.readFileSync(gitignorePath, 'utf-8');
388
+ const alreadyIgnored = content.split(/\r?\n/).some(line => {
389
+ const trimmed = line.trim();
390
+ return trimmed === LOCAL_RUN_GITIGNORE_ENTRY || trimmed === run_local_1.CHAT_ROOT_DIR;
391
+ });
392
+ if (alreadyIgnored) {
393
+ return;
394
+ }
395
+ const prefix = content.length > 0 && !content.endsWith('\n') ? '\n' : '';
396
+ fs.appendFileSync(gitignorePath, `${prefix}${LOCAL_RUN_GITIGNORE_COMMENT}\n${LOCAL_RUN_GITIGNORE_ENTRY}\n`);
397
+ }
398
+ catch (error) {
399
+ // Best-effort hardening: a read/write failure here must not abort the render. Warn loudly so
400
+ // the user knows .deployment/ (which may hold secret material) may not be gitignored.
401
+ anypoint_cli_command_lib_1.Logger.warn(`Could not update .gitignore at ${gitignorePath} to exclude ${run_local_1.CHAT_ROOT_DIR}/ ` +
402
+ `(which may hold secret material). Add a "${LOCAL_RUN_GITIGNORE_ENTRY}" entry manually to protect it. ` +
403
+ `Reason: ${error instanceof Error ? error.message : String(error)}`);
404
+ }
405
+ }
406
+ static loadVariablesCache(localRenderDir) {
407
+ const cacheFile = (0, node_path_1.join)(localRenderDir, VARIABLES_CACHE_FILE);
408
+ if (!fs.existsSync(cacheFile)) {
409
+ return {};
410
+ }
411
+ try {
412
+ const data = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
413
+ if (data.properties) {
414
+ return { ...data.properties, ...data.securedProperties };
415
+ }
416
+ return data;
417
+ }
418
+ catch {
419
+ return {};
420
+ }
421
+ }
422
+ static saveVariablesCache(localRenderDir, properties) {
423
+ const cacheFile = (0, node_path_1.join)(localRenderDir, VARIABLES_CACHE_FILE);
424
+ fs.writeFileSync(cacheFile, JSON.stringify(properties.properties, null, 2));
425
+ }
426
+ /** Best-effort hint only: a TOCTOU race or an IPv6-only bind can still make Docker hit EADDRINUSE. */
427
+ static async findAvailablePort(start, maxAttempts = 50) {
428
+ for (let port = start; port < start + maxAttempts && port <= 65535; port++) {
429
+ // eslint-disable-next-line no-await-in-loop
430
+ if (await RunLocal.isPortAvailable(port)) {
431
+ return port;
432
+ }
433
+ }
434
+ throw error_factory_1.ErrorFactory.noAvailablePort(start, start + maxAttempts - 1);
435
+ }
436
+ static isPortAvailable(port) {
437
+ return new Promise(resolveFn => {
438
+ const server = (0, node_net_1.createServer)();
439
+ server.unref();
440
+ server.once('error', () => resolveFn(false));
441
+ server.once('listening', () => server.close(() => resolveFn(true)));
442
+ server.listen(port, '0.0.0.0');
443
+ });
444
+ }
445
+ static loadDescriptor(projectPath) {
446
+ const exchangeJsonPath = (0, node_path_1.join)(projectPath, constants_1.DESCRIPTOR_FILE);
447
+ return (0, utils_1.safeJsonFileParse)(exchangeJsonPath).jsonObject;
448
+ }
449
+ static hasV2Components(space) {
450
+ return Object.values(space.components).some(component => Object.keys(component.agentGraphs).length > 0);
451
+ }
452
+ static ownedAssetVersionKey(space, component, assetId, asset) {
453
+ if (asset.assetId !== assetId) {
454
+ throw error_factory_1.ErrorFactory.genericError(`Malformed build output: asset map key '${assetId}' does not match assetId '${asset.assetId}'. Rebuild the Agent Network project.`);
455
+ }
456
+ if (typeof component.version !== 'string' || component.version.trim().length === 0) {
457
+ throw error_factory_1.ErrorFactory.genericError(`Malformed build output: owned asset '${assetId}' has no component version. Rebuild the Agent Network project.`);
458
+ }
459
+ const key = (0, network_lock_1.versionVariableKey)({ groupId: space.gav.groupId, assetId });
460
+ return key;
461
+ }
462
+ static assertVersionKeyUnique(key, versions) {
463
+ if (key in versions) {
464
+ throw error_factory_1.ErrorFactory.genericError(`Malformed build output: duplicate owned asset identity '${key}'. Rebuild the Agent Network project.`);
465
+ }
466
+ }
467
+ static assertUniqueLocalDestination(assetId, destinationAssets) {
468
+ const destination = (0, naming_1.toSlug)(assetId);
469
+ if (!destination) {
470
+ throw error_factory_1.ErrorFactory.genericError(`Malformed build output: owned asset '${assetId}' has an empty local Exchange destination. Rename the asset and rebuild.`);
471
+ }
472
+ const destinationAsset = destinationAssets.get(destination);
473
+ if (destinationAsset !== undefined && destinationAsset !== assetId) {
474
+ throw error_factory_1.ErrorFactory.genericError(`Malformed build output: owned assets '${destinationAsset}' and '${assetId}' both map to 'exchange/assets/${destination}'. Rename an asset and rebuild.`);
475
+ }
476
+ return destination;
477
+ }
478
+ static deriveLocalVersionVariables(space) {
479
+ const versions = {};
480
+ const destinationAssets = new Map();
481
+ for (const component of Object.values(space.components)) {
482
+ for (const [assetId, asset] of Object.entries(component.assets)) {
483
+ const key = RunLocal.ownedAssetVersionKey(space, component, assetId, asset);
484
+ RunLocal.assertVersionKeyUnique(key, versions);
485
+ const destination = RunLocal.assertUniqueLocalDestination(assetId, destinationAssets);
486
+ versions[key] = component.version;
487
+ destinationAssets.set(destination, assetId);
488
+ }
489
+ }
490
+ return versions;
491
+ }
492
+ /** Fails loud before the interactive prompt for undeclared `${...}` refs; excludes facet-injected and exact generated local-version placeholders. */
493
+ static validateReferencedVariablesDeclared(space, localVersionVariables = {}) {
494
+ var _a, _b, _c;
495
+ const declared = new Set(Object.keys(variables_1.VariablesHelper.flattenVariables((_a = space.variables) !== null && _a !== void 0 ? _a : {})));
496
+ const injected = facets_1.ProjectFacets.collectInjectedVariableKeys(project_builder_1.Stages.LocalRender, space);
497
+ const generated = new Set(Object.keys(localVersionVariables));
498
+ const referenced = new Set();
499
+ for (const component of Object.values(space.components)) {
500
+ variables_1.VariablesHelper.collectPlaceholderNames(Object.values(component.apiInstances), referenced);
501
+ variables_1.VariablesHelper.collectPlaceholderNames(Object.values(component.connections), referenced);
502
+ for (const agentGraph of Object.values(component.agentGraphs)) {
503
+ variables_1.VariablesHelper.collectPlaceholderNames((_b = agentGraph.properties) !== null && _b !== void 0 ? _b : {}, referenced);
504
+ variables_1.VariablesHelper.collectPlaceholderNames((_c = agentGraph.securedProperties) !== null && _c !== void 0 ? _c : {}, referenced);
505
+ }
506
+ }
507
+ const undeclared = [...referenced].filter(name => !declared.has(name) && !injected.has(name) && !generated.has(name));
508
+ if (undeclared.length > 0) {
509
+ const sortedUndeclared = [...undeclared].sort();
510
+ throw error_factory_1.ErrorFactory.undeclaredVariables(sortedUndeclared);
511
+ }
512
+ }
513
+ /**
514
+ * Fails loud on a declared secret in a route path or upstream address: unlike a policy config,
515
+ * neither can be redacted (the gateway listens on / dials them), so both reach the CRDs verbatim.
516
+ */
517
+ static firstSecretIn(value, secretKeys) {
518
+ return [...variables_1.VariablesHelper.collectPlaceholderNames(value, new Set())].find(name => secretKeys.has(name));
519
+ }
520
+ static assertNoSecretInApiInstance(instance, secretKeys) {
521
+ const inPath = RunLocal.firstSecretIn(instance.path, secretKeys);
522
+ if (inPath) {
523
+ throw error_factory_1.ErrorFactory.secretRouteSegment(instance.id, inPath);
524
+ }
525
+ const inUpstream = RunLocal.firstSecretIn(instance.upstreamUrl, secretKeys);
526
+ if (inUpstream) {
527
+ throw error_factory_1.ErrorFactory.secretUpstreamAddress(instance.id, inUpstream);
528
+ }
529
+ }
530
+ static assertNoSecretInConnection(connection, secretKeys) {
531
+ const inUpstream = RunLocal.firstSecretIn(connection.upstreamUrl, secretKeys);
532
+ if (inUpstream) {
533
+ throw error_factory_1.ErrorFactory.secretUpstreamAddress(connection.id, inUpstream);
534
+ }
535
+ }
536
+ static validateNoSecretInGatewayRoutingFields(space) {
537
+ var _a;
538
+ const secretKeys = new Set(Object.entries(variables_1.VariablesHelper.flattenVariables((_a = space.variables) !== null && _a !== void 0 ? _a : {}))
539
+ .filter(([, varDef]) => variables_1.VariablesHelper.isSecret(varDef))
540
+ .map(([key]) => key));
541
+ if (secretKeys.size === 0) {
542
+ return;
543
+ }
544
+ for (const component of Object.values(space.components)) {
545
+ for (const instance of Object.values(component.apiInstances)) {
546
+ RunLocal.assertNoSecretInApiInstance(instance, secretKeys);
547
+ }
548
+ for (const connection of Object.values(component.connections)) {
549
+ RunLocal.assertNoSecretInConnection(connection, secretKeys);
550
+ }
551
+ }
552
+ }
553
+ /**
554
+ * Fails loud when two distinct declared secret variables collapse to the same runtime env var
555
+ * name — both normalizers strip non-alphanumerics and uppercase, so e.g. `openai.apiKey` and
556
+ * `openai-apiKey` would silently overwrite each other in the passthrough maps. Each normalizer
557
+ * owns its own namespace (SECURE_-prefixed vs bare), so a bare-vs-SECURE_ match across
558
+ * normalizers is not a collision; only same-normalizer duplicates are.
559
+ */
560
+ static validateNoEnvVarNameCollisions(space, normalizers) {
561
+ var _a;
562
+ const secretKeys = Object.entries(variables_1.VariablesHelper.flattenVariables((_a = space.variables) !== null && _a !== void 0 ? _a : {}))
563
+ .filter(([, varDef]) => variables_1.VariablesHelper.isSecret(varDef))
564
+ .map(([key]) => key);
565
+ for (const normalize of normalizers) {
566
+ const seen = new Map();
567
+ for (const key of secretKeys) {
568
+ const envVarName = normalize(key);
569
+ const existing = seen.get(envVarName);
570
+ if (existing !== undefined) {
571
+ throw error_factory_1.ErrorFactory.secretEnvVarNameCollision(existing, key, envVarName);
572
+ }
573
+ seen.set(envVarName, key);
574
+ }
575
+ }
576
+ }
577
+ }
578
+ exports.RunLocal = RunLocal;
579
+ RunLocal.description = 'Render a local Docker Compose environment that runs the Agent Network on the developer machine.';
580
+ RunLocal.hidden = true;
581
+ RunLocal.examples = [
582
+ '$ agent-network project run-local',
583
+ '$ agent-network project run-local --build-only',
584
+ '$ agent-network project run-local --build',
585
+ '$ agent-network project run-local --watch',
586
+ '$ agent-network project run-local --property apiKey:sk-xxx',
587
+ '$ agent-network project run-local --port 9090',
588
+ '$ agent-network project run-local --path ./my-project --property myAgent.url:https://api.example.com',
589
+ ];
590
+ RunLocal.flags = {
591
+ ...anypoint_cli_command_lib_1.AuthenticationBaseCommand.flags,
592
+ path: core_1.Flags.file({
593
+ description: 'The path to the project.',
594
+ default: '.',
595
+ }),
596
+ property: core_1.Flags.string({
597
+ multiple: true,
598
+ description: 'Property to override in format name:value (e.g., --property apiKey:sk-xxx)',
599
+ default: [],
600
+ }),
601
+ 'build-only': core_1.Flags.boolean({
602
+ description: 'Only render the local-run configuration without starting Docker Compose.',
603
+ default: false,
604
+ }),
605
+ build: core_1.Flags.boolean({
606
+ description: 'Build the project (agent-network project build) before rendering the local-run configuration.',
607
+ default: false,
608
+ }),
609
+ watch: core_1.Flags.boolean({
610
+ description: 'Watch project files for changes and automatically rebuild + restart.',
611
+ default: false,
612
+ }),
613
+ port: core_1.Flags.integer({
614
+ description: `Host port to bind the ingress Flex Gateway to (also the in-container listen port). When omitted, the first available port at or above ${run_local_1.DEFAULT_INGRESS_PORT} is used.`,
615
+ }),
616
+ };
617
+ /**
618
+ * The watch-mode state machine, extracted from `RunLocal.runWithWatch` so each transition is a
619
+ * method rather than a closure over shared mutable locals. Collaborators are threaded in as bound
620
+ * thunks so no `RunLocal` member visibility has to widen.
621
+ */
622
+ class WatchSession {
623
+ constructor(options, runtimeManager, secretsManager, buildProject, render, loadBuiltSpace, isMaskedPromptOpen, settleOrTimeout, buildStatus) {
624
+ this.options = options;
625
+ this.runtimeManager = runtimeManager;
626
+ this.secretsManager = secretsManager;
627
+ this.buildProject = buildProject;
628
+ this.render = render;
629
+ this.loadBuiltSpace = loadBuiltSpace;
630
+ this.isMaskedPromptOpen = isMaskedPromptOpen;
631
+ this.settleOrTimeout = settleOrTimeout;
632
+ this.buildStatus = buildStatus;
633
+ this.pendingRebuild = false;
634
+ this.shuttingDown = false;
635
+ this.debounceTimer = null;
636
+ this.onFileChange = (_event, filename) => {
637
+ if (!filename || filename.startsWith('target') || filename.startsWith('node_modules') || filename.startsWith('.')) {
638
+ return;
639
+ }
640
+ const parts = filename.split(/[/\\]/);
641
+ if (parts.some(p => p.startsWith('.'))) {
642
+ return;
643
+ }
644
+ if (this.debounceTimer) {
645
+ clearTimeout(this.debounceTimer);
646
+ }
647
+ this.debounceTimer = setTimeout(() => this.rebuild(), WATCH_DEBOUNCE_MS);
648
+ };
649
+ this.shutdownOnSignal = () => {
650
+ this.shutdown('signal');
651
+ };
652
+ }
653
+ async run() {
654
+ var _a, _b;
655
+ const { projectPath, targetDir, localRenderDir } = this.options;
656
+ const env = this.runtimeManager.buildEnv(this.secretsManager, projectPath, this.loadBuiltSpace(targetDir));
657
+ // With compose detached, nothing else keeps the command alive: only a signal ends the session.
658
+ const session = new Promise(resolveFn => {
659
+ this.resolveSession = resolveFn;
660
+ });
661
+ // Before the first container exists: unhandled, Ctrl+C leaves a half-started environment up.
662
+ process.on('SIGINT', this.shutdownOnSignal);
663
+ process.on('SIGTERM', this.shutdownOnSignal);
664
+ try {
665
+ try {
666
+ // Detached: an attached `up` owns its containers, so a rebuild's recreate would kill the session.
667
+ (_a = this.buildStatus) === null || _a === void 0 ? void 0 : _a.writeRunning('deploying');
668
+ this.runtimeManager.assertAgentGraphImage();
669
+ await this.trackCompose(() => this.runtimeManager.startDetached(localRenderDir, env));
670
+ // Baseline off the initial render (already on disk, force-recreated by startDetached) so the
671
+ // first rebuild diffs against real prior state rather than recreating every broker by default.
672
+ this.priorFingerprints = (0, run_local_1.computeRecreateFingerprints)(this.loadBuiltSpace(targetDir), localRenderDir);
673
+ // A signal during the start: the teardown is already running, so don't watch or follow.
674
+ if (!this.shuttingDown) {
675
+ (_b = this.buildStatus) === null || _b === void 0 ? void 0 : _b.writeRunning();
676
+ this.logFollower = this.runtimeManager.followLogs(localRenderDir);
677
+ this.watcher = (0, node_fs_1.watch)(projectPath, { recursive: true }, this.onFileChange);
678
+ anypoint_cli_command_lib_1.Logger.info(`Watching ${projectPath} for changes... (Ctrl+C to stop)`);
679
+ }
680
+ await session;
681
+ }
682
+ catch (error) {
683
+ // Either a partial `up` (containers holding the ingress port) or a post-start throw from
684
+ // fingerprinting/watcher setup with the detached environment up. Route the teardown through
685
+ // shutdown() so its `shuttingDown` guard owns the single `compose down` even if a signal races
686
+ // in; await session (rethrowing would skip it and oclif exits mid-`down`).
687
+ this.shutdown('error');
688
+ await session;
689
+ throw error;
690
+ }
691
+ }
692
+ finally {
693
+ process.off('SIGINT', this.shutdownOnSignal);
694
+ process.off('SIGTERM', this.shutdownOnSignal);
695
+ // A SIGTERM mid-prompt skips `password-prompt`'s cleanup, leaving a referenced raw-mode stdin
696
+ // handle that outlives the teardown. `pause()` frees it; unsetting raw restores shell echo.
697
+ if (process.stdin.isTTY && process.stdin.isRaw) {
698
+ process.stdin.setRawMode(false);
699
+ }
700
+ process.stdin.pause();
701
+ }
702
+ }
703
+ // Takes a thunk so the handle is published before `start()` can throw. Only ever resolves.
704
+ async trackCompose(start) {
705
+ // Assigned synchronously by the executor below; a skipped resolve would hang a shutdown waiting on this promise.
706
+ let settled;
707
+ this.inFlightCompose = new Promise(resolveFn => {
708
+ settled = resolveFn;
709
+ });
710
+ try {
711
+ await start();
712
+ }
713
+ finally {
714
+ this.inFlightCompose = undefined;
715
+ settled();
716
+ }
717
+ }
718
+ async rebuild() {
719
+ if (this.inFlightRebuild || this.shuttingDown) {
720
+ this.pendingRebuild = !this.shuttingDown;
721
+ return;
722
+ }
723
+ this.inFlightRebuild = this.runRebuild();
724
+ try {
725
+ await this.inFlightRebuild;
726
+ }
727
+ finally {
728
+ this.inFlightRebuild = undefined;
729
+ }
730
+ if (this.pendingRebuild && !this.shuttingDown) {
731
+ this.pendingRebuild = false;
732
+ await this.rebuild();
733
+ }
734
+ }
735
+ async runRebuild() {
736
+ var _a, _b, _c, _d, _e, _f, _g;
737
+ const { projectPath, targetDir, localRenderDir, host } = this.options;
738
+ anypoint_cli_command_lib_1.Logger.print('');
739
+ anypoint_cli_command_lib_1.Logger.info('Change detected, rebuilding...');
740
+ // Stopped for the whole rebuild so inherited container output can't drown a masked secret prompt.
741
+ // Fire-and-forget: the watch loop stays alive, so the unref'd escalation timer still fires;
742
+ // awaiting would stall each rebuild up to the grace period.
743
+ (_b = (_a = this.logFollower) === null || _a === void 0 ? void 0 : _a.stop()) === null || _b === void 0 ? void 0 : _b.catch(() => { });
744
+ this.logFollower = undefined;
745
+ this.lastDetachAt = new Date().toISOString();
746
+ (_c = this.buildStatus) === null || _c === void 0 ? void 0 : _c.beginWatchGeneration();
747
+ (_d = this.buildStatus) === null || _d === void 0 ? void 0 : _d.writeRunning('building');
748
+ try {
749
+ await this.buildProject(projectPath, host);
750
+ await this.render(this.options);
751
+ anypoint_cli_command_lib_1.Logger.info('Applying changes to the local environment...');
752
+ // Re-read: this render may have declared a variable the pre-loop env doesn't carry.
753
+ const space = this.loadBuiltSpace(targetDir);
754
+ const env = this.runtimeManager.buildEnv(this.secretsManager, projectPath, space);
755
+ if (this.shuttingDown) {
756
+ return;
757
+ }
758
+ // Recreate only the brokers whose env file changed, or every broker when the shared source
759
+ // tree changed (source edits aren't per-broker-attributable). Thread the new fingerprints
760
+ // forward so the next rebuild diffs against the state this one just applied.
761
+ const { services, fingerprints } = (0, run_local_1.selectBrokersToRecreate)(space, localRenderDir, this.priorFingerprints);
762
+ (_e = this.buildStatus) === null || _e === void 0 ? void 0 : _e.writeRunning('deploying');
763
+ await this.trackCompose(() => this.runtimeManager.applyChanges(localRenderDir, env, services));
764
+ // Advanced only after the apply resolves: a failed recreate must leave the baseline at the
765
+ // last-applied state so the next rebuild re-selects the still-pending broker.
766
+ this.priorFingerprints = fingerprints;
767
+ (_f = this.buildStatus) === null || _f === void 0 ? void 0 : _f.writeRunning();
768
+ anypoint_cli_command_lib_1.Logger.info('Local environment updated. ✅');
769
+ }
770
+ catch (error) {
771
+ // Raw mode disables ISIG: a Ctrl+C at the secret prompt rejects instead of raising a signal.
772
+ // maskedPromptOpen is the fail-safe: if password-prompt's message drifts from the recognized
773
+ // literal, an unrecognized rejection thrown while a prompt is open still tears down rather
774
+ // than logging and hanging on `await session` with the environment up.
775
+ if ((error === null || error === void 0 ? void 0 : error.message) === RAW_MODE_SIGINT_MESSAGE || this.isMaskedPromptOpen()) {
776
+ anypoint_cli_command_lib_1.Logger.print('');
777
+ this.shutdown('signal');
778
+ return;
779
+ }
780
+ // A signal may have sealed status mid-apply; don't overwrite cancelled or log a user cancel as failure.
781
+ if (this.shuttingDown) {
782
+ return;
783
+ }
784
+ (_g = this.buildStatus) === null || _g === void 0 ? void 0 : _g.writeFailed(error);
785
+ anypoint_cli_command_lib_1.Logger.error(`Rebuild failed: ${error.message}`);
786
+ }
787
+ finally {
788
+ // Every way out of the rebuild left the follower stopped; a session without one stays silent.
789
+ // Bounded by the detach timestamp so the reattach shows the rebuild window (notably a recreated
790
+ // broker's startup, emitted after the detach) without re-dumping the persistent backlog.
791
+ if (!this.shuttingDown) {
792
+ this.logFollower = this.runtimeManager.followLogs(localRenderDir, { since: this.lastDetachAt });
793
+ }
794
+ }
795
+ }
796
+ shutdown(reason) {
797
+ var _a, _b, _c, _d, _e;
798
+ // Both signals may arrive, or a second Ctrl+C: re-entry would run a concurrent `compose down`.
799
+ if (this.shuttingDown) {
800
+ return;
801
+ }
802
+ this.shuttingDown = true;
803
+ // On user cancel, latch before teardown so an in-flight rebuild cannot overwrite cancelled.
804
+ if (reason === 'signal') {
805
+ (_a = this.buildStatus) === null || _a === void 0 ? void 0 : _a.seal();
806
+ }
807
+ if (this.debounceTimer) {
808
+ clearTimeout(this.debounceTimer);
809
+ }
810
+ // Gates the session: awaited (not fire-and-forget) so the follower's group SIGKILL is issued
811
+ // before the process exits, else a SIGTERM-ignoring plugin grandchild is orphaned still writing.
812
+ const followerStopped = (_c = (_b = this.logFollower) === null || _b === void 0 ? void 0 : _b.stop()) !== null && _c !== void 0 ? _c : Promise.resolve();
813
+ (_d = this.watcher) === null || _d === void 0 ? void 0 : _d.close();
814
+ // Compose teardown is sequenced behind the in-flight `compose` call only, never the whole
815
+ // rebuild: its `render` may be parked on a masked secret prompt no signal can interrupt.
816
+ const composeTornDown = this.settleOrTimeout(this.inFlightCompose, exports.COMPOSE_SETTLE_TIMEOUT_MS)
817
+ .then(() => this.runtimeManager.stop(this.options.localRenderDir));
818
+ // Status I/O is advisory and must not delay teardown; cancelled only for user signals.
819
+ if (reason === 'signal') {
820
+ (_e = this.buildStatus) === null || _e === void 0 ? void 0 : _e.writeCancelled();
821
+ }
822
+ Promise.allSettled([composeTornDown, followerStopped]).finally(() => this.resolveSession());
823
+ }
824
+ }
825
+ //# sourceMappingURL=run-local.js.map