@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.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 (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-BNEOn-cl.mjs} +15 -6
  4. package/dist/build-skills-BNEOn-cl.mjs.map +1 -0
  5. package/dist/dist--xzirmg-.mjs +655 -0
  6. package/dist/dist--xzirmg-.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-BDnj7kqd.mjs +1922 -0
  23. package/dist/powerhouse-BDnj7kqd.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-BQzq4yfO.mjs +69 -0
  27. package/dist/remote-reactor-BQzq4yfO.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-BehwgLP6.mjs} +395 -1481
  45. package/dist/src-BehwgLP6.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -0,0 +1,1588 @@
1
+ import { n as slugToTitle, t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import crypto from "node:crypto";
6
+ import os from "node:os";
7
+ import { execSync, spawn } from "node:child_process";
8
+ import { killTree } from "@powerhousedao/host-core/kill-tree";
9
+ import net from "node:net";
10
+ import { Marked } from "marked";
11
+ import { markedTerminal } from "marked-terminal";
12
+ import { supportsLanguage } from "cli-highlight";
13
+ //#region src/core/stream.ts
14
+ const DIM = "\x1B[2m";
15
+ const RESET = "\x1B[0m";
16
+ const RED = "\x1B[31m";
17
+ const GREEN_DIM = "\x1B[32;2m";
18
+ /**
19
+ * Format a single StreamChunk into a display string.
20
+ *
21
+ * This is the framework-level formatter. The Mastra integration maps
22
+ * Mastra's fullStream chunks to StreamChunk first, then this renders them.
23
+ *
24
+ * Tool activity is styled with dim green (calls/results) and red (errors)
25
+ * so it's visually distinct from the agent's text output.
26
+ */
27
+ function formatStreamChunk(chunk) {
28
+ switch (chunk.type) {
29
+ case "text-delta": return chunk.text;
30
+ case "tool-call": return `\n${DIM}${GREEN_DIM}▶ ${chunk.toolName}${RESET}${DIM}(${truncateArgs(chunk.args)})${RESET}\n`;
31
+ case "tool-result":
32
+ if (chunk.isError) return `${RED}✗ ${chunk.toolName} error: ${formatResult(chunk.result)}${RESET}\n`;
33
+ const body = hasTextField(chunk.result) ? chunk.result.text : typeof chunk.result === "string" ? chunk.result : null;
34
+ if (body && body.length > 0) return `${DIM}${GREEN_DIM}✓ ${chunk.toolName}${RESET}\n${body}\n`;
35
+ return `${DIM}${GREEN_DIM}✓ ${chunk.toolName}${RESET}${DIM} → ${truncateResult(chunk.result)}${RESET}\n`;
36
+ case "tool-output": return chunk.text;
37
+ case "error": return `${RED}Error: ${chunk.error}${RESET}\n`;
38
+ case "step-finish":
39
+ case "finish": return "";
40
+ }
41
+ }
42
+ /**
43
+ * Consume a stream of StreamChunks and yield { chunk, formatted } pairs.
44
+ *
45
+ * Inserts an extra newline before the first text-delta after tool activity,
46
+ * so the agent's prose is visually separated from tool call/result lines.
47
+ */
48
+ async function* renderStream(stream) {
49
+ let lastChunkWasText = false;
50
+ for await (const chunk of stream) {
51
+ let prefix = "";
52
+ if (chunk.type === "text-delta") {
53
+ if (!lastChunkWasText) {
54
+ prefix = "\n";
55
+ lastChunkWasText = true;
56
+ }
57
+ } else lastChunkWasText = false;
58
+ yield {
59
+ chunk,
60
+ formatted: prefix + formatStreamChunk(chunk)
61
+ };
62
+ }
63
+ }
64
+ function truncateArgs(args) {
65
+ const json = JSON.stringify(args);
66
+ return json.length > 120 ? json.slice(0, 120) + "…" : json;
67
+ }
68
+ function truncateResult(result) {
69
+ const str = formatResult(result);
70
+ return str.length > 200 ? str.slice(0, 200) + "…" : str;
71
+ }
72
+ function formatResult(result) {
73
+ if (result === void 0 || result === null) return "ok";
74
+ if (typeof result === "string") return result;
75
+ return JSON.stringify(result);
76
+ }
77
+ function hasTextField(result) {
78
+ return typeof result === "object" && result !== null && "text" in result && typeof result.text === "string";
79
+ }
80
+ //#endregion
81
+ //#region src/core/process-platform.ts
82
+ /**
83
+ * Supervised children are ATTACHED: no process clint starts may outlive the
84
+ * process that started it. They are spawned without `detached` on every
85
+ * platform (hidden on Windows, where `detached` would also force a console
86
+ * per child), and every one is registered with {@link superviseChild}, which
87
+ * fells the ones still alive when this process ends.
88
+ *
89
+ * Attached children share this process's group on POSIX, so there is no
90
+ * group of their own to signal: {@link killTree} (host-core's, which a
91
+ * compound's own-process members are killed with too) walks the process
92
+ * table instead. On Windows it uses `taskkill /T /F`.
93
+ */
94
+ const isWindows = process.platform === "win32";
95
+ /** Spawn options fragment for a supervised child. */
96
+ function supervisedSpawnOptions() {
97
+ return {
98
+ detached: false,
99
+ windowsHide: true
100
+ };
101
+ }
102
+ /** Supervised children still running. */
103
+ const liveChildren = /* @__PURE__ */ new Set();
104
+ /** Signals whose default action ends this process. */
105
+ const ENDING_SIGNALS = isWindows ? [
106
+ "SIGINT",
107
+ "SIGTERM",
108
+ "SIGHUP",
109
+ "SIGBREAK"
110
+ ] : [
111
+ "SIGINT",
112
+ "SIGTERM",
113
+ "SIGHUP"
114
+ ];
115
+ /** Forcefully fell every supervised child still running (synchronous, so it
116
+ * also works from an `exit` listener). */
117
+ function fellLiveChildren() {
118
+ for (const child of liveChildren) if (child.pid !== void 0 && child.exitCode === null && child.signalCode === null) killTree(child.pid, "SIGKILL");
119
+ liveChildren.clear();
120
+ }
121
+ /**
122
+ * The signal listeners signal-exit (Ink's dependency) installs, one per
123
+ * loaded copy, read from the counts its copies share. Each acts only when
124
+ * signal-exit's listeners are the only ones left, so counted as application
125
+ * handlers they and the guard below would each wait for the other. (The
126
+ * same count as ph-cli's package-build/run-build.ts.)
127
+ */
128
+ function exitOnlyListeners() {
129
+ const count = (emitter) => {
130
+ const value = emitter?.count;
131
+ return typeof value === "number" ? value : 0;
132
+ };
133
+ const shared = globalThis;
134
+ const legacy = process;
135
+ return count(shared[Symbol.for("signal-exit emitter")]) + count(legacy.__signal_exit_emitter__);
136
+ }
137
+ /**
138
+ * A signal whose default action would end this process. An application
139
+ * listener (the CLI's own shutdown, which stops services gracefully) owns
140
+ * the signal: the guard leaves it alone and the `exit` listener backs it up.
141
+ * With no such listener the process would simply die and leave its children
142
+ * running, so the guard does what the default would, children first.
143
+ */
144
+ function onEndingSignal(signal) {
145
+ if (process.listenerCount(signal) - 1 - exitOnlyListeners() > 0) return;
146
+ fellLiveChildren();
147
+ const signals = os.constants.signals;
148
+ process.exit(128 + (signals[signal] ?? 0));
149
+ }
150
+ let guarded = false;
151
+ function installGuard() {
152
+ if (guarded) return;
153
+ guarded = true;
154
+ process.on("exit", fellLiveChildren);
155
+ for (const signal of ENDING_SIGNALS) process.on(signal, onEndingSignal);
156
+ }
157
+ function removeGuard() {
158
+ if (!guarded) return;
159
+ guarded = false;
160
+ process.removeListener("exit", fellLiveChildren);
161
+ for (const signal of ENDING_SIGNALS) process.removeListener(signal, onEndingSignal);
162
+ }
163
+ /**
164
+ * Register a spawned child so it cannot outlive this process: when the
165
+ * process exits (normally, through `process.exit`, or on an uncaught error)
166
+ * or is ended by a signal nobody handles, the child's tree is killed. The
167
+ * listeners exist only while a supervised child is running. Graceful stops
168
+ * are the owner's job (the services manager's `stopAll`); this is the last
169
+ * line, and it kills hard. A process killed outright (SIGKILL, Task Manager)
170
+ * runs no code at all, so its children cannot be reached.
171
+ */
172
+ function superviseChild(child) {
173
+ if (child.pid === void 0) return;
174
+ installGuard();
175
+ liveChildren.add(child);
176
+ child.once("exit", () => {
177
+ if (!liveChildren.delete(child)) return;
178
+ if (liveChildren.size === 0) removeGuard();
179
+ });
180
+ }
181
+ //#endregion
182
+ //#region src/core/preflight.ts
183
+ /**
184
+ * Check if a TCP port is free by attempting to bind to it.
185
+ */
186
+ function isPortFree(port) {
187
+ return new Promise((resolve) => {
188
+ const server = net.createServer();
189
+ server.once("error", () => resolve(false));
190
+ server.once("listening", () => {
191
+ server.close(() => resolve(true));
192
+ });
193
+ server.listen(port, "127.0.0.1");
194
+ });
195
+ }
196
+ /**
197
+ * Check that the working directory satisfies a condition.
198
+ *
199
+ * @param test A function that receives the cwd and returns true if valid.
200
+ * @param message Error message on failure.
201
+ * @param hint Optional guidance.
202
+ */
203
+ function checkWorkdir(test, message, hint) {
204
+ return (ctx) => {
205
+ if (test(ctx.cwd)) return { ok: true };
206
+ return {
207
+ ok: false,
208
+ message: `${message} (cwd: ${ctx.cwd})`,
209
+ hint
210
+ };
211
+ };
212
+ }
213
+ /**
214
+ * Check that a command is available on PATH, optionally matching a version.
215
+ *
216
+ * @param binary Binary name (e.g. 'ph', 'node', 'pnpm').
217
+ * @param options Optional version flag, version predicate, and hint.
218
+ */
219
+ function checkCommand(binary, options) {
220
+ return (ctx) => {
221
+ try {
222
+ const output = execSync(`${binary} ${options?.versionFlag ?? "--version"}`, {
223
+ cwd: ctx.cwd,
224
+ timeout: 5e3,
225
+ stdio: [
226
+ "ignore",
227
+ "pipe",
228
+ "pipe"
229
+ ],
230
+ env: { ...process.env }
231
+ }).toString().trim();
232
+ if (options?.versionTest && !options.versionTest(output)) return {
233
+ ok: false,
234
+ message: `${binary} version mismatch: ${output}`,
235
+ hint: options.hint
236
+ };
237
+ return { ok: true };
238
+ } catch {
239
+ return {
240
+ ok: false,
241
+ message: `'${binary}' not found`,
242
+ hint: options?.hint ?? `Install ${binary} or check your PATH`
243
+ };
244
+ }
245
+ };
246
+ }
247
+ /**
248
+ * Check that a TCP port is available.
249
+ *
250
+ * @param port Port number, or a function that extracts it from the preflight context.
251
+ * @param label Human-readable name for the port (e.g. 'Connect Studio').
252
+ */
253
+ function checkPort(port, label) {
254
+ return async (ctx) => {
255
+ const p = typeof port === "function" ? port(ctx) : port;
256
+ if (p === void 0) return { ok: true };
257
+ if (await isPortFree(p)) return { ok: true };
258
+ return {
259
+ ok: false,
260
+ message: `${label ? `${label} port` : "Port"} ${p} is already in use`,
261
+ hint: `Stop the process using port ${p}, or use a different port`
262
+ };
263
+ };
264
+ }
265
+ //#endregion
266
+ //#region src/core/project-scanner.ts
267
+ /**
268
+ * Common project indicator files/dirs. When any of these exist in a folder
269
+ * that isn't matched by the scanner, the folder is treated as a foreign
270
+ * project and its subtree is pruned from the search.
271
+ */
272
+ const PROJECT_INDICATORS = [
273
+ ".git",
274
+ "package.json",
275
+ "node_modules",
276
+ "pyproject.toml",
277
+ "setup.py",
278
+ "Cargo.toml",
279
+ "go.mod",
280
+ "pom.xml",
281
+ "build.gradle",
282
+ "build.gradle.kts",
283
+ ".sln",
284
+ "Gemfile",
285
+ "composer.json"
286
+ ];
287
+ function detectType(folderPath, scanner) {
288
+ if (scanner.isProjectFolder(folderPath)) return "match";
289
+ for (const indicator of PROJECT_INDICATORS) if (fs.existsSync(path.join(folderPath, indicator))) return "mismatch";
290
+ return "non-project";
291
+ }
292
+ function enqueueSubdirs(dir, queue) {
293
+ let entries;
294
+ try {
295
+ entries = fs.readdirSync(dir, { withFileTypes: true });
296
+ } catch {
297
+ return;
298
+ }
299
+ for (const entry of entries) if (entry.isDirectory() && !entry.name.startsWith(".")) queue.push(path.join(dir, entry.name));
300
+ }
301
+ /**
302
+ * Breadth-first search for project folders starting from `rootDir`.
303
+ *
304
+ * - If root itself matches, returns it immediately.
305
+ * - Otherwise searches subfolders breadth-first:
306
+ * - Match → added to results, subtree pruned
307
+ * - Mismatch (foreign project) → subtree pruned
308
+ * - Non-project → subfolders enqueued for further search
309
+ *
310
+ * Uses `scanner.getProjectName` for the result name (default: `path.basename`),
311
+ * and `scanner.getProjectConfig` when provided.
312
+ */
313
+ function scanProjects(rootDir, scanner) {
314
+ const getName = (p) => scanner.getProjectName ? scanner.getProjectName(p) : path.basename(p);
315
+ const getConfig = (p) => scanner.getProjectConfig ? scanner.getProjectConfig(p) : void 0;
316
+ function toResult(folderPath) {
317
+ const result = {
318
+ name: getName(folderPath),
319
+ path: folderPath,
320
+ config: getConfig(folderPath)
321
+ };
322
+ if (scanner.getDocumentLink) {
323
+ const link = scanner.getDocumentLink(folderPath);
324
+ if (link) {
325
+ result.documentId = link.documentId;
326
+ result.documentType = link.documentType;
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+ if (detectType(rootDir, scanner) === "match") return [toResult(rootDir)];
332
+ const results = [];
333
+ const queue = [];
334
+ enqueueSubdirs(rootDir, queue);
335
+ while (queue.length > 0) {
336
+ const dir = queue.shift();
337
+ switch (detectType(dir, scanner)) {
338
+ case "match":
339
+ results.push(toResult(dir));
340
+ break;
341
+ case "mismatch": break;
342
+ case "non-project": enqueueSubdirs(dir, queue);
343
+ }
344
+ }
345
+ return results;
346
+ }
347
+ //#endregion
348
+ //#region src/core/services.ts
349
+ /**
350
+ * Resolve the display name for a service definition.
351
+ * Uses `def.name` if provided, otherwise auto-generates from `def.id`.
352
+ */
353
+ function resolveServiceName(def) {
354
+ return def.name ?? slugToTitle(def.id);
355
+ }
356
+ /**
357
+ * Identity wrapper for service definitions — provides type checking and IDE support.
358
+ */
359
+ function defineService(opts) {
360
+ return opts;
361
+ }
362
+ /**
363
+ * Get the directory for a service's instance state files.
364
+ */
365
+ function serviceDir(servicesDir, serviceId) {
366
+ return path.join(servicesDir, serviceId);
367
+ }
368
+ /**
369
+ * NOTE(port): instance ids are `{serviceId}:{name|hash}` — and a COLON in a
370
+ * filename is not a filename on NTFS: it silently writes an Alternate Data
371
+ * Stream (invisible to readdir), so state files vanished on Windows. Encode
372
+ * ids for FILENAMES only; the logical id (parsed on ':' elsewhere, stored
373
+ * inside the state JSON) is untouched.
374
+ */
375
+ function fileSafeId(instanceId) {
376
+ return instanceId.replace(/[<>:"/\\|?*]/g, "+");
377
+ }
378
+ function stateFilePath(servicesDir, serviceId, instanceId) {
379
+ return path.join(serviceDir(servicesDir, serviceId), `${fileSafeId(instanceId)}.json`);
380
+ }
381
+ /** Base (run-less) log name, kept as a final fallback for older state. */
382
+ function logFilePath(servicesDir, serviceId, instanceId) {
383
+ return path.join(serviceDir(servicesDir, serviceId), `${fileSafeId(instanceId)}.log`);
384
+ }
385
+ /** Number of per-run log files kept per instance. */
386
+ const MAX_RUN_LOGS = 5;
387
+ /** Match a per-run log file for an instance: `<fileSafeId>.<runId>.log`. */
388
+ function runLogPattern(instanceId) {
389
+ const safe = fileSafeId(instanceId);
390
+ return new RegExp(`^${safe.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.(\\d+)\\.log$`);
391
+ }
392
+ /** Allocate a fresh per-run log file name for an instance, unique within the dir. */
393
+ function newRunLogFile(servicesDir, serviceId, instanceId) {
394
+ const dir = serviceDir(servicesDir, serviceId);
395
+ const safe = fileSafeId(instanceId);
396
+ let runId = Date.now();
397
+ let name = `${safe}.${runId}.log`;
398
+ while (fs.existsSync(path.join(dir, name))) {
399
+ runId += 1;
400
+ name = `${safe}.${runId}.log`;
401
+ }
402
+ return name;
403
+ }
404
+ /** List an instance's per-run log files, newest first by runId. */
405
+ function listRunLogs(servicesDir, serviceId, instanceId) {
406
+ const dir = serviceDir(servicesDir, serviceId);
407
+ const re = runLogPattern(instanceId);
408
+ try {
409
+ return fs.readdirSync(dir).filter((f) => re.test(f)).sort((a, b) => Number(re.exec(b)[1]) - Number(re.exec(a)[1]));
410
+ } catch {
411
+ return [];
412
+ }
413
+ }
414
+ /**
415
+ * Resolve the active log path for an instance: the run recorded in the state
416
+ * file, else the newest per-run log, else the base log name.
417
+ */
418
+ function activeLogPath(servicesDir, serviceId, instanceId) {
419
+ const dir = serviceDir(servicesDir, serviceId);
420
+ const state = readStateFile(stateFilePath(servicesDir, serviceId, instanceId));
421
+ if (state?.logFile && fs.existsSync(path.join(dir, state.logFile))) return path.join(dir, state.logFile);
422
+ const runs = listRunLogs(servicesDir, serviceId, instanceId);
423
+ if (runs.length > 0) return path.join(dir, runs[0]);
424
+ return logFilePath(servicesDir, serviceId, instanceId);
425
+ }
426
+ /** Keep only the newest `MAX_RUN_LOGS` per-run logs for an instance. */
427
+ function pruneRunLogs(servicesDir, serviceId, instanceId) {
428
+ const dir = serviceDir(servicesDir, serviceId);
429
+ const runs = listRunLogs(servicesDir, serviceId, instanceId);
430
+ for (const f of runs.slice(MAX_RUN_LOGS)) try {
431
+ fs.unlinkSync(path.join(dir, f));
432
+ } catch {}
433
+ }
434
+ const MAX_LINE_CHARS = 2e3;
435
+ const MAX_TOTAL_CHARS = 16e3;
436
+ /**
437
+ * Strip NUL bytes and non-printable control chars (keeping \n and \t), then
438
+ * cap each line and the total length. Keeps the tail when over the total cap,
439
+ * since recent log lines matter most. Guards against truncate-while-open gaps
440
+ * that fill the file with NUL runs containing no newlines.
441
+ */
442
+ function sanitizeLogText(text, maxTotal = MAX_TOTAL_CHARS) {
443
+ let out = text.replace(/[\x00-\x08\x0B-\x1F\x7F]/g, "").split("\n").map((line) => {
444
+ if (line.length <= MAX_LINE_CHARS) return line;
445
+ const dropped = line.length - MAX_LINE_CHARS;
446
+ return line.slice(0, MAX_LINE_CHARS) + `…[truncated ${dropped} chars]`;
447
+ }).join("\n");
448
+ if (out.length > maxTotal) out = `…[truncated ${out.length - maxTotal} chars]\n` + out.slice(out.length - maxTotal);
449
+ return out;
450
+ }
451
+ /**
452
+ * Watch a log file for the lines appended from now on. Returns the function
453
+ * that stops watching.
454
+ */
455
+ function watchLogFile(logPath, onLine) {
456
+ let lastPos = 0;
457
+ try {
458
+ lastPos = fs.statSync(logPath).size;
459
+ } catch {}
460
+ let watcher;
461
+ try {
462
+ watcher = fs.watch(logPath, () => {
463
+ try {
464
+ const buf = fs.readFileSync(logPath);
465
+ if (buf.length < lastPos) lastPos = 0;
466
+ const newContent = buf.toString("utf-8", lastPos);
467
+ lastPos = buf.length;
468
+ if (newContent) {
469
+ const lines = newContent.split("\n").filter((l) => l.length > 0);
470
+ for (const line of lines) onLine(line);
471
+ }
472
+ } catch {}
473
+ });
474
+ } catch {
475
+ onLine("Log file not found");
476
+ return () => {};
477
+ }
478
+ return () => {
479
+ watcher.close();
480
+ };
481
+ }
482
+ /**
483
+ * Read the last N lines from a log file, returning an empty string if unavailable.
484
+ */
485
+ function tailLogFile(filePath, lines = 20) {
486
+ try {
487
+ return sanitizeLogText(fs.readFileSync(filePath, "utf-8")).split("\n").filter((l) => l.length > 0).slice(-lines).join("\n");
488
+ } catch {
489
+ return "";
490
+ }
491
+ }
492
+ function readStateFile(filePath) {
493
+ try {
494
+ const raw = fs.readFileSync(filePath, "utf-8");
495
+ return JSON.parse(raw);
496
+ } catch {
497
+ return null;
498
+ }
499
+ }
500
+ function writeStateFile(filePath, state) {
501
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
502
+ }
503
+ function removeStateFile(filePath) {
504
+ try {
505
+ fs.unlinkSync(filePath);
506
+ } catch {}
507
+ }
508
+ function isPidAlive(pid) {
509
+ try {
510
+ process.kill(pid, 0);
511
+ return true;
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+ /** Whether the manager that spawned a recorded instance is still running. */
517
+ function isOwnerAlive(state) {
518
+ return state.owner !== void 0 && isPidAlive(state.owner.pid);
519
+ }
520
+ /** Whether a recorded instance's process is still running. */
521
+ function isInstanceAlive(state) {
522
+ return state.pid > 0 && isPidAlive(state.pid);
523
+ }
524
+ /**
525
+ * Why a live instance this manager did not spawn is not its to manage: it
526
+ * belongs to another running process, or it is a leftover whose owner is
527
+ * gone. Either way it is never adopted, stopped or restarted from here (a
528
+ * recorded pid can also have been reused by an unrelated process).
529
+ */
530
+ function notOursMessage(state) {
531
+ const where = `${state.serviceId} (${state.instanceId}, pid ${state.pid})`;
532
+ if (state.owner && isOwnerAlive(state)) return `${where} belongs to process ${state.owner.pid}, which is still running; this process does not manage it. Stop it there.`;
533
+ return `${where} is a leftover from ${state.owner ? `process ${state.owner.pid}, which has exited` : "an earlier run"}; this process does not manage it. End pid ${state.pid} by hand if it is the old service.`;
534
+ }
535
+ /**
536
+ * Wait for a PID to exit, polling with kill(pid, 0).
537
+ * Returns true if the process exited, false on timeout.
538
+ */
539
+ function waitForExit(pid, timeout, interval = 100) {
540
+ return new Promise((resolve) => {
541
+ const deadline = Date.now() + timeout;
542
+ const check = () => {
543
+ if (!isPidAlive(pid)) {
544
+ resolve(true);
545
+ return;
546
+ }
547
+ if (Date.now() >= deadline) {
548
+ resolve(false);
549
+ return;
550
+ }
551
+ setTimeout(check, interval);
552
+ };
553
+ check();
554
+ });
555
+ }
556
+ /**
557
+ * Generate an instance ID from start options.
558
+ * - Default (no name, no workdir) → serviceId
559
+ * - Named → serviceId:name
560
+ * - Workdir-derived → serviceId:hash8
561
+ */
562
+ function resolveInstanceId(serviceId, opts) {
563
+ if (opts?.name) return `${serviceId}:${opts.name}`;
564
+ if (opts?.workdir) return `${serviceId}:${crypto.createHash("sha256").update(opts.workdir).digest("hex").slice(0, 8)}`;
565
+ return serviceId;
566
+ }
567
+ /**
568
+ * Resolve a service command — supports static string or dynamic function. A
569
+ * host service's is its `ph run` line, as the state file and preflight show
570
+ * it.
571
+ */
572
+ function resolveCommand(def, ctx) {
573
+ if (def.run) return hostCommandLine(def.run);
574
+ return typeof def.command === "function" ? def.command(ctx) : def.command;
575
+ }
576
+ /** The `ph run` a host service is. */
577
+ function hostCommandLine(run) {
578
+ return [
579
+ "ph",
580
+ "run",
581
+ run.host,
582
+ ...run.verb === void 0 ? [] : [run.verb],
583
+ ...run.argv?.length ? ["--", ...run.argv] : []
584
+ ].join(" ");
585
+ }
586
+ /** A definition with both or neither of `command` and `run` (an untyped one). */
587
+ function assertOneForm(def) {
588
+ const forms = [def.command !== void 0, def.run !== void 0];
589
+ if (forms.filter(Boolean).length !== 1) throw new Error(`Service ${def.id}: give it a command or a host run (run), not ${forms[0] ? "both" : "neither"}.`);
590
+ }
591
+ /** The failure a start reports: what went wrong, where, and the log's end. */
592
+ function startFailure(id, error, cwd, command, tail) {
593
+ const lines = [
594
+ error,
595
+ "",
596
+ ` workdir: ${cwd}`,
597
+ ` command: ${command}`
598
+ ];
599
+ if (tail) {
600
+ lines.push("", " Recent log output:");
601
+ lines.push(...tail.split("\n").map((l) => " " + l));
602
+ }
603
+ lines.push("", ` Check the workdir and run '${id}-logs' for the full log.`);
604
+ return new Error(lines.join("\n"));
605
+ }
606
+ /**
607
+ * Scan a service's instance directory for all state files.
608
+ */
609
+ function scanInstances(servicesDir, serviceId) {
610
+ const dir = serviceDir(servicesDir, serviceId);
611
+ try {
612
+ return fs.readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => readStateFile(path.join(dir, f))).filter((s) => s !== null);
613
+ } catch {
614
+ return [];
615
+ }
616
+ }
617
+ /**
618
+ * Strip the `.<runId>.log` or `.log` suffix from a log file name to get its
619
+ * instance ID. The runId is a `Date.now()` millisecond timestamp (see
620
+ * newRunLogFile), so we only treat a timestamp-width digit run (>=10) as a
621
+ * runId — otherwise a legacy `<instanceId>.log` whose instance name ends in
622
+ * `.<digits>` (e.g. `svc:agent.1`) would have that suffix wrongly stripped.
623
+ */
624
+ function instanceIdFromLogFile(name) {
625
+ return name.replace(/(?:\.\d{10,})?\.log$/, "");
626
+ }
627
+ /**
628
+ * Find the instance ID of the most recently modified .log file in a service directory.
629
+ * Used as a fallback when no .json state files exist (e.g. after stop).
630
+ */
631
+ function mostRecentLogInstance(servicesDir, serviceId) {
632
+ const dir = serviceDir(servicesDir, serviceId);
633
+ try {
634
+ const logFiles = fs.readdirSync(dir).filter((f) => f.endsWith(".log"));
635
+ if (logFiles.length === 0) return void 0;
636
+ let best;
637
+ for (const f of logFiles) {
638
+ const stat = fs.statSync(path.join(dir, f));
639
+ if (!best || stat.mtimeMs > best.mtime) best = {
640
+ name: f,
641
+ mtime: stat.mtimeMs
642
+ };
643
+ }
644
+ return best ? instanceIdFromLogFile(best.name) : void 0;
645
+ } catch {
646
+ return;
647
+ }
648
+ }
649
+ /**
650
+ * Create a ServiceManager for long-running services. Every instance is a
651
+ * child of this process: spawned attached, stopped by `stopAll()` (the CLI
652
+ * runtime's teardown) and, failing that, felled when the process ends (see
653
+ * process-platform.ts). The manager reports, stops and restarts only the
654
+ * instances it spawned itself; state left by another process is never
655
+ * adopted (see `foreignStatus`).
656
+ */
657
+ function createServiceManager(definitions, opts) {
658
+ const { config, servicesDir, eventBus } = opts;
659
+ const defMap = /* @__PURE__ */ new Map();
660
+ for (const def of definitions) defMap.set(def.id, def);
661
+ /** This manager's identity in the state files it writes. */
662
+ const owner = {
663
+ pid: process.pid,
664
+ token: crypto.randomUUID()
665
+ };
666
+ const isMine = (state) => state.owner?.token === owner.token;
667
+ /** Set while `stopAll()` runs: no start or restart may begin. */
668
+ let closing = false;
669
+ /** State paths of instances being stopped: never restarted meanwhile. */
670
+ const stopping = /* @__PURE__ */ new Set();
671
+ /** Pending restart-policy timers, cancelled by `stopAll()`. */
672
+ const restartTimers = /* @__PURE__ */ new Set();
673
+ /** Host services' runs by state path, from ready until they exit. */
674
+ const hostRuns = /* @__PURE__ */ new Map();
675
+ /** Host services waiting for their run record, by state path: a stop
676
+ * aborts the wait and awaits `settled`. */
677
+ const hostStarts = /* @__PURE__ */ new Map();
678
+ /**
679
+ * The status of a recorded instance this manager did not spawn. One whose
680
+ * process is gone reads as stopped (and, when its owner is gone too, the
681
+ * stale state is settled as stopped on disk); one still alive reads as
682
+ * failed with the reason, so it never counts as running here.
683
+ */
684
+ function foreignStatus(def, state) {
685
+ if (!isInstanceAlive(state)) {
686
+ if (!isOwnerAlive(state)) {
687
+ state.status = "stopped";
688
+ state.pid = 0;
689
+ state.stoppedAt ??= (/* @__PURE__ */ new Date()).toISOString();
690
+ writeStateFile(stateFilePath(servicesDir, def.id, state.instanceId), state);
691
+ }
692
+ return {
693
+ serviceId: def.id,
694
+ instanceId: state.instanceId,
695
+ name: state.name,
696
+ status: "stopped",
697
+ workdir: state.workdir,
698
+ params: state.params
699
+ };
700
+ }
701
+ return {
702
+ serviceId: def.id,
703
+ instanceId: state.instanceId,
704
+ name: resolveServiceName(def),
705
+ status: "failed",
706
+ pid: state.pid,
707
+ error: notOursMessage(state),
708
+ workdir: state.workdir,
709
+ params: state.params
710
+ };
711
+ }
712
+ function ensureServiceDir(serviceId) {
713
+ fs.mkdirSync(serviceDir(servicesDir, serviceId), { recursive: true });
714
+ }
715
+ function buildContext(params) {
716
+ return {
717
+ params,
718
+ config
719
+ };
720
+ }
721
+ async function start(id, startOpts) {
722
+ const def = defMap.get(id);
723
+ if (!def) throw new Error(`Unknown service: ${id}`);
724
+ assertOneForm(def);
725
+ const instanceId = resolveInstanceId(id, startOpts);
726
+ const maxInstances = def.maxInstances ?? 1;
727
+ if (hostStarts.has(stateFilePath(servicesDir, id, instanceId))) throw new Error(`Service ${id} is already starting`);
728
+ const existingState = readStateFile(stateFilePath(servicesDir, id, instanceId));
729
+ if (existingState && existingState.status === "stopped") removeStateFile(stateFilePath(servicesDir, id, instanceId));
730
+ else if (existingState && isInstanceAlive(existingState)) {
731
+ if (!isMine(existingState)) throw new Error(`Service ${id}: ${notOursMessage(existingState)}`);
732
+ if (existingState.status === "ready" || existingState.status === "starting") throw new Error(`Service ${id} is already running (pid ${existingState.pid})`);
733
+ }
734
+ if (scanInstances(servicesDir, id).filter((s) => s.instanceId !== instanceId && s.status !== "stopped" && isMine(s) && (isInstanceAlive(s) || hostStarts.has(stateFilePath(servicesDir, id, s.instanceId)))).length >= maxInstances) throw new Error(`Service ${id} has reached max instances (${maxInstances})`);
735
+ ensureServiceDir(id);
736
+ const params = startOpts?.params;
737
+ const buildCtx = buildContext(params);
738
+ const commandStr = resolveCommand(def, buildCtx);
739
+ const spawnCwd = startOpts?.cwd ?? startOpts?.workdir;
740
+ if (def.preflight?.length) {
741
+ const preflightCtx = {
742
+ cwd: spawnCwd ?? process.cwd(),
743
+ config,
744
+ params,
745
+ command: commandStr
746
+ };
747
+ for (const check of def.preflight) {
748
+ const result = await check(preflightCtx);
749
+ if (!result.ok) {
750
+ const parts = [`${resolveServiceName(def)}: ${result.message}`];
751
+ if (result.hint) parts.push(` Hint: ${result.hint}`);
752
+ throw new Error(parts.join("\n"));
753
+ }
754
+ }
755
+ }
756
+ if (closing) throw new Error(`Service ${id}: the service manager is stopping`);
757
+ const logFile = newRunLogFile(servicesDir, id, instanceId);
758
+ const logPath = path.join(serviceDir(servicesDir, id), logFile);
759
+ const logFd = fs.openSync(logPath, "w");
760
+ pruneRunLogs(servicesDir, id, instanceId);
761
+ const inherited = { ...process.env };
762
+ delete inherited.PH_STOP_ON_STDIN;
763
+ const restartAttempt = existingState && isMine(existingState) ? existingState.restartAttempt ?? 0 : 0;
764
+ if (def.run) {
765
+ fs.closeSync(logFd);
766
+ return startHost(def, {
767
+ instanceId,
768
+ cwd: spawnCwd ?? process.cwd(),
769
+ workdir: startOpts?.workdir,
770
+ params,
771
+ command: commandStr,
772
+ logFile,
773
+ logPath,
774
+ baseEnv: inherited,
775
+ env: {
776
+ ...def.run.env,
777
+ ...def.env ? def.env(buildCtx) : {}
778
+ },
779
+ restartAttempt
780
+ });
781
+ }
782
+ const env = {
783
+ ...inherited,
784
+ ...def.env ? def.env(buildCtx) : {}
785
+ };
786
+ const child = spawn(commandStr, {
787
+ shell: true,
788
+ ...supervisedSpawnOptions(),
789
+ stdio: [
790
+ "ignore",
791
+ logFd,
792
+ logFd
793
+ ],
794
+ env,
795
+ cwd: spawnCwd
796
+ });
797
+ superviseChild(child);
798
+ child.unref();
799
+ fs.closeSync(logFd);
800
+ const pid = child.pid;
801
+ const state = {
802
+ serviceId: id,
803
+ instanceId,
804
+ name: resolveServiceName(def),
805
+ pid,
806
+ owner,
807
+ status: "starting",
808
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
809
+ command: commandStr,
810
+ restartAttempt,
811
+ workdir: startOpts?.workdir,
812
+ params,
813
+ logFile
814
+ };
815
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
816
+ /* istanbul ignore next -- defensive guard */
817
+ child.on("error", () => {
818
+ state.status = "failed";
819
+ state.error = "Failed to spawn process";
820
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
821
+ eventBus?.emit("service:failed", {
822
+ id,
823
+ instanceId,
824
+ name: resolveServiceName(def),
825
+ error: state.error
826
+ });
827
+ });
828
+ if (!def.readiness || def.readiness.wait === false) {
829
+ state.status = "ready";
830
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
831
+ eventBus?.emit("service:ready", {
832
+ id,
833
+ instanceId,
834
+ name: resolveServiceName(def),
835
+ endpoints: state.endpoints
836
+ });
837
+ return instanceId;
838
+ }
839
+ const readinessPatterns = def.readiness.patterns ? def.readiness.patterns : [{
840
+ name: "_default",
841
+ pattern: def.readiness.pattern,
842
+ captures: def.readiness.captures
843
+ }];
844
+ const { timeout } = def.readiness;
845
+ const startTime = Date.now();
846
+ let lastPos = 0;
847
+ const matched = /* @__PURE__ */ new Set();
848
+ state.endpoints = {};
849
+ state.endpointTypes = {};
850
+ await new Promise((resolve, reject) => {
851
+ const pollInterval = setInterval(() => {
852
+ if (!isPidAlive(pid)) {
853
+ clearInterval(pollInterval);
854
+ state.status = "failed";
855
+ state.error = "Process exited before becoming ready";
856
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
857
+ eventBus?.emit("service:failed", {
858
+ id,
859
+ instanceId,
860
+ name: resolveServiceName(def),
861
+ error: state.error
862
+ });
863
+ reject(startFailure(id, state.error, spawnCwd, commandStr, tailLogFile(logPath)));
864
+ return;
865
+ }
866
+ try {
867
+ const logContent = fs.readFileSync(logPath, "utf-8");
868
+ const newContent = logContent.slice(lastPos);
869
+ lastPos = logContent.length;
870
+ if (newContent) {
871
+ for (const rp of readinessPatterns) {
872
+ if (matched.has(rp.name)) continue;
873
+ const match = rp.pattern.exec(newContent);
874
+ if (match) {
875
+ matched.add(rp.name);
876
+ if (rp.captures) for (const [name, captureDef] of Object.entries(rp.captures)) {
877
+ const groupIdx = typeof captureDef === "number" ? captureDef : captureDef.group;
878
+ if (match[groupIdx]) {
879
+ state.endpoints[name] = match[groupIdx];
880
+ if (typeof captureDef !== "number" && captureDef.type) state.endpointTypes[name] = captureDef.type;
881
+ }
882
+ }
883
+ eventBus?.emit("service:pattern-matched", {
884
+ id,
885
+ instanceId,
886
+ name: resolveServiceName(def),
887
+ patternName: rp.name,
888
+ endpoints: state.endpoints,
889
+ endpointTypes: state.endpointTypes,
890
+ remaining: readinessPatterns.length - matched.size
891
+ });
892
+ }
893
+ }
894
+ if (matched.size === readinessPatterns.length) {
895
+ clearInterval(pollInterval);
896
+ state.status = "ready";
897
+ state.restartAttempt = 0;
898
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
899
+ eventBus?.emit("service:ready", {
900
+ id,
901
+ instanceId,
902
+ name: resolveServiceName(def),
903
+ endpoints: state.endpoints,
904
+ endpointTypes: state.endpointTypes
905
+ });
906
+ resolve();
907
+ return;
908
+ }
909
+ }
910
+ } catch {}
911
+ if (Date.now() - startTime > timeout) {
912
+ clearInterval(pollInterval);
913
+ try {
914
+ killTree(pid, "SIGKILL");
915
+ } catch {}
916
+ const unmatched = readinessPatterns.filter((rp) => !matched.has(rp.name)).map((rp) => rp.name);
917
+ state.status = "failed";
918
+ state.error = `Readiness timeout exceeded (unmatched: ${unmatched.join(", ")})`;
919
+ writeStateFile(stateFilePath(servicesDir, id, instanceId), state);
920
+ eventBus?.emit("service:failed", {
921
+ id,
922
+ instanceId,
923
+ name: resolveServiceName(def),
924
+ error: state.error
925
+ });
926
+ reject(startFailure(id, state.error, spawnCwd, commandStr, tailLogFile(logPath)));
927
+ }
928
+ }, 100);
929
+ });
930
+ return instanceId;
931
+ }
932
+ /**
933
+ * Starts a host service: `spawnHost` in the project, stopped through its
934
+ * stdin. Ready when its run record is live, with the endpoints the
935
+ * definition reads from the record. A stop while it waits aborts the wait.
936
+ */
937
+ async function startHost(def, run) {
938
+ const { id } = def;
939
+ const { instanceId } = run;
940
+ const name = resolveServiceName(def);
941
+ const statePath = stateFilePath(servicesDir, id, instanceId);
942
+ const state = {
943
+ serviceId: id,
944
+ instanceId,
945
+ name,
946
+ pid: 0,
947
+ owner,
948
+ status: "starting",
949
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
950
+ command: run.command,
951
+ restartAttempt: run.restartAttempt,
952
+ workdir: run.workdir,
953
+ params: run.params,
954
+ logFile: run.logFile
955
+ };
956
+ writeStateFile(statePath, state);
957
+ const fail = (error) => {
958
+ state.status = "failed";
959
+ state.error = error;
960
+ writeStateFile(statePath, state);
961
+ eventBus?.emit("service:failed", {
962
+ id,
963
+ instanceId,
964
+ name,
965
+ error
966
+ });
967
+ return startFailure(id, error, run.cwd, run.command, tailLogFile(run.logPath));
968
+ };
969
+ const abort = new AbortController();
970
+ const spawning = (async () => {
971
+ const { spawnHost } = await import("@powerhousedao/host-core");
972
+ return spawnHost({
973
+ projectRoot: run.cwd,
974
+ dataDir: run.cwd,
975
+ host: def.run.host,
976
+ ...def.run.verb === void 0 ? {} : { verb: def.run.verb },
977
+ ...def.run.argv ? { argv: def.run.argv } : {},
978
+ env: run.env,
979
+ baseEnv: run.baseEnv,
980
+ stopOnStdin: true,
981
+ logFile: run.logPath,
982
+ ...def.readiness ? { readyTimeoutMs: def.readiness.timeout } : {},
983
+ ...def.shutdown ? { stopTimeoutMs: def.shutdown.timeout } : {},
984
+ signal: abort.signal
985
+ });
986
+ })();
987
+ hostStarts.set(statePath, {
988
+ abort,
989
+ settled: spawning.catch(() => void 0)
990
+ });
991
+ let spawned;
992
+ try {
993
+ spawned = await spawning;
994
+ } catch (error) {
995
+ hostStarts.delete(statePath);
996
+ if (abort.signal.aborted) {
997
+ state.status = "stopped";
998
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
999
+ writeStateFile(statePath, state);
1000
+ eventBus?.emit("service:stopped", {
1001
+ id,
1002
+ instanceId,
1003
+ name
1004
+ });
1005
+ throw new Error(`Service ${id} was stopped before it was ready`);
1006
+ }
1007
+ throw fail((error instanceof Error ? error.message : String(error)).split("\n--- output tail ---\n")[0]);
1008
+ }
1009
+ hostStarts.delete(statePath);
1010
+ let endpoints;
1011
+ try {
1012
+ endpoints = def.endpoints?.(spawned.record) ?? {};
1013
+ } catch (error) {
1014
+ await spawned.stop();
1015
+ throw fail(`Reading its endpoints from the run record failed: ${error instanceof Error ? error.message : String(error)}`);
1016
+ }
1017
+ state.pid = spawned.pid;
1018
+ state.status = "ready";
1019
+ state.restartAttempt = 0;
1020
+ state.endpoints = {};
1021
+ state.endpointTypes = {};
1022
+ for (const [key, endpoint] of Object.entries(endpoints)) {
1023
+ state.endpoints[key] = endpoint.url;
1024
+ if (endpoint.type) state.endpointTypes[key] = endpoint.type;
1025
+ }
1026
+ writeStateFile(statePath, state);
1027
+ hostRuns.set(statePath, spawned);
1028
+ spawned.exited.then(() => {
1029
+ if (hostRuns.get(statePath) === spawned) hostRuns.delete(statePath);
1030
+ });
1031
+ eventBus?.emit("service:ready", {
1032
+ id,
1033
+ instanceId,
1034
+ name,
1035
+ endpoints: state.endpoints,
1036
+ endpointTypes: state.endpointTypes
1037
+ });
1038
+ return instanceId;
1039
+ }
1040
+ /**
1041
+ * Force-kill a process tree with SIGKILL, then wait for it to exit.
1042
+ */
1043
+ /* istanbul ignore next -- force-kill path requires processes that resist SIGTERM */
1044
+ async function forceKill(pid) {
1045
+ killTree(pid, "SIGKILL");
1046
+ await waitForExit(pid, 2e3);
1047
+ }
1048
+ async function stopInstance(def, serviceId, instanceId) {
1049
+ const statePath = stateFilePath(servicesDir, serviceId, instanceId);
1050
+ const starting = hostStarts.get(statePath);
1051
+ if (starting) {
1052
+ starting.abort.abort();
1053
+ await starting.settled;
1054
+ return;
1055
+ }
1056
+ const state = readStateFile(statePath);
1057
+ if (!state || !state.pid) {
1058
+ if (state?.status === "stopped") return;
1059
+ throw new Error(`Service ${serviceId} is not running`);
1060
+ }
1061
+ if (!isMine(state)) {
1062
+ if (foreignStatus(def, state).status === "stopped") return;
1063
+ throw new Error(`Service ${serviceId}: ${notOursMessage(state)}`);
1064
+ }
1065
+ if (!isPidAlive(state.pid)) {
1066
+ state.status = "stopped";
1067
+ state.pid = 0;
1068
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1069
+ writeStateFile(statePath, state);
1070
+ return;
1071
+ }
1072
+ const hostRun = hostRuns.get(statePath);
1073
+ if (hostRun) {
1074
+ stopping.add(statePath);
1075
+ try {
1076
+ await hostRun.stop();
1077
+ hostRuns.delete(statePath);
1078
+ state.status = "stopped";
1079
+ state.pid = 0;
1080
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1081
+ writeStateFile(statePath, state);
1082
+ } finally {
1083
+ stopping.delete(statePath);
1084
+ }
1085
+ eventBus?.emit("service:stopped", {
1086
+ id: serviceId,
1087
+ instanceId,
1088
+ name: resolveServiceName(def)
1089
+ });
1090
+ return;
1091
+ }
1092
+ const signal = (def.run ? void 0 : def.shutdown?.signal) ?? "SIGTERM";
1093
+ const timeout = def.shutdown?.timeout ?? 5e3;
1094
+ stopping.add(statePath);
1095
+ try {
1096
+ killTree(state.pid, signal);
1097
+ if (!await waitForExit(state.pid, timeout)) await forceKill(state.pid);
1098
+ if (state.endpoints?.port) {
1099
+ const port = parseInt(state.endpoints.port, 10);
1100
+ if (!isNaN(port)) {
1101
+ let portFree = false;
1102
+ for (let i = 0; i < 10; i++) {
1103
+ portFree = await isPortFree(port);
1104
+ if (portFree) break;
1105
+ await new Promise((r) => setTimeout(r, 100));
1106
+ }
1107
+ }
1108
+ }
1109
+ state.status = "stopped";
1110
+ state.pid = 0;
1111
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1112
+ writeStateFile(statePath, state);
1113
+ } finally {
1114
+ stopping.delete(statePath);
1115
+ }
1116
+ eventBus?.emit("service:stopped", {
1117
+ id: serviceId,
1118
+ instanceId,
1119
+ name: resolveServiceName(def)
1120
+ });
1121
+ }
1122
+ async function stop(id, instanceId) {
1123
+ const def = defMap.get(id);
1124
+ if (!def) throw new Error(`Unknown service: ${id}`);
1125
+ if (instanceId) return stopInstance(def, id, instanceId);
1126
+ const instances = scanInstances(servicesDir, id);
1127
+ if (instances.length === 0) throw new Error(`Service ${id} is not running`);
1128
+ const mine = instances.filter((s) => s.status !== "stopped" && isMine(s));
1129
+ if (mine.length === 0) {
1130
+ const theirs = instances.find((s) => s.status !== "stopped" && isInstanceAlive(s));
1131
+ if (theirs) throw new Error(`Service ${id}: ${notOursMessage(theirs)}`);
1132
+ return;
1133
+ }
1134
+ for (const inst of mine) try {
1135
+ await stopInstance(def, id, inst.instanceId);
1136
+ } catch {}
1137
+ }
1138
+ /** Stop every instance this manager started, gracefully (each service's
1139
+ * shutdown signal and timeout), and cancel pending restarts. Nothing
1140
+ * starts while it runs. */
1141
+ async function stopAll() {
1142
+ closing = true;
1143
+ for (const timer of restartTimers) clearTimeout(timer);
1144
+ restartTimers.clear();
1145
+ try {
1146
+ for (const def of definitions) for (const state of scanInstances(servicesDir, def.id)) {
1147
+ if (state.status === "stopped" || !isMine(state)) continue;
1148
+ try {
1149
+ await stopInstance(def, def.id, state.instanceId);
1150
+ } catch {}
1151
+ }
1152
+ } finally {
1153
+ closing = false;
1154
+ }
1155
+ }
1156
+ function list(serviceId) {
1157
+ const results = [];
1158
+ const defs = serviceId ? [defMap.get(serviceId)].filter(Boolean) : definitions;
1159
+ for (const def of defs) {
1160
+ const instances = scanInstances(servicesDir, def.id);
1161
+ if (instances.length === 0) {
1162
+ results.push({
1163
+ serviceId: def.id,
1164
+ instanceId: def.id,
1165
+ name: resolveServiceName(def),
1166
+ status: "idle"
1167
+ });
1168
+ continue;
1169
+ }
1170
+ for (const state of instances) {
1171
+ if (state.status === "stopped") {
1172
+ results.push({
1173
+ serviceId: def.id,
1174
+ instanceId: state.instanceId,
1175
+ name: state.name,
1176
+ status: "stopped",
1177
+ workdir: state.workdir,
1178
+ params: state.params
1179
+ });
1180
+ continue;
1181
+ }
1182
+ if (!isMine(state)) {
1183
+ results.push(foreignStatus(def, state));
1184
+ continue;
1185
+ }
1186
+ const statePath = stateFilePath(servicesDir, def.id, state.instanceId);
1187
+ if (hostStarts.has(statePath)) {
1188
+ results.push({
1189
+ serviceId: def.id,
1190
+ instanceId: state.instanceId,
1191
+ name: resolveServiceName(def),
1192
+ status: "starting",
1193
+ params: state.params,
1194
+ workdir: state.workdir
1195
+ });
1196
+ continue;
1197
+ }
1198
+ if (stopping.has(statePath)) {
1199
+ results.push({
1200
+ serviceId: def.id,
1201
+ instanceId: state.instanceId,
1202
+ name: resolveServiceName(def),
1203
+ status: "stopping",
1204
+ pid: state.pid,
1205
+ params: state.params,
1206
+ workdir: state.workdir
1207
+ });
1208
+ continue;
1209
+ }
1210
+ if (!state.pid || !isPidAlive(state.pid)) {
1211
+ if (!closing && def.restart?.enabled && (state.restartAttempt ?? 0) < def.restart.maxRetries && state.status === "ready") {
1212
+ const attempt = (state.restartAttempt ?? 0) + 1;
1213
+ eventBus?.emit("service:restarting", {
1214
+ id: def.id,
1215
+ instanceId: state.instanceId,
1216
+ name: resolveServiceName(def),
1217
+ attempt,
1218
+ maxRetries: def.restart.maxRetries
1219
+ });
1220
+ state.status = "starting";
1221
+ state.restartAttempt = attempt;
1222
+ writeStateFile(statePath, state);
1223
+ const restartParams = state.params;
1224
+ const restartWorkdir = state.workdir;
1225
+ const restartName = state.instanceId.includes(":") ? state.instanceId.split(":")[1] : void 0;
1226
+ const timer = setTimeout(async () => {
1227
+ restartTimers.delete(timer);
1228
+ try {
1229
+ removeStateFile(statePath);
1230
+ ensureServiceDir(def.id);
1231
+ const commandStr = resolveCommand(def, buildContext(restartParams));
1232
+ const tempState = {
1233
+ serviceId: def.id,
1234
+ instanceId: state.instanceId,
1235
+ name: resolveServiceName(def),
1236
+ pid: 0,
1237
+ owner,
1238
+ status: "failed",
1239
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1240
+ command: commandStr,
1241
+ restartAttempt: attempt,
1242
+ params: restartParams,
1243
+ workdir: restartWorkdir
1244
+ };
1245
+ writeStateFile(statePath, tempState);
1246
+ await start(def.id, {
1247
+ params: restartParams,
1248
+ workdir: restartWorkdir,
1249
+ name: restartName
1250
+ });
1251
+ } catch {}
1252
+ }, def.restart.delay);
1253
+ restartTimers.add(timer);
1254
+ results.push({
1255
+ serviceId: def.id,
1256
+ instanceId: state.instanceId,
1257
+ name: resolveServiceName(def),
1258
+ status: "starting",
1259
+ restartAttempt: attempt,
1260
+ params: state.params,
1261
+ workdir: state.workdir
1262
+ });
1263
+ } else {
1264
+ const isFailed = state.status === "failed" || def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries;
1265
+ if (def.restart?.enabled && (state.restartAttempt ?? 0) >= def.restart.maxRetries) eventBus?.emit("service:failed", {
1266
+ id: def.id,
1267
+ instanceId: state.instanceId,
1268
+ name: resolveServiceName(def),
1269
+ error: "Max restart retries exceeded"
1270
+ });
1271
+ if (isFailed) {
1272
+ removeStateFile(statePath);
1273
+ results.push({
1274
+ serviceId: def.id,
1275
+ instanceId: state.instanceId,
1276
+ name: resolveServiceName(def),
1277
+ status: "failed",
1278
+ error: state.error ?? "Process exited unexpectedly",
1279
+ restartAttempt: state.restartAttempt
1280
+ });
1281
+ } else {
1282
+ state.status = "stopped";
1283
+ state.pid = 0;
1284
+ state.stoppedAt = (/* @__PURE__ */ new Date()).toISOString();
1285
+ writeStateFile(statePath, state);
1286
+ results.push({
1287
+ serviceId: def.id,
1288
+ instanceId: state.instanceId,
1289
+ name: state.name,
1290
+ status: "stopped",
1291
+ workdir: state.workdir,
1292
+ params: state.params
1293
+ });
1294
+ }
1295
+ }
1296
+ continue;
1297
+ }
1298
+ results.push({
1299
+ serviceId: def.id,
1300
+ instanceId: state.instanceId,
1301
+ name: resolveServiceName(def),
1302
+ status: state.status,
1303
+ pid: state.pid,
1304
+ endpoints: state.endpoints,
1305
+ endpointTypes: state.endpointTypes,
1306
+ restartAttempt: state.restartAttempt,
1307
+ params: state.params,
1308
+ workdir: state.workdir
1309
+ });
1310
+ }
1311
+ }
1312
+ return results;
1313
+ }
1314
+ function logs(id, instanceId, lines = 50) {
1315
+ const def = defMap.get(id);
1316
+ if (!def) throw new Error(`Unknown service: ${id}`);
1317
+ let resolvedInstanceId = instanceId;
1318
+ let warning = "";
1319
+ if (!resolvedInstanceId) {
1320
+ const instances = scanInstances(servicesDir, id);
1321
+ const running = instances.filter((s) => s.status === "ready" || s.status === "starting");
1322
+ if (running.length === 1) resolvedInstanceId = running[0].instanceId;
1323
+ else if (running.length > 1) {
1324
+ warning = `⚠ Multiple running instances — showing logs for ${running[0].instanceId}. Use --instance to specify: ${running.map((r) => r.instanceId).join(", ")}\n`;
1325
+ resolvedInstanceId = running[0].instanceId;
1326
+ } else if (instances.length > 0) resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? instances[instances.length - 1].instanceId;
1327
+ else resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? id;
1328
+ }
1329
+ const logPath = activeLogPath(servicesDir, id, resolvedInstanceId);
1330
+ const instanceState = (instanceId ? null : scanInstances(servicesDir, id))?.find((s) => s.instanceId === resolvedInstanceId);
1331
+ const statusTag = instanceState ? ` [${instanceState.status}]` : "";
1332
+ const instanceTag = resolvedInstanceId !== id ? ` (${resolvedInstanceId})` : "";
1333
+ const workdirLine = instanceState?.workdir ? `\n (dir: ${instanceState.workdir})` : "";
1334
+ const footer = `\n— ${resolveServiceName(def)}${instanceTag}${statusTag} log${workdirLine}`;
1335
+ try {
1336
+ const body = sanitizeLogText(sanitizeLogText(fs.readFileSync(logPath, "utf-8")).split("\n").slice(-lines).join("\n"));
1337
+ return warning + body + footer;
1338
+ } catch {
1339
+ return warning;
1340
+ }
1341
+ }
1342
+ function watchLogs(id, instanceId, onLine) {
1343
+ if (!defMap.get(id)) throw new Error(`Unknown service: ${id}`);
1344
+ return watchLogFile(activeLogPath(servicesDir, id, instanceId), onLine);
1345
+ }
1346
+ function getDefinition(id) {
1347
+ return defMap.get(id);
1348
+ }
1349
+ function scanProjectsForService(id, rootDir) {
1350
+ const def = defMap.get(id);
1351
+ if (!def) throw new Error(`Unknown service: ${id}`);
1352
+ if (!def.projectScanner) return [];
1353
+ return scanProjects(rootDir, def.projectScanner);
1354
+ }
1355
+ function purgeStoppedInstances(id) {
1356
+ if (!defMap.get(id)) throw new Error(`Unknown service: ${id}`);
1357
+ const instances = scanInstances(servicesDir, id);
1358
+ for (const state of instances) if (state.status === "stopped") {
1359
+ removeStateFile(stateFilePath(servicesDir, id, state.instanceId));
1360
+ const dir = serviceDir(servicesDir, id);
1361
+ try {
1362
+ fs.unlinkSync(logFilePath(servicesDir, id, state.instanceId));
1363
+ } catch {}
1364
+ for (const f of listRunLogs(servicesDir, id, state.instanceId)) try {
1365
+ fs.unlinkSync(path.join(dir, f));
1366
+ } catch {}
1367
+ }
1368
+ }
1369
+ function watchChunks(_id, _instanceId, _onChunk) {
1370
+ if (!defMap.get(_id)) throw new Error(`Unknown service: ${_id}`);
1371
+ return () => {};
1372
+ }
1373
+ return {
1374
+ start,
1375
+ stop,
1376
+ stopAll,
1377
+ list,
1378
+ getDefinition,
1379
+ logs,
1380
+ watchLogs,
1381
+ watchChunks,
1382
+ scanProjects: scanProjectsForService,
1383
+ purgeStoppedInstances
1384
+ };
1385
+ }
1386
+ //#endregion
1387
+ //#region src/interactive/completions.ts
1388
+ /**
1389
+ * Tokenize input respecting quotes, and report whether the cursor is inside
1390
+ * an open quote (meaning we should not offer completions).
1391
+ */
1392
+ function tokenizeInput(input) {
1393
+ const tokens = [];
1394
+ let current = "";
1395
+ let inQuote = false;
1396
+ let quoteChar = "";
1397
+ for (const ch of input) if (inQuote) {
1398
+ if (ch === quoteChar) inQuote = false;
1399
+ else current += ch;
1400
+ } else if (ch === "\"" || ch === "'") {
1401
+ inQuote = true;
1402
+ quoteChar = ch;
1403
+ } else if (ch === " " || ch === " ") {
1404
+ if (current) {
1405
+ tokens.push(current);
1406
+ current = "";
1407
+ }
1408
+ } else current += ch;
1409
+ if (current) tokens.push(current);
1410
+ const trailingSpace = !inQuote && input.length > 0 && (input[input.length - 1] === " " || input[input.length - 1] === " ");
1411
+ return {
1412
+ tokens,
1413
+ inQuote,
1414
+ trailingSpace
1415
+ };
1416
+ }
1417
+ /**
1418
+ * Collect flag names already present in the tokens.
1419
+ */
1420
+ function usedFlags(tokens) {
1421
+ const used = /* @__PURE__ */ new Set();
1422
+ for (const t of tokens) if (t.startsWith("--")) used.add(t);
1423
+ return used;
1424
+ }
1425
+ /**
1426
+ * Get auto-completion suggestions for partial REPL input.
1427
+ *
1428
+ * Supports:
1429
+ * - Command name completion: `/gr` → ['/greet']
1430
+ * - Flag name completion: `/add --` → ['--title', '--priority', '--due']
1431
+ * - Flag name after trailing space: `/add ` → ['--title', '--priority', '--due']
1432
+ * - Enum value completion: `/list --filter d` → ['done']
1433
+ * - No completions inside quoted strings
1434
+ */
1435
+ function getCompletions(input, commands) {
1436
+ const trimmed = input.trimStart();
1437
+ if (!trimmed.startsWith("/")) return [];
1438
+ const { tokens, inQuote, trailingSpace } = tokenizeInput(trimmed);
1439
+ if (tokens.length === 0) return [];
1440
+ if (inQuote) return [];
1441
+ if (tokens.length === 1 && !trailingSpace) {
1442
+ const prefix = tokens[0].slice(1).toLowerCase();
1443
+ const builtins = ["exit", "quit"];
1444
+ return [...commands.map((c) => c.id), ...builtins].filter((name) => name.toLowerCase().startsWith(prefix)).map((name) => `/${name}`);
1445
+ }
1446
+ const cmdName = tokens[0].slice(1).toLowerCase();
1447
+ const cmd = commands.find((c) => c.id === cmdName);
1448
+ if (!cmd) return [];
1449
+ const fields = getSchemaFields(cmd.inputSchema);
1450
+ const used = usedFlags(tokens);
1451
+ if (trailingSpace) {
1452
+ const lastToken = tokens[tokens.length - 1];
1453
+ if (lastToken.startsWith("--")) {
1454
+ const fieldName = lastToken.slice(2);
1455
+ const field = fields.find((f) => f.key === fieldName);
1456
+ if (field && field.baseType !== "boolean") return getFieldValueCompletions(cmd, fieldName, "");
1457
+ }
1458
+ return fields.filter((f) => !used.has(`--${f.key}`)).map((f) => `--${f.key}`);
1459
+ }
1460
+ const lastToken = tokens[tokens.length - 1];
1461
+ const prevToken = tokens.length >= 2 ? tokens[tokens.length - 2] : "";
1462
+ if (prevToken.startsWith("--")) {
1463
+ const fieldName = prevToken.slice(2);
1464
+ const field = fields.find((f) => f.key === fieldName);
1465
+ if (field && field.baseType !== "boolean") return getFieldValueCompletions(cmd, fieldName, lastToken);
1466
+ }
1467
+ if (lastToken.startsWith("-")) {
1468
+ const prefix = lastToken.startsWith("--") ? lastToken.slice(2).toLowerCase() : "";
1469
+ return fields.filter((f) => f.key.toLowerCase().startsWith(prefix) && !used.has(`--${f.key}`)).map((f) => `--${f.key}`);
1470
+ }
1471
+ return [];
1472
+ }
1473
+ /**
1474
+ * Get value completions for an enum field.
1475
+ */
1476
+ function getFieldValueCompletions(cmd, fieldName, partial) {
1477
+ const enumValues = getEnumValues(cmd.inputSchema, fieldName);
1478
+ if (!enumValues) return [];
1479
+ const prefix = partial.toLowerCase();
1480
+ return enumValues.filter((v) => v.toLowerCase().startsWith(prefix));
1481
+ }
1482
+ /**
1483
+ * Get the suffix to append after a flag completion.
1484
+ * Returns ` "` for non-boolean, non-enum fields (opening a value quote),
1485
+ * empty string otherwise.
1486
+ */
1487
+ function getCompletionSuffix(completion, input, commands) {
1488
+ if (!completion.startsWith("--")) return "";
1489
+ const { tokens } = tokenizeInput(input.trimStart());
1490
+ const cmdName = tokens[0]?.slice(1).toLowerCase();
1491
+ const cmd = commands.find((c) => c.id === cmdName);
1492
+ if (!cmd) return "";
1493
+ const fieldName = completion.slice(2);
1494
+ const field = getSchemaFields(cmd.inputSchema).find((f) => f.key === fieldName);
1495
+ if (!field || field.baseType === "boolean") return "";
1496
+ if (getEnumValues(cmd.inputSchema, fieldName)) return " ";
1497
+ return " \"";
1498
+ }
1499
+ /**
1500
+ * Get the ghost suggestion for the current input — the full input string
1501
+ * with the first completion applied, suitable for inline preview.
1502
+ *
1503
+ * Returns null if no suggestion is available.
1504
+ */
1505
+ function getGhostSuggestion(input, commands) {
1506
+ const { inQuote } = tokenizeInput(input.trimStart());
1507
+ if (inQuote) return input + "\"";
1508
+ const completions = getCompletions(input, commands);
1509
+ if (completions.length === 0) return null;
1510
+ return applyCompletion(input, completions[0]) + getCompletionSuffix(completions[0], input, commands);
1511
+ }
1512
+ /**
1513
+ * Apply a completion candidate to the current input by replacing the last token.
1514
+ * If the input ends with a trailing space, the completion is appended.
1515
+ *
1516
+ * For command completions (`/gr` + `/greet` → `/greet`), replaces the only token.
1517
+ * For flag completions (`/greet --na` + `--name` → `/greet --name`), replaces the last token.
1518
+ * For value completions (`/list --filter d` + `done` → `/list --filter done`), replaces the last token.
1519
+ * For trailing space (`/add ` + `--title` → `/add --title`), appends.
1520
+ */
1521
+ function applyCompletion(input, completion) {
1522
+ if (input.length > 0 && (input[input.length - 1] === " " || input[input.length - 1] === " ")) return input + completion;
1523
+ const lastSpaceIdx = input.lastIndexOf(" ");
1524
+ if (lastSpaceIdx === -1) return completion;
1525
+ return input.slice(0, lastSpaceIdx + 1) + completion;
1526
+ }
1527
+ /**
1528
+ * Extract enum values from a Zod schema field, if it's an enum type.
1529
+ * Unwraps Default/Optional/Nullable wrappers to find the underlying ZodEnum.
1530
+ */
1531
+ function getEnumValues(schema, fieldName) {
1532
+ if (!(schema instanceof z.ZodObject)) return null;
1533
+ let field = schema.shape[fieldName];
1534
+ if (!field) return null;
1535
+ const wrapperTypes = /* @__PURE__ */ new Set([
1536
+ "default",
1537
+ "optional",
1538
+ "nullable"
1539
+ ]);
1540
+ let current = field;
1541
+ while (wrapperTypes.has(current.type) && current.def.innerType) {
1542
+ current = current.def.innerType;
1543
+ field = current;
1544
+ }
1545
+ if (field instanceof z.ZodEnum) return field.options;
1546
+ return null;
1547
+ }
1548
+ //#endregion
1549
+ //#region src/interactive/markdown.ts
1550
+ const marked = new Marked();
1551
+ const terminalExt = markedTerminal();
1552
+ const originalCode = terminalExt.renderer.code;
1553
+ terminalExt.renderer.code = function(...args) {
1554
+ const [first, second, third] = args;
1555
+ if (first && typeof first === "object") {
1556
+ const token = first;
1557
+ if (token.lang && !supportsLanguage(token.lang)) return originalCode.call(this, {
1558
+ ...token,
1559
+ lang: ""
1560
+ });
1561
+ return originalCode.call(this, first);
1562
+ }
1563
+ if (typeof second === "string" && !supportsLanguage(second)) return originalCode.call(this, first, "", third);
1564
+ return originalCode.call(this, ...args);
1565
+ };
1566
+ marked.use(terminalExt);
1567
+ marked.use({ walkTokens(token) {
1568
+ if (token.type === "list" || token.type === "list_item") token.loose = false;
1569
+ } });
1570
+ /**
1571
+ * Render a markdown string for terminal display.
1572
+ * Returns ANSI-formatted text suitable for terminal output.
1573
+ *
1574
+ * For plain text (no markdown), the output is the same as the input
1575
+ * (with a trailing newline trimmed).
1576
+ */
1577
+ function renderMarkdown(text) {
1578
+ if (!text) return "";
1579
+ const rendered = marked.parse(text);
1580
+ /* istanbul ignore next -- marked.parse() always returns string with sync config */
1581
+ if (typeof rendered !== "string") return text;
1582
+ const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
1583
+ return rendered.split("\n").filter((line) => line.length === 0 || stripAnsi(line).trim().length > 0).join("\n").trimEnd();
1584
+ }
1585
+ //#endregion
1586
+ export { renderStream as S, isPortFree as _, getGhostSuggestion as a, supervisedSpawnOptions as b, hostCommandLine as c, watchLogFile as d, PROJECT_INDICATORS as f, checkWorkdir as g, checkPort as h, getCompletions as i, resolveServiceName as l, checkCommand as m, applyCompletion as n, createServiceManager as o, scanProjects as p, getCompletionSuffix as r, defineService as s, renderMarkdown as t, sanitizeLogText as u, killTree as v, formatStreamChunk as x, superviseChild as y };
1587
+
1588
+ //# sourceMappingURL=markdown-BUeGwhbR.mjs.map