@powerhousedao/clint 6.4.0-next.2 → 6.4.0-next.4

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 (48) hide show
  1. package/dist/{build-skills-Bpbbnin0.mjs → build-skills-BTkuL8ne.mjs} +2 -2
  2. package/dist/{build-skills-Bpbbnin0.mjs.map → build-skills-BTkuL8ne.mjs.map} +1 -1
  3. package/dist/command-control-Dp41aY0o.mjs +224 -0
  4. package/dist/command-control-Dp41aY0o.mjs.map +1 -0
  5. package/dist/{dist-Bd6hUl0J.mjs → dist-BTVqrpN4.mjs} +2 -2
  6. package/dist/{dist-Bd6hUl0J.mjs.map → dist-BTVqrpN4.mjs.map} +1 -1
  7. package/dist/{index-CfHcet4v.d.mts → index-DJlqIVLv.d.mts} +13 -10
  8. package/dist/{index-CfHcet4v.d.mts.map → index-DJlqIVLv.d.mts.map} +1 -1
  9. package/dist/index.d.mts +227 -8
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +6 -5
  12. package/dist/integrations/mastra/index.d.mts +20 -3
  13. package/dist/integrations/mastra/index.d.mts.map +1 -1
  14. package/dist/integrations/mastra/index.mjs +25 -3
  15. package/dist/integrations/mastra/index.mjs.map +1 -1
  16. package/dist/integrations/powerhouse/index.d.mts +3 -3
  17. package/dist/integrations/powerhouse/index.mjs +1 -1
  18. package/dist/{markdown-BUeGwhbR.mjs → markdown-B-HyDpvO.mjs} +471 -39
  19. package/dist/markdown-B-HyDpvO.mjs.map +1 -0
  20. package/dist/{powerhouse-3XZmdY3_.mjs → powerhouse-C4O-raTW.mjs} +168 -12
  21. package/dist/powerhouse-C4O-raTW.mjs.map +1 -0
  22. package/dist/{proxy-ji3EHzLn.mjs → proxy-DgnOKu1A.mjs} +2 -2
  23. package/dist/proxy-DgnOKu1A.mjs.map +1 -0
  24. package/dist/remote-reactor-oBsHphPT.mjs.map +1 -1
  25. package/dist/{repl-Czb7u0x_.mjs → repl-C4gHgy6P.mjs} +2 -2
  26. package/dist/{repl-Czb7u0x_.mjs.map → repl-C4gHgy6P.mjs.map} +1 -1
  27. package/dist/runners/cli-runner.d.mts +5 -2
  28. package/dist/runners/cli-runner.d.mts.map +1 -1
  29. package/dist/runners/cli-runner.mjs +21 -7
  30. package/dist/runners/cli-runner.mjs.map +1 -1
  31. package/dist/runners/mastra-runner.mjs +1 -1
  32. package/dist/runners/proxy-runner.mjs +1 -1
  33. package/dist/{src-BmMd0Wl4.mjs → src-FF3zDJY7.mjs} +606 -53
  34. package/dist/src-FF3zDJY7.mjs.map +1 -0
  35. package/dist/{start-BHn9LIyX.mjs → start-CCegR8Pi.mjs} +2 -2
  36. package/dist/{start-BHn9LIyX.mjs.map → start-CCegR8Pi.mjs.map} +1 -1
  37. package/dist/testing/index.d.mts +2 -2
  38. package/dist/testing/index.mjs +1 -1
  39. package/dist/{types-3TnDjQ1w.d.mts → types-BnPpIAL6.d.mts} +2 -2
  40. package/dist/{types-3TnDjQ1w.d.mts.map → types-BnPpIAL6.d.mts.map} +1 -1
  41. package/dist/{types-DbQKfvWc.d.mts → types-CIZtG2TY.d.mts} +219 -13
  42. package/dist/types-CIZtG2TY.d.mts.map +1 -0
  43. package/package.json +13 -13
  44. package/dist/markdown-BUeGwhbR.mjs.map +0 -1
  45. package/dist/powerhouse-3XZmdY3_.mjs.map +0 -1
  46. package/dist/proxy-ji3EHzLn.mjs.map +0 -1
  47. package/dist/src-BmMd0Wl4.mjs.map +0 -1
  48. package/dist/types-DbQKfvWc.d.mts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"markdown-BUeGwhbR.mjs","names":["scanProjectsImpl"],"sources":["../src/core/stream.ts","../src/core/process-platform.ts","../src/core/preflight.ts","../src/core/project-scanner.ts","../src/core/services.ts","../src/interactive/completions.ts","../src/interactive/markdown.ts"],"sourcesContent":["import type { StreamChunk } from \"./types.js\";\n\n// ANSI escape codes for semantic coloring of tool activity\nconst DIM = \"\\x1b[2m\";\nconst RESET = \"\\x1b[0m\";\nconst RED = \"\\x1b[31m\";\nconst GREEN_DIM = \"\\x1b[32;2m\";\n\n/**\n * Format a single StreamChunk into a display string.\n *\n * This is the framework-level formatter. The Mastra integration maps\n * Mastra's fullStream chunks to StreamChunk first, then this renders them.\n *\n * Tool activity is styled with dim green (calls/results) and red (errors)\n * so it's visually distinct from the agent's text output.\n */\nexport function formatStreamChunk(chunk: StreamChunk): string {\n switch (chunk.type) {\n case \"text-delta\":\n return chunk.text;\n\n case \"tool-call\":\n return `\\n${DIM}${GREEN_DIM}▶ ${chunk.toolName}${RESET}${DIM}(${truncateArgs(chunk.args)})${RESET}\\n`;\n\n case \"tool-result\":\n if (chunk.isError) {\n return `${RED}✗ ${chunk.toolName} error: ${formatResult(chunk.result)}${RESET}\\n`;\n }\n // Extract text body: from { text: string } field or raw string result\n // eslint-disable-next-line no-case-declarations\n const body = hasTextField(chunk.result)\n ? (chunk.result as { text: string }).text\n : typeof chunk.result === \"string\"\n ? chunk.result\n : null;\n if (body && body.length > 0) {\n return `${DIM}${GREEN_DIM}✓ ${chunk.toolName}${RESET}\\n${body}\\n`;\n }\n // Short/null/object results: inline summary\n return `${DIM}${GREEN_DIM}✓ ${chunk.toolName}${RESET}${DIM} → ${truncateResult(chunk.result)}${RESET}\\n`;\n\n case \"tool-output\":\n return chunk.text;\n\n case \"error\":\n return `${RED}Error: ${chunk.error}${RESET}\\n`;\n\n case \"step-finish\":\n case \"finish\":\n // Lifecycle chunks carry token usage for cost accounting; no display\n // text by default. Renderers that care (eg. observability/eval) read\n // the chunk directly instead of relying on `formatted`.\n return \"\";\n }\n}\n\n/** A rendered stream element: the raw chunk paired with its formatted text. */\nexport interface RenderedChunk {\n chunk: StreamChunk;\n formatted: string;\n}\n\n/**\n * Consume a stream of StreamChunks and yield { chunk, formatted } pairs.\n *\n * Inserts an extra newline before the first text-delta after tool activity,\n * so the agent's prose is visually separated from tool call/result lines.\n */\nexport async function* renderStream(\n stream: AsyncGenerator<StreamChunk>,\n): AsyncGenerator<RenderedChunk, void, unknown> {\n let lastChunkWasText = false;\n\n for await (const chunk of stream) {\n let prefix = \"\";\n if (chunk.type === \"text-delta\") {\n if (!lastChunkWasText) {\n prefix = \"\\n\";\n lastChunkWasText = true;\n }\n } else {\n lastChunkWasText = false;\n }\n yield { chunk, formatted: prefix + formatStreamChunk(chunk) };\n }\n}\n\nfunction truncateArgs(args: unknown): string {\n const json = JSON.stringify(args);\n return json.length > 120 ? json.slice(0, 120) + \"…\" : json;\n}\n\nfunction truncateResult(result: unknown): string {\n const str = formatResult(result);\n return str.length > 200 ? str.slice(0, 200) + \"…\" : str;\n}\n\nfunction formatResult(result: unknown): string {\n if (result === undefined || result === null) return \"ok\";\n if (typeof result === \"string\") return result;\n return JSON.stringify(result);\n}\n\nfunction hasTextField(result: unknown): boolean {\n return (\n typeof result === \"object\" &&\n result !== null &&\n \"text\" in result &&\n typeof (result as Record<string, unknown>).text === \"string\"\n );\n}\n","import type { ChildProcess } from \"node:child_process\";\nimport os from \"node:os\";\n// The subpath, not the main entry: every Cli loads this module at startup.\nimport { killTree } from \"@powerhousedao/host-core/kill-tree\";\n\n/**\n * Supervised children are ATTACHED: no process clint starts may outlive the\n * process that started it. They are spawned without `detached` on every\n * platform (hidden on Windows, where `detached` would also force a console\n * per child), and every one is registered with {@link superviseChild}, which\n * fells the ones still alive when this process ends.\n *\n * Attached children share this process's group on POSIX, so there is no\n * group of their own to signal: {@link killTree} (host-core's, which a\n * compound's own-process members are killed with too) walks the process\n * table instead. On Windows it uses `taskkill /T /F`.\n */\nexport const isWindows = process.platform === \"win32\";\n\nexport { killTree };\n\n/** Spawn options fragment for a supervised child. */\nexport function supervisedSpawnOptions(): {\n detached: false;\n windowsHide: true;\n} {\n return { detached: false, windowsHide: true };\n}\n\n// ── Supervision: children end with this process ──────────────────\n\n/** Supervised children still running. */\nconst liveChildren = new Set<ChildProcess>();\n\n/** Signals whose default action ends this process. */\nconst ENDING_SIGNALS: NodeJS.Signals[] = isWindows\n ? [\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGBREAK\"]\n : [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n\n/** Forcefully fell every supervised child still running (synchronous, so it\n * also works from an `exit` listener). */\nfunction fellLiveChildren(): void {\n for (const child of liveChildren) {\n if (\n child.pid !== undefined &&\n child.exitCode === null &&\n child.signalCode === null\n ) {\n killTree(child.pid, \"SIGKILL\");\n }\n }\n liveChildren.clear();\n}\n\n/**\n * The signal listeners signal-exit (Ink's dependency) installs, one per\n * loaded copy, read from the counts its copies share. Each acts only when\n * signal-exit's listeners are the only ones left, so counted as application\n * handlers they and the guard below would each wait for the other. (The\n * same count as ph-cli's package-build/run-build.ts.)\n */\nfunction exitOnlyListeners(): number {\n const count = (emitter: unknown) => {\n const value = (emitter as { count?: unknown } | undefined)?.count;\n return typeof value === \"number\" ? value : 0;\n };\n const shared = globalThis as Record<symbol, unknown>;\n const legacy = process as unknown as Record<string, unknown>;\n return (\n count(shared[Symbol.for(\"signal-exit emitter\")]) +\n count(legacy.__signal_exit_emitter__)\n );\n}\n\n/**\n * A signal whose default action would end this process. An application\n * listener (the CLI's own shutdown, which stops services gracefully) owns\n * the signal: the guard leaves it alone and the `exit` listener backs it up.\n * With no such listener the process would simply die and leave its children\n * running, so the guard does what the default would, children first.\n */\nfunction onEndingSignal(signal: NodeJS.Signals): void {\n const others = process.listenerCount(signal) - 1 - exitOnlyListeners();\n if (others > 0) return;\n fellLiveChildren();\n const signals = os.constants.signals as Record<string, number | undefined>;\n process.exit(128 + (signals[signal] ?? 0));\n}\n\nlet guarded = false;\n\nfunction installGuard(): void {\n if (guarded) return;\n guarded = true;\n process.on(\"exit\", fellLiveChildren);\n for (const signal of ENDING_SIGNALS) process.on(signal, onEndingSignal);\n}\n\nfunction removeGuard(): void {\n if (!guarded) return;\n guarded = false;\n process.removeListener(\"exit\", fellLiveChildren);\n for (const signal of ENDING_SIGNALS) {\n process.removeListener(signal, onEndingSignal);\n }\n}\n\n/**\n * Register a spawned child so it cannot outlive this process: when the\n * process exits (normally, through `process.exit`, or on an uncaught error)\n * or is ended by a signal nobody handles, the child's tree is killed. The\n * listeners exist only while a supervised child is running. Graceful stops\n * are the owner's job (the services manager's `stopAll`); this is the last\n * line, and it kills hard. A process killed outright (SIGKILL, Task Manager)\n * runs no code at all, so its children cannot be reached.\n */\nexport function superviseChild(child: ChildProcess): void {\n if (child.pid === undefined) return; // never started\n installGuard();\n liveChildren.add(child);\n child.once(\"exit\", () => {\n if (!liveChildren.delete(child)) return;\n if (liveChildren.size === 0) removeGuard();\n });\n}\n","import { execSync } from \"node:child_process\";\nimport net from \"node:net\";\nimport type { PreflightCheck, PreflightContext } from \"./types.js\";\n\n/**\n * Check if a TCP port is free by attempting to bind to it.\n */\nexport function isPortFree(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once(\"error\", () => resolve(false));\n server.once(\"listening\", () => {\n server.close(() => resolve(true));\n });\n server.listen(port, \"127.0.0.1\");\n });\n}\n\n/**\n * Check that the working directory satisfies a condition.\n *\n * @param test A function that receives the cwd and returns true if valid.\n * @param message Error message on failure.\n * @param hint Optional guidance.\n */\nexport function checkWorkdir(\n test: (cwd: string) => boolean,\n message: string,\n hint?: string,\n): PreflightCheck {\n return (ctx) => {\n if (test(ctx.cwd)) return { ok: true };\n return { ok: false, message: `${message} (cwd: ${ctx.cwd})`, hint };\n };\n}\n\n/**\n * Check that a command is available on PATH, optionally matching a version.\n *\n * @param binary Binary name (e.g. 'ph', 'node', 'pnpm').\n * @param options Optional version flag, version predicate, and hint.\n */\nexport function checkCommand(\n binary: string,\n options?: {\n versionFlag?: string;\n versionTest?: (version: string) => boolean;\n hint?: string;\n },\n): PreflightCheck {\n return (ctx) => {\n try {\n const output = execSync(\n `${binary} ${options?.versionFlag ?? \"--version\"}`,\n {\n cwd: ctx.cwd,\n timeout: 5_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n },\n )\n .toString()\n .trim();\n\n if (options?.versionTest && !options.versionTest(output)) {\n return {\n ok: false,\n message: `${binary} version mismatch: ${output}`,\n hint: options.hint,\n };\n }\n return { ok: true };\n } catch {\n return {\n ok: false,\n message: `'${binary}' not found`,\n hint: options?.hint ?? `Install ${binary} or check your PATH`,\n };\n }\n };\n}\n\n/**\n * Check that a TCP port is available.\n *\n * @param port Port number, or a function that extracts it from the preflight context.\n * @param label Human-readable name for the port (e.g. 'Connect Studio').\n */\nexport function checkPort(\n port: number | ((ctx: PreflightContext) => number | undefined),\n label?: string,\n): PreflightCheck {\n return async (ctx) => {\n const p = typeof port === \"function\" ? port(ctx) : port;\n if (p === undefined) return { ok: true };\n\n const free = await isPortFree(p);\n if (free) return { ok: true };\n\n const name = label ? `${label} port` : \"Port\";\n return {\n ok: false,\n message: `${name} ${p} is already in use`,\n hint: `Stop the process using port ${p}, or use a different port`,\n };\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ProjectScanner, ProjectScanResult } from \"./types.js\";\n\n// Re-export for convenience\nexport type { ProjectScanResult } from \"./types.js\";\n\n/**\n * Common project indicator files/dirs. When any of these exist in a folder\n * that isn't matched by the scanner, the folder is treated as a foreign\n * project and its subtree is pruned from the search.\n */\nexport const PROJECT_INDICATORS = [\n // JS/TS ecosystem\n \".git\",\n \"package.json\",\n \"node_modules\",\n // Python\n \"pyproject.toml\",\n \"setup.py\",\n // Rust\n \"Cargo.toml\",\n // Go\n \"go.mod\",\n // Java / Kotlin\n \"pom.xml\",\n \"build.gradle\",\n \"build.gradle.kts\",\n // .NET\n \".sln\",\n // Ruby\n \"Gemfile\",\n // PHP\n \"composer.json\",\n] as const;\n\ntype FolderType = \"match\" | \"mismatch\" | \"non-project\";\n\nfunction detectType(folderPath: string, scanner: ProjectScanner): FolderType {\n if (scanner.isProjectFolder(folderPath)) return \"match\";\n\n for (const indicator of PROJECT_INDICATORS) {\n if (fs.existsSync(path.join(folderPath, indicator))) {\n return \"mismatch\";\n }\n }\n\n return \"non-project\";\n}\n\nfunction enqueueSubdirs(dir: string, queue: string[]): void {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\")) {\n queue.push(path.join(dir, entry.name));\n }\n }\n}\n\n/**\n * Breadth-first search for project folders starting from `rootDir`.\n *\n * - If root itself matches, returns it immediately.\n * - Otherwise searches subfolders breadth-first:\n * - Match → added to results, subtree pruned\n * - Mismatch (foreign project) → subtree pruned\n * - Non-project → subfolders enqueued for further search\n *\n * Uses `scanner.getProjectName` for the result name (default: `path.basename`),\n * and `scanner.getProjectConfig` when provided.\n */\nexport function scanProjects(\n rootDir: string,\n scanner: ProjectScanner,\n): ProjectScanResult[] {\n const getName = (p: string) =>\n scanner.getProjectName ? scanner.getProjectName(p) : path.basename(p);\n const getConfig = (p: string) =>\n scanner.getProjectConfig ? scanner.getProjectConfig(p) : undefined;\n\n function toResult(folderPath: string): ProjectScanResult {\n const result: ProjectScanResult = {\n name: getName(folderPath),\n path: folderPath,\n config: getConfig(folderPath),\n };\n\n if (scanner.getDocumentLink) {\n const link = scanner.getDocumentLink(folderPath);\n if (link) {\n result.documentId = link.documentId;\n result.documentType = link.documentType;\n }\n }\n\n return result;\n }\n\n // Check root first\n const rootType = detectType(rootDir, scanner);\n if (rootType === \"match\") {\n return [toResult(rootDir)];\n }\n\n const results: ProjectScanResult[] = [];\n const queue: string[] = [];\n\n enqueueSubdirs(rootDir, queue);\n\n while (queue.length > 0) {\n const dir = queue.shift()!;\n const type = detectType(dir, scanner);\n\n switch (type) {\n case \"match\":\n results.push(toResult(dir));\n break; // prune subtree\n case \"mismatch\":\n break; // prune subtree\n case \"non-project\":\n enqueueSubdirs(dir, queue);\n break;\n }\n }\n\n return results;\n}\n","import { spawn } from \"node:child_process\";\nimport {\n killTree,\n superviseChild,\n supervisedSpawnOptions,\n} from \"./process-platform.js\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport type { SpawnedHost } from \"@powerhousedao/host-core\";\nimport type {\n CaptureDefinition,\n EndpointType,\n EventBus,\n HostServiceDefinition,\n PreflightContext,\n ReadinessPattern,\n ServiceBuildContext,\n ServiceDefinition,\n ServiceHostRun,\n ServiceInstanceStatus,\n ServiceManager,\n ServiceStartOptions,\n} from \"./types.js\";\nimport { isPortFree } from \"./preflight.js\";\nimport { scanProjects as scanProjectsImpl } from \"./project-scanner.js\";\nimport { slugToTitle } from \"./schema.js\";\n\n/**\n * Resolve the display name for a service definition.\n * Uses `def.name` if provided, otherwise auto-generates from `def.id`.\n */\nexport function resolveServiceName(def: ServiceDefinition<any>): string {\n return def.name ?? slugToTitle(def.id);\n}\n\n/**\n * Identity wrapper for service definitions — provides type checking and IDE support.\n */\nexport function defineService<TConfig = Record<string, unknown>>(\n opts: ServiceDefinition<TConfig>,\n): ServiceDefinition<TConfig> {\n return opts;\n}\n\n/**\n * Persisted state for a service instance on disk. The files outlive the run\n * for the logs lookup, the stopped-instance history (`ps`, the panel's\n * relaunch, `purgeStoppedInstances`) and for spotting leftovers; they are\n * never used to adopt an instance another process started.\n */\ninterface ServiceStateFile {\n serviceId: string;\n instanceId: string;\n name: string;\n pid: number;\n /** The manager that spawned the instance: its process and a token unique\n * to that manager. Only the owner reports the instance as running, stops\n * or restarts it. Absent in state written before ownership was recorded\n * (the detached era), which therefore belongs to no live manager. */\n owner?: { pid: number; token: string };\n status: \"starting\" | \"ready\" | \"failed\" | \"stopped\";\n endpoints?: Record<string, string>;\n endpointTypes?: Record<string, EndpointType>;\n error?: string;\n startedAt: string;\n stoppedAt?: string;\n command: string;\n restartAttempt?: number;\n workdir?: string;\n params?: Record<string, unknown>;\n /** Active log file for the current run, relative to the service dir. */\n logFile?: string;\n}\n\nexport interface ServiceManagerOptions {\n config: Record<string, unknown>;\n servicesDir: string;\n eventBus?: EventBus;\n}\n\n/**\n * Get the directory for a service's instance state files.\n */\nfunction serviceDir(servicesDir: string, serviceId: string): string {\n return path.join(servicesDir, serviceId);\n}\n\n/**\n * NOTE(port): instance ids are `{serviceId}:{name|hash}` — and a COLON in a\n * filename is not a filename on NTFS: it silently writes an Alternate Data\n * Stream (invisible to readdir), so state files vanished on Windows. Encode\n * ids for FILENAMES only; the logical id (parsed on ':' elsewhere, stored\n * inside the state JSON) is untouched.\n */\nfunction fileSafeId(instanceId: string): string {\n return instanceId.replace(/[<>:\"/\\\\|?*]/g, \"+\");\n}\n\nfunction stateFilePath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n return path.join(\n serviceDir(servicesDir, serviceId),\n `${fileSafeId(instanceId)}.json`,\n );\n}\n\n/** Base (run-less) log name, kept as a final fallback for older state. */\nfunction logFilePath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n return path.join(\n serviceDir(servicesDir, serviceId),\n `${fileSafeId(instanceId)}.log`,\n );\n}\n\n/** Number of per-run log files kept per instance. */\nconst MAX_RUN_LOGS = 5;\n\n/** Match a per-run log file for an instance: `<fileSafeId>.<runId>.log`. */\nfunction runLogPattern(instanceId: string): RegExp {\n const safe = fileSafeId(instanceId);\n return new RegExp(\n `^${safe.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\.(\\\\d+)\\\\.log$`,\n );\n}\n\n/** Allocate a fresh per-run log file name for an instance, unique within the dir. */\nfunction newRunLogFile(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n const dir = serviceDir(servicesDir, serviceId);\n const safe = fileSafeId(instanceId);\n let runId = Date.now();\n let name = `${safe}.${runId}.log`;\n while (fs.existsSync(path.join(dir, name))) {\n runId += 1;\n name = `${safe}.${runId}.log`;\n }\n return name;\n}\n\n/** List an instance's per-run log files, newest first by runId. */\nfunction listRunLogs(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string[] {\n const dir = serviceDir(servicesDir, serviceId);\n const re = runLogPattern(instanceId);\n try {\n return fs\n .readdirSync(dir)\n .filter((f) => re.test(f))\n .sort((a, b) => Number(re.exec(b)![1]) - Number(re.exec(a)![1]));\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve the active log path for an instance: the run recorded in the state\n * file, else the newest per-run log, else the base log name.\n */\nfunction activeLogPath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n const dir = serviceDir(servicesDir, serviceId);\n const state = readStateFile(\n stateFilePath(servicesDir, serviceId, instanceId),\n );\n if (state?.logFile && fs.existsSync(path.join(dir, state.logFile))) {\n return path.join(dir, state.logFile);\n }\n const runs = listRunLogs(servicesDir, serviceId, instanceId);\n if (runs.length > 0) return path.join(dir, runs[0]!);\n return logFilePath(servicesDir, serviceId, instanceId);\n}\n\n/** Keep only the newest `MAX_RUN_LOGS` per-run logs for an instance. */\nfunction pruneRunLogs(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): void {\n const dir = serviceDir(servicesDir, serviceId);\n const runs = listRunLogs(servicesDir, serviceId, instanceId);\n for (const f of runs.slice(MAX_RUN_LOGS)) {\n try {\n fs.unlinkSync(path.join(dir, f));\n } catch {\n /* already gone */\n }\n }\n}\n\nconst MAX_LINE_CHARS = 2_000;\nconst MAX_TOTAL_CHARS = 16_000;\n\n/**\n * Strip NUL bytes and non-printable control chars (keeping \\n and \\t), then\n * cap each line and the total length. Keeps the tail when over the total cap,\n * since recent log lines matter most. Guards against truncate-while-open gaps\n * that fill the file with NUL runs containing no newlines.\n */\nexport function sanitizeLogText(\n text: string,\n maxTotal = MAX_TOTAL_CHARS,\n): string {\n // Drop control chars except \\t (\\x09) and \\n (\\x0A); \\x0B-\\x1F covers\n // \\r (\\x0D) so Windows-style \\r\\n logs don't leak carriage returns.\n // eslint-disable-next-line no-control-regex\n const cleaned = text.replace(/[\\x00-\\x08\\x0B-\\x1F\\x7F]/g, \"\");\n const lines = cleaned.split(\"\\n\").map((line) => {\n if (line.length <= MAX_LINE_CHARS) return line;\n const dropped = line.length - MAX_LINE_CHARS;\n return line.slice(0, MAX_LINE_CHARS) + `…[truncated ${dropped} chars]`;\n });\n let out = lines.join(\"\\n\");\n if (out.length > maxTotal) {\n const dropped = out.length - maxTotal;\n out = `…[truncated ${dropped} chars]\\n` + out.slice(out.length - maxTotal);\n }\n return out;\n}\n\n/**\n * Watch a log file for the lines appended from now on. Returns the function\n * that stops watching.\n */\nexport function watchLogFile(\n logPath: string,\n onLine: (line: string) => void,\n): () => void {\n let lastPos = 0;\n\n // Initialize position to end of file\n try {\n const stat = fs.statSync(logPath);\n lastPos = stat.size;\n } catch {\n // File doesn't exist yet\n }\n\n let watcher: fs.FSWatcher;\n try {\n watcher = fs.watch(logPath, () => {\n try {\n // Read as a Buffer and slice by byte offset: lastPos is seeded from\n // stat.size (bytes), so slicing the decoded string by char index\n // would drift on any multi-byte UTF-8 content and drop new lines.\n const buf = fs.readFileSync(logPath);\n // File shrank (truncated/rotated) — re-read from the start.\n if (buf.length < lastPos) lastPos = 0;\n const newContent = buf.toString(\"utf-8\", lastPos);\n lastPos = buf.length;\n if (newContent) {\n const lines = newContent.split(\"\\n\").filter((l) => l.length > 0);\n for (const line of lines) {\n onLine(line);\n }\n }\n } catch {\n // File might have been removed\n }\n });\n } catch {\n onLine(\"Log file not found\");\n return () => {};\n }\n\n return () => {\n watcher.close();\n };\n}\n\n/**\n * Read the last N lines from a log file, returning an empty string if unavailable.\n */\nfunction tailLogFile(filePath: string, lines = 20): string {\n try {\n const content = fs.readFileSync(filePath, \"utf-8\");\n const allLines = sanitizeLogText(content)\n .split(\"\\n\")\n .filter((l) => l.length > 0);\n return allLines.slice(-lines).join(\"\\n\");\n } catch {\n return \"\";\n }\n}\n\nfunction readStateFile(filePath: string): ServiceStateFile | null {\n try {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n return JSON.parse(raw) as ServiceStateFile;\n } catch {\n return null;\n }\n}\n\nfunction writeStateFile(filePath: string, state: ServiceStateFile): void {\n fs.writeFileSync(filePath, JSON.stringify(state, null, 2));\n}\n\nfunction removeStateFile(filePath: string): void {\n try {\n fs.unlinkSync(filePath);\n } catch {\n // Already gone\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Whether the manager that spawned a recorded instance is still running. */\nfunction isOwnerAlive(state: ServiceStateFile): boolean {\n return state.owner !== undefined && isPidAlive(state.owner.pid);\n}\n\n/** Whether a recorded instance's process is still running. */\nfunction isInstanceAlive(state: ServiceStateFile): boolean {\n return state.pid > 0 && isPidAlive(state.pid);\n}\n\n/**\n * Why a live instance this manager did not spawn is not its to manage: it\n * belongs to another running process, or it is a leftover whose owner is\n * gone. Either way it is never adopted, stopped or restarted from here (a\n * recorded pid can also have been reused by an unrelated process).\n */\nfunction notOursMessage(state: ServiceStateFile): string {\n const where = `${state.serviceId} (${state.instanceId}, pid ${state.pid})`;\n if (state.owner && isOwnerAlive(state)) {\n return `${where} belongs to process ${state.owner.pid}, which is still running; this process does not manage it. Stop it there.`;\n }\n const by = state.owner\n ? `process ${state.owner.pid}, which has exited`\n : \"an earlier run\";\n return `${where} is a leftover from ${by}; this process does not manage it. End pid ${state.pid} by hand if it is the old service.`;\n}\n\n// isPortFree is imported from ./preflight.js\n\n/**\n * Wait for a PID to exit, polling with kill(pid, 0).\n * Returns true if the process exited, false on timeout.\n */\nfunction waitForExit(\n pid: number,\n timeout: number,\n interval = 100,\n): Promise<boolean> {\n return new Promise((resolve) => {\n const deadline = Date.now() + timeout;\n const check = () => {\n if (!isPidAlive(pid)) {\n resolve(true);\n return;\n }\n if (Date.now() >= deadline) {\n resolve(false);\n return;\n }\n setTimeout(check, interval);\n };\n check();\n });\n}\n\n/**\n * Generate an instance ID from start options.\n * - Default (no name, no workdir) → serviceId\n * - Named → serviceId:name\n * - Workdir-derived → serviceId:hash8\n */\nfunction resolveInstanceId(\n serviceId: string,\n opts?: ServiceStartOptions,\n): string {\n if (opts?.name) return `${serviceId}:${opts.name}`;\n if (opts?.workdir) {\n const hash = crypto\n .createHash(\"sha256\")\n .update(opts.workdir)\n .digest(\"hex\")\n .slice(0, 8);\n return `${serviceId}:${hash}`;\n }\n return serviceId;\n}\n\n/**\n * Resolve a service command — supports static string or dynamic function. A\n * host service's is its `ph run` line, as the state file and preflight show\n * it.\n */\nfunction resolveCommand(\n def: ServiceDefinition<any>,\n ctx: ServiceBuildContext,\n): string {\n if (def.run) return hostCommandLine(def.run);\n return typeof def.command === \"function\" ? def.command(ctx) : def.command;\n}\n\n/** The `ph run` a host service is. */\nexport function hostCommandLine(run: ServiceHostRun): string {\n return [\n \"ph\",\n \"run\",\n run.host,\n ...(run.verb === undefined ? [] : [run.verb]),\n ...(run.argv?.length ? [\"--\", ...run.argv] : []),\n ].join(\" \");\n}\n\n/** A definition with both or neither of `command` and `run` (an untyped one). */\nfunction assertOneForm(def: ServiceDefinition<any>): void {\n const forms = [def.command !== undefined, def.run !== undefined];\n if (forms.filter(Boolean).length !== 1) {\n throw new Error(\n `Service ${def.id}: give it a command or a host run (run), not ${forms[0] ? \"both\" : \"neither\"}.`,\n );\n }\n}\n\n/** The failure a start reports: what went wrong, where, and the log's end. */\nfunction startFailure(\n id: string,\n error: string,\n cwd: string | undefined,\n command: string,\n tail: string,\n): Error {\n const lines = [error, \"\", ` workdir: ${cwd}`, ` command: ${command}`];\n if (tail) {\n lines.push(\"\", \" Recent log output:\");\n lines.push(...tail.split(\"\\n\").map((l) => \" \" + l));\n }\n lines.push(\"\", ` Check the workdir and run '${id}-logs' for the full log.`);\n return new Error(lines.join(\"\\n\"));\n}\n\n/**\n * Scan a service's instance directory for all state files.\n */\nfunction scanInstances(\n servicesDir: string,\n serviceId: string,\n): ServiceStateFile[] {\n const dir = serviceDir(servicesDir, serviceId);\n try {\n return fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(\".json\"))\n .map((f) => readStateFile(path.join(dir, f)))\n .filter((s): s is ServiceStateFile => s !== null);\n } catch {\n return [];\n }\n}\n\n/**\n * Strip the `.<runId>.log` or `.log` suffix from a log file name to get its\n * instance ID. The runId is a `Date.now()` millisecond timestamp (see\n * newRunLogFile), so we only treat a timestamp-width digit run (>=10) as a\n * runId — otherwise a legacy `<instanceId>.log` whose instance name ends in\n * `.<digits>` (e.g. `svc:agent.1`) would have that suffix wrongly stripped.\n */\nfunction instanceIdFromLogFile(name: string): string {\n return name.replace(/(?:\\.\\d{10,})?\\.log$/, \"\");\n}\n\n/**\n * Find the instance ID of the most recently modified .log file in a service directory.\n * Used as a fallback when no .json state files exist (e.g. after stop).\n */\nfunction mostRecentLogInstance(\n servicesDir: string,\n serviceId: string,\n): string | undefined {\n const dir = serviceDir(servicesDir, serviceId);\n try {\n const logFiles = fs.readdirSync(dir).filter((f) => f.endsWith(\".log\"));\n if (logFiles.length === 0) return undefined;\n let best: { name: string; mtime: number } | undefined;\n for (const f of logFiles) {\n const stat = fs.statSync(path.join(dir, f));\n if (!best || stat.mtimeMs > best.mtime) {\n best = { name: f, mtime: stat.mtimeMs };\n }\n }\n return best ? instanceIdFromLogFile(best.name) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Create a ServiceManager for long-running services. Every instance is a\n * child of this process: spawned attached, stopped by `stopAll()` (the CLI\n * runtime's teardown) and, failing that, felled when the process ends (see\n * process-platform.ts). The manager reports, stops and restarts only the\n * instances it spawned itself; state left by another process is never\n * adopted (see `foreignStatus`).\n */\nexport function createServiceManager(\n definitions: ServiceDefinition<any>[],\n opts: ServiceManagerOptions,\n): ServiceManager {\n const { config, servicesDir, eventBus } = opts;\n const defMap = new Map<string, ServiceDefinition<any>>();\n for (const def of definitions) {\n defMap.set(def.id, def);\n }\n\n /** This manager's identity in the state files it writes. */\n const owner = { pid: process.pid, token: crypto.randomUUID() };\n const isMine = (state: ServiceStateFile) =>\n state.owner?.token === owner.token;\n /** Set while `stopAll()` runs: no start or restart may begin. */\n let closing = false;\n /** State paths of instances being stopped: never restarted meanwhile. */\n const stopping = new Set<string>();\n /** Pending restart-policy timers, cancelled by `stopAll()`. */\n const restartTimers = new Set<NodeJS.Timeout>();\n /** Host services' runs by state path, from ready until they exit. */\n const hostRuns = new Map<string, SpawnedHost>();\n /** Host services waiting for their run record, by state path: a stop\n * aborts the wait and awaits `settled`. */\n const hostStarts = new Map<\n string,\n { abort: AbortController; settled: Promise<unknown> }\n >();\n\n /**\n * The status of a recorded instance this manager did not spawn. One whose\n * process is gone reads as stopped (and, when its owner is gone too, the\n * stale state is settled as stopped on disk); one still alive reads as\n * failed with the reason, so it never counts as running here.\n */\n function foreignStatus(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n ): ServiceInstanceStatus {\n if (!isInstanceAlive(state)) {\n if (!isOwnerAlive(state)) {\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt ??= new Date().toISOString();\n writeStateFile(\n stateFilePath(servicesDir, def.id, state.instanceId),\n state,\n );\n }\n return {\n serviceId: def.id,\n instanceId: state.instanceId,\n name: state.name,\n status: \"stopped\",\n workdir: state.workdir,\n params: state.params,\n };\n }\n return {\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"failed\",\n pid: state.pid,\n error: notOursMessage(state),\n workdir: state.workdir,\n params: state.params,\n };\n }\n\n function ensureServiceDir(serviceId: string): void {\n fs.mkdirSync(serviceDir(servicesDir, serviceId), { recursive: true });\n }\n\n function buildContext(params?: Record<string, unknown>): ServiceBuildContext {\n return { params, config };\n }\n\n async function start(\n id: string,\n startOpts?: ServiceStartOptions,\n ): Promise<string> {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n assertOneForm(def);\n\n const instanceId = resolveInstanceId(id, startOpts);\n const maxInstances = def.maxInstances ?? 1;\n\n // A host run has no pid until its record is live.\n if (hostStarts.has(stateFilePath(servicesDir, id, instanceId))) {\n throw new Error(`Service ${id} is already starting`);\n }\n\n // Check if this specific instance is already running\n const existingState = readStateFile(\n stateFilePath(servicesDir, id, instanceId),\n );\n if (existingState && existingState.status === \"stopped\") {\n // Clean up stopped state — we're restarting this instance\n removeStateFile(stateFilePath(servicesDir, id, instanceId));\n } else if (existingState && isInstanceAlive(existingState)) {\n // Another process's instance (or a leftover) is never adopted, and\n // a second copy would fight it for its port: refuse.\n if (!isMine(existingState)) {\n throw new Error(`Service ${id}: ${notOursMessage(existingState)}`);\n }\n if (\n existingState.status === \"ready\" ||\n existingState.status === \"starting\"\n ) {\n throw new Error(\n `Service ${id} is already running (pid ${existingState.pid})`,\n );\n }\n }\n\n // Check maxInstances limit among this manager's running instances\n const running = scanInstances(servicesDir, id).filter(\n (s) =>\n s.instanceId !== instanceId &&\n s.status !== \"stopped\" &&\n isMine(s) &&\n (isInstanceAlive(s) ||\n hostStarts.has(stateFilePath(servicesDir, id, s.instanceId))),\n );\n if (running.length >= maxInstances) {\n throw new Error(\n `Service ${id} has reached max instances (${maxInstances})`,\n );\n }\n\n ensureServiceDir(id);\n\n const params = startOpts?.params;\n const buildCtx = buildContext(params);\n const commandStr = resolveCommand(def, buildCtx);\n const spawnCwd = startOpts?.cwd ?? startOpts?.workdir;\n\n // Run preflight checks before any side effects (log file, state file, spawn)\n if (def.preflight?.length) {\n const preflightCtx: PreflightContext = {\n cwd: spawnCwd ?? process.cwd(),\n config,\n params,\n command: commandStr,\n };\n for (const check of def.preflight) {\n const result = await check(preflightCtx);\n if (!result.ok) {\n const parts = [`${resolveServiceName(def)}: ${result.message}`];\n if (result.hint) parts.push(` Hint: ${result.hint}`);\n throw new Error(parts.join(\"\\n\"));\n }\n }\n }\n\n // stopAll() is running: nothing new may start (it would outlive the\n // teardown). Checked right before the spawn, after the awaits above.\n if (closing) {\n throw new Error(`Service ${id}: the service manager is stopping`);\n }\n\n // Fresh log file per start, so a late write from a dying child can't\n // corrupt the new run's log. Prune older runs to bound accumulation.\n const logFile = newRunLogFile(servicesDir, id, instanceId);\n const logPath = path.join(serviceDir(servicesDir, id), logFile);\n const logFd = fs.openSync(logPath, \"w\");\n pruneRunLogs(servicesDir, id, instanceId);\n\n // A supervisor's stdin rule is this process's: the child gets no stdin,\n // and under PH_STOP_ON_STDIN a `ph run` would take that as a stop.\n const inherited: NodeJS.ProcessEnv = { ...process.env };\n delete inherited.PH_STOP_ON_STDIN;\n // A restart attempt counts only within this manager's own lifetime.\n const restartAttempt =\n existingState && isMine(existingState)\n ? (existingState.restartAttempt ?? 0)\n : 0;\n\n if (def.run) {\n // spawnHost appends to the log itself.\n fs.closeSync(logFd);\n return startHost(def, {\n instanceId,\n cwd: spawnCwd ?? process.cwd(),\n workdir: startOpts?.workdir,\n params,\n command: commandStr,\n logFile,\n logPath,\n baseEnv: inherited,\n env: { ...def.run.env, ...(def.env ? def.env(buildCtx) : {}) },\n restartAttempt,\n });\n }\n\n const env = { ...inherited, ...(def.env ? def.env(buildCtx) : {}) };\n\n const child = spawn(commandStr, {\n shell: true,\n // Attached and hidden: the child belongs to this process and ends\n // with it at the latest (see process-platform.ts).\n ...supervisedSpawnOptions(),\n stdio: [\"ignore\", logFd, logFd],\n env,\n cwd: spawnCwd,\n });\n superviseChild(child);\n\n // The child does not keep this process alive; stopAll() or the\n // supervision exit hook ends it.\n child.unref();\n fs.closeSync(logFd);\n\n const pid = child.pid!;\n\n // Write initial state\n const state: ServiceStateFile = {\n serviceId: id,\n instanceId,\n name: resolveServiceName(def),\n pid,\n owner,\n status: \"starting\",\n startedAt: new Date().toISOString(),\n command: commandStr,\n restartAttempt,\n workdir: startOpts?.workdir,\n params,\n logFile,\n };\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n\n // Handle early exit (unreachable with shell: true — the shell always spawns)\n /* istanbul ignore next -- defensive guard */\n child.on(\"error\", () => {\n state.status = \"failed\";\n state.error = \"Failed to spawn process\";\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n eventBus?.emit(\"service:failed\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n error: state.error,\n });\n });\n\n // If no readiness or wait === false, mark ready immediately\n if (!def.readiness || def.readiness.wait === false) {\n state.status = \"ready\";\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n eventBus?.emit(\"service:ready\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n endpoints: state.endpoints,\n });\n return instanceId;\n }\n\n // Normalize to a list of named patterns\n const readinessPatterns: ReadinessPattern[] = def.readiness.patterns\n ? def.readiness.patterns\n : [\n {\n name: \"_default\",\n pattern: def.readiness.pattern!,\n captures: def.readiness.captures,\n },\n ];\n\n const { timeout } = def.readiness;\n const startTime = Date.now();\n let lastPos = 0;\n const matched = new Set<string>();\n state.endpoints = {};\n state.endpointTypes = {};\n\n await new Promise<void>((resolve, reject) => {\n const pollInterval = setInterval(() => {\n // Check if process is still alive\n if (!isPidAlive(pid)) {\n clearInterval(pollInterval);\n state.status = \"failed\";\n state.error = \"Process exited before becoming ready\";\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n eventBus?.emit(\"service:failed\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n error: state.error,\n });\n reject(\n startFailure(\n id,\n state.error,\n spawnCwd,\n commandStr,\n tailLogFile(logPath),\n ),\n );\n return;\n }\n\n // Read new content from log\n try {\n const logContent = fs.readFileSync(logPath, \"utf-8\");\n const newContent = logContent.slice(lastPos);\n lastPos = logContent.length;\n\n if (newContent) {\n for (const rp of readinessPatterns) {\n if (matched.has(rp.name)) continue;\n const match = rp.pattern.exec(newContent);\n if (match) {\n matched.add(rp.name);\n // Extract captures as endpoints (supports number or CaptureDefinition)\n if (rp.captures) {\n for (const [name, captureDef] of Object.entries(\n rp.captures,\n )) {\n const groupIdx =\n typeof captureDef === \"number\"\n ? captureDef\n : captureDef.group;\n if (match[groupIdx]) {\n state.endpoints![name] = match[groupIdx]!;\n // Store endpoint type if provided via CaptureDefinition\n if (typeof captureDef !== \"number\" && captureDef.type) {\n state.endpointTypes![name] = captureDef.type;\n }\n }\n }\n }\n eventBus?.emit(\"service:pattern-matched\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n patternName: rp.name,\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n remaining: readinessPatterns.length - matched.size,\n });\n }\n }\n\n // All patterns matched → service is ready\n if (matched.size === readinessPatterns.length) {\n clearInterval(pollInterval);\n state.status = \"ready\";\n state.restartAttempt = 0;\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n eventBus?.emit(\"service:ready\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n });\n resolve();\n return;\n }\n }\n } catch {\n // Log file might not exist yet\n }\n\n // Check timeout\n if (Date.now() - startTime > timeout) {\n clearInterval(pollInterval);\n // Kill the process on timeout\n try {\n killTree(pid, \"SIGKILL\");\n } catch {\n // Already dead\n }\n const unmatched = readinessPatterns\n .filter((rp) => !matched.has(rp.name))\n .map((rp) => rp.name);\n state.status = \"failed\";\n state.error = `Readiness timeout exceeded (unmatched: ${unmatched.join(\", \")})`;\n writeStateFile(stateFilePath(servicesDir, id, instanceId), state);\n eventBus?.emit(\"service:failed\", {\n id,\n instanceId,\n name: resolveServiceName(def),\n error: state.error,\n });\n reject(\n startFailure(\n id,\n state.error,\n spawnCwd,\n commandStr,\n tailLogFile(logPath),\n ),\n );\n }\n }, 100);\n });\n\n return instanceId;\n }\n\n /**\n * Starts a host service: `spawnHost` in the project, stopped through its\n * stdin. Ready when its run record is live, with the endpoints the\n * definition reads from the record. A stop while it waits aborts the wait.\n */\n async function startHost(\n def: HostServiceDefinition<any>,\n run: {\n instanceId: string;\n cwd: string;\n workdir?: string;\n params?: Record<string, unknown>;\n command: string;\n logFile: string;\n logPath: string;\n baseEnv: NodeJS.ProcessEnv;\n env: Record<string, string>;\n restartAttempt: number;\n },\n ): Promise<string> {\n const { id } = def;\n const { instanceId } = run;\n const name = resolveServiceName(def);\n const statePath = stateFilePath(servicesDir, id, instanceId);\n const state: ServiceStateFile = {\n serviceId: id,\n instanceId,\n name,\n pid: 0,\n owner,\n status: \"starting\",\n startedAt: new Date().toISOString(),\n command: run.command,\n restartAttempt: run.restartAttempt,\n workdir: run.workdir,\n params: run.params,\n logFile: run.logFile,\n };\n writeStateFile(statePath, state);\n\n const fail = (error: string): Error => {\n state.status = \"failed\";\n state.error = error;\n writeStateFile(statePath, state);\n eventBus?.emit(\"service:failed\", { id, instanceId, name, error });\n return startFailure(\n id,\n error,\n run.cwd,\n run.command,\n tailLogFile(run.logPath),\n );\n };\n\n const abort = new AbortController();\n const spawning = (async () => {\n const { spawnHost } = await import(\"@powerhousedao/host-core\");\n return spawnHost({\n projectRoot: run.cwd,\n dataDir: run.cwd,\n host: def.run.host,\n ...(def.run.verb === undefined ? {} : { verb: def.run.verb }),\n ...(def.run.argv ? { argv: def.run.argv } : {}),\n env: run.env,\n baseEnv: run.baseEnv,\n stopOnStdin: true,\n logFile: run.logPath,\n ...(def.readiness ? { readyTimeoutMs: def.readiness.timeout } : {}),\n ...(def.shutdown ? { stopTimeoutMs: def.shutdown.timeout } : {}),\n signal: abort.signal,\n });\n })();\n hostStarts.set(statePath, {\n abort,\n settled: spawning.catch(() => undefined),\n });\n\n let spawned: SpawnedHost;\n try {\n spawned = await spawning;\n } catch (error) {\n hostStarts.delete(statePath);\n if (abort.signal.aborted) {\n state.status = \"stopped\";\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n eventBus?.emit(\"service:stopped\", { id, instanceId, name });\n throw new Error(`Service ${id} was stopped before it was ready`);\n }\n const message = error instanceof Error ? error.message : String(error);\n // The tail follows from the log; the error carries its own copy.\n throw fail(message.split(\"\\n--- output tail ---\\n\")[0]!);\n }\n hostStarts.delete(statePath);\n\n let endpoints: Record<string, { url: string; type?: EndpointType }>;\n try {\n endpoints = def.endpoints?.(spawned.record) ?? {};\n } catch (error) {\n await spawned.stop();\n const message = error instanceof Error ? error.message : String(error);\n throw fail(\n `Reading its endpoints from the run record failed: ${message}`,\n );\n }\n\n state.pid = spawned.pid;\n state.status = \"ready\";\n state.restartAttempt = 0;\n state.endpoints = {};\n state.endpointTypes = {};\n for (const [key, endpoint] of Object.entries(endpoints)) {\n state.endpoints[key] = endpoint.url;\n if (endpoint.type) state.endpointTypes[key] = endpoint.type;\n }\n writeStateFile(statePath, state);\n hostRuns.set(statePath, spawned);\n void spawned.exited.then(() => {\n if (hostRuns.get(statePath) === spawned) hostRuns.delete(statePath);\n });\n eventBus?.emit(\"service:ready\", {\n id,\n instanceId,\n name,\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n });\n return instanceId;\n }\n\n /**\n * Force-kill a process tree with SIGKILL, then wait for it to exit.\n */\n /* istanbul ignore next -- force-kill path requires processes that resist SIGTERM */\n async function forceKill(pid: number): Promise<void> {\n killTree(pid, \"SIGKILL\");\n await waitForExit(pid, 2_000);\n }\n\n async function stopInstance(\n def: ServiceDefinition<any>,\n serviceId: string,\n instanceId: string,\n ): Promise<void> {\n const statePath = stateFilePath(servicesDir, serviceId, instanceId);\n // A host run still waiting for its record: abort the wait, which stops\n // it and settles its state.\n const starting = hostStarts.get(statePath);\n if (starting) {\n starting.abort.abort();\n await starting.settled;\n return;\n }\n const state = readStateFile(statePath);\n if (!state || !state.pid) {\n // If it's a stopped state file, it's already stopped\n if (state?.status === \"stopped\") return;\n throw new Error(`Service ${serviceId} is not running`);\n }\n\n if (!isMine(state)) {\n // Never kill a process this manager did not spawn: settle stale state\n // (as list() does) or refuse.\n if (foreignStatus(def, state).status === \"stopped\") return;\n throw new Error(`Service ${serviceId}: ${notOursMessage(state)}`);\n }\n\n if (!isPidAlive(state.pid)) {\n // Process already dead — persist as stopped\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n return;\n }\n\n // A host run ends through its stdin; its tree is killed only after the\n // stop timeout (see spawnHost).\n const hostRun = hostRuns.get(statePath);\n if (hostRun) {\n stopping.add(statePath);\n try {\n await hostRun.stop();\n hostRuns.delete(statePath);\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n } finally {\n stopping.delete(statePath);\n }\n eventBus?.emit(\"service:stopped\", {\n id: serviceId,\n instanceId,\n name: resolveServiceName(def),\n });\n return;\n }\n\n const signal = (def.run ? undefined : def.shutdown?.signal) ?? \"SIGTERM\";\n const timeout = def.shutdown?.timeout ?? 5_000;\n\n // Until the stopped state is on disk, list() reports the instance as\n // stopping and its restart policy cannot bring it back.\n stopping.add(statePath);\n try {\n killTree(state.pid, signal);\n\n const exited = await waitForExit(state.pid, timeout);\n\n if (!exited) {\n await forceKill(state.pid);\n }\n\n // Verify port release if endpoints had ports\n if (state.endpoints?.port) {\n const port = parseInt(state.endpoints.port, 10);\n if (!isNaN(port)) {\n // Wait briefly for port to be released\n let portFree = false;\n for (let i = 0; i < 10; i++) {\n portFree = await isPortFree(port);\n if (portFree) break;\n await new Promise((r) => setTimeout(r, 100));\n }\n }\n }\n\n // Persist stopped state instead of removing\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n } finally {\n stopping.delete(statePath);\n }\n eventBus?.emit(\"service:stopped\", {\n id: serviceId,\n instanceId,\n name: resolveServiceName(def),\n });\n }\n\n async function stop(id: string, instanceId?: string): Promise<void> {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n\n if (instanceId) {\n return stopInstance(def, id, instanceId);\n }\n\n // Stop all of this manager's instances of this service\n const instances = scanInstances(servicesDir, id);\n if (instances.length === 0) {\n throw new Error(`Service ${id} is not running`);\n }\n\n const mine = instances.filter((s) => s.status !== \"stopped\" && isMine(s));\n if (mine.length === 0) {\n // Nothing of ours: a live instance of another process is refused by\n // name; stopped history (or stale state) leaves nothing to do.\n const theirs = instances.find(\n (s) => s.status !== \"stopped\" && isInstanceAlive(s),\n );\n if (theirs) throw new Error(`Service ${id}: ${notOursMessage(theirs)}`);\n return;\n }\n\n for (const inst of mine) {\n try {\n await stopInstance(def, id, inst.instanceId);\n } catch {\n // Instance may already be dead\n }\n }\n }\n\n /** Stop every instance this manager started, gracefully (each service's\n * shutdown signal and timeout), and cancel pending restarts. Nothing\n * starts while it runs. */\n async function stopAll(): Promise<void> {\n closing = true;\n for (const timer of restartTimers) clearTimeout(timer);\n restartTimers.clear();\n try {\n for (const def of definitions) {\n for (const state of scanInstances(servicesDir, def.id)) {\n if (state.status === \"stopped\" || !isMine(state)) continue;\n try {\n await stopInstance(def, def.id, state.instanceId);\n } catch {\n // already gone\n }\n }\n }\n } finally {\n closing = false;\n }\n }\n\n function list(serviceId?: string): ServiceInstanceStatus[] {\n const results: ServiceInstanceStatus[] = [];\n const defs = serviceId\n ? ([defMap.get(serviceId)].filter(Boolean) as ServiceDefinition<any>[])\n : definitions;\n\n for (const def of defs) {\n const instances = scanInstances(servicesDir, def.id);\n\n if (instances.length === 0) {\n // No instances — show idle placeholder\n results.push({\n serviceId: def.id,\n instanceId: def.id,\n name: resolveServiceName(def),\n status: \"idle\",\n });\n continue;\n }\n\n for (const state of instances) {\n // Stopped instances are shown as-is\n if (state.status === \"stopped\") {\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: state.name,\n status: \"stopped\",\n workdir: state.workdir,\n params: state.params,\n });\n continue;\n }\n\n // Another process's instance, or a leftover: never adopted.\n if (!isMine(state)) {\n results.push(foreignStatus(def, state));\n continue;\n }\n\n const statePath = stateFilePath(servicesDir, def.id, state.instanceId);\n // A host run has no pid while it waits for its record.\n if (hostStarts.has(statePath)) {\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"starting\",\n params: state.params,\n workdir: state.workdir,\n });\n continue;\n }\n if (stopping.has(statePath)) {\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"stopping\",\n pid: state.pid,\n params: state.params,\n workdir: state.workdir,\n });\n continue;\n }\n\n // Verify PID is alive (pid <= 0 means not yet spawned — treat as dead)\n if (!state.pid || !isPidAlive(state.pid)) {\n // Process died — check restart policy (never while stopAll runs)\n if (\n !closing &&\n def.restart?.enabled &&\n (state.restartAttempt ?? 0) < def.restart.maxRetries &&\n state.status === \"ready\"\n ) {\n // Mark for restart (async, don't block list())\n const attempt = (state.restartAttempt ?? 0) + 1;\n eventBus?.emit(\"service:restarting\", {\n id: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n attempt,\n maxRetries: def.restart.maxRetries,\n });\n\n // Update state file with incremented attempt\n state.status = \"starting\";\n state.restartAttempt = attempt;\n writeStateFile(statePath, state);\n\n // Trigger async restart after delay — recover params from state\n const restartParams = state.params;\n const restartWorkdir = state.workdir;\n const restartName = state.instanceId.includes(\":\")\n ? state.instanceId.split(\":\")[1]\n : undefined;\n const timer = setTimeout(async () => {\n restartTimers.delete(timer);\n try {\n removeStateFile(statePath);\n // Write a temp state so start() knows the attempt count\n ensureServiceDir(def.id);\n const commandStr = resolveCommand(\n def,\n buildContext(restartParams),\n );\n const tempState: ServiceStateFile = {\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n pid: 0,\n owner,\n status: \"failed\",\n startedAt: new Date().toISOString(),\n command: commandStr,\n restartAttempt: attempt,\n params: restartParams,\n workdir: restartWorkdir,\n };\n writeStateFile(statePath, tempState);\n await start(def.id, {\n params: restartParams,\n workdir: restartWorkdir,\n name: restartName,\n });\n } catch {\n // Restart failed — dir may have been removed (test teardown)\n }\n }, def.restart.delay);\n restartTimers.add(timer);\n\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"starting\",\n restartAttempt: attempt,\n params: state.params,\n workdir: state.workdir,\n });\n } else {\n // No restart or max retries exceeded\n const isFailed =\n state.status === \"failed\" ||\n (def.restart?.enabled &&\n (state.restartAttempt ?? 0) >= def.restart.maxRetries);\n if (\n def.restart?.enabled &&\n (state.restartAttempt ?? 0) >= def.restart.maxRetries\n ) {\n eventBus?.emit(\"service:failed\", {\n id: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n error: \"Max restart retries exceeded\",\n });\n }\n\n if (isFailed) {\n // Keep as failed (readiness error or max retries) — remove state file\n removeStateFile(statePath);\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"failed\",\n error: state.error ?? \"Process exited unexpectedly\",\n restartAttempt: state.restartAttempt,\n });\n } else {\n // Was running/starting but died — persist as stopped for re-launch\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: state.name,\n status: \"stopped\",\n workdir: state.workdir,\n params: state.params,\n });\n }\n }\n continue;\n }\n\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: state.status as ServiceInstanceStatus[\"status\"],\n pid: state.pid,\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n restartAttempt: state.restartAttempt,\n params: state.params,\n workdir: state.workdir,\n });\n }\n }\n\n return results;\n }\n\n function logs(id: string, instanceId?: string, lines = 50): string {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n\n // Resolve instance ID: if not provided, prefer running instances\n let resolvedInstanceId = instanceId;\n let warning = \"\";\n if (!resolvedInstanceId) {\n const instances = scanInstances(servicesDir, id);\n const running = instances.filter(\n (s) => s.status === \"ready\" || s.status === \"starting\",\n );\n if (running.length === 1) {\n resolvedInstanceId = running[0]!.instanceId;\n } else if (running.length > 1) {\n warning = `⚠ Multiple running instances — showing logs for ${running[0]!.instanceId}. Use --instance to specify: ${running.map((r) => r.instanceId).join(\", \")}\\n`;\n resolvedInstanceId = running[0]!.instanceId;\n } else if (instances.length > 0) {\n // No running instances — fall back to most recent log file or last state file\n resolvedInstanceId =\n mostRecentLogInstance(servicesDir, id) ??\n instances[instances.length - 1]!.instanceId;\n } else {\n // No state files at all — find the most recent .log file by mtime\n resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? id;\n }\n }\n const logPath = activeLogPath(servicesDir, id, resolvedInstanceId);\n\n // Build informational footer showing which instance log was printed\n const instances = instanceId ? null : scanInstances(servicesDir, id);\n const instanceState = instances?.find(\n (s) => s.instanceId === resolvedInstanceId,\n );\n const statusTag = instanceState ? ` [${instanceState.status}]` : \"\";\n const instanceTag =\n resolvedInstanceId !== id ? ` (${resolvedInstanceId})` : \"\";\n const workdirLine = instanceState?.workdir\n ? `\\n (dir: ${instanceState.workdir})`\n : \"\";\n const footer = `\\n— ${resolveServiceName(def)}${instanceTag}${statusTag} log${workdirLine}`;\n\n try {\n const content = fs.readFileSync(logPath, \"utf-8\");\n const allLines = sanitizeLogText(content).split(\"\\n\");\n const body = sanitizeLogText(allLines.slice(-lines).join(\"\\n\"));\n return warning + body + footer;\n } catch {\n return warning;\n }\n }\n\n function watchLogs(\n id: string,\n instanceId: string,\n onLine: (line: string) => void,\n ): () => void {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n\n return watchLogFile(activeLogPath(servicesDir, id, instanceId), onLine);\n }\n\n function getDefinition(id: string): ServiceDefinition<any> | undefined {\n return defMap.get(id);\n }\n\n function scanProjectsForService(id: string, rootDir: string) {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n if (!def.projectScanner) return [];\n return scanProjectsImpl(rootDir, def.projectScanner);\n }\n\n function purgeStoppedInstances(id: string): void {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n const instances = scanInstances(servicesDir, id);\n for (const state of instances) {\n if (state.status === \"stopped\") {\n const statePath = stateFilePath(servicesDir, id, state.instanceId);\n removeStateFile(statePath);\n // Remove the base log and every per-run log for this instance.\n const dir = serviceDir(servicesDir, id);\n try {\n fs.unlinkSync(logFilePath(servicesDir, id, state.instanceId));\n } catch {\n /* Already gone */\n }\n for (const f of listRunLogs(servicesDir, id, state.instanceId)) {\n try {\n fs.unlinkSync(path.join(dir, f));\n } catch {\n /* Already gone */\n }\n }\n }\n }\n }\n\n // Process-based services don't emit structured chunks — no-op subscriber.\n function watchChunks(\n _id: string,\n _instanceId: string,\n _onChunk: (chunk: import(\"./types.js\").StreamChunk) => void,\n ): () => void {\n const def = defMap.get(_id);\n if (!def) throw new Error(`Unknown service: ${_id}`);\n return () => {};\n }\n\n return {\n start,\n stop,\n stopAll,\n list,\n getDefinition,\n logs,\n watchLogs,\n watchChunks,\n scanProjects: scanProjectsForService,\n purgeStoppedInstances,\n };\n}\n","import { z } from \"zod\";\nimport type { Command } from \"../core/types.js\";\nimport { getSchemaFields } from \"../core/schema.js\";\nimport type { FieldInfo } from \"../core/schema.js\";\n\n/**\n * Tokenize input respecting quotes, and report whether the cursor is inside\n * an open quote (meaning we should not offer completions).\n */\nfunction tokenizeInput(input: string): {\n tokens: string[];\n inQuote: boolean;\n trailingSpace: boolean;\n} {\n const tokens: string[] = [];\n let current = \"\";\n let inQuote = false;\n let quoteChar = \"\";\n\n for (const ch of input) {\n if (inQuote) {\n if (ch === quoteChar) {\n inQuote = false;\n } else {\n current += ch;\n }\n } else if (ch === '\"' || ch === \"'\") {\n inQuote = true;\n quoteChar = ch;\n } else if (ch === \" \" || ch === \"\\t\") {\n if (current) {\n tokens.push(current);\n current = \"\";\n }\n } else {\n current += ch;\n }\n }\n if (current) tokens.push(current);\n\n const trailingSpace =\n !inQuote &&\n input.length > 0 &&\n (input[input.length - 1] === \" \" || input[input.length - 1] === \"\\t\");\n return { tokens, inQuote, trailingSpace };\n}\n\n/**\n * Collect flag names already present in the tokens.\n */\nfunction usedFlags(tokens: string[]): Set<string> {\n const used = new Set<string>();\n for (const t of tokens) {\n if (t.startsWith(\"--\")) used.add(t);\n }\n return used;\n}\n\n/**\n * Get auto-completion suggestions for partial REPL input.\n *\n * Supports:\n * - Command name completion: `/gr` → ['/greet']\n * - Flag name completion: `/add --` → ['--title', '--priority', '--due']\n * - Flag name after trailing space: `/add ` → ['--title', '--priority', '--due']\n * - Enum value completion: `/list --filter d` → ['done']\n * - No completions inside quoted strings\n */\nexport function getCompletions(input: string, commands: Command[]): string[] {\n const trimmed = input.trimStart();\n if (!trimmed.startsWith(\"/\")) return [];\n\n const { tokens, inQuote, trailingSpace } = tokenizeInput(trimmed);\n if (tokens.length === 0) return [];\n\n // Don't complete inside quoted strings\n if (inQuote) return [];\n\n // Completing the command name: `/gr` → ['/greet']\n if (tokens.length === 1 && !trailingSpace) {\n const prefix = tokens[0]!.slice(1).toLowerCase();\n const builtins = [\"exit\", \"quit\"];\n const allNames = [...commands.map((c) => c.id), ...builtins];\n return allNames\n .filter((name) => name.toLowerCase().startsWith(prefix))\n .map((name) => `/${name}`);\n }\n\n // Find the command\n const cmdName = tokens[0]!.slice(1).toLowerCase();\n const cmd = commands.find((c) => c.id === cmdName);\n if (!cmd) return [];\n\n const fields = getSchemaFields(cmd.inputSchema);\n const used = usedFlags(tokens);\n\n // Trailing space after input — suggest next possible flags or values\n if (trailingSpace) {\n const lastToken = tokens[tokens.length - 1]!;\n // If the last token is a non-boolean flag, suggest its values\n if (lastToken.startsWith(\"--\")) {\n const fieldName = lastToken.slice(2);\n const field = fields.find((f) => f.key === fieldName);\n if (field && field.baseType !== \"boolean\") {\n return getFieldValueCompletions(cmd, fieldName, \"\");\n }\n }\n // Suggest unused flags\n return fields\n .filter((f) => !used.has(`--${f.key}`))\n .map((f) => `--${f.key}`);\n }\n\n const lastToken = tokens[tokens.length - 1]!;\n const prevToken = tokens.length >= 2 ? tokens[tokens.length - 2]! : \"\";\n\n // If previous token is a non-boolean flag, complete the value\n if (prevToken.startsWith(\"--\")) {\n const fieldName = prevToken.slice(2);\n const field = fields.find((f) => f.key === fieldName);\n if (field && field.baseType !== \"boolean\") {\n return getFieldValueCompletions(cmd, fieldName, lastToken);\n }\n }\n\n // If the current token starts with - or --, complete the flag name\n if (lastToken.startsWith(\"-\")) {\n const prefix = lastToken.startsWith(\"--\")\n ? lastToken.slice(2).toLowerCase()\n : \"\";\n return fields\n .filter(\n (f) =>\n f.key.toLowerCase().startsWith(prefix) && !used.has(`--${f.key}`),\n )\n .map((f) => `--${f.key}`);\n }\n\n return [];\n}\n\n/**\n * Get value completions for an enum field.\n */\nfunction getFieldValueCompletions(\n cmd: Command,\n fieldName: string,\n partial: string,\n): string[] {\n const enumValues = getEnumValues(cmd.inputSchema, fieldName);\n if (!enumValues) return [];\n\n const prefix = partial.toLowerCase();\n return enumValues.filter((v) => v.toLowerCase().startsWith(prefix));\n}\n\n/**\n * Get the suffix to append after a flag completion.\n * Returns ` \"` for non-boolean, non-enum fields (opening a value quote),\n * empty string otherwise.\n */\nexport function getCompletionSuffix(\n completion: string,\n input: string,\n commands: Command[],\n): string {\n if (!completion.startsWith(\"--\")) return \"\";\n\n const trimmed = input.trimStart();\n const { tokens } = tokenizeInput(trimmed);\n const cmdName = tokens[0]?.slice(1).toLowerCase();\n const cmd = commands.find((c) => c.id === cmdName);\n if (!cmd) return \"\";\n\n const fieldName = completion.slice(2);\n const fields = getSchemaFields(cmd.inputSchema);\n const field = fields.find((f) => f.key === fieldName);\n if (!field || field.baseType === \"boolean\") return \"\";\n\n // Enum fields don't need quotes\n const enumValues = getEnumValues(cmd.inputSchema, fieldName);\n if (enumValues) return \" \";\n\n return ' \"';\n}\n\n/**\n * Get the ghost suggestion for the current input — the full input string\n * with the first completion applied, suitable for inline preview.\n *\n * Returns null if no suggestion is available.\n */\nexport function getGhostSuggestion(\n input: string,\n commands: Command[],\n): string | null {\n // Inside an open quote — suggest closing it\n const trimmed = input.trimStart();\n const { inQuote } = tokenizeInput(trimmed);\n if (inQuote) return input + '\"';\n\n const completions = getCompletions(input, commands);\n if (completions.length === 0) return null;\n\n const applied = applyCompletion(input, completions[0]!);\n const suffix = getCompletionSuffix(completions[0]!, input, commands);\n\n return applied + suffix;\n}\n\n/**\n * Apply a completion candidate to the current input by replacing the last token.\n * If the input ends with a trailing space, the completion is appended.\n *\n * For command completions (`/gr` + `/greet` → `/greet`), replaces the only token.\n * For flag completions (`/greet --na` + `--name` → `/greet --name`), replaces the last token.\n * For value completions (`/list --filter d` + `done` → `/list --filter done`), replaces the last token.\n * For trailing space (`/add ` + `--title` → `/add --title`), appends.\n */\nexport function applyCompletion(input: string, completion: string): string {\n const trailingSpace =\n input.length > 0 &&\n (input[input.length - 1] === \" \" || input[input.length - 1] === \"\\t\");\n if (trailingSpace) return input + completion;\n const lastSpaceIdx = input.lastIndexOf(\" \");\n if (lastSpaceIdx === -1) return completion;\n return input.slice(0, lastSpaceIdx + 1) + completion;\n}\n\n/**\n * Extract enum values from a Zod schema field, if it's an enum type.\n * Unwraps Default/Optional/Nullable wrappers to find the underlying ZodEnum.\n */\nfunction getEnumValues(schema: z.ZodType, fieldName: string): string[] | null {\n if (!(schema instanceof z.ZodObject)) return null;\n\n let field = (schema.shape as Record<string, z.ZodType>)[fieldName];\n if (!field) return null;\n\n // Unwrap Default/Optional/Nullable wrappers using public Zod v4 API\n const wrapperTypes = new Set([\"default\", \"optional\", \"nullable\"]);\n let current = field as { type: string; def: { innerType?: unknown } };\n while (wrapperTypes.has(current.type) && current.def.innerType) {\n current = current.def.innerType as typeof current;\n field = current as unknown as z.ZodType;\n }\n\n // Check if it's a ZodEnum\n if (field instanceof z.ZodEnum) {\n return field.options as string[];\n }\n\n return null;\n}\n","import { Marked } from \"marked\";\nimport { markedTerminal } from \"marked-terminal\";\nimport { supportsLanguage } from \"cli-highlight\";\n\n// Create a dedicated Marked instance with terminal rendering.\n// This avoids mutating the global marked instance.\nconst marked = new Marked();\nconst terminalExt = markedTerminal() as {\n renderer: Record<string, (...args: unknown[]) => string>;\n useNewRenderer: boolean;\n};\n// marked-terminal bundles highlight.js v10 (via cli-highlight), which does not\n// register `graphql` (and a handful of other langs). When the agent emits a\n// ```graphql fence, the bundled hljs logs \"Could not find the language ...\" to\n// stderr before falling back to plain styling. Strip the lang for any\n// unsupported language so we hit the auto-detect path instead of the noisy\n// explicit-language path.\nconst originalCode = terminalExt.renderer.code;\nterminalExt.renderer.code = function (\n this: unknown,\n ...args: unknown[]\n): string {\n const [first, second, third] = args;\n if (first && typeof first === \"object\") {\n const token = first as { lang?: string };\n if (token.lang && !supportsLanguage(token.lang)) {\n return originalCode.call(this, { ...token, lang: \"\" });\n }\n return originalCode.call(this, first);\n }\n if (typeof second === \"string\" && !supportsLanguage(second)) {\n return originalCode.call(this, first, \"\", third);\n }\n return originalCode.call(this, ...args);\n};\nmarked.use(terminalExt as any);\n// Force all lists to render as \"tight\" (no extra newlines between items).\n// Without this, a single blank line between top-level items makes marked\n// set loose:true on the entire list, causing marked-terminal to add\n// double newlines between ALL items including tight nested ones.\nmarked.use({\n walkTokens(token: { type: string; loose?: boolean }) {\n if (token.type === \"list\" || token.type === \"list_item\") {\n token.loose = false;\n }\n },\n});\n\n/**\n * Render a markdown string for terminal display.\n * Returns ANSI-formatted text suitable for terminal output.\n *\n * For plain text (no markdown), the output is the same as the input\n * (with a trailing newline trimmed).\n */\nexport function renderMarkdown(text: string): string {\n if (!text) return \"\";\n const rendered = marked.parse(text);\n /* istanbul ignore next -- marked.parse() always returns string with sync config */\n if (typeof rendered !== \"string\") {\n return text;\n }\n // marked-terminal inserts whitespace-only lines (with ANSI resets)\n // between list items as separators. Remove these but keep truly empty\n // lines which serve as paragraph breaks.\n const stripAnsi = (s: string) => s.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n return rendered\n .split(\"\\n\")\n .filter((line) => line.length === 0 || stripAnsi(line).trim().length > 0)\n .join(\"\\n\")\n .trimEnd();\n}\n"],"mappings":";;;;;;;;;;;;;AAGA,MAAM,MAAM;AACZ,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,YAAY;;;;;;;;;;AAWlB,SAAgB,kBAAkB,OAA4B;CAC5D,QAAQ,MAAM,MAAd;EACE,KAAK,cACH,OAAO,MAAM;EAEf,KAAK,aACH,OAAO,KAAK,MAAM,UAAU,IAAI,MAAM,WAAW,QAAQ,IAAI,GAAG,aAAa,MAAM,IAAI,EAAE,GAAG,M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