agent-relay 17.2.1 → 18.0.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 (243) hide show
  1. package/README.md +45 -270
  2. package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
  3. package/dist/cli/agent-relay-mcp.js +6 -5
  4. package/dist/cli/agent-relay-mcp.js.map +1 -1
  5. package/dist/cli/bootstrap.d.ts +1 -1
  6. package/dist/cli/bootstrap.d.ts.map +1 -1
  7. package/dist/cli/bootstrap.js +11 -29
  8. package/dist/cli/bootstrap.js.map +1 -1
  9. package/dist/cli/commands/agent.d.ts.map +1 -1
  10. package/dist/cli/commands/agent.js +3 -2
  11. package/dist/cli/commands/agent.js.map +1 -1
  12. package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
  13. package/dist/cli/commands/cloud-integration.js +2 -1
  14. package/dist/cli/commands/cloud-integration.js.map +1 -1
  15. package/dist/cli/commands/cloud-room.d.ts.map +1 -1
  16. package/dist/cli/commands/cloud-room.js +2 -1
  17. package/dist/cli/commands/cloud-room.js.map +1 -1
  18. package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
  19. package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
  20. package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
  21. package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
  22. package/dist/cli/commands/cloud-worker.d.ts +1 -1
  23. package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
  24. package/dist/cli/commands/cloud-worker.js +42 -31
  25. package/dist/cli/commands/cloud-worker.js.map +1 -1
  26. package/dist/cli/commands/cloud.d.ts.map +1 -1
  27. package/dist/cli/commands/cloud.js +6 -7
  28. package/dist/cli/commands/cloud.js.map +1 -1
  29. package/dist/cli/commands/core.d.ts +3 -91
  30. package/dist/cli/commands/core.d.ts.map +1 -1
  31. package/dist/cli/commands/core.js +5 -254
  32. package/dist/cli/commands/core.js.map +1 -1
  33. package/dist/cli/commands/fleet-agent.d.ts +9 -54
  34. package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
  35. package/dist/cli/commands/fleet-agent.js +105 -314
  36. package/dist/cli/commands/fleet-agent.js.map +1 -1
  37. package/dist/cli/commands/fleet.d.ts +0 -3
  38. package/dist/cli/commands/fleet.d.ts.map +1 -1
  39. package/dist/cli/commands/fleet.js +48 -267
  40. package/dist/cli/commands/fleet.js.map +1 -1
  41. package/dist/cli/commands/init.js +1 -1
  42. package/dist/cli/commands/init.js.map +1 -1
  43. package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
  44. package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
  45. package/dist/cli/commands/integration-cleanup-journal.js +611 -134
  46. package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
  47. package/dist/cli/commands/integration-recipient.d.ts +0 -17
  48. package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
  49. package/dist/cli/commands/integration-recipient.js +1 -104
  50. package/dist/cli/commands/integration-recipient.js.map +1 -1
  51. package/dist/cli/commands/integration.d.ts +7 -3
  52. package/dist/cli/commands/integration.d.ts.map +1 -1
  53. package/dist/cli/commands/integration.js +37 -82
  54. package/dist/cli/commands/integration.js.map +1 -1
  55. package/dist/cli/commands/local-workflow.d.ts +1 -1
  56. package/dist/cli/commands/local-workflow.d.ts.map +1 -1
  57. package/dist/cli/commands/local-workflow.js +20 -6
  58. package/dist/cli/commands/local-workflow.js.map +1 -1
  59. package/dist/cli/commands/node.d.ts +18 -20
  60. package/dist/cli/commands/node.d.ts.map +1 -1
  61. package/dist/cli/commands/node.js +42 -272
  62. package/dist/cli/commands/node.js.map +1 -1
  63. package/dist/cli/commands/product-surfaces.js +2 -2
  64. package/dist/cli/commands/session.d.ts.map +1 -1
  65. package/dist/cli/commands/session.js +2 -1
  66. package/dist/cli/commands/session.js.map +1 -1
  67. package/dist/cli/commands/skills.d.ts.map +1 -1
  68. package/dist/cli/commands/skills.js +2 -1
  69. package/dist/cli/commands/skills.js.map +1 -1
  70. package/dist/cli/commands/status.d.ts +1 -7
  71. package/dist/cli/commands/status.d.ts.map +1 -1
  72. package/dist/cli/commands/status.js +2 -28
  73. package/dist/cli/commands/status.js.map +1 -1
  74. package/dist/cli/commands/workspace.d.ts.map +1 -1
  75. package/dist/cli/commands/workspace.js +2 -2
  76. package/dist/cli/commands/workspace.js.map +1 -1
  77. package/dist/cli/index.d.ts.map +1 -1
  78. package/dist/cli/index.js +1 -3
  79. package/dist/cli/index.js.map +1 -1
  80. package/dist/cli/lib/agent-relay-cli-reentry.d.ts +37 -0
  81. package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
  82. package/dist/cli/lib/agent-relay-cli-reentry.js +40 -0
  83. package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
  84. package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
  85. package/dist/cli/lib/agent-tools-mcp.js +3 -2
  86. package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
  87. package/dist/cli/lib/core-maintenance.d.ts +2 -3
  88. package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
  89. package/dist/cli/lib/core-maintenance.js +3 -37
  90. package/dist/cli/lib/core-maintenance.js.map +1 -1
  91. package/dist/cli/lib/desktop-presence.js +1 -1
  92. package/dist/cli/lib/desktop-presence.js.map +1 -1
  93. package/dist/cli/lib/install-paths.d.ts +100 -0
  94. package/dist/cli/lib/install-paths.d.ts.map +1 -0
  95. package/dist/cli/lib/install-paths.js +157 -0
  96. package/dist/cli/lib/install-paths.js.map +1 -0
  97. package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
  98. package/dist/cli/lib/product-surface-store.js +4 -1
  99. package/dist/cli/lib/product-surface-store.js.map +1 -1
  100. package/dist/cli/lib/relay-node.d.ts +7 -34
  101. package/dist/cli/lib/relay-node.d.ts.map +1 -1
  102. package/dist/cli/lib/relay-node.js +7 -182
  103. package/dist/cli/lib/relay-node.js.map +1 -1
  104. package/dist/cli/lib/removed-broker-command.d.ts +7 -0
  105. package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
  106. package/dist/cli/lib/removed-broker-command.js +13 -0
  107. package/dist/cli/lib/removed-broker-command.js.map +1 -0
  108. package/dist/cli/lib/sdk-client.d.ts +4 -4
  109. package/dist/cli/lib/sdk-client.js +4 -4
  110. package/dist/cli/lib/self-update.d.ts +8 -19
  111. package/dist/cli/lib/self-update.d.ts.map +1 -1
  112. package/dist/cli/lib/self-update.js +14 -28
  113. package/dist/cli/lib/self-update.js.map +1 -1
  114. package/dist/cli/lib/skills-install.d.ts.map +1 -1
  115. package/dist/cli/lib/skills-install.js +3 -2
  116. package/dist/cli/lib/skills-install.js.map +1 -1
  117. package/dist/cli/telemetry/events.d.ts +4 -1
  118. package/dist/cli/telemetry/events.d.ts.map +1 -1
  119. package/package.json +9 -14
  120. package/dist/auto/classifier.d.ts +0 -29
  121. package/dist/auto/classifier.d.ts.map +0 -1
  122. package/dist/auto/classifier.js +0 -126
  123. package/dist/auto/classifier.js.map +0 -1
  124. package/dist/auto/composer.d.ts +0 -105
  125. package/dist/auto/composer.d.ts.map +0 -1
  126. package/dist/auto/composer.js +0 -454
  127. package/dist/auto/composer.js.map +0 -1
  128. package/dist/auto/director-prompt.d.ts +0 -25
  129. package/dist/auto/director-prompt.d.ts.map +0 -1
  130. package/dist/auto/director-prompt.js +0 -53
  131. package/dist/auto/director-prompt.js.map +0 -1
  132. package/dist/auto/index.d.ts +0 -15
  133. package/dist/auto/index.d.ts.map +0 -1
  134. package/dist/auto/index.js +0 -13
  135. package/dist/auto/index.js.map +0 -1
  136. package/dist/cli/commands/local-agent.d.ts +0 -74
  137. package/dist/cli/commands/local-agent.d.ts.map +0 -1
  138. package/dist/cli/commands/local-agent.js +0 -969
  139. package/dist/cli/commands/local-agent.js.map +0 -1
  140. package/dist/cli/lib/attach-broker.d.ts +0 -17
  141. package/dist/cli/lib/attach-broker.d.ts.map +0 -1
  142. package/dist/cli/lib/attach-broker.js +0 -27
  143. package/dist/cli/lib/attach-broker.js.map +0 -1
  144. package/dist/cli/lib/attach-drive.d.ts +0 -376
  145. package/dist/cli/lib/attach-drive.d.ts.map +0 -1
  146. package/dist/cli/lib/attach-drive.js +0 -1212
  147. package/dist/cli/lib/attach-drive.js.map +0 -1
  148. package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
  149. package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
  150. package/dist/cli/lib/attach-fleet-node.js +0 -1347
  151. package/dist/cli/lib/attach-fleet-node.js.map +0 -1
  152. package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
  153. package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
  154. package/dist/cli/lib/attach-input-recovery.js +0 -559
  155. package/dist/cli/lib/attach-input-recovery.js.map +0 -1
  156. package/dist/cli/lib/attach-mode.d.ts +0 -2
  157. package/dist/cli/lib/attach-mode.d.ts.map +0 -1
  158. package/dist/cli/lib/attach-mode.js +0 -2
  159. package/dist/cli/lib/attach-mode.js.map +0 -1
  160. package/dist/cli/lib/attach-native.d.ts +0 -27
  161. package/dist/cli/lib/attach-native.d.ts.map +0 -1
  162. package/dist/cli/lib/attach-native.js +0 -267
  163. package/dist/cli/lib/attach-native.js.map +0 -1
  164. package/dist/cli/lib/attach-passthrough.d.ts +0 -193
  165. package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
  166. package/dist/cli/lib/attach-passthrough.js +0 -778
  167. package/dist/cli/lib/attach-passthrough.js.map +0 -1
  168. package/dist/cli/lib/attach-remote-node.d.ts +0 -21
  169. package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
  170. package/dist/cli/lib/attach-remote-node.js +0 -133
  171. package/dist/cli/lib/attach-remote-node.js.map +0 -1
  172. package/dist/cli/lib/attach-view.d.ts +0 -177
  173. package/dist/cli/lib/attach-view.d.ts.map +0 -1
  174. package/dist/cli/lib/attach-view.js +0 -455
  175. package/dist/cli/lib/attach-view.js.map +0 -1
  176. package/dist/cli/lib/attach.d.ts +0 -555
  177. package/dist/cli/lib/attach.d.ts.map +0 -1
  178. package/dist/cli/lib/attach.js +0 -1180
  179. package/dist/cli/lib/attach.js.map +0 -1
  180. package/dist/cli/lib/broker-connection.d.ts +0 -65
  181. package/dist/cli/lib/broker-connection.d.ts.map +0 -1
  182. package/dist/cli/lib/broker-connection.js +0 -144
  183. package/dist/cli/lib/broker-connection.js.map +0 -1
  184. package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
  185. package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
  186. package/dist/cli/lib/broker-lifecycle.js +0 -2290
  187. package/dist/cli/lib/broker-lifecycle.js.map +0 -1
  188. package/dist/cli/lib/broker-process-identity.d.ts +0 -38
  189. package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
  190. package/dist/cli/lib/broker-process-identity.js +0 -304
  191. package/dist/cli/lib/broker-process-identity.js.map +0 -1
  192. package/dist/cli/lib/client-factory.d.ts +0 -44
  193. package/dist/cli/lib/client-factory.d.ts.map +0 -1
  194. package/dist/cli/lib/client-factory.js +0 -64
  195. package/dist/cli/lib/client-factory.js.map +0 -1
  196. package/dist/cli/lib/collect-with-retry.d.ts +0 -24
  197. package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
  198. package/dist/cli/lib/collect-with-retry.js +0 -33
  199. package/dist/cli/lib/collect-with-retry.js.map +0 -1
  200. package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
  201. package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
  202. package/dist/cli/lib/fleet-attach-target.js +0 -57
  203. package/dist/cli/lib/fleet-attach-target.js.map +0 -1
  204. package/dist/cli/lib/fleet-hint.d.ts +0 -49
  205. package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
  206. package/dist/cli/lib/fleet-hint.js +0 -113
  207. package/dist/cli/lib/fleet-hint.js.map +0 -1
  208. package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
  209. package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
  210. package/dist/cli/lib/fleet-sidecar.js +0 -84
  211. package/dist/cli/lib/fleet-sidecar.js.map +0 -1
  212. package/dist/cli/lib/join-ticket.d.ts +0 -22
  213. package/dist/cli/lib/join-ticket.d.ts.map +0 -1
  214. package/dist/cli/lib/join-ticket.js +0 -96
  215. package/dist/cli/lib/join-ticket.js.map +0 -1
  216. package/dist/cli/lib/node-claim.d.ts +0 -468
  217. package/dist/cli/lib/node-claim.d.ts.map +0 -1
  218. package/dist/cli/lib/node-claim.js +0 -1349
  219. package/dist/cli/lib/node-claim.js.map +0 -1
  220. package/dist/cli/lib/node-definition-loader.d.ts +0 -19
  221. package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
  222. package/dist/cli/lib/node-definition-loader.js +0 -143
  223. package/dist/cli/lib/node-definition-loader.js.map +0 -1
  224. package/dist/cli/lib/node-provider-child.d.ts +0 -129
  225. package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
  226. package/dist/cli/lib/node-provider-child.js +0 -755
  227. package/dist/cli/lib/node-provider-child.js.map +0 -1
  228. package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
  229. package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
  230. package/dist/cli/lib/predictive-echo-screen.js +0 -74
  231. package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
  232. package/dist/cli/lib/project-broker-client.d.ts +0 -4
  233. package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
  234. package/dist/cli/lib/project-broker-client.js +0 -12
  235. package/dist/cli/lib/project-broker-client.js.map +0 -1
  236. package/dist/cli/lib/reflex-capture.d.ts +0 -41
  237. package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
  238. package/dist/cli/lib/reflex-capture.js +0 -128
  239. package/dist/cli/lib/reflex-capture.js.map +0 -1
  240. package/dist/cli/lib/workspace-env.d.ts +0 -8
  241. package/dist/cli/lib/workspace-env.d.ts.map +0 -1
  242. package/dist/cli/lib/workspace-env.js +0 -16
  243. package/dist/cli/lib/workspace-env.js.map +0 -1
@@ -1,755 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { createRequire } from 'node:module';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
6
- import { MAX_FLEET_NODE_AGENTS, normalizeFleetRepoPaths } from '@agent-relay/fleet';
7
- import { createLogger } from '@agent-relay/utils';
8
- import { describeError } from './describe-error.js';
9
- /** Derive a package root from a resolved entry on both POSIX and Windows. */
10
- export function packageRootFromEntry(entry, packageName) {
11
- const index = entry.replace(/\\/g, '/').lastIndexOf(packageName);
12
- return index >= 0 ? entry.slice(0, index + packageName.length) : entry;
13
- }
14
- /**
15
- * Bootstrap executed by a child `node` process to serve a JS/TS fleet node
16
- * definition.
17
- *
18
- * Why this exists: a `bun build --compile` binary cannot resolve a bare package
19
- * specifier out of a user's on-disk `node_modules` when the package's entry
20
- * point lives in a subdirectory (`dist/`, `lib/`) rather than at the package
21
- * root — which is every package built from TypeScript, `@agent-relay/factory`
22
- * and `@agent-relay/fleet` included. So importing a node config inside the
23
- * shipped binary fails on the config's own `@agent-relay/factory/node` import,
24
- * and the failure is transitive through the user's whole dependency graph, so
25
- * no entry-point-only resolution fix can work.
26
- *
27
- * Node resolves bare specifiers relative to the *importing file*, so importing
28
- * the config by absolute path from this bootstrap (wherever the bootstrap
29
- * itself lives) resolves the config's imports against the config's own
30
- * `node_modules`, exactly as a plain `node` run would.
31
- *
32
- * Kept as source text rather than a shipped file because the compiled binary
33
- * has no `dist/` on disk to point `node` at; it is materialized to a temp file
34
- * at spawn time.
35
- *
36
- * `@agent-relay/fleet` and `@agent-relay/sdk` are resolved from the *config's*
37
- * directory — the only copies on disk, since the compiled binary's own are
38
- * sealed inside it. The child uses the user's installed SDK.
39
- * That makes the user's fleet version part of the contract: `serveNode`'s
40
- * connection shape changed in fleet 10 (`{nodeToken, nodeId}`; fleet 9 took
41
- * `{url, apiKey}`), so an older fleet is rejected up front rather than left to
42
- * fail as an endless reconnect loop against a URL it never received.
43
- */
44
- export const NODE_PROVIDER_CHILD_SOURCE = String.raw `
45
- import { createRequire } from 'node:module';
46
- import { pathToFileURL } from 'node:url';
47
-
48
- const configPath = process.argv[2];
49
- const describeOnly = process.argv.includes('--describe');
50
- const FAILURE = Symbol('node-provider-failure');
51
-
52
- const fail = (message) => {
53
- console.error('[agent-relay] node provider: ' + message);
54
- process.exitCode = 2;
55
- throw FAILURE;
56
- };
57
-
58
- const isDefinition = (value) =>
59
- Boolean(value && typeof value === 'object' && value.__agentRelayFleetNode === true);
60
-
61
- const unwrap = (loaded) => {
62
- let candidate = loaded;
63
- for (let depth = 0; depth < 3; depth += 1) {
64
- if (isDefinition(candidate)) return candidate;
65
- if (!candidate || typeof candidate !== 'object' || !('default' in candidate)) return candidate;
66
- candidate = candidate.default;
67
- }
68
- return candidate;
69
- };
70
-
71
- const errorText = (err) => (err && (err.stack || err.message)) || String(err);
72
- const packageRootFromEntry = ${packageRootFromEntry.toString()};
73
-
74
- const main = async () => {
75
- if (!configPath) {
76
- fail('missing config path argument.');
77
- }
78
- const requireFromConfig = createRequire(configPath);
79
- const importFromConfig = async (specifier) =>
80
- import(pathToFileURL(requireFromConfig.resolve(specifier)).href);
81
-
82
- let definition;
83
- try {
84
- definition = unwrap(await import(pathToFileURL(configPath).href));
85
- } catch (err) {
86
- fail('failed to load ' + configPath + ': ' + errorText(err));
87
- }
88
-
89
- if (!isDefinition(definition)) {
90
- fail(configPath + ' must default-export defineNode(...)');
91
- }
92
-
93
- // Describe mode: report the definition's identity/capability names so the CLI can
94
- // advertise spawn:<harness> capacity and fail fast on a bad explicit --config
95
- // without ever loading the definition in-process. Marker-prefixed and read from
96
- // the last matching line, so a config that prints on import cannot corrupt it.
97
- if (describeOnly) {
98
- const descriptor = {
99
- name: definition.name,
100
- capabilities: Object.keys(definition.capabilities || {}),
101
- ...(typeof definition.maxAgents === 'number' ? { maxAgents: definition.maxAgents } : {}),
102
- // Local child -> CLI IPC only. The parent passes these values directly to
103
- // its native broker; serveNode registration independently emits keys only.
104
- ...(definition.repoPaths && typeof definition.repoPaths === 'object'
105
- ? { repoPaths: definition.repoPaths }
106
- : {}),
107
- };
108
- console.log('__AGENT_RELAY_NODE_DESCRIPTOR__' + JSON.stringify(descriptor));
109
- return;
110
- }
111
-
112
- // Only serving needs the fleet runtime; describing must not require it, so a
113
- // config can be validated even where @agent-relay/fleet is not installed.
114
- let fleetEntry;
115
- try {
116
- fleetEntry = requireFromConfig.resolve('@agent-relay/fleet');
117
- } catch (err) {
118
- fail(
119
- "cannot resolve '@agent-relay/fleet' from " +
120
- configPath +
121
- '. Install it alongside your node config (npm i @agent-relay/fleet). Cause: ' +
122
- errorText(err)
123
- );
124
- }
125
-
126
- // serveNode's connection contract below is fleet >=10 ({nodeToken, nodeId}).
127
- // Fleet 9 took {url, apiKey} and would silently reconnect forever instead.
128
- const fleetPackage = '@agent-relay/fleet';
129
- const fleetRoot = packageRootFromEntry(fleetEntry, fleetPackage);
130
- let fleetVersion;
131
- try {
132
- fleetVersion = requireFromConfig(fleetRoot + '/package.json').version;
133
- } catch {
134
- // Version unreadable (exports-gated package.json): proceed rather than block
135
- // an install that may well work.
136
- }
137
- const fleetMajor = Number.parseInt(String(fleetVersion).split('.')[0], 10);
138
- if (Number.isFinite(fleetMajor) && fleetMajor < 10) {
139
- fail(
140
- 'the @agent-relay/fleet installed next to ' +
141
- configPath +
142
- ' is v' +
143
- fleetVersion +
144
- ', which cannot be served by this CLI (needs >=10). Upgrade it: npm i @agent-relay/fleet@latest'
145
- );
146
- }
147
-
148
- let fleet;
149
- try {
150
- fleet = await import(pathToFileURL(fleetEntry).href);
151
- } catch (err) {
152
- fail('failed to load @agent-relay/fleet from ' + configPath + ': ' + errorText(err));
153
- }
154
-
155
- const env = process.env;
156
- const nodeToken = env.RELAY_NODE_TOKEN;
157
- const nodeId = env.RELAY_NODE_ID;
158
- const nodeName = env.RELAY_NODE_NAME;
159
- const baseUrl = env.RELAY_BASE_URL && env.RELAY_BASE_URL.trim();
160
- const workspaceKey = env.RELAY_WORKSPACE_KEY && env.RELAY_WORKSPACE_KEY.trim();
161
- const loggingEnabled = Boolean(
162
- env.AGENT_RELAY_LOG_FILE || env.AGENT_RELAY_LOG_LEVEL || env.AGENT_RELAY_LOG_JSON === '1'
163
- );
164
-
165
- const sendLog = (level, message, extra) => {
166
- if (typeof process.send === 'function') {
167
- process.send({
168
- __agentRelayNodeProviderLog: true,
169
- level,
170
- message,
171
- ...(extra && typeof extra === 'object' ? { extra } : {}),
172
- });
173
- }
174
- };
175
- const logger = {
176
- debug: (message, extra) => sendLog('debug', message, extra),
177
- info: (message, extra) => sendLog('info', message, extra),
178
- warn: (message, extra) => sendLog('warn', message, extra),
179
- error: (message, extra) => sendLog('error', message, extra),
180
- };
181
- const warn = loggingEnabled
182
- ? (message, extra) => logger.warn(message, extra)
183
- : (message) => console.warn('[agent-relay][node] ' + message);
184
-
185
- if (!nodeToken || !nodeId) {
186
- fail('RELAY_NODE_TOKEN and RELAY_NODE_ID are required.');
187
- }
188
-
189
- let triggers;
190
- if (workspaceKey) {
191
- try {
192
- const { AgentRelay } = await importFromConfig('@agent-relay/sdk');
193
- const relay = new AgentRelay({ workspaceKey, ...(baseUrl ? { baseUrl } : {}) });
194
- triggers = {
195
- list: () => relay.triggers.list(),
196
- create: (input) => relay.triggers.create(input),
197
- update: (id, input) => relay.triggers.update(id, input),
198
- delete: (id) => relay.triggers.delete(id),
199
- };
200
- } catch (err) {
201
- warn('Message triggers will not sync (' + errorText(err) + ').');
202
- }
203
- }
204
-
205
- const stopSignal = new AbortController();
206
- for (const signal of ['SIGTERM', 'SIGINT']) {
207
- process.on(signal, () => stopSignal.abort());
208
- }
209
-
210
- try {
211
- await fleet.serveNode({
212
- definition,
213
- connection: { nodeToken, nodeId, ...(baseUrl ? { baseUrl } : {}) },
214
- ...(nodeName ? { nameOverride: nodeName } : {}),
215
- providerName: definition.name,
216
- ...(triggers ? { triggers } : {}),
217
- reconnect: true,
218
- signal: stopSignal.signal,
219
- ...(loggingEnabled ? { logger } : { warn }),
220
- });
221
- } catch (err) {
222
- if (!stopSignal.signal.aborted) {
223
- fail('serving ' + configPath + ' failed: ' + errorText(err));
224
- }
225
- }
226
- };
227
-
228
- try {
229
- await main();
230
- } catch (err) {
231
- if (err !== FAILURE) {
232
- throw err;
233
- }
234
- }
235
- `;
236
- /** Marker the child prints its descriptor JSON behind, so config output can't corrupt it. */
237
- export const NODE_DESCRIPTOR_MARKER = '__AGENT_RELAY_NODE_DESCRIPTOR__';
238
- /**
239
- * Parse the descriptor a `--describe` child printed.
240
- * @param stdout - Raw child stdout, which may contain the config's own output.
241
- * @returns The descriptor, or `undefined` when no marker line was produced.
242
- */
243
- export function parseNodeDescriptor(stdout) {
244
- const lines = stdout
245
- .split('\n')
246
- .map((line) => line.trim())
247
- .filter((line) => line.startsWith(NODE_DESCRIPTOR_MARKER));
248
- const last = lines.at(-1);
249
- if (!last) {
250
- return undefined;
251
- }
252
- const parsed = JSON.parse(last.slice(NODE_DESCRIPTOR_MARKER.length));
253
- const repoPaths = parseDescriptorRepoPaths(parsed.repoPaths);
254
- const maxAgents = parseDescriptorMaxAgents(parsed.maxAgents);
255
- return {
256
- name: parsed.name,
257
- capabilities: Array.isArray(parsed.capabilities) ? parsed.capabilities : [],
258
- ...(maxAgents !== undefined ? { maxAgents } : {}),
259
- ...(repoPaths !== undefined ? { repoPaths } : {}),
260
- };
261
- }
262
- /**
263
- * Validate a descriptor's agent cap against the shared range. The `--describe`
264
- * child reports whatever the installed `@agent-relay/fleet` accepted, which
265
- * may predate the range check — and the JSON itself is just printed text, so a
266
- * malformed line must fail fast here rather than forward a cap the broker
267
- * would silently normalize to unlimited.
268
- */
269
- function parseDescriptorMaxAgents(value) {
270
- if (value === undefined) {
271
- return undefined;
272
- }
273
- if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0 || value > MAX_FLEET_NODE_AGENTS) {
274
- throw new Error(`Fleet node descriptor maxAgents must be a positive integer no larger than ${MAX_FLEET_NODE_AGENTS}`);
275
- }
276
- return value;
277
- }
278
- function parseDescriptorRepoPaths(value) {
279
- return normalizeFleetRepoPaths(value);
280
- }
281
- /**
282
- * Adapt a descriptor to the capacity shape, so a node definition served
283
- * out-of-process still contributes its `spawn:<harness>` capabilities and its
284
- * `maxAgents` cap to the broker's advertised capacity.
285
- * @param descriptor - Descriptor reported by the `--describe` child.
286
- */
287
- export function descriptorCapacitySource(descriptor) {
288
- return {
289
- capabilities: Object.fromEntries(descriptor.capabilities.map((name) => [name, true])),
290
- ...(typeof descriptor.maxAgents === 'number' ? { maxAgents: descriptor.maxAgents } : {}),
291
- };
292
- }
293
- /**
294
- * File extensions served through a child `node` process when the CLI itself is
295
- * a `bun build --compile` binary.
296
- */
297
- const JS_NODE_DEFINITION_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs']);
298
- const TS_NODE_DEFINITION_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);
299
- /** Whether `configPath` is a JS/TS node definition. */
300
- export function isJsNodeDefinition(configPath) {
301
- return JS_NODE_DEFINITION_EXTENSIONS.has(path.extname(configPath).toLowerCase());
302
- }
303
- /**
304
- * Write the child bootstrap to a temp file so a child `node` process has
305
- * something on disk to execute. The compiled binary has no `dist/` on disk, so
306
- * the source is materialized per run.
307
- * TypeScript inputs are pre-transpiled by the compiled Bun parent and served
308
- * through a Node loader hook at their original file URLs. Keeping the original
309
- * URLs preserves both relative imports and bare-specifier resolution from the
310
- * config's own `node_modules`.
311
- * @param configPath - Node definition the bootstrap will load.
312
- * @param tempRoot - Root in which to create the private bootstrap directory.
313
- * @returns Materialized bootstrap arguments and an idempotent cleanup handle.
314
- */
315
- export function materializeNodeProviderChildScript(configPath, tempRoot = os.tmpdir()) {
316
- const directory = fs.mkdtempSync(path.join(tempRoot, 'agent-relay-node-provider-'));
317
- activeTempDirectories.add(directory);
318
- registerTempCleanupFallback();
319
- try {
320
- const scriptPath = path.join(directory, 'node-provider-child.mjs');
321
- fs.writeFileSync(scriptPath, NODE_PROVIDER_CHILD_SOURCE, 'utf8');
322
- const nodeArgs = [];
323
- const transpiled = transpileTypeScriptGraph(configPath);
324
- if (transpiled) {
325
- const loaderPath = path.join(directory, 'node-definition-loader.mjs');
326
- const registerPath = path.join(directory, 'register-node-definition-loader.mjs');
327
- fs.writeFileSync(loaderPath, renderNodeLoader(transpiled), 'utf8');
328
- fs.writeFileSync(registerPath, [
329
- "import { register } from 'node:module';",
330
- `register(${JSON.stringify(pathToFileURL(loaderPath).href)}, import.meta.url);`,
331
- '',
332
- ].join('\n'), 'utf8');
333
- nodeArgs.push('--import', registerPath);
334
- }
335
- let cleaned = false;
336
- return {
337
- scriptPath,
338
- nodeArgs,
339
- directory,
340
- cleanup: () => {
341
- if (cleaned)
342
- return;
343
- cleaned = true;
344
- cleanupTempDirectory(directory);
345
- },
346
- };
347
- }
348
- catch (err) {
349
- cleanupTempDirectory(directory);
350
- throw err;
351
- }
352
- }
353
- const activeTempDirectories = new Set();
354
- let tempCleanupFallbackRegistered = false;
355
- function registerTempCleanupFallback() {
356
- if (tempCleanupFallbackRegistered)
357
- return;
358
- tempCleanupFallbackRegistered = true;
359
- process.once('exit', () => {
360
- for (const directory of [...activeTempDirectories]) {
361
- cleanupTempDirectory(directory);
362
- }
363
- });
364
- }
365
- function cleanupTempDirectory(directory) {
366
- activeTempDirectories.delete(directory);
367
- try {
368
- fs.rmSync(directory, { recursive: true, force: true });
369
- }
370
- catch {
371
- // Best effort: lifecycle cleanup must never mask the provider result.
372
- }
373
- }
374
- /** Pre-transpile the entry and its statically imported local TypeScript graph. */
375
- function transpileTypeScriptGraph(configPath) {
376
- if (!TS_NODE_DEFINITION_EXTENSIONS.has(path.extname(configPath).toLowerCase())) {
377
- return undefined;
378
- }
379
- const bun = globalThis.Bun;
380
- if (!bun?.Transpiler) {
381
- // This helper is only selected by the compiled-Bun serving plan. Retaining
382
- // the native Node path here keeps isolated Node unit tests injectable.
383
- return undefined;
384
- }
385
- const sources = {};
386
- const resolutions = {};
387
- const commonJsSources = {};
388
- const queued = [path.resolve(configPath)];
389
- const seen = new Set();
390
- while (queued.length > 0) {
391
- const file = queued.pop();
392
- if (seen.has(file))
393
- continue;
394
- seen.add(file);
395
- const source = fs.readFileSync(file, 'utf8');
396
- const extension = path.extname(file).toLowerCase();
397
- const loader = extension === '.tsx' ? 'tsx' : 'ts';
398
- const transpiler = new bun.Transpiler({
399
- loader,
400
- target: 'node',
401
- ...(extension === '.cts'
402
- ? {
403
- define: {
404
- __filename: '__relayCommonJsFilename',
405
- __dirname: '__relayCommonJsDirname',
406
- },
407
- }
408
- : {}),
409
- });
410
- const parentUrls = new Set([pathToFileURL(file).href, pathToFileURL(fs.realpathSync(file)).href]);
411
- const transformed = transpiler.transformSync(source, loader);
412
- for (const parentUrl of parentUrls) {
413
- if (extension === '.cts') {
414
- commonJsSources[parentUrl] = transformed;
415
- }
416
- else {
417
- sources[parentUrl] = transformed;
418
- }
419
- }
420
- for (const imported of transpiler.scanImports(source)) {
421
- const resolved = resolveImportedTypeScript(file, imported.path);
422
- if (!resolved)
423
- continue;
424
- const resolvedUrl = pathToFileURL(fs.realpathSync(resolved)).href;
425
- for (const parentUrl of parentUrls) {
426
- resolutions[loaderResolutionKey(parentUrl, imported.path)] = resolvedUrl;
427
- }
428
- queued.push(resolved);
429
- }
430
- }
431
- for (const entryUrl of Object.keys(commonJsSources)) {
432
- sources[entryUrl] = wrapCommonJsAsModule(entryUrl, commonJsSources, resolutions);
433
- }
434
- return { sources, resolutions };
435
- }
436
- /** Execute a transpiled .cts graph synchronously with Node-like CommonJS modules. */
437
- function wrapCommonJsAsModule(entryUrl, commonJsSources, resolutions) {
438
- return [
439
- "import { Module as __RelayModule, createRequire as __relayCreateRequire } from 'node:module';",
440
- "import { dirname as __relayDirname } from 'node:path';",
441
- "import { fileURLToPath as __relayFileURLToPath } from 'node:url';",
442
- `const __relaySources = new Map(Object.entries(${JSON.stringify(commonJsSources)}));`,
443
- `const __relayResolutions = new Map(Object.entries(${JSON.stringify(resolutions)}));`,
444
- `const __relayKey = (parentURL, specifier) => parentURL + '\\0' + specifier;`,
445
- 'const __relayCache = new Map();',
446
- 'const __relayLoad = (url, parent) => {',
447
- ' const cached = __relayCache.get(url);',
448
- ' if (cached) return cached.exports;',
449
- ' const source = __relaySources.get(url);',
450
- " if (source === undefined) throw new Error('Missing transpiled CommonJS source for ' + url);",
451
- ' const filename = __relayFileURLToPath(url);',
452
- ' const dirname = __relayDirname(filename);',
453
- ' const nativeRequire = __relayCreateRequire(url);',
454
- ' const relayModule = new __RelayModule(filename, parent);',
455
- ' relayModule.filename = filename;',
456
- ' relayModule.path = dirname;',
457
- " relayModule.paths = nativeRequire.resolve.paths('__agent_relay_module_paths__') || [];",
458
- ' const relayRequire = (specifier) => {',
459
- ' const resolved = __relayResolutions.get(__relayKey(url, specifier));',
460
- ' return resolved && __relaySources.has(resolved)',
461
- ' ? __relayLoad(resolved, relayModule)',
462
- ' : nativeRequire(specifier);',
463
- ' };',
464
- ' relayRequire.resolve = nativeRequire.resolve;',
465
- ' relayRequire.cache = nativeRequire.cache;',
466
- ' relayRequire.extensions = nativeRequire.extensions;',
467
- ' relayRequire.main = nativeRequire.main;',
468
- ' relayModule.require = relayRequire;',
469
- ' __relayCache.set(url, relayModule);',
470
- ' const factory = new Function(',
471
- " 'exports', 'require', 'module', '__filename', '__dirname',",
472
- " '__relayCommonJsFilename', '__relayCommonJsDirname', source",
473
- ' );',
474
- ' factory.call(',
475
- ' relayModule.exports, relayModule.exports, relayRequire, relayModule,',
476
- ' filename, dirname, filename, dirname',
477
- ' );',
478
- ' relayModule.loaded = true;',
479
- ' return relayModule.exports;',
480
- '};',
481
- `export default __relayLoad(${JSON.stringify(entryUrl)}, undefined);`,
482
- '',
483
- ].join('\n');
484
- }
485
- function resolveImportedTypeScript(parentFile, specifier) {
486
- let candidate;
487
- try {
488
- if (specifier.startsWith('file:')) {
489
- candidate = fileURLToPath(specifier);
490
- }
491
- else if (specifier.startsWith('.') || path.isAbsolute(specifier)) {
492
- candidate = path.resolve(path.dirname(parentFile), specifier);
493
- }
494
- else {
495
- candidate = createRequire(parentFile).resolve(specifier);
496
- }
497
- }
498
- catch {
499
- return undefined;
500
- }
501
- const attempts = [candidate];
502
- if (!path.extname(candidate)) {
503
- for (const extension of TS_NODE_DEFINITION_EXTENSIONS) {
504
- attempts.push(candidate + extension, path.join(candidate, 'index' + extension));
505
- }
506
- }
507
- else if (/\.[cm]?js$/i.test(candidate)) {
508
- const stem = candidate.replace(/\.[cm]?js$/i, '');
509
- attempts.push(stem + '.ts', stem + '.tsx', stem + '.mts', stem + '.cts');
510
- }
511
- const resolved = attempts.find((attempt) => TS_NODE_DEFINITION_EXTENSIONS.has(path.extname(attempt).toLowerCase()) && isFile(attempt));
512
- return resolved ? path.resolve(resolved) : undefined;
513
- }
514
- function isFile(file) {
515
- try {
516
- return fs.statSync(file).isFile();
517
- }
518
- catch {
519
- return false;
520
- }
521
- }
522
- function loaderResolutionKey(parentUrl, specifier) {
523
- return `${parentUrl}\0${specifier}`;
524
- }
525
- function renderNodeLoader(graph) {
526
- return [
527
- `const sources = new Map(Object.entries(${JSON.stringify(graph.sources)}));`,
528
- `const resolutions = new Map(Object.entries(${JSON.stringify(graph.resolutions)}));`,
529
- `const key = (parentURL, specifier) => parentURL + '\\0' + specifier;`,
530
- 'export async function resolve(specifier, context, nextResolve) {',
531
- ' const url = resolutions.get(key(context.parentURL || "", specifier));',
532
- ' return url ? { url, shortCircuit: true } : nextResolve(specifier, context);',
533
- '}',
534
- 'export async function load(url, context, nextLoad) {',
535
- ' const source = sources.get(url);',
536
- " return source === undefined ? nextLoad(url, context) : { format: 'module', source, shortCircuit: true };",
537
- '}',
538
- '',
539
- ].join('\n');
540
- }
541
- /** Single-quote a path for safe interpolation into a shell command. */
542
- function shellQuote(value) {
543
- return `'${value.replace(/'/g, `'\\''`)}'`;
544
- }
545
- /**
546
- * Load a node definition's descriptor by running the bootstrap in `--describe`
547
- * mode under a child `node` process.
548
- *
549
- * This is how the compiled binary learns anything at all about a JS/TS node
550
- * definition: it cannot import one itself (scoped specifiers in the user's
551
- * `node_modules` do not resolve under `bun build --compile`), so it asks Node.
552
- *
553
- * @param configPath - Absolute path to the user's node definition file.
554
- * @param deps - Core dependencies (exec, env).
555
- * @returns The descriptor.
556
- * @throws When the child cannot load or validate the definition.
557
- */
558
- export async function describeNodeDefinitionViaNode(configPath, deps) {
559
- const nodeBin = deps.env.AGENT_RELAY_NODE?.trim() || 'node';
560
- const materialized = materializeNodeProviderChildScript(configPath, deps.env.TMPDIR?.trim() || os.tmpdir());
561
- const command = [nodeBin, ...materialized.nodeArgs, materialized.scriptPath, configPath, '--describe']
562
- .map(shellQuote)
563
- .join(' ');
564
- let stdout;
565
- try {
566
- ({ stdout } = await deps.execCommand(command));
567
- }
568
- catch (err) {
569
- const detail = extractChildFailure(err);
570
- throw new Error(`Failed to load ${configPath} via ${nodeBin}: ${detail}. ` +
571
- `Serving a JS/TS node definition from the standalone agent-relay binary requires \`${nodeBin}\` on PATH ` +
572
- '(set AGENT_RELAY_NODE to override).');
573
- }
574
- finally {
575
- materialized.cleanup();
576
- }
577
- const descriptor = parseNodeDescriptor(stdout);
578
- if (!descriptor) {
579
- throw new Error(`Fleet node file ${configPath} must default-export defineNode(...)`);
580
- }
581
- return descriptor;
582
- }
583
- /** Pull the useful text out of an execCommand rejection (stderr beats the generic message). */
584
- function extractChildFailure(err) {
585
- const stderr = err && typeof err === 'object' && 'stderr' in err ? String(err.stderr) : '';
586
- const trimmed = stderr.trim();
587
- if (trimmed) {
588
- return trimmed;
589
- }
590
- return describeError(err);
591
- }
592
- /**
593
- * Serve a JS/TS fleet node definition in a child `node` process.
594
- *
595
- * Used only when the CLI is running as a `bun build --compile` binary, where
596
- * loading the definition in-process is impossible (see
597
- * {@link NODE_PROVIDER_CHILD_SOURCE}). Under Node the definition is still
598
- * served in-process, which keeps the existing behavior unchanged.
599
- *
600
- * @param configPath - Absolute path to the user's node definition file.
601
- * @param credentials - Node identity/token the child registers with.
602
- * @param deps - Core dependencies (spawn, env, logging).
603
- * @returns A supervised child handle, or `undefined` when it could not be started.
604
- */
605
- export async function startNodeJsNodeProvider(configPath, credentials, deps) {
606
- const nodeBin = deps.env.AGENT_RELAY_NODE?.trim() || 'node';
607
- const env = {
608
- ...deps.env,
609
- RELAY_NODE_TOKEN: credentials.nodeToken,
610
- RELAY_NODE_ID: credentials.nodeId,
611
- RELAY_NODE_NAME: credentials.nodeName,
612
- ...(credentials.baseUrl ? { RELAY_BASE_URL: credentials.baseUrl } : {}),
613
- ...(credentials.workspaceKey ? { RELAY_WORKSPACE_KEY: credentials.workspaceKey } : {}),
614
- };
615
- const loggingEnabled = childLoggingEnabled(env);
616
- let materialized;
617
- try {
618
- materialized = materializeNodeProviderChildScript(configPath, deps.env.TMPDIR?.trim() || os.tmpdir());
619
- const child = deps.spawnProcess(nodeBin, [...materialized.nodeArgs, materialized.scriptPath, configPath], {
620
- stdio: loggingEnabled ? ['inherit', 'inherit', 'inherit', 'ipc'] : 'inherit',
621
- env,
622
- cwd: path.dirname(configPath),
623
- });
624
- attachChildLogger(child, loggingEnabled);
625
- const managed = manageNodeProviderChild(child, materialized, deps, configPath);
626
- await managed.started;
627
- deps.log(`Serving fleet node provider: ${nodeBin} ${path.basename(configPath)} (pid: ${child.pid ?? 'unknown'}).`);
628
- return managed.handle;
629
- }
630
- catch (err) {
631
- materialized?.cleanup();
632
- deps.warn(`Fleet node provider skipped: ${err instanceof Error ? err.message : String(err)}. ` +
633
- `Serving a JS/TS node definition from the standalone agent-relay binary requires \`${nodeBin}\` on PATH; ` +
634
- 'set AGENT_RELAY_NODE to point at a Node.js executable.');
635
- return undefined;
636
- }
637
- }
638
- function childLoggingEnabled(env) {
639
- return Boolean(env.AGENT_RELAY_LOG_FILE || env.AGENT_RELAY_LOG_LEVEL || env.AGENT_RELAY_LOG_JSON === '1');
640
- }
641
- function attachChildLogger(child, enabled) {
642
- const evented = child;
643
- if (!enabled || typeof evented.on !== 'function')
644
- return;
645
- const logger = createLogger('fleet');
646
- evented.on('message', (message) => {
647
- if (!isChildLogMessage(message))
648
- return;
649
- logger[message.level](message.message, message.extra);
650
- });
651
- }
652
- function isChildLogMessage(value) {
653
- if (!value || typeof value !== 'object')
654
- return false;
655
- const candidate = value;
656
- return (candidate.__agentRelayNodeProviderLog === true &&
657
- typeof candidate.message === 'string' &&
658
- ['debug', 'info', 'warn', 'error'].includes(String(candidate.level)) &&
659
- (candidate.extra === undefined ||
660
- (typeof candidate.extra === 'object' && candidate.extra !== null && !Array.isArray(candidate.extra))));
661
- }
662
- function manageNodeProviderChild(child, materialized, deps, configPath) {
663
- const evented = child;
664
- const observesLifecycle = typeof evented.once === 'function';
665
- let stopping = false;
666
- let settled = false;
667
- let resolveDone;
668
- let rejectDone;
669
- let resolveStarted;
670
- let rejectStarted;
671
- const done = new Promise((resolve, reject) => {
672
- resolveDone = resolve;
673
- rejectDone = reject;
674
- });
675
- // A child may fail between startNodeJsNodeProvider returning and the broker
676
- // attaching its lifecycle race. Mark the promise handled without changing
677
- // what callers observe when they await the original promise.
678
- void done.catch(() => undefined);
679
- const started = new Promise((resolve, reject) => {
680
- resolveStarted = resolve;
681
- rejectStarted = reject;
682
- });
683
- const finish = (error) => {
684
- if (settled)
685
- return;
686
- settled = true;
687
- materialized.cleanup();
688
- if (error && !stopping) {
689
- rejectDone(error);
690
- }
691
- else {
692
- resolveDone();
693
- }
694
- };
695
- if (observesLifecycle) {
696
- evented.once('spawn', () => resolveStarted());
697
- evented.once('error', (rawError) => {
698
- const error = rawError instanceof Error ? rawError : new Error(String(rawError));
699
- rejectStarted(error);
700
- finish(new Error(`Fleet node provider for ${configPath} failed: ${error.message}`, { cause: error }));
701
- });
702
- evented.once('exit', (code, signal) => {
703
- const detail = signal ? `signal ${String(signal)}` : `code ${String(code)}`;
704
- finish(new Error(`Fleet node provider for ${configPath} exited unexpectedly (${detail}).`));
705
- });
706
- }
707
- else {
708
- resolveStarted();
709
- }
710
- return {
711
- started,
712
- handle: {
713
- ...(child.pid !== undefined ? { pid: child.pid } : {}),
714
- done,
715
- stop: async () => {
716
- stopping = true;
717
- if (!settled) {
718
- try {
719
- if (child.pid) {
720
- deps.killProcess(child.pid, 'SIGTERM');
721
- }
722
- else {
723
- child.kill?.('SIGTERM');
724
- }
725
- }
726
- catch {
727
- // The child may already have exited between the state check and kill.
728
- }
729
- }
730
- if (observesLifecycle && !settled) {
731
- const exited = await Promise.race([
732
- done.then(() => true, () => true),
733
- deps.sleep(5_000).then(() => false),
734
- ]);
735
- if (!exited && !settled) {
736
- try {
737
- if (child.pid) {
738
- deps.killProcess(child.pid, 'SIGKILL');
739
- }
740
- else {
741
- child.kill?.('SIGKILL');
742
- }
743
- }
744
- catch {
745
- // The child may have exited while graceful shutdown timed out.
746
- }
747
- await Promise.race([done.catch(() => undefined), deps.sleep(1_000)]);
748
- }
749
- }
750
- finish();
751
- },
752
- },
753
- };
754
- }
755
- //# sourceMappingURL=node-provider-child.js.map