@powerhousedao/clint 0.0.0-stage → 6.2.3-dev.101

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/build-skills-Cfj0OGnW.mjs +293 -0
  3. package/dist/build-skills-Cfj0OGnW.mjs.map +1 -0
  4. package/dist/dist-CUltriBW.mjs +1628 -0
  5. package/dist/dist-CUltriBW.mjs.map +1 -0
  6. package/dist/drive-BEshRPDR.mjs +84 -0
  7. package/dist/drive-BEshRPDR.mjs.map +1 -0
  8. package/dist/esm-C1DOsF1a.mjs +13140 -0
  9. package/dist/esm-C1DOsF1a.mjs.map +1 -0
  10. package/dist/events-BnwGFTjv.mjs +237 -0
  11. package/dist/events-BnwGFTjv.mjs.map +1 -0
  12. package/dist/folders-C-pFsTXT.mjs +256 -0
  13. package/dist/folders-C-pFsTXT.mjs.map +1 -0
  14. package/dist/index.d.mts +1005 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +8 -0
  17. package/dist/local-signer-EFzJV3bn.mjs +128 -0
  18. package/dist/local-signer-EFzJV3bn.mjs.map +1 -0
  19. package/dist/markdown-D-sP2zw_.mjs +275 -0
  20. package/dist/markdown-D-sP2zw_.mjs.map +1 -0
  21. package/dist/proxy-BFR8GScT.mjs +302 -0
  22. package/dist/proxy-BFR8GScT.mjs.map +1 -0
  23. package/dist/proxy-routes-DP3ztsnS.mjs +215 -0
  24. package/dist/proxy-routes-DP3ztsnS.mjs.map +1 -0
  25. package/dist/reactor-C9VIUX1H.mjs +51 -0
  26. package/dist/reactor-C9VIUX1H.mjs.map +1 -0
  27. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  28. package/dist/runners/clint-runner.d.mts +398 -0
  29. package/dist/runners/clint-runner.d.mts.map +1 -0
  30. package/dist/runners/clint-runner.mjs +522 -0
  31. package/dist/runners/clint-runner.mjs.map +1 -0
  32. package/dist/runners/mastra-runner.d.mts +300 -0
  33. package/dist/runners/mastra-runner.d.mts.map +1 -0
  34. package/dist/runners/mastra-runner.mjs +516 -0
  35. package/dist/runners/mastra-runner.mjs.map +1 -0
  36. package/dist/services-9E-r0nWl.mjs +999 -0
  37. package/dist/services-9E-r0nWl.mjs.map +1 -0
  38. package/dist/src-DD8PWpD5.mjs +4767 -0
  39. package/dist/src-DD8PWpD5.mjs.map +1 -0
  40. package/dist/start-b7Mn2cxB.mjs +1526 -0
  41. package/dist/start-b7Mn2cxB.mjs.map +1 -0
  42. package/dist/stdin-BjAO9gPK.mjs +17 -0
  43. package/dist/stdin-BjAO9gPK.mjs.map +1 -0
  44. package/dist/stream-DVuufwIj.mjs +148 -0
  45. package/dist/stream-DVuufwIj.mjs.map +1 -0
  46. package/dist/subscriptions-CfiflAsI.mjs +38 -0
  47. package/dist/subscriptions-CfiflAsI.mjs.map +1 -0
  48. package/dist/switchboard-CyvOavqL.mjs +57 -0
  49. package/dist/switchboard-CyvOavqL.mjs.map +1 -0
  50. package/dist/types-CRkoD-Mm.d.mts +1770 -0
  51. package/dist/types-CRkoD-Mm.d.mts.map +1 -0
  52. package/package.json +102 -3
  53. package/README.md +0 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services-9E-r0nWl.mjs","names":["scanProjectsImpl"],"sources":["../src/core/schema.ts","../src/core/preflight.ts","../src/core/process-platform.ts","../src/core/project-scanner.ts","../src/core/services.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Schema introspection utilities for Zod v4.\n *\n * Uses the public Zod v4 API: .type, .shape, .description, .def,\n * .isOptional(), and instanceof checks.\n */\n\nexport interface FieldInfo {\n key: string;\n description: string | undefined;\n isOptional: boolean;\n hasDefault: boolean;\n defaultValue: unknown;\n baseType: string;\n sensitive: boolean;\n}\n\nconst WRAPPER_TYPES = new Set([\"default\", \"optional\", \"nullable\"]);\n\n/**\n * Extract field entries from a ZodObject schema's shape.\n * Returns an empty array for non-object schemas.\n *\n * When `sensitiveKeys` is provided, those fields are marked `sensitive: true`.\n */\nexport function getSchemaFields(\n schema: z.ZodType,\n sensitiveKeys?: ReadonlySet<string>,\n): FieldInfo[] {\n if (!(schema instanceof z.ZodObject)) {\n return [];\n }\n\n const fields: FieldInfo[] = [];\n for (const [key, field] of Object.entries(schema.shape) as [\n string,\n z.ZodType,\n ][]) {\n fields.push({\n key,\n description: field.description,\n isOptional: field.isOptional(),\n hasDefault: field instanceof z.ZodDefault,\n defaultValue:\n field instanceof z.ZodDefault ? field.def.defaultValue : undefined,\n baseType: resolveBaseType(field),\n sensitive: sensitiveKeys?.has(key) ?? false,\n });\n }\n return fields;\n}\n\n/**\n * Resolve the base type name by unwrapping Default/Optional/Nullable wrappers.\n * Uses .type and .def.innerType (both public Zod v4 API).\n */\nfunction resolveBaseType(schema: z.ZodType): string {\n let current = schema as {\n type: string;\n def: { innerType?: { type: string; def: any } };\n };\n while (WRAPPER_TYPES.has(current.type) && current.def.innerType) {\n current = current.def.innerType as typeof current;\n }\n return current.type;\n}\n\n/**\n * Convert a kebab-case slug to a Title Case string.\n * E.g. 'document-modeling' → 'Document Modeling'\n */\nexport function slugToTitle(slug: string): string {\n return slug\n .split(\"-\")\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\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 { spawnSync } from \"node:child_process\";\n\n/**\n * NOTE(port): the ph-clint repo was POSIX-only. Its supervision model —\n * `detached: true` to create a process GROUP, then `process.kill(-pid)` to\n * fell the whole tree — does not exist on Windows: negative-pid kills throw,\n * and `detached` forces a new console per child that even `windowsHide`\n * cannot suppress (libuv allocates one for a detached shell). The split:\n *\n * - POSIX: keep the group model exactly as ported.\n * - Windows: spawn attached + hidden; kill trees with `taskkill /T /F`,\n * which walks the child tree the way the group kill does on POSIX.\n */\nexport const isWindows = process.platform === \"win32\";\n\n/** Spawn options fragment for a supervised child. */\nexport function supervisedSpawnOptions(): {\n detached: boolean;\n windowsHide: boolean;\n} {\n return { detached: !isWindows, windowsHide: true };\n}\n\n/** Kill a supervised child's whole tree. `signal` only applies on POSIX;\n * Windows tree-kill is always forceful (there are no signals to deliver). */\nexport function killTree(\n pid: number,\n signal: NodeJS.Signals = \"SIGTERM\",\n): void {\n if (isWindows) {\n spawnSync(\"taskkill\", [\"/PID\", String(pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n return;\n }\n process.kill(-pid, signal);\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 { killTree, supervisedSpawnOptions } from \"./process-platform.js\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport type {\n CaptureDefinition,\n EndpointType,\n EventBus,\n PreflightContext,\n ReadinessPattern,\n ServiceBuildContext,\n ServiceDefinition,\n ServiceInstanceStatus,\n ServiceManager,\n ServiceStartOptions,\n} from \"./types.js\";\nimport { isPortFree } from \"./preflight.js\";\nimport { resolveServiceProxyContext } from \"./proxy-routes.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.\n */\ninterface ServiceStateFile {\n serviceId: string;\n instanceId: string;\n name: string;\n pid: number;\n status: \"starting\" | \"ready\" | \"failed\" | \"stopped\";\n endpoints?: Record<string, string>;\n endpointTypes?: Record<string, EndpointType>;\n error?: string;\n startedAt: string;\n stoppedAt?: string;\n command: string;\n restartAttempt?: number;\n workdir?: string;\n params?: Record<string, unknown>;\n /** Active log file for the current run, relative to the service dir. */\n logFile?: string;\n}\n\nexport interface ServiceManagerOptions {\n config: Record<string, unknown>;\n servicesDir: string;\n eventBus?: EventBus;\n}\n\n/**\n * Get the directory for a service's instance state files.\n */\nfunction serviceDir(servicesDir: string, serviceId: string): string {\n return path.join(servicesDir, serviceId);\n}\n\n/**\n * NOTE(port): instance ids are `{serviceId}:{name|hash}` — and a COLON in a\n * filename is not a filename on NTFS: it silently writes an Alternate Data\n * Stream (invisible to readdir), so state files vanished on Windows. Encode\n * ids for FILENAMES only; the logical id (parsed on ':' elsewhere, stored\n * inside the state JSON) is untouched.\n */\nfunction fileSafeId(instanceId: string): string {\n return instanceId.replace(/[<>:\"/\\\\|?*]/g, \"+\");\n}\n\nfunction stateFilePath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n return path.join(\n serviceDir(servicesDir, serviceId),\n `${fileSafeId(instanceId)}.json`,\n );\n}\n\n/** Base (run-less) log name, kept as a final fallback for older state. */\nfunction logFilePath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n return path.join(\n serviceDir(servicesDir, serviceId),\n `${fileSafeId(instanceId)}.log`,\n );\n}\n\n/** Number of per-run log files kept per instance. */\nconst MAX_RUN_LOGS = 5;\n\n/** Match a per-run log file for an instance: `<fileSafeId>.<runId>.log`. */\nfunction runLogPattern(instanceId: string): RegExp {\n const safe = fileSafeId(instanceId);\n return new RegExp(\n `^${safe.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\.(\\\\d+)\\\\.log$`,\n );\n}\n\n/** Allocate a fresh per-run log file name for an instance, unique within the dir. */\nfunction newRunLogFile(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n const dir = serviceDir(servicesDir, serviceId);\n const safe = fileSafeId(instanceId);\n let runId = Date.now();\n let name = `${safe}.${runId}.log`;\n while (fs.existsSync(path.join(dir, name))) {\n runId += 1;\n name = `${safe}.${runId}.log`;\n }\n return name;\n}\n\n/** List an instance's per-run log files, newest first by runId. */\nfunction listRunLogs(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string[] {\n const dir = serviceDir(servicesDir, serviceId);\n const re = runLogPattern(instanceId);\n try {\n return fs\n .readdirSync(dir)\n .filter((f) => re.test(f))\n .sort((a, b) => Number(re.exec(b)![1]) - Number(re.exec(a)![1]));\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve the active log path for an instance: the run recorded in the state\n * file, else the newest per-run log, else the base log name.\n */\nfunction activeLogPath(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): string {\n const dir = serviceDir(servicesDir, serviceId);\n const state = readStateFile(\n stateFilePath(servicesDir, serviceId, instanceId),\n );\n if (state?.logFile && fs.existsSync(path.join(dir, state.logFile))) {\n return path.join(dir, state.logFile);\n }\n const runs = listRunLogs(servicesDir, serviceId, instanceId);\n if (runs.length > 0) return path.join(dir, runs[0]!);\n return logFilePath(servicesDir, serviceId, instanceId);\n}\n\n/** Keep only the newest `MAX_RUN_LOGS` per-run logs for an instance. */\nfunction pruneRunLogs(\n servicesDir: string,\n serviceId: string,\n instanceId: string,\n): void {\n const dir = serviceDir(servicesDir, serviceId);\n const runs = listRunLogs(servicesDir, serviceId, instanceId);\n for (const f of runs.slice(MAX_RUN_LOGS)) {\n try {\n fs.unlinkSync(path.join(dir, f));\n } catch {\n /* already gone */\n }\n }\n}\n\nconst MAX_LINE_CHARS = 2_000;\nconst MAX_TOTAL_CHARS = 16_000;\n\n/**\n * Strip NUL bytes and non-printable control chars (keeping \\n and \\t), then\n * cap each line and the total length. Keeps the tail when over the total cap,\n * since recent log lines matter most. Guards against truncate-while-open gaps\n * that fill the file with NUL runs containing no newlines.\n */\nexport function sanitizeLogText(\n text: string,\n maxTotal = MAX_TOTAL_CHARS,\n): string {\n // Drop control chars except \\t (\\x09) and \\n (\\x0A); \\x0B-\\x1F covers\n // \\r (\\x0D) so Windows-style \\r\\n logs don't leak carriage returns.\n // eslint-disable-next-line no-control-regex\n const cleaned = text.replace(/[\\x00-\\x08\\x0B-\\x1F\\x7F]/g, \"\");\n const lines = cleaned.split(\"\\n\").map((line) => {\n if (line.length <= MAX_LINE_CHARS) return line;\n const dropped = line.length - MAX_LINE_CHARS;\n return line.slice(0, MAX_LINE_CHARS) + `…[truncated ${dropped} chars]`;\n });\n let out = lines.join(\"\\n\");\n if (out.length > maxTotal) {\n const dropped = out.length - maxTotal;\n out = `…[truncated ${dropped} chars]\\n` + out.slice(out.length - maxTotal);\n }\n return out;\n}\n\n/**\n * 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// 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.\n */\nfunction resolveCommand(\n def: ServiceDefinition<any>,\n ctx: ServiceBuildContext,\n): string {\n return typeof def.command === \"function\" ? def.command(ctx) : def.command;\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 managing long-running detached services.\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 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 {\n params,\n config,\n proxy: resolveServiceProxyContext(\n config.proxyPublicUrl as string | undefined,\n ),\n };\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\n const instanceId = resolveInstanceId(id, startOpts);\n const maxInstances = def.maxInstances ?? 1;\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 (\n existingState &&\n existingState.pid &&\n isPidAlive(existingState.pid)\n ) {\n if (\n existingState.status === \"ready\" ||\n existingState.status === \"starting\"\n ) {\n throw new Error(\n `Service ${id} is already running (pid ${existingState.pid})`,\n );\n }\n }\n\n // Check maxInstances limit (exclude stopped instances)\n const running = scanInstances(servicesDir, id).filter(\n (s) =>\n s.instanceId !== instanceId &&\n s.status !== \"stopped\" &&\n s.pid &&\n isPidAlive(s.pid),\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 // 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 const env = { ...process.env, ...(def.env ? def.env(buildCtx) : {}) };\n\n const child = spawn(commandStr, {\n shell: true,\n // POSIX: detached process group; Windows: attached+hidden, trees felled\n // via taskkill (see process-platform.ts).\n ...supervisedSpawnOptions(),\n stdio: [\"ignore\", logFd, logFd],\n env,\n cwd: spawnCwd,\n });\n\n child.unref();\n fs.closeSync(logFd);\n\n const pid = child.pid!;\n const restartAttempt = existingState?.restartAttempt ?? 0;\n\n // Write initial state\n const state: ServiceStateFile = {\n serviceId: id,\n instanceId,\n name: resolveServiceName(def),\n pid,\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 const tail = tailLogFile(logPath);\n const hint = `Check the workdir and run '${id}-logs' for the full log.`;\n const lines = [state.error];\n lines.push(\"\");\n lines.push(` workdir: ${spawnCwd}`);\n lines.push(` command: ${commandStr}`);\n if (tail) {\n lines.push(\"\");\n lines.push(\" Recent log output:\");\n lines.push(...tail.split(\"\\n\").map((l) => \" \" + l));\n }\n lines.push(\"\");\n lines.push(` ${hint}`);\n reject(new Error(lines.join(\"\\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 const tail = tailLogFile(logPath);\n const hint = `Check the workdir and run '${id}-logs' for the full log.`;\n const tLines = [state.error];\n tLines.push(\"\");\n tLines.push(` workdir: ${spawnCwd}`);\n tLines.push(` command: ${commandStr}`);\n if (tail) {\n tLines.push(\"\");\n tLines.push(\" Recent log output:\");\n tLines.push(...tail.split(\"\\n\").map((l) => \" \" + l));\n }\n tLines.push(\"\");\n tLines.push(` ${hint}`);\n const detail = tLines.join(\"\\n\");\n reject(new Error(detail));\n }\n }, 100);\n });\n\n return instanceId;\n }\n\n /**\n * Send a signal to a process, trying the process group first, then direct PID.\n */\n /* istanbul ignore next -- kill fallbacks depend on OS process group behavior */\n function killProcess(pid: number, signal: string): void {\n try {\n killTree(pid, signal as NodeJS.Signals);\n } catch {\n try {\n process.kill(pid, signal);\n } catch {\n // Already dead\n }\n }\n }\n\n /**\n * Force-kill a process 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 killProcess(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 const state = readStateFile(statePath);\n if (!state || !state.pid) {\n // If it's a stopped state file, it's already stopped\n if (state?.status === \"stopped\") return;\n throw new Error(`Service ${serviceId} is not running`);\n }\n\n if (!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 const signal = def.shutdown?.signal ?? \"SIGTERM\";\n const timeout = def.shutdown?.timeout ?? 5_000;\n\n killProcess(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 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 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 for (const inst of instances) {\n try {\n await stopInstance(def, id, inst.instanceId);\n } catch {\n // Instance may already be dead\n }\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 // Verify PID is alive (pid <= 0 means not yet spawned — treat as dead)\n if (!state.pid || !isPidAlive(state.pid)) {\n const statePath = stateFilePath(\n servicesDir,\n def.id,\n state.instanceId,\n );\n\n // Process died — check restart policy\n if (\n def.restart?.enabled &&\n (state.restartAttempt ?? 0) < def.restart.maxRetries &&\n state.status === \"ready\"\n ) {\n // Mark for restart (async, don't block list())\n const attempt = (state.restartAttempt ?? 0) + 1;\n eventBus?.emit(\"service:restarting\", {\n id: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n attempt,\n maxRetries: def.restart.maxRetries,\n });\n\n // Update state file with incremented attempt\n state.status = \"starting\";\n state.restartAttempt = attempt;\n writeStateFile(statePath, state);\n\n // Trigger async restart after delay — recover params from state\n const restartParams = state.params;\n const restartWorkdir = state.workdir;\n const restartName = state.instanceId.includes(\":\")\n ? state.instanceId.split(\":\")[1]\n : undefined;\n setTimeout(async () => {\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 status: \"failed\",\n startedAt: new Date().toISOString(),\n command: commandStr,\n restartAttempt: attempt,\n params: restartParams,\n workdir: restartWorkdir,\n };\n writeStateFile(statePath, tempState);\n await start(def.id, {\n params: restartParams,\n workdir: restartWorkdir,\n name: restartName,\n });\n } catch {\n // Restart failed — dir may have been removed (test teardown)\n }\n }, def.restart.delay);\n\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"starting\",\n restartAttempt: attempt,\n params: state.params,\n workdir: state.workdir,\n });\n } else {\n // No restart or max retries exceeded\n const isFailed =\n state.status === \"failed\" ||\n (def.restart?.enabled &&\n (state.restartAttempt ?? 0) >= def.restart.maxRetries);\n if (\n def.restart?.enabled &&\n (state.restartAttempt ?? 0) >= def.restart.maxRetries\n ) {\n eventBus?.emit(\"service:failed\", {\n id: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n error: \"Max restart retries exceeded\",\n });\n }\n\n if (isFailed) {\n // Keep as failed (readiness error or max retries) — remove state file\n removeStateFile(statePath);\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: \"failed\",\n error: state.error ?? \"Process exited unexpectedly\",\n restartAttempt: state.restartAttempt,\n });\n } else {\n // Was running/starting but died — persist as stopped for re-launch\n state.status = \"stopped\";\n state.pid = 0;\n state.stoppedAt = new Date().toISOString();\n writeStateFile(statePath, state);\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: state.name,\n status: \"stopped\",\n workdir: state.workdir,\n params: state.params,\n });\n }\n }\n continue;\n }\n\n results.push({\n serviceId: def.id,\n instanceId: state.instanceId,\n name: resolveServiceName(def),\n status: state.status as ServiceInstanceStatus[\"status\"],\n pid: state.pid,\n endpoints: state.endpoints,\n endpointTypes: state.endpointTypes,\n restartAttempt: state.restartAttempt,\n params: state.params,\n workdir: state.workdir,\n });\n }\n }\n\n return results;\n }\n\n function logs(id: string, instanceId?: string, lines = 50): string {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n\n // Resolve instance ID: if not provided, prefer running instances\n let resolvedInstanceId = instanceId;\n let warning = \"\";\n if (!resolvedInstanceId) {\n const instances = scanInstances(servicesDir, id);\n const running = instances.filter(\n (s) => s.status === \"ready\" || s.status === \"starting\",\n );\n if (running.length === 1) {\n resolvedInstanceId = running[0]!.instanceId;\n } else if (running.length > 1) {\n warning = `⚠ Multiple running instances — showing logs for ${running[0]!.instanceId}. Use --instance to specify: ${running.map((r) => r.instanceId).join(\", \")}\\n`;\n resolvedInstanceId = running[0]!.instanceId;\n } else if (instances.length > 0) {\n // No running instances — fall back to most recent log file or last state file\n resolvedInstanceId =\n mostRecentLogInstance(servicesDir, id) ??\n instances[instances.length - 1]!.instanceId;\n } else {\n // No state files at all — find the most recent .log file by mtime\n resolvedInstanceId = mostRecentLogInstance(servicesDir, id) ?? id;\n }\n }\n const logPath = activeLogPath(servicesDir, id, resolvedInstanceId);\n\n // Build informational footer showing which instance log was printed\n const instances = instanceId ? null : scanInstances(servicesDir, id);\n const instanceState = instances?.find(\n (s) => s.instanceId === resolvedInstanceId,\n );\n const statusTag = instanceState ? ` [${instanceState.status}]` : \"\";\n const instanceTag =\n resolvedInstanceId !== id ? ` (${resolvedInstanceId})` : \"\";\n const workdirLine = instanceState?.workdir\n ? `\\n (dir: ${instanceState.workdir})`\n : \"\";\n const footer = `\\n— ${resolveServiceName(def)}${instanceTag}${statusTag} log${workdirLine}`;\n\n try {\n const content = fs.readFileSync(logPath, \"utf-8\");\n const allLines = sanitizeLogText(content).split(\"\\n\");\n const body = sanitizeLogText(allLines.slice(-lines).join(\"\\n\"));\n return warning + body + footer;\n } catch {\n return warning;\n }\n }\n\n function watchLogs(\n id: string,\n instanceId: string,\n onLine: (line: string) => void,\n ): () => void {\n const def = defMap.get(id);\n if (!def) throw new Error(`Unknown service: ${id}`);\n\n const logPath = activeLogPath(servicesDir, id, instanceId);\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 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 list,\n getDefinition,\n logs,\n watchLogs,\n watchChunks,\n scanProjects: scanProjectsForService,\n purgeStoppedInstances,\n };\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAW;CAAY;AAAU,CAAC;;;;;;;AAQjE,SAAgB,gBACd,QACA,eACa;CACb,IAAI,EAAE,kBAAkB,EAAE,YACxB,OAAO,CAAC;CAGV,MAAM,SAAsB,CAAC;C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