@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.
- package/dist/{build-skills-Bpbbnin0.mjs → build-skills-BTkuL8ne.mjs} +2 -2
- package/dist/{build-skills-Bpbbnin0.mjs.map → build-skills-BTkuL8ne.mjs.map} +1 -1
- package/dist/command-control-Dp41aY0o.mjs +224 -0
- package/dist/command-control-Dp41aY0o.mjs.map +1 -0
- package/dist/{dist-Bd6hUl0J.mjs → dist-BTVqrpN4.mjs} +2 -2
- package/dist/{dist-Bd6hUl0J.mjs.map → dist-BTVqrpN4.mjs.map} +1 -1
- package/dist/{index-CfHcet4v.d.mts → index-DJlqIVLv.d.mts} +13 -10
- package/dist/{index-CfHcet4v.d.mts.map → index-DJlqIVLv.d.mts.map} +1 -1
- package/dist/index.d.mts +227 -8
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -5
- package/dist/integrations/mastra/index.d.mts +20 -3
- package/dist/integrations/mastra/index.d.mts.map +1 -1
- package/dist/integrations/mastra/index.mjs +25 -3
- package/dist/integrations/mastra/index.mjs.map +1 -1
- package/dist/integrations/powerhouse/index.d.mts +3 -3
- package/dist/integrations/powerhouse/index.mjs +1 -1
- package/dist/{markdown-BUeGwhbR.mjs → markdown-B-HyDpvO.mjs} +471 -39
- package/dist/markdown-B-HyDpvO.mjs.map +1 -0
- package/dist/{powerhouse-3XZmdY3_.mjs → powerhouse-C4O-raTW.mjs} +168 -12
- package/dist/powerhouse-C4O-raTW.mjs.map +1 -0
- package/dist/{proxy-ji3EHzLn.mjs → proxy-DgnOKu1A.mjs} +2 -2
- package/dist/proxy-DgnOKu1A.mjs.map +1 -0
- package/dist/remote-reactor-oBsHphPT.mjs.map +1 -1
- package/dist/{repl-Czb7u0x_.mjs → repl-C4gHgy6P.mjs} +2 -2
- package/dist/{repl-Czb7u0x_.mjs.map → repl-C4gHgy6P.mjs.map} +1 -1
- package/dist/runners/cli-runner.d.mts +5 -2
- package/dist/runners/cli-runner.d.mts.map +1 -1
- package/dist/runners/cli-runner.mjs +21 -7
- package/dist/runners/cli-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.mjs +1 -1
- package/dist/runners/proxy-runner.mjs +1 -1
- package/dist/{src-BmMd0Wl4.mjs → src-FF3zDJY7.mjs} +606 -53
- package/dist/src-FF3zDJY7.mjs.map +1 -0
- package/dist/{start-BHn9LIyX.mjs → start-CCegR8Pi.mjs} +2 -2
- package/dist/{start-BHn9LIyX.mjs.map → start-CCegR8Pi.mjs.map} +1 -1
- package/dist/testing/index.d.mts +2 -2
- package/dist/testing/index.mjs +1 -1
- package/dist/{types-3TnDjQ1w.d.mts → types-BnPpIAL6.d.mts} +2 -2
- package/dist/{types-3TnDjQ1w.d.mts.map → types-BnPpIAL6.d.mts.map} +1 -1
- package/dist/{types-DbQKfvWc.d.mts → types-CIZtG2TY.d.mts} +219 -13
- package/dist/types-CIZtG2TY.d.mts.map +1 -0
- package/package.json +13 -13
- package/dist/markdown-BUeGwhbR.mjs.map +0 -1
- package/dist/powerhouse-3XZmdY3_.mjs.map +0 -1
- package/dist/proxy-ji3EHzLn.mjs.map +0 -1
- package/dist/src-BmMd0Wl4.mjs.map +0 -1
- package/dist/types-DbQKfvWc.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown-B-HyDpvO.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 { restartDecision } from \"@powerhousedao/host-core/instance\";\nimport type {\n CaptureDefinition,\n EndpointType,\n EventBus,\n HostServiceDefinition,\n PreflightContext,\n ReadinessPattern,\n ServiceBuildContext,\n ServiceDefinition,\n ServiceHostRun,\n ServiceInstanceStatus,\n ServiceLifetime,\n ServiceManager,\n ServiceStartOptions,\n SupervisorHold,\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 /** Set when the user's supervisor holds the instance: its process, its\n * handle for the instance, and how long the instance lives. The\n * supervisor then applies the restart policy, and this manager does not.\n * `restarting`: it ended on its own and the supervisor starts it again. */\n supervisor?: SupervisorHold;\n}\n\n/** What the supervisor says of an instance beyond its status, as the state\n * keeps it for every listing. */\nfunction supervisedFacts(\n held: SupervisedInstance,\n): Pick<SupervisorHold, \"runnerVersion\" | \"missing\" | \"restart\"> {\n return {\n ...(held.runnerVersion === undefined\n ? {}\n : { runnerVersion: held.runnerVersion }),\n ...(held.missing.length > 0 ? { missing: held.missing } : {}),\n ...(held.restart ? { restart: held.restart } : {}),\n };\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 * Whether a recorded instance is the supervisor's to manage for any tool of\n * the user: the supervisor holds it and the manager that asked for it has\n * ended. While that manager runs, the instance is managed there.\n */\nfunction isHeldBySupervisor(state: ServiceStateFile): boolean {\n return (\n state.supervisor !== undefined &&\n !isOwnerAlive(state) &&\n isPidAlive(state.supervisor.pid) &&\n // One the supervisor starts again has no process for a moment.\n (isInstanceAlive(state) || state.supervisor.restarting === true)\n );\n}\n\ntype SupervisorModule = typeof import(\"@powerhousedao/host-core/supervisor\");\ntype SupervisedInstance = Awaited<\n ReturnType<SupervisorModule[\"listSupervised\"]>\n>[\"instances\"][number];\ntype SupervisorLease = Awaited<\n ReturnType<SupervisorModule[\"holdSupervisorLease\"]>\n>;\n\n/** The supervisor of this OS user, when one runs. */\ninterface RunningSupervisor {\n api: SupervisorModule;\n pid: number;\n control: Parameters<SupervisorModule[\"listSupervised\"]>[0];\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 const hasHostServices = definitions.some((def) => def.run !== undefined);\n /** This process's lease with the supervisor: what it started there \"with\n * the caller\" is stopped when the lease's connection ends. */\n let leased: { pid: number; lease: Promise<SupervisorLease> } | undefined;\n\n /**\n * The user's supervisor, when one runs: host services are then its\n * children, not this process's. One file is looked for when none is\n * recorded, and nothing of the supervisor is loaded. A recorded supervisor\n * that does not answer is an error: supervising here in its place could\n * run an instance twice.\n */\n async function runningSupervisor(): Promise<RunningSupervisor | undefined> {\n if (!hasHostServices) return undefined;\n const { supervisorRecorded } =\n await import(\"@powerhousedao/host-core/supervisor-record\");\n if (!supervisorRecorded()) return undefined;\n const api = await import(\"@powerhousedao/host-core/supervisor\");\n const found = await api.findSupervisor();\n if (found.status === \"none\") return undefined;\n if (found.status === \"silent\") {\n throw new Error(api.silentSupervisorMessage(found));\n }\n return { api, pid: found.record.pid, control: found.record.control };\n }\n\n function holdLease(supervisor: RunningSupervisor): Promise<SupervisorLease> {\n if (leased?.pid === supervisor.pid) return leased.lease;\n const lease = supervisor.api.holdSupervisorLease(supervisor.control);\n const mine = { pid: supervisor.pid, lease };\n leased = mine;\n const forget = () => {\n if (leased === mine) leased = undefined;\n };\n lease.then((held) => held.ended.then(forget), forget);\n return lease;\n }\n\n /**\n * The instance of `state` as the supervisor lists it, when it holds it:\n * the handle, and the same process or (after the supervisor started it\n * again) the same log file, which this manager named for it alone.\n */\n async function heldInstance(\n supervisor: RunningSupervisor,\n state: ServiceStateFile,\n listed?: SupervisedInstance[],\n ): Promise<SupervisedInstance | undefined> {\n if (state.supervisor?.pid !== supervisor.pid) return undefined;\n const instances =\n listed ??\n (await supervisor.api.listSupervised(supervisor.control)).instances;\n const logPath =\n state.logFile === undefined\n ? undefined\n : path.resolve(serviceDir(servicesDir, state.serviceId), state.logFile);\n return instances.find(\n (i) =>\n i.handle === state.supervisor?.handle &&\n i.mine &&\n (i.pid === state.pid ||\n (logPath !== undefined &&\n i.logFile !== undefined &&\n path.resolve(i.logFile) === logPath)),\n );\n }\n\n /**\n * Brings the state of an instance the supervisor holds in line with what\n * the supervisor says of it: the process it runs as now, a restart it\n * waits for, or that it was left ended. Returns whether it is settled\n * (false: the supervisor is starting it again).\n */\n function applySupervised(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n held: SupervisedInstance | undefined,\n ): boolean {\n const statePath = stateFilePath(servicesDir, def.id, state.instanceId);\n if (!state.supervisor || state.status === \"stopped\") return true;\n if (hostStarts.has(statePath) || stopping.has(statePath)) return true;\n const name = resolveServiceName(def);\n const before = JSON.stringify(state);\n const attempt = held?.restart?.attempt;\n let settled = true;\n if (held) {\n const { pid, handle, lifetime, restarting } = state.supervisor;\n state.supervisor = {\n pid,\n handle,\n lifetime,\n ...(restarting ? { restarting } : {}),\n ...supervisedFacts(held),\n };\n }\n if (held?.status === \"starting\" || held?.status === \"restarting\") {\n settled = false;\n const first = !state.supervisor.restarting;\n state.supervisor.restarting = true;\n if (\n attempt !== undefined &&\n (first || attempt !== state.restartAttempt)\n ) {\n state.restartAttempt = attempt;\n if (isMine(state) && held.restart) {\n eventBus?.emit(\"service:restarting\", {\n id: def.id,\n instanceId: state.instanceId,\n name,\n attempt,\n maxRetries: held.restart.maxRetries,\n });\n }\n }\n } else if (\n held?.status === \"running\" &&\n held.pid === state.pid &&\n !isInstanceAlive(state)\n ) {\n // Its end has not reached the supervisor yet.\n settled = false;\n } else if (held?.status === \"running\") {\n const moved = held.pid !== state.pid || state.supervisor.restarting;\n delete state.supervisor.restarting;\n if (moved) {\n state.pid = held.pid;\n state.status = \"ready\";\n delete state.error;\n if (attempt !== undefined) state.restartAttempt = attempt;\n if (held.record && def.run && def.endpoints) {\n try {\n const endpoints = def.endpoints(held.record);\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 } catch {\n // what it published before stands\n }\n }\n if (isMine(state)) {\n eventBus?.emit(\"service:ready\", {\n id: def.id,\n instanceId: state.instanceId,\n name,\n endpoints: state.endpoints ?? {},\n endpointTypes: state.endpointTypes ?? {},\n });\n }\n }\n } else if (held?.status === \"failed\") {\n delete state.supervisor.restarting;\n if (state.status !== \"failed\") {\n state.status = \"failed\";\n state.error = `The supervisor left it ended: ${held.restart?.failed ?? \"it ended on its own\"}.`;\n if (attempt !== undefined) state.restartAttempt = attempt;\n if (isMine(state)) {\n eventBus?.emit(\"service:failed\", {\n id: def.id,\n instanceId: state.instanceId,\n name,\n error: state.error,\n });\n }\n }\n } else if (!isInstanceAlive(state) || state.supervisor.restarting) {\n // Ended there, or not known there: nothing starts it again.\n delete state.supervisor.restarting;\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt ??= new Date().toISOString();\n }\n if (JSON.stringify(state) !== before) writeStateFile(statePath, state);\n return settled;\n }\n\n /** Whether this manager speaks for a recorded instance: its own, or one\n * whose manager has ended. */\n const speaksFor = (state: ServiceStateFile) =>\n isMine(state) || !isOwnerAlive(state);\n\n /**\n * Whether the supervisor is to say what became of an instance it holds\n * under a restart policy: it ended on its own, or is being started again.\n */\n function awaitsSupervisor(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n ): boolean {\n return (\n state.supervisor !== undefined &&\n def.restart?.enabled === true &&\n speaksFor(state) &&\n state.status !== \"stopped\" &&\n state.status !== \"failed\" &&\n isPidAlive(state.supervisor.pid) &&\n (state.supervisor.restarting === true || !isInstanceAlive(state))\n );\n }\n\n /** State paths whose instance the supervisor is asked about until it is\n * settled. */\n const following = new Set<string>();\n const FOLLOW_POLL_MS = 250;\n\n /**\n * An instance the supervisor holds has ended on its own: the supervisor\n * decides whether it starts again, and this follows what it does until\n * the instance runs again or is left ended.\n */\n function followSupervised(def: ServiceDefinition<any>, statePath: string) {\n if (following.has(statePath)) return;\n following.add(statePath);\n void (async () => {\n try {\n for (;;) {\n const state = readStateFile(statePath);\n if (!state?.supervisor || !speaksFor(state)) return;\n if (state.status === \"stopped\" || stopping.has(statePath)) return;\n let held: SupervisedInstance | undefined;\n try {\n const supervisor = await runningSupervisor();\n if (supervisor) held = await heldInstance(supervisor, state);\n } catch {\n // The supervisor is gone, and what it held with it.\n }\n // A stop may have run meanwhile.\n const now = readStateFile(statePath);\n if (\n !now?.supervisor ||\n !speaksFor(now) ||\n now.status === \"stopped\" ||\n stopping.has(statePath)\n ) {\n return;\n }\n if (applySupervised(def, now, held)) return;\n await new Promise((resolve) => {\n setTimeout(resolve, FOLLOW_POLL_MS).unref();\n });\n }\n } finally {\n following.delete(statePath);\n }\n })();\n }\n\n /**\n * Asks the supervisor about every instance it holds for this manager or\n * for one that has ended, and brings their state in line. Returns the\n * supervisor, when one runs.\n */\n async function syncSupervised(): Promise<RunningSupervisor | undefined> {\n const supervisor = await runningSupervisor();\n if (!supervisor) return undefined;\n let listed: SupervisedInstance[] | undefined;\n for (const def of definitions) {\n if (!def.run) continue;\n for (const state of scanInstances(servicesDir, def.id)) {\n if (state.supervisor?.pid !== supervisor.pid) continue;\n if (state.status === \"stopped\") continue;\n // Another manager that still runs follows its own.\n if (!isMine(state) && isOwnerAlive(state)) continue;\n listed ??= (await supervisor.api.listSupervised(supervisor.control))\n .instances;\n applySupervised(\n def,\n state,\n await heldInstance(supervisor, state, listed),\n );\n }\n }\n return supervisor;\n }\n\n /** Stops, at the supervisor, the instance it holds for `state`: also one\n * it would start again. False when it holds none. */\n async function stopAtSupervisor(state: ServiceStateFile): Promise<boolean> {\n if (!state.supervisor) return false;\n const supervisor = await runningSupervisor();\n if (!supervisor || !(await heldInstance(supervisor, state))) return false;\n await supervisor.api.stopSupervised(\n supervisor.control,\n state.supervisor.handle,\n );\n return true;\n }\n\n /** The status of an instance whose restart the supervisor decides on. */\n function awaitedStatus(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n ): ServiceInstanceStatus {\n return {\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"starting\",\n restartAttempt: state.restartAttempt,\n params: state.params,\n workdir: state.workdir,\n ...(state.supervisor ? { supervisor: state.supervisor } : {}),\n };\n }\n\n /** The status of an instance the supervisor's restart policy gave up on:\n * listed as failed, with the reason, until it is started or stopped. */\n function leftEndedStatus(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n ): ServiceInstanceStatus {\n return {\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 params: state.params,\n workdir: state.workdir,\n ...(state.supervisor ? { supervisor: state.supervisor } : {}),\n };\n }\n\n /** The status of an instance the supervisor holds for an ended manager. */\n function heldStatus(\n def: ServiceDefinition<any>,\n state: ServiceStateFile,\n ): ServiceInstanceStatus {\n return {\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: state.supervisor?.restarting\n ? \"starting\"\n : (state.status as ServiceInstanceStatus[\"status\"]),\n ...(state.supervisor?.restarting\n ? { restartAttempt: state.restartAttempt }\n : {}),\n pid: state.pid,\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n params: state.params,\n workdir: state.workdir,\n supervisor: state.supervisor,\n };\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 // One instance per key: a second start is the instance that runs (or\n // starts), and starts nothing. A host run has no pid until its record\n // is live.\n if (hostStarts.has(stateFilePath(servicesDir, id, instanceId))) {\n return instanceId;\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 && awaitsSupervisor(def, existingState)) {\n // The supervisor says what became of it: it may run again already.\n const supervisor = await runningSupervisor();\n const settled =\n supervisor !== undefined &&\n applySupervised(\n def,\n existingState,\n await heldInstance(supervisor, existingState),\n );\n // It is being started again there, or runs again: that is the instance.\n if (!settled || existingState.status === \"ready\") return instanceId;\n if (existingState.status === \"stopped\") {\n removeStateFile(stateFilePath(servicesDir, id, instanceId));\n }\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. One the\n // supervisor holds is the instance that runs.\n if (!isMine(existingState)) {\n if (\n isHeldBySupervisor(existingState) &&\n existingState.status === \"ready\"\n ) {\n return instanceId;\n }\n throw new Error(`Service ${id}: ${notOursMessage(existingState)}`);\n }\n if (\n existingState.status === \"ready\" ||\n existingState.status === \"starting\"\n ) {\n return instanceId;\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 // A host service is the supervisor's child when one runs.\n const lifetime = startOpts?.lifetime ?? \"caller\";\n const supervisor = def.run ? await runningSupervisor() : undefined;\n if (lifetime === \"supervisor\" && !supervisor) {\n throw new Error(\n def.run\n ? `Service ${id}: no supervisor runs for this user, so nothing can outlive this process. Start one with \\`ph run supervisor\\`.`\n : `Service ${id} is no host service: it lives with the process that starts it.`,\n );\n }\n const supervised = supervisor\n ? {\n supervisor,\n lifetime,\n ...(lifetime === \"caller\"\n ? { lease: (await holdLease(supervisor)).id }\n : {}),\n }\n : undefined;\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 ...(supervised ? { supervised } : {}),\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 /** Set when the user's supervisor starts and holds it. */\n supervised?: {\n supervisor: RunningSupervisor;\n lifetime: ServiceLifetime;\n lease?: string;\n };\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 { supervised } = run;\n let handle: string | undefined;\n let startedAs: SupervisedInstance | undefined;\n const spawning = (async (): Promise<SpawnedHost> => {\n if (supervised) {\n const { api, control } = supervised.supervisor;\n const held = await api.startSupervisedHost(\n control,\n {\n host: def.run.host,\n projectDir: run.cwd,\n dataDir: run.cwd,\n ...(def.run.verb === undefined ? {} : { verb: def.run.verb }),\n ...(def.run.argv ? { argv: [...def.run.argv] } : {}),\n env: run.env,\n baseEnv: Object.fromEntries(\n Object.entries(run.baseEnv).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n ),\n lifetime: supervised.lifetime,\n ...(supervised.lease ? { lease: supervised.lease } : {}),\n logFile: run.logPath,\n ...(def.readiness ? { readyTimeoutMs: def.readiness.timeout } : {}),\n ...(def.shutdown ? { stopTimeoutMs: def.shutdown.timeout } : {}),\n // The supervisor applies the policy from here on: it also does\n // after this process has ended. This manager then restarts\n // nothing itself (see list()).\n ...(def.restart ? { restart: def.restart } : {}),\n },\n { signal: abort.signal },\n );\n handle = held.handle;\n startedAs = held.instance;\n return held;\n }\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 // One that ran already is not the supervisor's to stop for this manager.\n if (supervised && handle !== undefined && !spawned.existing) {\n state.supervisor = {\n pid: supervised.supervisor.pid,\n handle,\n lifetime: supervised.lifetime,\n ...(startedAs ? supervisedFacts(startedAs) : {}),\n };\n }\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 // The supervisor decides whether it starts again.\n if (state.supervisor) followSupervised(def, 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 /** Stopped at the supervisor: a stop that was asked for, so its restart\n * policy leaves the instance ended. */\n const stoppedThere = async (): Promise<boolean> => {\n stopping.add(statePath);\n try {\n if (!(await stopAtSupervisor(state))) return false;\n hostRuns.delete(statePath);\n if (state.supervisor) delete state.supervisor.restarting;\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 true;\n };\n\n if (!isMine(state)) {\n // What the supervisor holds for an ended manager is stopped there.\n if (\n (isHeldBySupervisor(state) || awaitsSupervisor(def, state)) &&\n (await stoppedThere())\n ) {\n return;\n }\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 // One the supervisor restarts is stopped there and only there: ended\n // from here it would be started again. That holds for the run this\n // manager started, for one the supervisor started after it, and for one\n // that waits for its restart.\n if (\n state.supervisor &&\n def.restart?.enabled &&\n isPidAlive(state.supervisor.pid) &&\n (await stoppedThere())\n ) {\n return;\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(\n (s) =>\n s.status !== \"stopped\" &&\n (isMine(s) || isHeldBySupervisor(s) || awaitsSupervisor(def, s)),\n );\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. An instance started to live with the supervisor\n * stays: it is the supervisor's from here on. */\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 if (state.supervisor?.lifetime === \"supervisor\") continue;\n try {\n await stopInstance(def, def.id, state.instanceId);\n } catch {\n // already gone\n }\n }\n }\n // Whatever still lives with this caller ends with the lease.\n const held = leased;\n leased = undefined;\n if (held) {\n await held.lease.then((lease) => lease.release()).catch(() => {});\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 // One the supervisor restarts for a manager that has ended.\n if (awaitsSupervisor(def, state)) {\n followSupervised(\n def,\n stateFilePath(servicesDir, def.id, state.instanceId),\n );\n results.push(awaitedStatus(def, state));\n continue;\n }\n if (\n state.supervisor &&\n state.status === \"failed\" &&\n !isOwnerAlive(state) &&\n !isInstanceAlive(state)\n ) {\n results.push(leftEndedStatus(def, state));\n continue;\n }\n results.push(\n isHeldBySupervisor(state)\n ? heldStatus(def, state)\n : foreignStatus(def, state),\n );\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 // One the supervisor holds is restarted there, never here: exactly\n // one party applies the policy. Its end is followed until the\n // supervisor has it running again or has left it ended.\n if (awaitsSupervisor(def, state)) {\n followSupervised(def, statePath);\n results.push(awaitedStatus(def, state));\n continue;\n }\n if (state.supervisor && def.restart?.enabled) {\n if (state.status === \"failed\") {\n results.push(leftEndedStatus(def, state));\n continue;\n }\n if (!isInstanceAlive(state)) {\n // The supervisor ended, and what it held with it.\n delete state.supervisor.restarting;\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 params: state.params,\n workdir: state.workdir,\n });\n continue;\n }\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 — the host layer's restart rule decides.\n const decision = restartDecision(def.restart, {\n attempt: state.restartAttempt ?? 0,\n wasReady: state.status === \"ready\",\n closing,\n });\n if (decision.action === \"restart\" && def.restart) {\n // Mark for restart (async, don't block list())\n const attempt = decision.attempt;\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 }, decision.delayMs);\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 gaveUp = decision.action === \"give-up\";\n const isFailed = state.status === \"failed\" || gaveUp;\n if (gaveUp) {\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 ...(state.supervisor ? { supervisor: state.supervisor } : {}),\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 supervisor: async () => {\n // What it holds may have been started again since it was recorded.\n const running = await syncSupervised();\n return running ? { pid: running.pid } : undefined;\n },\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 { createRequire } from \"node:module\";\nimport type { Marked } from \"marked\";\n\ninterface MarkdownModules {\n Marked: typeof Marked;\n markedTerminal: typeof import(\"marked-terminal\").markedTerminal;\n supportsLanguage: typeof import(\"cli-highlight\").supportsLanguage;\n}\n\nlet renderer: Marked | undefined;\n\n/**\n * Build the Marked instance with terminal rendering.\n * A dedicated instance avoids mutating the global marked instance.\n */\nfunction createRenderer({\n Marked,\n markedTerminal,\n supportsLanguage,\n}: MarkdownModules): Marked {\n const marked = new Marked();\n const 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.\n const originalCode = terminalExt.renderer.code;\n terminalExt.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 };\n marked.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.\n marked.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 return marked;\n}\n\n/**\n * Load the markdown renderer ahead of a render. marked, marked-terminal and\n * cli-highlight stay off the start path: they load here or on the first\n * sync call.\n */\nexport async function loadMarkdown(): Promise<void> {\n if (renderer) return;\n const [{ Marked }, { markedTerminal }, { supportsLanguage }] =\n await Promise.all([\n import(\"marked\"),\n import(\"marked-terminal\"),\n import(\"cli-highlight\"),\n ]);\n renderer ??= createRenderer({ Marked, markedTerminal, supportsLanguage });\n}\n\n/** Renderer for sync callers; required on first use unless already loaded. */\nfunction markdownRenderer(): Marked {\n if (!renderer) {\n const require = createRequire(import.meta.url);\n renderer = createRenderer({\n Marked: (require(\"marked\") as typeof import(\"marked\")).Marked,\n markedTerminal: (\n require(\"marked-terminal\") as typeof import(\"marked-terminal\")\n ).markedTerminal,\n supportsLanguage: (\n require(\"cli-highlight\") as typeof import(\"cli-highlight\")\n ).supportsLanguage,\n });\n }\n return renderer;\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 = markdownRenderer().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,MAAM;EAEpG,KAAK;GACH,IAAI,MAAM,SACR,OAAO,GAAG,IAAI,IAAI,MAAM,SAAS,UAAU,aAAa,MAAM,MAAM,IAAI,MAAM;GAIhF,MAAM,OAAO,aAAa,MAAM,MAAM,IACjC,MAAM,OAA4B,OACnC,OAAO,MAAM,WAAW,WACtB,MAAM,SACN;GACN,IAAI,QAAQ,KAAK,SAAS,GACxB,OAAO,GAAG,MAAM,UAAU,IAAI,MAAM,WAAW,MAAM,IAAI,KAAK;GAGhE,OAAO,GAAG,MAAM,UAAU,IAAI,MAAM,WAAW,QAAQ,IAAI,KAAK,eAAe,MAAM,MAAM,IAAI,MAAM;EAEvG,KAAK,eACH,OAAO,MAAM;EAEf,KAAK,SACH,OAAO,GAAG,IAAI,SAAS,MAAM,QAAQ,MAAM;EAE7C,KAAK;EACL,KAAK,UAIH,OAA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ACD,OAAO;AACT;;;;;;AAOA,eAAsB,eAA8B;CAClD,IAAI,UAAU;CACd,MAAM,CAAC,EAAE,UAAU,EAAE,kBAAkB,EAAE,sBACvC,MAAM,QAAQ,IAAI;EAChB,OAAO;EACP,OAAO;EACP,OAAO;CACT,CAAC;CACH,aAAa,eAAe;EAAE;EAAQ;EAAgB;CAAiB,CAAC;AAC1E;;AAGA,SAAS,mBAA2B;CAClC,IAAI,CAAC,UAAU;EACb,MAAM,UAAU,cAAc,YAAY,GAAG;EAC7C,WAAW,eAAe;GACxB,QAAS,QAAQ,QAAQ,CAAC,CAA6B;GACvD,gBACE,QAAQ,iBAAiB,CAAC,CAC1B;GACF,kBACE,QAAQ,eAAe,CAAC,CACxB;EACJ,CAAC;CACH;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,eAAe,MAAsB;CACnD,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,WAAW,iBAAiB,CAAC,CAAC,MAAM,IAAI;;CAE9C,IAAI,OAAO,aAAa,UACtB,OAAO;CAKT,MAAM,aAAa,MAAc,EAAE,QAAQ,mBAAmB,EAAE;CAChE,OAAO,SACJ,MAAM,IAAI,CAAC,CACX,QAAQ,SAAS,KAAK,WAAW,KAAK,UAAU,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CACxE,KAAK,IAAI,CAAC,CACV,QAAQ;AACb"}
|
|
@@ -5,6 +5,7 @@ import { createWriteStream, openAsBlob } from "node:fs";
|
|
|
5
5
|
import path, { extname } from "node:path";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
9
|
import { Readable } from "node:stream";
|
|
9
10
|
import { pipeline } from "node:stream/promises";
|
|
10
11
|
//#region src/core/command.ts
|
|
@@ -31,6 +32,145 @@ function defineCommand(options) {
|
|
|
31
32
|
return options;
|
|
32
33
|
}
|
|
33
34
|
//#endregion
|
|
35
|
+
//#region src/core/forwarded-signing.ts
|
|
36
|
+
/** The asks a caller answers so that its command signs as the caller. */
|
|
37
|
+
const SIGNING_ASKS = [
|
|
38
|
+
"signer",
|
|
39
|
+
"sign-action",
|
|
40
|
+
"bearer"
|
|
41
|
+
];
|
|
42
|
+
/** What `hello` says when this instance's commands sign as their callers. */
|
|
43
|
+
const COMMAND_SIGNING = 1;
|
|
44
|
+
/** Work a forwarded command left running tried to sign after the command ended. */
|
|
45
|
+
var CommandEndedError = class extends Error {
|
|
46
|
+
constructor() {
|
|
47
|
+
super("The command that started this work has ended: work it left running cannot sign as its caller.");
|
|
48
|
+
this.name = "CommandEndedError";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const scopes = new AsyncLocalStorage();
|
|
52
|
+
function isIdentity(value) {
|
|
53
|
+
const v = value;
|
|
54
|
+
return typeof v?.user?.address === "string" && typeof v.user.networkId === "string" && typeof v.user.chainId === "number" && typeof v.app?.name === "string" && typeof v.app.key === "string" && v.user.address !== "" && v.app.key !== "";
|
|
55
|
+
}
|
|
56
|
+
function isSignature(value, key) {
|
|
57
|
+
return Array.isArray(value) && value.length === 5 && value.every((part) => typeof part === "string") && value[1] === key;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* An `ISigner` whose actions the caller signs. Only actions are forwarded:
|
|
61
|
+
* raw bytes would make the caller sign whatever it is handed.
|
|
62
|
+
*/
|
|
63
|
+
function forwardedSigner(identity, ask) {
|
|
64
|
+
const signer = {
|
|
65
|
+
user: { ...identity.user },
|
|
66
|
+
app: { ...identity.app },
|
|
67
|
+
sign: () => Promise.reject(/* @__PURE__ */ new Error("A forwarded command's caller signs actions only.")),
|
|
68
|
+
verify: () => Promise.reject(/* @__PURE__ */ new Error("A forwarded command's caller signs actions only.")),
|
|
69
|
+
async signAction(action, target, abortSignal) {
|
|
70
|
+
abortSignal?.throwIfAborted();
|
|
71
|
+
const tuple = await ask("sign-action", {
|
|
72
|
+
action: {
|
|
73
|
+
id: action.id,
|
|
74
|
+
type: action.type,
|
|
75
|
+
scope: action.scope,
|
|
76
|
+
input: action.input,
|
|
77
|
+
timestampUtcMs: action.timestampUtcMs
|
|
78
|
+
},
|
|
79
|
+
target: {
|
|
80
|
+
documentId: target.documentId,
|
|
81
|
+
branch: target.branch
|
|
82
|
+
},
|
|
83
|
+
previousStateHash: action.context?.prevOpHash ?? ""
|
|
84
|
+
});
|
|
85
|
+
if (!isSignature(tuple, identity.app.key)) throw new Error(`The caller answered no signature of ${identity.app.key} for action ${action.id}.`);
|
|
86
|
+
return tuple;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
Object.defineProperty(signer, "publicKey", {
|
|
90
|
+
enumerable: false,
|
|
91
|
+
get() {
|
|
92
|
+
throw new Error("A forwarded command's signer has no key here: its caller holds it.");
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
return signer;
|
|
96
|
+
}
|
|
97
|
+
/** A bearer is minted for ten minutes and kept until one is left. */
|
|
98
|
+
const BEARER_SECONDS = 600;
|
|
99
|
+
const BEARER_MARGIN_MS = 6e4;
|
|
100
|
+
/** The signing of a command whose caller lists the {@link SIGNING_ASKS}. */
|
|
101
|
+
function callerSigningOf(caller) {
|
|
102
|
+
if (!caller.asks.has("sign-action")) return void 0;
|
|
103
|
+
let signer;
|
|
104
|
+
let bearer;
|
|
105
|
+
const identity = async () => {
|
|
106
|
+
if (caller.signer) return caller.signer;
|
|
107
|
+
const answer = await caller.ask("signer");
|
|
108
|
+
if (!isIdentity(answer)) throw new Error("The caller named no identity to sign as.");
|
|
109
|
+
return answer;
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
signer: () => signer ??= identity().then((known) => forwardedSigner(known, (kind, payload) => caller.ask(kind, payload))).catch((error) => {
|
|
113
|
+
signer = void 0;
|
|
114
|
+
throw error;
|
|
115
|
+
}),
|
|
116
|
+
bearer: async () => {
|
|
117
|
+
if (!caller.asks.has("bearer")) return void 0;
|
|
118
|
+
if (bearer && bearer.until > Date.now()) return bearer.token;
|
|
119
|
+
const answer = await caller.ask("bearer", { expiresIn: BEARER_SECONDS });
|
|
120
|
+
if (typeof answer?.token !== "string" || answer.token === "") return;
|
|
121
|
+
bearer = {
|
|
122
|
+
token: answer.token,
|
|
123
|
+
until: Date.now() + BEARER_SECONDS * 1e3 - BEARER_MARGIN_MS
|
|
124
|
+
};
|
|
125
|
+
return bearer.token;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/** Runs `work` signing as `caller` until it settles. */
|
|
130
|
+
function withCallerSigning(caller, work) {
|
|
131
|
+
if (!caller) return scopes.run(void 0, work);
|
|
132
|
+
const scope = {
|
|
133
|
+
open: true,
|
|
134
|
+
caller
|
|
135
|
+
};
|
|
136
|
+
let running;
|
|
137
|
+
try {
|
|
138
|
+
running = scopes.run(scope, work);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
scope.open = false;
|
|
141
|
+
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
142
|
+
}
|
|
143
|
+
return running.finally(() => {
|
|
144
|
+
scope.open = false;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** Runs `fn` signing as the instance, whatever command called (an agent's turn, a listener). */
|
|
148
|
+
function asOwnSigner(fn) {
|
|
149
|
+
return scopes.getStore() ? scopes.run(void 0, fn) : fn();
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The signer of a write made now: the caller's while its command runs,
|
|
153
|
+
* {@link CommandEndedError} once it ended, else `own`.
|
|
154
|
+
*/
|
|
155
|
+
function signerForWrite(own) {
|
|
156
|
+
const scope = scopes.getStore();
|
|
157
|
+
if (scope?.open) return scope.caller.signer();
|
|
158
|
+
if (scope) throw new CommandEndedError();
|
|
159
|
+
return own?.();
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The bearer of a request made now: the caller's while its command runs and
|
|
163
|
+
* the caller lends one, else `own`'s.
|
|
164
|
+
*/
|
|
165
|
+
async function bearerForRequest(own) {
|
|
166
|
+
const scope = scopes.getStore();
|
|
167
|
+
if (scope?.open) {
|
|
168
|
+
const lent = await scope.caller.bearer();
|
|
169
|
+
if (lent !== void 0) return lent;
|
|
170
|
+
}
|
|
171
|
+
return own?.();
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
34
174
|
//#region src/integrations/powerhouse/change-trigger.ts
|
|
35
175
|
/**
|
|
36
176
|
* Build a Trigger that listens for document change events on the event bus,
|
|
@@ -295,11 +435,17 @@ function canWrite(rules, document) {
|
|
|
295
435
|
}
|
|
296
436
|
//#endregion
|
|
297
437
|
//#region src/integrations/powerhouse/writes.ts
|
|
438
|
+
/** Whether `signer` is opened at its first write. */
|
|
439
|
+
function isLazySigner(signer) {
|
|
440
|
+
return typeof signer.open === "function";
|
|
441
|
+
}
|
|
298
442
|
/** See {@link ReactorWritesOptions} and {@link ReactorWritesHandle}. */
|
|
299
443
|
function createReactorWrites(options = {}) {
|
|
300
444
|
const source = options.signer;
|
|
445
|
+
const lazy = source && isLazySigner(source) ? source : void 0;
|
|
446
|
+
const eager = source && !lazy ? source : void 0;
|
|
301
447
|
const rules = {
|
|
302
|
-
ready: () =>
|
|
448
|
+
ready: () => lazy ? lazy.ready() : eager ? signerReady(eager) : true,
|
|
303
449
|
legacyDocuments: options.legacyDocuments ?? "sign-when-ready",
|
|
304
450
|
accepts: options.accepts
|
|
305
451
|
};
|
|
@@ -308,10 +454,14 @@ function createReactorWrites(options = {}) {
|
|
|
308
454
|
canWrite: (document) => canWrite(rules, document)
|
|
309
455
|
};
|
|
310
456
|
let signer;
|
|
311
|
-
if (
|
|
312
|
-
|
|
457
|
+
if (lazy) signer = () => {
|
|
458
|
+
if (!lazy.ready()) throw new SignerNotReadyError();
|
|
459
|
+
return lazy.open();
|
|
460
|
+
};
|
|
461
|
+
else if (eager) {
|
|
462
|
+
const gated = createGatedSigner(eager);
|
|
313
463
|
signer = () => {
|
|
314
|
-
if (!signerReady(
|
|
464
|
+
if (!signerReady(eager)) throw new SignerNotReadyError();
|
|
315
465
|
return gated;
|
|
316
466
|
};
|
|
317
467
|
}
|
|
@@ -1693,6 +1843,7 @@ function createAttachmentCommands() {
|
|
|
1693
1843
|
return [
|
|
1694
1844
|
defineCommand({
|
|
1695
1845
|
id: "attachment-preprocess",
|
|
1846
|
+
needs: "reactor",
|
|
1696
1847
|
description: "Compute an attachment's content-addressed ref (attachment://v1:<sha256>) from a local file WITHOUT uploading. Embed the returned ref in a document action now, then send the bytes with attachment-upload for the same file after / in parallel with submitting the action.",
|
|
1697
1848
|
inputSchema: z.object({
|
|
1698
1849
|
filePath: z.string().describe("Path to the local file to reference (absolute, or relative to the workdir)."),
|
|
@@ -1715,6 +1866,7 @@ function createAttachmentCommands() {
|
|
|
1715
1866
|
}),
|
|
1716
1867
|
defineCommand({
|
|
1717
1868
|
id: "attachment-upload",
|
|
1869
|
+
needs: "reactor",
|
|
1718
1870
|
description: "Upload a local file to the attachment store and return its content-addressed ref (attachment://v1:<sha256>). The ref is deterministic from the bytes and identical content dedups. Embed the ref in a document action; the action may be submitted before or after this upload.",
|
|
1719
1871
|
inputSchema: z.object({
|
|
1720
1872
|
filePath: z.string().describe("Path to the local file to upload (absolute, or relative to the workdir)."),
|
|
@@ -1750,6 +1902,7 @@ function createAttachmentCommands() {
|
|
|
1750
1902
|
}),
|
|
1751
1903
|
defineCommand({
|
|
1752
1904
|
id: "attachment-stat",
|
|
1905
|
+
needs: "reactor",
|
|
1753
1906
|
description: "Look up an attachment by ref (attachment://v1:<sha256>) and report its status + metadata. status='pending' = reserved but not yet uploaded; 'available' = stored; 'evicted' = metadata known, bytes reclaimed. On a switchboard, pass the documentId of a document whose operations reference the attachment.",
|
|
1754
1907
|
inputSchema: z.object({
|
|
1755
1908
|
ref: z.string().describe("Attachment ref, e.g. attachment://v1:<sha256hex>."),
|
|
@@ -1768,6 +1921,7 @@ function createAttachmentCommands() {
|
|
|
1768
1921
|
}),
|
|
1769
1922
|
defineCommand({
|
|
1770
1923
|
id: "attachment-get",
|
|
1924
|
+
needs: "reactor",
|
|
1771
1925
|
description: "Download an attachment's bytes by ref (attachment://v1:<sha256>) to a local file. Errors if the attachment is still pending (bytes not yet uploaded). On a switchboard, pass the documentId of a document whose operations reference the attachment.",
|
|
1772
1926
|
inputSchema: z.object({
|
|
1773
1927
|
ref: z.string().describe("Attachment ref, e.g. attachment://v1:<sha256hex>."),
|
|
@@ -1813,7 +1967,7 @@ async function resolveRemoteReactorConfig(source, setup) {
|
|
|
1813
1967
|
* `/attachments/*` routes mount at the host root, so the origin is used.
|
|
1814
1968
|
*/
|
|
1815
1969
|
async function remoteAttachmentService(endpoint, jwtHandler) {
|
|
1816
|
-
const { createRemoteAttachmentService } = await import("./dist-
|
|
1970
|
+
const { createRemoteAttachmentService } = await import("./dist-BTVqrpN4.mjs");
|
|
1817
1971
|
return createRemoteAttachmentService({
|
|
1818
1972
|
remoteUrl: new URL(endpoint).origin,
|
|
1819
1973
|
...jwtHandler ? { jwtHandler } : {}
|
|
@@ -1836,7 +1990,8 @@ async function driveOfAddress(client, slug, endpoint) {
|
|
|
1836
1990
|
* a signer change also reconnects the realtime socket with the current
|
|
1837
1991
|
* bearer. Without `ctx.attachments` the context gets the switchboard's own
|
|
1838
1992
|
* attachment service, authenticated by `ctx.attachmentJwtHandler`, else by
|
|
1839
|
-
*
|
|
1993
|
+
* the bearer the writes carry (a forwarded command's caller's, else
|
|
1994
|
+
* `tokenProvider`'s). `shutdown` releases only this process's side (the
|
|
1840
1995
|
* bridged subscriptions, the signer watch, the client) and runs once.
|
|
1841
1996
|
*/
|
|
1842
1997
|
async function attachDefaultReactor(ctx, options) {
|
|
@@ -1854,13 +2009,15 @@ async function attachDefaultReactor(ctx, options) {
|
|
|
1854
2009
|
}) } : {},
|
|
1855
2010
|
...ctx.emit ? { emit: ctx.emit } : {}
|
|
1856
2011
|
});
|
|
2012
|
+
const ownSigner = handle.signer;
|
|
2013
|
+
const ownToken = options.tokenProvider;
|
|
1857
2014
|
let attachment;
|
|
1858
2015
|
try {
|
|
1859
2016
|
attachment = await attachRemoteReactor({
|
|
1860
2017
|
url: options.url,
|
|
1861
2018
|
documentModels: options.documentModels ?? [],
|
|
1862
|
-
|
|
1863
|
-
|
|
2019
|
+
signer: () => signerForWrite(ownSigner),
|
|
2020
|
+
tokenProvider: () => bearerForRequest(ownToken)
|
|
1864
2021
|
});
|
|
1865
2022
|
} catch (error) {
|
|
1866
2023
|
handle.stop();
|
|
@@ -1892,8 +2049,7 @@ async function attachDefaultReactor(ctx, options) {
|
|
|
1892
2049
|
}
|
|
1893
2050
|
let unsubscribe;
|
|
1894
2051
|
if (options.subscriptions && ctx.emit) unsubscribe = bridgeSubscriptions(client, options.subscriptions, ctx.emit);
|
|
1895
|
-
const
|
|
1896
|
-
const attachments = ctx.attachments ?? await remoteAttachmentService(attachment.endpoint, ctx.attachmentJwtHandler ?? (tokenProvider && (() => tokenProvider())));
|
|
2052
|
+
const attachments = ctx.attachments ?? await remoteAttachmentService(attachment.endpoint, ctx.attachmentJwtHandler ?? (() => bearerForRequest(ownToken)));
|
|
1897
2053
|
let stopped = false;
|
|
1898
2054
|
const result = {
|
|
1899
2055
|
client,
|
|
@@ -1917,6 +2073,6 @@ async function attachDefaultReactor(ctx, options) {
|
|
|
1917
2073
|
return result;
|
|
1918
2074
|
}
|
|
1919
2075
|
//#endregion
|
|
1920
|
-
export { bridgeSubscriptions as A, isDocType as C, policyOfHeader as D, createGatedSigner as E, createDocumentChangeTrigger as M,
|
|
2076
|
+
export { bridgeSubscriptions as A, signerForWrite as B, isDocType as C, policyOfHeader as D, createGatedSigner as E, SIGNING_ASKS as F, defineCommand as H, asOwnSigner as I, bearerForRequest as L, createDocumentChangeTrigger as M, COMMAND_SIGNING as N, signerReady as O, CommandEndedError as P, callerSigningOf as R, folders_exports as S, SignerNotReadyError as T, withCallerSigning as V, buildAuthHeaders as _, fileToBlob as a, createFolderCommands as b, isAttachmentAlreadyExists as c, AttachmentPending as d, AttachmentTransferError as f, SizeMismatch as g, ReservationNotFound as h, asRef as i, defineRegistry as j, ensureDrive as k, AttachmentAlreadyExists as l, InvalidAttachmentRef as m, resolveRemoteReactorConfig as n, getAttachmentService as o, HashMismatch as p, createAttachmentCommands as r, inferMimeType as s, attachDefaultReactor as t, AttachmentNotFound as u, createRef as v, createReactorWrites as w, createFolderOperations as x, parseRef as y, forwardedSigner as z };
|
|
1921
2077
|
|
|
1922
|
-
//# sourceMappingURL=powerhouse-
|
|
2078
|
+
//# sourceMappingURL=powerhouse-C4O-raTW.mjs.map
|