@amd-gaia/agent-ui 0.26.1-rc.2 → 0.27.0-rc.1

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 (56) hide show
  1. package/dist/assets/AdvancedSettings-znkqGWxt.js +1 -0
  2. package/dist/assets/AutomationsSettings-By0Cy-Gu.js +1 -0
  3. package/dist/assets/ConnectorsPane-6hKjjRWm.js +1 -0
  4. package/dist/assets/ConnectorsPane-BGI8nBUb.css +1 -0
  5. package/dist/assets/DocumentLibrary-_PZjdm8h.js +5 -0
  6. package/dist/assets/DocumentLibrary-fEMoY7lH.css +1 -0
  7. package/dist/assets/FileBrowser-1goNp4CP.css +1 -0
  8. package/dist/assets/FileBrowser-C_cpUmtN.js +4 -0
  9. package/dist/assets/MemoryDashboard-BEafsLNv.js +1 -0
  10. package/dist/assets/MemoryDashboard-TCZiujy9.css +1 -0
  11. package/dist/assets/MessagingSettings-sBXQSmjR.js +1 -0
  12. package/dist/assets/{MobileAccessModal-CX4NZmr4.css → MobileAccessModal-BrZMaERi.css} +1 -1
  13. package/dist/assets/MobileAccessModal-b23-QxSf.js +2 -0
  14. package/dist/assets/ScheduleManager-BZzEH2-W.css +1 -0
  15. package/dist/assets/ScheduleManager-D_U1Igck.js +1 -0
  16. package/dist/assets/Temml-CCjoacWt.woff2 +0 -0
  17. package/dist/assets/index-BgqO1M5f.js +220 -0
  18. package/dist/assets/index-BiETDNik.css +1 -0
  19. package/dist/assets/useFocusTrap-JsuLBsNA.js +6 -0
  20. package/dist/assets/zap-DmECnAbs.js +1 -0
  21. package/dist/index.html +3 -3
  22. package/dist/sw.js +1 -1
  23. package/main.cjs +130 -40
  24. package/package.json +5 -3
  25. package/preload.cjs +28 -0
  26. package/services/browser-pane/bridge-error.cjs +20 -0
  27. package/services/browser-pane/bridge-server.cjs +496 -0
  28. package/services/browser-pane/cdp-session.cjs +375 -0
  29. package/services/browser-pane/contract.d.ts +448 -0
  30. package/services/browser-pane/dev-servers.cjs +478 -0
  31. package/services/browser-pane/input.cjs +375 -0
  32. package/services/browser-pane/ipc.cjs +267 -0
  33. package/services/browser-pane/navigation-policy.cjs +255 -0
  34. package/services/browser-pane/pane-host.cjs +1686 -0
  35. package/services/browser-pane/picker-world.js +360 -0
  36. package/services/browser-pane/picker.cjs +261 -0
  37. package/services/browser-pane/service-ports.cjs +66 -0
  38. package/services/dev-qa-mode.cjs +32 -0
  39. package/dist/assets/AdvancedSettings-C-9ErldS.js +0 -1
  40. package/dist/assets/AutomationsSettings-CL3K4hLZ.js +0 -1
  41. package/dist/assets/ConnectorsPane-DpGR78cA.js +0 -1
  42. package/dist/assets/ConnectorsPane-w-HLcq3n.css +0 -1
  43. package/dist/assets/DocumentLibrary-BKZdx6rJ.css +0 -1
  44. package/dist/assets/DocumentLibrary-N7tBbt9v.js +0 -5
  45. package/dist/assets/FileBrowser-CO2p3xa2.js +0 -4
  46. package/dist/assets/FileBrowser-CrRQXiPo.css +0 -1
  47. package/dist/assets/MemoryDashboard-1OIrKFIa.js +0 -1
  48. package/dist/assets/MemoryDashboard-B4AO_CU8.css +0 -1
  49. package/dist/assets/MessagingSettings-0AJnsoWA.js +0 -1
  50. package/dist/assets/MobileAccessModal-CnPB1BEN.js +0 -2
  51. package/dist/assets/ScheduleManager-BYOhqnfv.js +0 -1
  52. package/dist/assets/ScheduleManager-DQBnf_IN.css +0 -1
  53. package/dist/assets/index-Bkx-QRv4.css +0 -1
  54. package/dist/assets/index-C-3wCH_s.js +0 -116
  55. package/dist/assets/useT-DuzpQY8p.js +0 -6
  56. package/dist/assets/zap-gF9QDKfa.js +0 -1
@@ -0,0 +1,478 @@
1
+ // Copyright(C) 2026 Advanced Micro Devices, Inc. All rights reserved.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * Dev servers the agent starts, owned by main so they outlive turns and
6
+ * sidecar restarts and stop when the app quits. Python parses launch.json
7
+ * and asks the user; this file only runs the spec Python sends, argv only,
8
+ * never through a shell.
9
+ *
10
+ * Servers are app-wide, but each remembers the chats that use it: the one
11
+ * that started it first, then any that asked for the same server since.
12
+ * Deleting a chat stops the servers only it was using and forgets them.
13
+ *
14
+ * A ledger file records each server's pids and command lines, so the next
15
+ * launch can stop servers a crash left behind. It only ever signals a pid it
16
+ * recorded whose command line still matches.
17
+ */
18
+
19
+ "use strict";
20
+
21
+ const childProcess = require("child_process");
22
+ const fs = require("fs");
23
+ const net = require("net");
24
+ const path = require("path");
25
+ const { BridgeError } = require("./bridge-error.cjs");
26
+ const { descendantsFromTable, killProcessTree, listProcesses } = require("../process-tree.cjs");
27
+
28
+ /** @typedef {import("./contract").DevServerSpec} DevServerSpec */
29
+ /** @typedef {import("./contract").DevServerState} DevServerState */
30
+
31
+ /** Names a launch.json may set. Python's dev_servers.ENV_NAMES is the same; both test bridge/dev_server_env.json. */
32
+ const ENV_NAMES = new Set([
33
+ "BROWSER", "CI", "DEBUG", "FORCE_COLOR", "HOST", "HOSTNAME", "LOG_LEVEL",
34
+ "NODE_ENV", "NO_COLOR", "PORT", "PYTHONUNBUFFERED", "TZ",
35
+ ]);
36
+ const ENV_PREFIXES = ["VITE_", "NEXT_PUBLIC_", "REACT_APP_", "PUBLIC_"];
37
+
38
+ /** What a server inherits from the app's own environment: enough to find and run its tools, no secrets. */
39
+ const INHERITED_ENV = [
40
+ "PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TEMP", "TMP", "TERM",
41
+ "NVM_DIR", "NVM_BIN", "VOLTA_HOME", "PNPM_HOME", "COREPACK_HOME",
42
+ "SystemRoot", "SYSTEMROOT", "ComSpec", "COMSPEC", "PATHEXT", "WINDIR", "APPDATA", "LOCALAPPDATA", "USERPROFILE",
43
+ "ProgramFiles", "ProgramFiles(x86)", "ProgramData",
44
+ ];
45
+
46
+ const LOG_CAP_BYTES = 1024 * 1024;
47
+ const FAIL_LINES = 30;
48
+ const LINE_CHARS = 500;
49
+ const PROBE_EVERY_MS = 100;
50
+ const PROBE_TIMEOUT_MS = 400;
51
+ const REAP_GRACE_MS = 3000;
52
+ const ERROR_LINE = /\berror\b|\bfailed\b|\bexception\b|\bfatal\b|\bpanic\b|ERR!/i;
53
+
54
+ function envNameAllowed(name) {
55
+ return ENV_NAMES.has(name) || (ENV_PREFIXES.some((p) => name.startsWith(p)) && /^[A-Z0-9_]+$/.test(name));
56
+ }
57
+
58
+ /**
59
+ * @param {DevServerSpec} spec @param {NodeJS.ProcessEnv} from
60
+ * @param {string | null} searchPath The backend's login-shell PATH; an app opened from the Dock has only launchd's.
61
+ */
62
+ function childEnv(spec, from, searchPath = null) {
63
+ const env = {};
64
+ for (const name of INHERITED_ENV) if (from[name] !== undefined) env[name] = from[name];
65
+ if (searchPath) env.PATH = searchPath;
66
+ return { ...env, ...spec.env };
67
+ }
68
+
69
+ /** True when something accepts a TCP connection on the port, over IPv4 or IPv6 loopback. */
70
+ function portAnswers(port) {
71
+ const one = (host) =>
72
+ new Promise((resolve) => {
73
+ const socket = net.connect({ host, port });
74
+ const done = (ok) => {
75
+ socket.destroy();
76
+ resolve(ok);
77
+ };
78
+ socket.setTimeout(PROBE_TIMEOUT_MS, () => done(false));
79
+ socket.once("connect", () => done(true));
80
+ socket.once("error", () => done(false));
81
+ });
82
+ return Promise.all([one("127.0.0.1"), one("::1")]).then(([v4, v6]) => v4 || v6);
83
+ }
84
+
85
+ const sameSpec = (a, b) => JSON.stringify(normalized(a)) === JSON.stringify(normalized(b));
86
+ const normalized = (s) => ({ ...s, env: Object.fromEntries(Object.entries(s.env).sort()) });
87
+
88
+ /** One log file per server, cut back to its newest half when it passes the cap. */
89
+ class CappedLog {
90
+ constructor(file, cap = LOG_CAP_BYTES) {
91
+ fs.mkdirSync(path.dirname(file), { recursive: true });
92
+ this.file = file;
93
+ this.cap = cap;
94
+ this.fd = fs.openSync(file, "w+");
95
+ this.size = 0;
96
+ }
97
+
98
+ write(chunk) {
99
+ if (this.fd === null) return;
100
+ let buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
101
+ if (buf.length > this.cap / 2) buf = buf.subarray(buf.length - Math.floor(this.cap / 2));
102
+ if (this.size + buf.length > this.cap) this.compact(buf.length);
103
+ fs.writeSync(this.fd, buf, 0, buf.length, this.size);
104
+ this.size += buf.length;
105
+ }
106
+
107
+ compact(incoming) {
108
+ const keep = Math.max(0, Math.min(this.size, Math.floor(this.cap / 2) - incoming));
109
+ const tail = Buffer.alloc(keep);
110
+ fs.readSync(this.fd, tail, 0, keep, this.size - keep);
111
+ const cut = tail.indexOf(10);
112
+ const kept = cut >= 0 ? tail.subarray(cut + 1) : tail;
113
+ const marker = Buffer.from("[GAIA: older lines were dropped to keep this log under 1 MB]\n");
114
+ fs.ftruncateSync(this.fd, 0);
115
+ fs.writeSync(this.fd, marker, 0, marker.length, 0);
116
+ fs.writeSync(this.fd, kept, 0, kept.length, marker.length);
117
+ this.size = marker.length + kept.length;
118
+ }
119
+
120
+ close() {
121
+ if (this.fd === null) return;
122
+ fs.closeSync(this.fd);
123
+ this.fd = null;
124
+ }
125
+ }
126
+
127
+ function readLines(file) {
128
+ let text;
129
+ try {
130
+ text = fs.readFileSync(file, "utf8");
131
+ } catch (err) {
132
+ if (err.code === "ENOENT") return [];
133
+ throw err;
134
+ }
135
+ return text
136
+ .split(/\r?\n/)
137
+ .filter((l) => l.trim() !== "")
138
+ .map((l) => (l.length > LINE_CHARS ? `${l.slice(0, LINE_CHARS)}…` : l));
139
+ }
140
+
141
+ class DevServerSupervisor {
142
+ /**
143
+ * @param {{
144
+ * dir: string,
145
+ * blockedPorts: () => number[],
146
+ * onChange: () => void,
147
+ * env?: NodeJS.ProcessEnv,
148
+ * spawn?: typeof childProcess.spawn,
149
+ * listProcesses?: typeof listProcesses,
150
+ * killTree?: typeof killProcessTree,
151
+ * reapGraceMs?: number,
152
+ * logger?: { log: Function, error: Function },
153
+ * }} deps
154
+ */
155
+ constructor(deps) {
156
+ this.deps = {
157
+ env: process.env,
158
+ spawn: childProcess.spawn,
159
+ listProcesses,
160
+ killTree: killProcessTree,
161
+ reapGraceMs: REAP_GRACE_MS,
162
+ logger: console,
163
+ ...deps,
164
+ };
165
+ this.ledgerPath = path.join(deps.dir, "ledger.json");
166
+ /** @type {Map<string, any>} */
167
+ this.entries = new Map();
168
+ /** @type {Map<string, Promise<unknown>>} */
169
+ this.queues = new Map();
170
+ /** @type {Promise<unknown> | null} */
171
+ this.started = null;
172
+ }
173
+
174
+ /** Reap what a crash left behind. ensure waits for it, so a new server never races an orphan for its port. */
175
+ start() {
176
+ if (!this.started) {
177
+ this.started = this.reapOrphans().catch((err) => {
178
+ this.deps.logger.error(`[dev-servers] Could not stop dev servers left by an earlier run: ${err.message}. Its ledger stays at ${this.ledgerPath}.`);
179
+ });
180
+ }
181
+ return this.started;
182
+ }
183
+
184
+ /**
185
+ * Every server for the user's menu, or only the ones a chat's agent started or reused.
186
+ * @param {string | null} chat
187
+ * @returns {DevServerState[]}
188
+ */
189
+ list(chat = null) {
190
+ return [...this.entries.values()].filter((e) => chat === null || e.chats.includes(chat)).map((e) => this.stateOf(e));
191
+ }
192
+
193
+ /**
194
+ * Converge on "this spec runs and answers on its port".
195
+ * @param {string} key @param {DevServerSpec} spec
196
+ * @param {string} chat The chat whose agent asked.
197
+ * @param {string | null} searchPath
198
+ * @returns {Promise<{ server: DevServerState, reused: boolean, ms: number }>}
199
+ */
200
+ ensure(key, spec, chat, searchPath = null) {
201
+ if (typeof chat !== "string" || chat === "") throw new Error(`A dev server must be started for a chat, got ${JSON.stringify(chat)}.`);
202
+ return this.serial(key, async () => {
203
+ if (!this.started) throw new BridgeError("internal", "Dev servers were used before main started them.");
204
+ await this.started;
205
+ const t0 = Date.now();
206
+ const current = this.entries.get(key);
207
+ if (current && current.status === "ready" && sameSpec(current.spec, spec)) {
208
+ if (!current.chats.includes(chat)) {
209
+ current.chats.push(chat);
210
+ this.deps.onChange();
211
+ }
212
+ return { server: this.stateOf(current), reused: true, ms: Date.now() - t0 };
213
+ }
214
+ if (current && this.running(current)) await this.halt(current);
215
+ await this.checkPort(key, spec);
216
+ const entry = this.spawn(key, spec, chat, searchPath);
217
+ try {
218
+ await this.recordLedger();
219
+ await this.untilReady(entry);
220
+ } finally {
221
+ await this.recordLedger();
222
+ }
223
+ return { server: this.stateOf(entry), reused: false, ms: Date.now() - t0 };
224
+ });
225
+ }
226
+
227
+ /** @param {string} key @param {string | null} chat The asking agent's chat, or null for the user. */
228
+ stop(key, chat = null) {
229
+ return this.serial(key, async () => {
230
+ const entry = this.require(key, chat);
231
+ if (this.running(entry)) {
232
+ await this.halt(entry);
233
+ await this.recordLedger();
234
+ }
235
+ return this.stateOf(entry);
236
+ });
237
+ }
238
+
239
+ /**
240
+ * The newest lines of one server's log, optionally only errors or lines holding `pattern`.
241
+ * @param {string} key
242
+ * @param {{ errorsOnly: boolean, pattern: string | null, limit: number }} q
243
+ * @param {string | null} chat The asking agent's chat, or null for the user.
244
+ */
245
+ logs(key, { errorsOnly, pattern, limit }, chat = null) {
246
+ const entry = this.require(key, chat);
247
+ const all = readLines(entry.logFile);
248
+ const needle = pattern ? pattern.toLowerCase() : null;
249
+ const hits = all.filter((l) => (!errorsOnly || ERROR_LINE.test(l)) && (!needle || l.toLowerCase().includes(needle)));
250
+ return { server: this.stateOf(entry), lines: hits.slice(-limit), matched: hits.length, total: all.length };
251
+ }
252
+
253
+ /**
254
+ * The chat was deleted: stop the servers no other chat uses and drop
255
+ * them from the list, after any start already under way finishes.
256
+ * @param {string} chat
257
+ */
258
+ async forgetChat(chat) {
259
+ await Promise.allSettled([...this.queues.values()]);
260
+ const used = [...this.entries.values()].filter((e) => e.chats.includes(chat));
261
+ await Promise.all(
262
+ used.map((e) =>
263
+ this.serial(e.key, async () => {
264
+ e.chats = e.chats.filter((c) => c !== chat);
265
+ if (e.chats.length > 0) return;
266
+ if (this.running(e)) await this.halt(e);
267
+ if (this.entries.get(e.key) === e) this.entries.delete(e.key);
268
+ })
269
+ )
270
+ );
271
+ await this.recordLedger();
272
+ this.deps.onChange();
273
+ }
274
+
275
+ /** Quit: stop every server, then forget the ones that are gone. */
276
+ async stopAll() {
277
+ await Promise.all([...this.entries.values()].filter((e) => this.running(e)).map((e) => this.halt(e)));
278
+ await this.recordLedger();
279
+ }
280
+
281
+ // ── Orphans ───────────────────────────────────────────────────────────
282
+
283
+ /** Stop every recorded pid whose command line still matches; leave everything else alone. */
284
+ async reapOrphans() {
285
+ let ledger;
286
+ try {
287
+ ledger = JSON.parse(fs.readFileSync(this.ledgerPath, "utf8"));
288
+ } catch (err) {
289
+ if (err.code === "ENOENT") return { reaped: [] };
290
+ throw new Error(`${this.ledgerPath} is unreadable (${err.message})`);
291
+ }
292
+ const recorded = (ledger.servers || []).flatMap((s) => s.processes || []);
293
+ const matching = (table) => {
294
+ const live = new Map(table.map((r) => [r.pid, r.command]));
295
+ return recorded.filter((p) => p.pid !== process.pid && live.get(p.pid) === p.command);
296
+ };
297
+ const signal = (procs, sig) => {
298
+ for (const p of procs) {
299
+ try {
300
+ process.kill(p.pid, sig);
301
+ } catch (err) {
302
+ if (err.code !== "ESRCH") this.deps.logger.error(`[dev-servers] ${sig} to orphan ${p.pid} failed: ${err.message}`);
303
+ }
304
+ }
305
+ };
306
+ const orphans = matching(await this.deps.listProcesses());
307
+ if (orphans.length) {
308
+ this.deps.logger.log(`[dev-servers] Stopping ${orphans.length} dev server process(es) left by an earlier run: ${orphans.map((p) => p.pid).join(", ")}`);
309
+ signal(orphans, "SIGTERM");
310
+ const deadline = Date.now() + this.deps.reapGraceMs;
311
+ let left = orphans;
312
+ while (left.length && Date.now() < deadline) {
313
+ await new Promise((r) => setTimeout(r, 100));
314
+ left = matching(await this.deps.listProcesses()).filter((p) => orphans.includes(p));
315
+ }
316
+ signal(left, "SIGKILL");
317
+ }
318
+ fs.rmSync(this.ledgerPath, { force: true });
319
+ return { reaped: orphans.map((p) => p.pid) };
320
+ }
321
+
322
+ /** Write every live server's pids and command lines, read back from the process table. */
323
+ async recordLedger() {
324
+ const live = [...this.entries.values()].filter((e) => this.running(e));
325
+ if (live.length === 0) {
326
+ fs.rmSync(this.ledgerPath, { force: true });
327
+ return;
328
+ }
329
+ const table = await this.deps.listProcesses();
330
+ const byPid = new Map(table.map((r) => [r.pid, r]));
331
+ const servers = live.map((e) => {
332
+ const root = byPid.get(e.child.pid);
333
+ const processes = root ? [{ pid: root.pid, command: root.command }, ...descendantsFromTable(table, root.pid).descendants] : [];
334
+ return { key: e.key, name: e.spec.name, processes };
335
+ });
336
+ fs.mkdirSync(path.dirname(this.ledgerPath), { recursive: true });
337
+ const tmp = `${this.ledgerPath}.tmp`;
338
+ fs.writeFileSync(tmp, JSON.stringify({ appPid: process.pid, servers }));
339
+ fs.renameSync(tmp, this.ledgerPath);
340
+ }
341
+
342
+ // ── Internals ─────────────────────────────────────────────────────────
343
+
344
+ serial(key, fn) {
345
+ const before = this.queues.get(key) || Promise.resolve();
346
+ const run = before.catch(() => {}).then(fn);
347
+ this.queues.set(key, run);
348
+ return run.finally(() => {
349
+ if (this.queues.get(key) === run) this.queues.delete(key);
350
+ });
351
+ }
352
+
353
+ /** Another chat's server is "not started" to an agent, never a hint that it exists. */
354
+ require(key, chat = null) {
355
+ const entry = this.entries.get(key);
356
+ if (!entry || (chat !== null && !entry.chats.includes(chat))) throw new BridgeError("no_such_server", "GAIA has not started that dev server. Call browser-pane/dev_server(action=\"list\") to see the ones it has.");
357
+ return entry;
358
+ }
359
+
360
+ running(entry) {
361
+ return entry.status === "starting" || entry.status === "ready";
362
+ }
363
+
364
+ async checkPort(key, spec) {
365
+ if (this.deps.blockedPorts().includes(spec.port)) {
366
+ throw new BridgeError("port_in_use", `Port ${spec.port} is GAIA's own. Pick another "port" in launch.json.`);
367
+ }
368
+ if (!(await portAnswers(spec.port))) return;
369
+ const other = [...this.entries.values()].find((e) => e.key !== key && this.running(e) && e.spec.port === spec.port);
370
+ const who = other ? `GAIA's dev server "${other.spec.name}" already uses it; stop that one first` : "another program is already listening there; stop it, or pick another \"port\" in launch.json";
371
+ throw new BridgeError("port_in_use", `Port ${spec.port} is taken: ${who}.`, { port: spec.port });
372
+ }
373
+
374
+ spawn(key, spec, chat, searchPath = null) {
375
+ const log = new CappedLog(path.join(this.deps.dir, `${key}.log`));
376
+ log.write(`[GAIA] ${new Date().toISOString()} starting: ${spec.argv.join(" ")} (in ${spec.cwd})\n`);
377
+ const entry = {
378
+ key,
379
+ spec,
380
+ chats: [chat],
381
+ log,
382
+ logFile: log.file,
383
+ status: "starting",
384
+ startedAt: Date.now(),
385
+ exitCode: null,
386
+ halting: false,
387
+ spawnError: null,
388
+ child: null,
389
+ };
390
+ this.entries.set(key, entry);
391
+ const child = this.deps.spawn(spec.argv[0], spec.argv.slice(1), {
392
+ cwd: spec.cwd,
393
+ env: childEnv(spec, this.deps.env, searchPath),
394
+ shell: false,
395
+ stdio: ["ignore", "pipe", "pipe"],
396
+ windowsHide: true,
397
+ });
398
+ entry.child = child;
399
+ child.stdout.on("data", (c) => log.write(c));
400
+ child.stderr.on("data", (c) => log.write(c));
401
+ child.once("error", (err) => {
402
+ entry.spawnError = err;
403
+ log.write(`[GAIA] could not start ${spec.argv[0]}: ${err.message}\n`);
404
+ });
405
+ child.once("close", (code, sig) => {
406
+ entry.exitCode = code === null ? null : code;
407
+ log.write(`[GAIA] exited ${code === null ? `on ${sig}` : `with code ${code}`}\n`);
408
+ log.close();
409
+ entry.status = entry.halting ? "stopped" : entry.status === "starting" ? "failed" : "exited";
410
+ this.deps.onChange();
411
+ if (!entry.halting) {
412
+ this.recordLedger().catch((err) => this.deps.logger.error(`[dev-servers] Ledger update failed: ${err.message}`));
413
+ }
414
+ });
415
+ this.deps.onChange();
416
+ return entry;
417
+ }
418
+
419
+ async untilReady(entry) {
420
+ const deadline = entry.startedAt + entry.spec.readyTimeoutMs;
421
+ for (;;) {
422
+ if (entry.status !== "starting") throw this.failed(entry, "exited before it answered");
423
+ if (await portAnswers(entry.spec.port)) break;
424
+ if (Date.now() > deadline) {
425
+ await this.halt(entry);
426
+ throw this.failed(entry, `did not answer within ${Math.round(entry.spec.readyTimeoutMs / 1000)} s, so GAIA stopped it`);
427
+ }
428
+ await new Promise((r) => setTimeout(r, PROBE_EVERY_MS));
429
+ }
430
+ entry.status = "ready";
431
+ this.deps.onChange();
432
+ }
433
+
434
+ failed(entry, what) {
435
+ const { spec } = entry;
436
+ const lines = readLines(entry.logFile).slice(-FAIL_LINES);
437
+ const code = entry.exitCode === null ? "" : ` (exit code ${entry.exitCode})`;
438
+ const cause = entry.spawnError ? ` Could not start ${spec.argv[0]}: ${entry.spawnError.message}.` : "";
439
+ return new BridgeError(
440
+ "dev_server_failed",
441
+ `Dev server "${spec.name}" (${spec.argv.join(" ")}) ${what} on port ${spec.port}${code}.${cause} Its last log lines:\n${lines.join("\n")}`,
442
+ { exitCode: entry.exitCode, lines }
443
+ );
444
+ }
445
+
446
+ async halt(entry) {
447
+ entry.halting = true;
448
+ const closed = new Promise((resolve) => {
449
+ if (entry.child.exitCode !== null || entry.child.signalCode !== null) resolve();
450
+ else entry.child.once("close", resolve);
451
+ });
452
+ await this.deps.killTree(entry.child, { label: `dev server "${entry.spec.name}"`, log: this.deps.logger.log, logError: this.deps.logger.error });
453
+ await closed;
454
+ entry.status = "stopped";
455
+ this.deps.onChange();
456
+ }
457
+
458
+ /** @returns {DevServerState} */
459
+ stateOf(e) {
460
+ return {
461
+ key: e.key,
462
+ name: e.spec.name,
463
+ argv: e.spec.argv.slice(),
464
+ cwd: e.spec.cwd,
465
+ port: e.spec.port,
466
+ env: { ...e.spec.env },
467
+ url: e.spec.url,
468
+ status: e.status,
469
+ pid: e.child && this.running(e) ? e.child.pid : null,
470
+ startedAt: e.startedAt,
471
+ exitCode: e.exitCode,
472
+ logFile: e.logFile,
473
+ chats: e.chats.slice(),
474
+ };
475
+ }
476
+ }
477
+
478
+ module.exports = { DevServerSupervisor, ENV_NAMES, ENV_PREFIXES, INHERITED_ENV, LOG_CAP_BYTES, CappedLog, childEnv, envNameAllowed, portAnswers };