poe-code 3.0.391 → 3.0.393

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.
@@ -1 +1,7 @@
1
- {"version":3,"file":"skills.js","sourceRoot":"","sources":["../src/skills.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EACL,YAAY,IAAI,iBAAiB,EAGlC,MAAM,8BAA8B,CAAC;AA0CtC,SAAS,oBAAoB;IAC3B,OAAO;QACL,QAAQ,EAAE,CAAC,CAAC,QAAgB,EAAE,QAAyB,EAAE,EAAE;YACzD,IAAI,QAAQ,EAAE,CAAC;gBACb,OAAO,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YACzC,CAAC;YACD,OAAO,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC,CAAuC;QACxC,OAAO,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC;QAC3D,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnE,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC7C,SAAS,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC;QAC7E,KAAK,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,OA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OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,OAAe,EACf,MAA0B,EAC1B,UAA+B,EAAE;IAEjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IACzC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IAChD,MAAM,UAAU,GAAG,OAAO,CAAC,EAAE,IAAI,oBAAoB,EAAE,CAAC;IACxD,MAAM,OAAO,GAAG,MAAM,mBAAmB,CAAC,MAAM,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IAE3E,OAAO,iBAAiB,CACtB,OAAO,EACP;QACE,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,OAAO;KACR,EACD;QACE,EAAE,EAAE,UAAU;QACd,GAAG;QACH,OAAO;QACP,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,OAAO;QAC/B,MAAM,EAAE,OAAO,CAAC,MAAM;KACvB,CACF,CAAC;AACJ,CAAC"}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/skills.ts", "../packages/agent-skill-config/src/configs.ts", "../packages/agent-defs/src/agents/claude-code.ts", "../packages/agent-defs/src/agents/claude-desktop.ts", "../packages/agent-defs/src/agents/codex.ts", "../packages/agent-defs/src/agents/cursor.ts", "../packages/agent-defs/src/agents/gemini-cli.ts", "../packages/agent-defs/src/agents/opencode.ts", "../packages/agent-defs/src/agents/kimi.ts", "../packages/agent-defs/src/agents/goose.ts", "../packages/agent-defs/src/agents/poe-agent.ts", "../packages/agent-defs/src/registry.ts", "../packages/config-mutations/src/mutations/file-mutation.ts", "../packages/config-mutations/src/mutations/template-mutation.ts", "../packages/config-mutations/src/execution/apply-mutation.ts", "../packages/toolcraft-design/src/internal/color-support.ts", "../packages/toolcraft-design/src/components/color.ts", "../packages/toolcraft-design/src/tokens/brand.ts", "../packages/toolcraft-design/src/internal/theme-state.ts", "../packages/toolcraft-design/src/tokens/colors.ts", "../packages/toolcraft-design/src/internal/output-format.ts", "../packages/toolcraft-design/src/internal/theme-detect.ts", "../packages/toolcraft-design/src/components/symbols.ts", "../packages/toolcraft-design/src/internal/strip-ansi.ts", "../packages/toolcraft-design/src/prompts/primitives/log.ts", "../packages/toolcraft-design/src/components/logger.ts", "../packages/toolcraft-design/src/components/help-formatter.ts", "../packages/toolcraft-design/src/components/table.ts", "../packages/toolcraft-design/src/components/detail-card.ts", "../packages/toolcraft-design/src/components/template.ts", "../packages/toolcraft-design/src/components/browser.ts", "../packages/frontmatter/src/parse.ts", "../packages/frontmatter/src/stringify.ts", "../packages/toolcraft-design/src/dashboard/terminal-width.ts", "../packages/toolcraft-design/src/acp/writer.ts", "../packages/toolcraft-design/src/dashboard/terminal.ts", "../packages/toolcraft-design/src/explorer/state.ts", "../packages/toolcraft-design/src/prompts/interactive/glyphs.ts", "../packages/toolcraft-design/src/prompts/interactive/core.ts", "../packages/toolcraft-design/src/prompts/interactive/wrap.ts", "../packages/toolcraft-design/src/prompts/interactive/pagination.ts", "../packages/toolcraft-design/src/static/spinner.ts", "../packages/config-mutations/src/formats/json.ts", "../packages/config-mutations/src/formats/object.ts", "../packages/config-mutations/src/formats/toml.ts", "../packages/config-mutations/src/formats/yaml.ts", "../packages/config-mutations/src/formats/index.ts", "../packages/config-mutations/src/execution/path-utils.ts", "../packages/config-mutations/src/error-codes.ts", "../packages/config-mutations/src/fs-utils.ts", "../packages/config-mutations/src/execution/run-mutations.ts", "../packages/agent-skill-config/src/error-codes.ts", "../packages/agent-skill-config/src/templates.ts", "../packages/agent-skill-config/src/apply.ts", "../packages/agent-skill-config/src/resolve-skill-reference.ts", "../packages/agent-skill-config/src/git-exclude.ts", "../packages/agent-skill-config/src/bridge-active-skills.ts"],
4
+ "sourcesContent": ["import type { Stats } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport {\n installSkill as installAgentSkill,\n type InstallSkillResult,\n type SkillScope\n} from \"@poe-code/agent-skill-config\";\n\nexport interface InstallSkillFileSystem {\n readFile(path: string, encoding: BufferEncoding): Promise<string>;\n readFile(path: string): Promise<Buffer>;\n symlink(target: string, path: string): Promise<void>;\n readlink(path: string): Promise<string>;\n realpath(path: string): Promise<string>;\n writeFile(\n path: string,\n data: string | NodeJS.ArrayBufferView,\n options?: { encoding?: BufferEncoding; flag?: string }\n ): Promise<void>;\n mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;\n stat(path: string): Promise<Stats>;\n lstat(path: string): Promise<Stats>;\n rename(oldPath: string, newPath: string): Promise<void>;\n rm?(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;\n unlink(path: string): Promise<void>;\n readdir(path: string): Promise<string[]>;\n copyFile?(src: string, dest: string): Promise<void>;\n chmod?(path: string, mode: number): Promise<void>;\n}\n\nexport type InstallSkillSource =\n | {\n name: string;\n content: string;\n }\n | {\n name: string;\n file: string;\n };\n\nexport interface InstallSkillOptions {\n cwd?: string;\n homeDir?: string;\n scope?: SkillScope;\n dryRun?: boolean;\n fs?: InstallSkillFileSystem;\n}\n\nfunction createNodeFileSystem(): InstallSkillFileSystem {\n return {\n readFile: ((filePath: string, encoding?: BufferEncoding) => {\n if (encoding) {\n return fs.readFile(filePath, encoding);\n }\n return fs.readFile(filePath);\n }) as InstallSkillFileSystem[\"readFile\"],\n symlink: (target, filePath) => fs.symlink(target, filePath),\n readlink: (filePath) => fs.readlink(filePath, { encoding: \"utf8\" }),\n realpath: (filePath) => fs.realpath(filePath),\n writeFile: (filePath, data, options) => fs.writeFile(filePath, data, options),\n mkdir: (filePath, options) => fs.mkdir(filePath, options).then(() => {}),\n stat: (filePath) => fs.stat(filePath),\n lstat: (filePath) => fs.lstat(filePath),\n rename: (oldPath, newPath) => fs.rename(oldPath, newPath),\n rm: (filePath, options) => fs.rm(filePath, options),\n unlink: (filePath) => fs.unlink(filePath),\n readdir: (filePath) => fs.readdir(filePath),\n copyFile: (src, dest) => fs.copyFile(src, dest),\n chmod: (filePath, mode) => fs.chmod(filePath, mode)\n };\n}\n\nasync function resolveSkillContent(\n source: InstallSkillSource,\n options: { cwd: string; fs: InstallSkillFileSystem }\n): Promise<string> {\n if (\"content\" in source) {\n return source.content;\n }\n\n const sourcePath = path.isAbsolute(source.file)\n ? source.file\n : path.resolve(options.cwd, source.file);\n return options.fs.readFile(sourcePath, \"utf8\");\n}\n\n/**\n * Install arbitrary skill content into an agent's native skill directory.\n *\n * The actual mutation and validation are delegated to poe-code's agent skill\n * configuration machinery, so SDK and CLI installs share the same safety rules.\n */\nexport async function installSkill(\n agentId: string,\n source: InstallSkillSource,\n options: InstallSkillOptions = {}\n): Promise<InstallSkillResult> {\n const cwd = options.cwd ?? process.cwd();\n const homeDir = options.homeDir ?? os.homedir();\n const fileSystem = options.fs ?? createNodeFileSystem();\n const content = await resolveSkillContent(source, { cwd, fs: fileSystem });\n\n return installAgentSkill(\n agentId,\n {\n name: source.name,\n content\n },\n {\n fs: fileSystem,\n cwd,\n homeDir,\n scope: options.scope ?? \"local\",\n dryRun: options.dryRun\n }\n );\n}\n\nexport type { InstallSkillResult, SkillScope };\n", "import os from \"node:os\";\nimport path from \"node:path\";\nimport { resolveAgentId } from \"@poe-code/agent-defs\";\n\nexport interface AgentSkillConfig {\n globalSkillDir: string;\n localSkillDir: string;\n}\n\nexport type SkillScope = \"global\" | \"local\";\n\nconst agentSkillConfigs: Record<string, AgentSkillConfig> = {\n \"claude-code\": {\n globalSkillDir: \"~/.claude/skills\",\n localSkillDir: \".claude/skills\"\n },\n codex: {\n globalSkillDir: \"~/.codex/skills\",\n localSkillDir: \".codex/skills\"\n },\n cursor: {\n globalSkillDir: \"~/.cursor/skills-cursor\",\n localSkillDir: \".cursor/skills\"\n },\n \"gemini-cli\": {\n globalSkillDir: \"~/.gemini/skills\",\n localSkillDir: \".gemini/skills\"\n },\n opencode: {\n globalSkillDir: \"~/.config/opencode/skills\",\n localSkillDir: \".opencode/skills\"\n },\n goose: {\n globalSkillDir: \"~/.agents/skills\",\n localSkillDir: \".agents/skills\"\n }\n};\n\nexport const supportedAgents = Object.freeze(Object.keys(agentSkillConfigs)) as readonly string[];\n\nexport type AgentSupportStatus = \"supported\" | \"unsupported\" | \"unknown\";\n\nexport interface AgentSupportResult {\n status: AgentSupportStatus;\n input: string;\n id?: string;\n config?: AgentSkillConfig;\n}\n\nexport function resolveAgentSupport(\n input: string,\n registry: Record<string, AgentSkillConfig> = agentSkillConfigs\n): AgentSupportResult {\n const resolvedId = resolveAgentId(input);\n if (!resolvedId) {\n return { status: \"unknown\", input };\n }\n\n const config = registry[resolvedId];\n if (!config) {\n return { status: \"unsupported\", input, id: resolvedId };\n }\n\n return { status: \"supported\", input, id: resolvedId, config: { ...config } };\n}\n\nexport function getAgentConfig(agentId: string): AgentSkillConfig | undefined {\n const support = resolveAgentSupport(agentId);\n return support.status === \"supported\" ? support.config : undefined;\n}\n\nfunction expandHome(targetPath: string, homeDir: string = os.homedir()): string {\n if (!targetPath?.startsWith(\"~\")) {\n return targetPath;\n }\n\n if (targetPath === \"~\") {\n return homeDir;\n }\n\n // Handle ~./ -> ~/.\n if (targetPath.startsWith(\"~./\")) {\n targetPath = `~/.${targetPath.slice(3)}`;\n }\n\n let remainder = targetPath.slice(1);\n if (remainder.startsWith(\"/\") || remainder.startsWith(\"\\\\\")) {\n remainder = remainder.slice(1);\n } else if (remainder.startsWith(\".\")) {\n remainder = remainder.slice(1);\n if (remainder.startsWith(\"/\") || remainder.startsWith(\"\\\\\")) {\n remainder = remainder.slice(1);\n }\n }\n\n return remainder.length === 0 ? homeDir : path.join(homeDir, remainder);\n}\n\nexport function resolveSkillDir(\n config: AgentSkillConfig,\n scope: SkillScope,\n cwd: string,\n homeDir?: string\n): string {\n if (scope === \"global\") {\n return path.resolve(expandHome(config.globalSkillDir, homeDir));\n }\n\n return path.resolve(cwd, config.localSkillDir);\n}\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const claudeCodeAgent: AgentDefinition = {\n id: \"claude-code\",\n name: \"claude-code\",\n label: \"Claude Code\",\n summary: \"Configure Claude Code to route through Poe.\",\n aliases: [\"claude\"],\n binaryName: \"claude\",\n apiShapes: [\"anthropic-messages\"],\n otelCapture: {\n env: {\n CLAUDE_CODE_ENABLE_TELEMETRY: \"1\"\n }\n },\n configPath: \"~/.claude.json\",\n branding: {\n colors: {\n dark: \"#C15F3C\",\n light: \"#C15F3C\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const claudeDesktopAgent: AgentDefinition = {\n id: \"claude-desktop\",\n name: \"claude-desktop\",\n label: \"Claude Desktop\",\n summary: \"Anthropic's official desktop application for Claude\",\n configPath: \"~/.config/Claude/claude_desktop_config.json\",\n configPaths: {\n darwin: \"~/Library/Application Support/Claude/claude_desktop_config.json\",\n linux: \"~/.config/Claude/claude_desktop_config.json\",\n win32: \"~/AppData/Roaming/Claude/claude_desktop_config.json\"\n },\n branding: {\n colors: {\n dark: \"#D97757\",\n light: \"#D97757\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const codexAgent: AgentDefinition = {\n id: \"codex\",\n name: \"codex\",\n label: \"Codex\",\n summary: \"Configure Codex to use Poe as the model provider.\",\n binaryName: \"codex\",\n apiShapes: [\"openai-responses\"],\n otelCapture: {\n args: (endpoint, content) => [\n \"-c\",\n `otel.trace_exporter={\"otlp-http\"={endpoint=${JSON.stringify(`${endpoint}/v1/traces`)},protocol=\"json\"}}`,\n \"-c\",\n `otel.exporter={\"otlp-http\"={endpoint=${JSON.stringify(`${endpoint}/v1/logs`)},protocol=\"json\"}}`,\n \"-c\",\n `otel.log_user_prompt=${content}`\n ]\n },\n configPath: \"~/.codex/config.toml\",\n branding: {\n colors: {\n dark: \"#D5D9DF\",\n light: \"#7A7F86\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const cursorAgent: AgentDefinition = {\n id: \"cursor\",\n name: \"cursor\",\n aliases: [\"cursor-agent\"],\n label: \"Cursor\",\n summary: \"Cursor's CLI coding agent.\",\n binaryName: \"cursor-agent\",\n configPath: \"~/.cursor/mcp.json\",\n branding: {\n colors: {\n dark: \"#FFFFFF\",\n light: \"#000000\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const geminiCliAgent: AgentDefinition = {\n id: \"gemini-cli\",\n name: \"gemini-cli\",\n aliases: [\"gemini\"],\n label: \"Gemini CLI\",\n summary: \"Configure Google's Gemini CLI to use a compatible Google generations API.\",\n binaryName: \"gemini\",\n configPath: \"~/.gemini/settings.json\",\n apiShapes: [\"google-generations\"],\n branding: {\n colors: {\n dark: \"#8AB4F8\",\n light: \"#1A73E8\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const openCodeAgent: AgentDefinition = {\n id: \"opencode\",\n name: \"opencode\",\n label: \"OpenCode CLI\",\n summary: \"Configure OpenCode CLI to use the Poe API.\",\n binaryName: \"opencode\",\n apiShapes: [\"openai-chat-completions\"],\n otelCapture: {\n env: {\n OPENCODE_CONFIG_CONTENT: '{\"experimental\":{\"openTelemetry\":true}}'\n }\n },\n configPath: \"~/.config/opencode/opencode.json\",\n branding: {\n colors: {\n dark: \"#4A4F55\",\n light: \"#2F3338\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const kimiAgent: AgentDefinition = {\n id: \"kimi\",\n name: \"kimi\",\n label: \"Kimi\",\n summary: \"Configure Kimi CLI to use Poe API\",\n aliases: [\"kimi-cli\"],\n binaryName: \"kimi\",\n apiShapes: [\"openai-chat-completions\"],\n configPath: \"~/.kimi/mcp.json\",\n branding: {\n colors: {\n dark: \"#7B68EE\",\n light: \"#6A5ACD\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const gooseAgent: AgentDefinition = {\n id: \"goose\",\n name: \"goose\",\n label: \"Goose\",\n summary: \"Block's open-source AI agent with ACP support.\",\n binaryName: \"goose\",\n apiShapes: [\"openai-chat-completions\"],\n otelCapture: {},\n configPath: \"~/.config/goose/config.yaml\",\n branding: {\n colors: {\n dark: \"#FF6B35\",\n light: \"#E85D26\"\n }\n }\n};\n", "import type { AgentDefinition } from \"../types.js\";\n\nexport const poeAgentAgent: AgentDefinition = {\n id: \"poe-agent\",\n name: \"poe-agent\",\n label: \"Poe Agent\",\n summary: \"Run one-shot prompts with the built-in Poe agent runtime.\",\n apiShapes: [\"openai-responses\", \"openai-chat-completions\"],\n configPath: \"~/.poe-code/config.json\",\n branding: {\n colors: {\n dark: \"#A465F7\",\n light: \"#7A3FD3\"\n }\n }\n};\n", "import type { AgentDefinition } from \"./types.js\";\nimport {\n claudeCodeAgent,\n claudeDesktopAgent,\n codexAgent,\n cursorAgent,\n geminiCliAgent,\n openCodeAgent,\n kimiAgent,\n gooseAgent,\n poeAgentAgent\n} from \"./agents/index.js\";\n\nfunction freezeAgent(agent: AgentDefinition): AgentDefinition {\n if (agent.aliases !== undefined) {\n Object.freeze(agent.aliases);\n }\n if (agent.apiShapes !== undefined) {\n Object.freeze(agent.apiShapes);\n }\n if (agent.otelCapture?.env !== undefined) {\n Object.freeze(agent.otelCapture.env);\n }\n if (agent.otelCapture !== undefined) {\n Object.freeze(agent.otelCapture);\n }\n Object.freeze(agent.branding.colors);\n Object.freeze(agent.branding);\n return Object.freeze(agent);\n}\n\nexport const allAgents: readonly AgentDefinition[] = Object.freeze([\n freezeAgent(claudeCodeAgent),\n freezeAgent(claudeDesktopAgent),\n freezeAgent(codexAgent),\n freezeAgent(cursorAgent),\n freezeAgent(geminiCliAgent),\n freezeAgent(openCodeAgent),\n freezeAgent(kimiAgent),\n freezeAgent(gooseAgent),\n freezeAgent(poeAgentAgent)\n]);\n\nconst lookup = new Map<string, string>();\n\nfor (const agent of allAgents) {\n const values = [agent.id, agent.name, ...(agent.aliases ?? [])];\n for (const value of values) {\n const normalized = value.toLowerCase();\n if (!lookup.has(normalized)) {\n lookup.set(normalized, agent.id);\n }\n }\n}\n\nexport function resolveAgentId(input: string): string | undefined {\n if (!input) {\n return undefined;\n }\n return lookup.get(input.trim().toLowerCase());\n}\n", "import type {\n EnsureDirectoryMutation,\n RemoveDirectoryMutation,\n RemoveFileMutation,\n ChmodMutation,\n BackupMutation,\n RestoreBackupMutation,\n ValueResolver\n} from \"../types.js\";\n\nexport interface EnsureDirectoryOptions {\n /** Directory path (must start with ~) */\n path: ValueResolver<string>;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface RemoveOptions {\n /** Target file path (must start with ~) */\n target: ValueResolver<string>;\n /** Only remove if file is empty/whitespace */\n whenEmpty?: boolean;\n /** Only remove if content matches regex */\n whenContentMatches?: RegExp;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface RemoveDirectoryOptions {\n /** Directory path (must start with ~) */\n path: ValueResolver<string>;\n /** Remove directory even when not empty */\n force?: boolean;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface ChmodOptions {\n /** Target file path (must start with ~) */\n target: ValueResolver<string>;\n /** File permission mode (e.g., 0o755) */\n mode: number;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface BackupOptions {\n /** Target file path to backup (must start with ~) */\n target: ValueResolver<string>;\n /** Keep the first baseline only, including an originally missing target. */\n once?: boolean;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface RestoreBackupOptions {\n /** Target file path whose latest generated backup should be restored. */\n target: ValueResolver<string>;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nfunction ensureDirectory(options: EnsureDirectoryOptions): EnsureDirectoryMutation {\n return {\n kind: \"ensureDirectory\",\n path: options.path,\n label: options.label\n };\n}\n\nfunction remove(options: RemoveOptions): RemoveFileMutation {\n return {\n kind: \"removeFile\",\n target: options.target,\n whenEmpty: options.whenEmpty,\n whenContentMatches: options.whenContentMatches,\n label: options.label\n };\n}\n\nfunction removeDirectory(\n options: RemoveDirectoryOptions\n): RemoveDirectoryMutation {\n return {\n kind: \"removeDirectory\",\n path: options.path,\n force: options.force,\n label: options.label\n };\n}\n\nfunction chmod(options: ChmodOptions): ChmodMutation {\n return {\n kind: \"chmod\",\n target: options.target,\n mode: options.mode,\n label: options.label\n };\n}\n\nfunction backup(options: BackupOptions): BackupMutation {\n return {\n kind: \"backup\",\n target: options.target,\n once: options.once,\n label: options.label\n };\n}\n\nfunction restoreBackup(options: RestoreBackupOptions): RestoreBackupMutation {\n return {\n kind: \"restoreBackup\",\n target: options.target,\n label: options.label\n };\n}\n\nexport const fileMutation = {\n ensureDirectory,\n remove,\n removeDirectory,\n chmod,\n backup,\n restoreBackup\n};\n", "import type {\n TemplateWriteMutation,\n TemplateMergeTomlMutation,\n TemplateMergeJsonMutation,\n ConfigObject,\n ValueResolver\n} from \"../types.js\";\n\nexport interface WriteOptions {\n /** Target file path (must start with ~) */\n target: ValueResolver<string>;\n /** Template ID to load via template loader */\n templateId: string;\n /** Context to pass to renderTemplate() */\n context?: ValueResolver<ConfigObject>;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface MergeTomlOptions {\n /** Target TOML file path (must start with ~) */\n target: ValueResolver<string>;\n /** Template ID to load via template loader */\n templateId: string;\n /** Context to pass to renderTemplate() */\n context?: ValueResolver<ConfigObject>;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nexport interface MergeJsonOptions {\n /** Target JSON file path (must start with ~) */\n target: ValueResolver<string>;\n /** Template ID to load via template loader */\n templateId: string;\n /** Context to pass to renderTemplate() */\n context?: ValueResolver<ConfigObject>;\n /** Optional human-readable label for logging */\n label?: string;\n}\n\nfunction write(options: WriteOptions): TemplateWriteMutation {\n return {\n kind: \"templateWrite\",\n target: options.target,\n templateId: options.templateId,\n context: options.context,\n label: options.label\n };\n}\n\nfunction mergeToml(options: MergeTomlOptions): TemplateMergeTomlMutation {\n return {\n kind: \"templateMergeToml\",\n target: options.target,\n templateId: options.templateId,\n context: options.context,\n label: options.label\n };\n}\n\nfunction mergeJson(options: MergeJsonOptions): TemplateMergeJsonMutation {\n return {\n kind: \"templateMergeJson\",\n target: options.target,\n templateId: options.templateId,\n context: options.context,\n label: options.label\n };\n}\n\nexport const templateMutation = {\n write,\n mergeToml,\n mergeJson\n};\n", "import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { renderTemplate } from \"toolcraft-design\";\nimport type {\n Mutation,\n MutationContext,\n MutationOutcome,\n MutationDetails,\n ConfigObject,\n MutationOptions,\n ValueResolver,\n FileSystem\n} from \"../types.js\";\nimport { getConfigFormat, detectFormat } from \"../formats/index.js\";\nimport { cloneConfigObject, setConfigEntry } from \"../formats/object.js\";\nimport { resolvePath } from \"./path-utils.js\";\nimport {\n isNotFound,\n readFileIfExists,\n pathExists,\n createTimestamp\n} from \"../fs-utils.js\";\nimport { hasOwnErrorCode } from \"../error-codes.js\";\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nfunction resolveValue<T>(\n resolver: ValueResolver<T>,\n options: MutationOptions\n): T {\n if (typeof resolver === \"function\") {\n return (resolver as (ctx: MutationOptions) => T)(options);\n }\n return resolver;\n}\n\nfunction createInvalidDocumentBackupPath(targetPath: string): string {\n const ext = targetPath.includes(\".\") ? targetPath.split(\".\").pop() : \"bak\";\n return `${targetPath}.invalid-${createTimestamp()}.${ext}`;\n}\n\nasync function backupInvalidDocument(\n context: MutationContext,\n targetPath: string,\n content: string\n): Promise<void> {\n const baseBackupPath = createInvalidDocumentBackupPath(targetPath);\n let attempt = 0;\n while (true) {\n const backupPath = attempt === 0 ? baseBackupPath : `${baseBackupPath}-${attempt}`;\n await assertRegularWriteTarget(context, backupPath);\n try {\n await context.fs.writeFile(backupPath, content, { encoding: \"utf8\", flag: \"wx\" });\n return;\n } catch (error) {\n if (!isAlreadyExists(error)) {\n await context.fs.unlink(backupPath).catch(() => undefined);\n throw error;\n }\n attempt += 1;\n }\n }\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return hasOwnErrorCode(error, \"EEXIST\");\n}\n\nasync function assertRegularWriteTarget(\n context: MutationContext,\n targetPath: string\n): Promise<void> {\n // Symlinks inside the managed home directory are untrusted: an attacker could\n // plant one to redirect a credential/config write outside it. Symlinks at or\n // above home are legitimate system links (e.g. /tmp -> /private/tmp on macOS,\n // /var -> /private/var) and must not block writes, so bound the walk at home.\n const boundary = path.dirname(path.resolve(context.homeDir));\n let currentPath = path.resolve(targetPath);\n while (currentPath !== boundary) {\n try {\n if ((await context.fs.lstat(currentPath)).isSymbolicLink()) {\n throw new Error(`Refusing mutation write through symbolic link: ${currentPath}`);\n }\n } catch (error) {\n if (!isNotFound(error)) {\n throw error;\n }\n }\n\n const parentPath = path.dirname(currentPath);\n if (parentPath === currentPath) {\n return;\n }\n currentPath = parentPath;\n }\n}\n\nasync function writeAtomically(\n context: MutationContext,\n targetPath: string,\n content: string\n): Promise<void> {\n await assertRegularWriteTarget(context, targetPath);\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const tempPath = `${targetPath}.mutation-tmp-${process.pid}-${randomUUID()}`;\n let tempCreated = false;\n try {\n await assertRegularWriteTarget(context, tempPath);\n await context.fs.writeFile(tempPath, content, { encoding: \"utf8\", flag: \"wx\" });\n tempCreated = true;\n await context.fs.rename(tempPath, targetPath);\n tempCreated = false;\n return;\n } catch (error) {\n const alreadyExists = isAlreadyExists(error);\n if (tempCreated || !alreadyExists) {\n try {\n await context.fs.unlink(tempPath);\n } catch (cleanupError) {\n if (!isNotFound(cleanupError)) {\n void cleanupError;\n }\n }\n }\n\n if (alreadyExists) {\n continue;\n }\n\n throw error;\n }\n }\n\n throw new Error(`Unable to create temporary mutation file for ${targetPath}.`);\n}\n\nfunction describeMutation(kind: string, targetPath?: string): string {\n const displayPath = targetPath ?? \"target\";\n switch (kind) {\n case \"ensureDirectory\":\n return `Create ${displayPath}`;\n case \"removeDirectory\":\n return `Remove directory ${displayPath}`;\n case \"backup\":\n return `Backup ${displayPath}`;\n case \"restoreBackup\":\n return `Restore ${displayPath}`;\n case \"templateWrite\":\n return `Write ${displayPath}`;\n case \"chmod\":\n return `Set permissions on ${displayPath}`;\n case \"removeFile\":\n return `Remove ${displayPath}`;\n case \"configMerge\":\n case \"configPrune\":\n case \"configTransform\":\n case \"templateMergeToml\":\n case \"templateMergeJson\":\n return `Update ${displayPath}`;\n default:\n return \"Operation\";\n }\n}\n\nfunction mutationTargetPath(\n mutation: Mutation,\n options: MutationOptions\n): string | undefined {\n switch (mutation.kind) {\n case \"ensureDirectory\":\n case \"removeDirectory\":\n return resolveValue(mutation.path, options);\n case \"removeFile\":\n case \"chmod\":\n case \"backup\":\n case \"restoreBackup\":\n case \"configMerge\":\n case \"configPrune\":\n case \"configTransform\":\n case \"templateWrite\":\n case \"templateMergeToml\":\n case \"templateMergeJson\":\n return resolveValue(mutation.target, options);\n default:\n return undefined;\n }\n}\n\nexport function resolveMutationDetails(\n mutation: Mutation,\n context: MutationContext,\n options: MutationOptions\n): MutationDetails {\n try {\n const rawTarget = mutationTargetPath(mutation, options);\n if (rawTarget === undefined) {\n return {\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind\n };\n }\n\n try {\n const targetPath = resolvePath(rawTarget, context.homeDir, context.pathMapper);\n return {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n } catch {\n return {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, rawTarget),\n targetPath: undefined\n };\n }\n } catch {\n return {\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind\n };\n }\n}\n\nfunction pruneKeysByPrefix(\n table: ConfigObject,\n prefix: string\n): ConfigObject {\n const result: ConfigObject = {};\n for (const [key, value] of Object.entries(table)) {\n if (!key.startsWith(prefix)) {\n setConfigEntry(result, key, value);\n }\n }\n return result;\n}\n\nfunction isConfigObject(value: unknown): value is ConfigObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction mergeWithPruneByPrefix(\n base: ConfigObject,\n patch: ConfigObject,\n pruneByPrefix?: Record<string, string>\n): ConfigObject {\n const result = cloneConfigObject(base);\n const prefixMap = pruneByPrefix ?? {};\n\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n\n const current = result[key];\n const prefix = prefixMap[key];\n\n if (isConfigObject(current) && isConfigObject(value)) {\n if (prefix) {\n const pruned = pruneKeysByPrefix(current, prefix);\n setConfigEntry(result, key, mergePrunedConfigObject(pruned, value));\n } else {\n setConfigEntry(result, key, mergeWithPruneByPrefix(current, value, prefixMap));\n }\n continue;\n }\n setConfigEntry(result, key, value);\n }\n return result;\n}\n\nfunction mergePrunedConfigObject(base: ConfigObject, patch: ConfigObject): ConfigObject {\n const result = cloneConfigObject(base);\n\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n\n setConfigEntry(result, key, value);\n }\n\n return result;\n}\n\nfunction serializeConfigUpdate(\n format: ReturnType<typeof getConfigFormat>,\n rawContent: string | null,\n current: ConfigObject,\n next: ConfigObject\n): string {\n if (rawContent !== null && format.serializeUpdate) {\n return format.serializeUpdate(rawContent, current, next);\n }\n return format.serialize(next);\n}\n\n// ============================================================================\n// Apply Mutation\n// ============================================================================\n\nexport async function applyMutation(\n mutation: Mutation,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n switch (mutation.kind) {\n case \"ensureDirectory\":\n return applyEnsureDirectory(mutation, context, options);\n case \"removeDirectory\":\n return applyRemoveDirectory(mutation, context, options);\n case \"removeFile\":\n return applyRemoveFile(mutation, context, options);\n case \"chmod\":\n return applyChmod(mutation, context, options);\n case \"backup\":\n return applyBackup(mutation, context, options);\n case \"restoreBackup\":\n return applyRestoreBackup(mutation, context, options);\n case \"configMerge\":\n return applyConfigMerge(mutation, context, options);\n case \"configPrune\":\n return applyConfigPrune(mutation, context, options);\n case \"configTransform\":\n return applyConfigTransform(mutation, context, options);\n case \"templateWrite\":\n return applyTemplateWrite(mutation, context, options);\n case \"templateMergeToml\":\n return applyTemplateMerge(mutation, context, options, \"toml\");\n case \"templateMergeJson\":\n return applyTemplateMerge(mutation, context, options, \"json\");\n default: {\n const never: never = mutation;\n throw new Error(`Unknown mutation kind: ${(never as Mutation).kind}`);\n }\n }\n}\n\n// ============================================================================\n// File Mutation Handlers\n// ============================================================================\n\nasync function applyEnsureDirectory(\n mutation: Extract<Mutation, { kind: \"ensureDirectory\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.path, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n await assertRegularWriteTarget(context, targetPath);\n const existed = await pathExists(context.fs, targetPath);\n\n if (!context.dryRun) {\n await context.fs.mkdir(targetPath, { recursive: true });\n }\n\n return {\n outcome: {\n changed: !existed,\n effect: \"mkdir\",\n detail: existed ? \"noop\" : \"create\"\n },\n details\n };\n}\n\nasync function applyRemoveDirectory(\n mutation: Extract<Mutation, { kind: \"removeDirectory\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.path, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const existed = await pathExists(context.fs, targetPath);\n if (!existed) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (typeof context.fs.rm !== \"function\") {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (mutation.force) {\n if (!context.dryRun) {\n await context.fs.rm(targetPath, { recursive: true, force: true });\n }\n return {\n outcome: { changed: true, effect: \"delete\", detail: \"delete\" },\n details\n };\n }\n\n const entries = await context.fs.readdir(targetPath);\n if (entries.length > 0) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n await context.fs.rm(targetPath, { recursive: true, force: true });\n }\n\n return {\n outcome: { changed: true, effect: \"delete\", detail: \"delete\" },\n details\n };\n}\n\nasync function applyRemoveFile(\n mutation: Extract<Mutation, { kind: \"removeFile\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n try {\n const content = await context.fs.readFile(targetPath, \"utf8\");\n const trimmed = content.trim();\n\n // Check whenContentMatches guard\n if (mutation.whenContentMatches) {\n mutation.whenContentMatches.lastIndex = 0;\n }\n if (mutation.whenContentMatches && !mutation.whenContentMatches.test(trimmed)) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n // Check whenEmpty guard\n if (mutation.whenEmpty && trimmed.length > 0) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n await context.fs.unlink(targetPath);\n }\n\n return {\n outcome: { changed: true, effect: \"delete\", detail: \"delete\" },\n details\n };\n } catch (error) {\n if (isNotFound(error)) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n throw error;\n }\n}\n\nasync function applyChmod(\n mutation: Extract<Mutation, { kind: \"chmod\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n if (typeof context.fs.chmod !== \"function\") {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n try {\n await assertRegularWriteTarget(context, targetPath);\n const stat = await context.fs.stat(targetPath);\n const currentMode = typeof stat.mode === \"number\" ? stat.mode & 0o777 : null;\n\n if (currentMode === mutation.mode) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n await context.fs.chmod(targetPath, mutation.mode);\n }\n\n return {\n outcome: { changed: true, effect: \"chmod\", detail: \"update\" },\n details\n };\n } catch (error) {\n if (isNotFound(error)) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n throw error;\n }\n}\n\nasync function applyBackup(\n mutation: Extract<Mutation, { kind: \"backup\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n await assertRegularWriteTarget(context, targetPath);\n if (mutation.once && (await findLatestGeneratedBackup(context.fs, targetPath)) !== null) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n const content = await readFileIfExists(context.fs, targetPath);\n if (content === null && !mutation.once) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n const baseBackupPath = `${targetPath}.backup-${createTimestamp()}${content === null ? \".missing\" : \"\"}`;\n let attempt = 0;\n while (true) {\n const backupPath = attempt === 0 ? baseBackupPath : `${baseBackupPath}-${attempt}`;\n try {\n await assertRegularWriteTarget(context, backupPath);\n await context.fs.writeFile(backupPath, content ?? \"\", { encoding: \"utf8\", flag: \"wx\" });\n break;\n } catch (error) {\n if (!isAlreadyExists(error)) {\n await context.fs.unlink(backupPath).catch(() => undefined);\n throw error;\n }\n attempt += 1;\n }\n }\n }\n\n return {\n outcome: { changed: true, effect: \"copy\", detail: \"backup\" },\n details\n };\n}\n\nasync function applyRestoreBackup(\n mutation: Extract<Mutation, { kind: \"restoreBackup\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n const backup = await findLatestGeneratedBackup(context.fs, targetPath);\n\n if (backup === null) {\n return { outcome: { changed: false, effect: \"none\", detail: \"noop\" }, details };\n }\n\n if (!context.dryRun) {\n await assertRegularWriteTarget(context, backup.path);\n if (backup.originallyMissing) {\n try {\n await context.fs.unlink(targetPath);\n } catch (error) {\n if (!isNotFound(error)) {\n throw error;\n }\n }\n } else {\n const content = await context.fs.readFile(backup.path, \"utf8\");\n await writeAtomically(context, targetPath, content);\n }\n await context.fs.unlink(backup.path);\n }\n\n return { outcome: { changed: true, effect: \"copy\", detail: \"restore\" }, details };\n}\n\nasync function findLatestGeneratedBackup(\n fs: FileSystem,\n targetPath: string\n): Promise<{ path: string; originallyMissing: boolean } | null> {\n const separatorIndex = targetPath.lastIndexOf(\"/\");\n const directoryPath = separatorIndex <= 0 ? \"/\" : targetPath.slice(0, separatorIndex);\n const targetName = targetPath.slice(separatorIndex + 1);\n let entries: string[];\n\n try {\n entries = await fs.readdir(directoryPath);\n } catch (error) {\n if (isNotFound(error)) {\n return null;\n }\n throw error;\n }\n\n const backupName = entries\n .filter((entry) => isGeneratedBackupName(entry, targetName))\n .sort()\n .at(-1);\n return backupName === undefined\n ? null\n : {\n path: `${directoryPath}/${backupName}`,\n originallyMissing: backupName.endsWith(\".missing\")\n };\n}\n\nfunction isGeneratedBackupName(entry: string, targetName: string): boolean {\n const prefix = `${targetName}.backup-`;\n if (!entry.startsWith(prefix)) {\n return false;\n }\n\n const suffix = entry.slice(prefix.length);\n const timestamp = suffix.slice(0, 24);\n if (timestamp.length !== 24 || timestamp[4] !== \"-\" || timestamp[7] !== \"-\" || timestamp[10] !== \"T\" || timestamp[13] !== \"-\" || timestamp[16] !== \"-\" || timestamp[19] !== \"-\" || timestamp[23] !== \"Z\") {\n return false;\n }\n const parsedTimestamp = `${timestamp.slice(0, 13)}:${timestamp.slice(14, 16)}:${timestamp.slice(17, 19)}.${timestamp.slice(20)}`;\n if (Number.isNaN(Date.parse(parsedTimestamp))) {\n return false;\n }\n const collisionSuffix = suffix.slice(24);\n if (collisionSuffix.length === 0) {\n return true;\n }\n if (collisionSuffix === \".missing\") {\n return true;\n }\n return collisionSuffix[0] === \"-\" && collisionSuffix.slice(1).length > 0 && [...collisionSuffix.slice(1)].every((character) => character >= \"0\" && character <= \"9\");\n}\n\n// ============================================================================\n// Config Mutation Handlers\n// ============================================================================\n\nasync function applyConfigMerge(\n mutation: Extract<Mutation, { kind: \"configMerge\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const formatName = mutation.format ?? detectFormat(rawPath);\n if (!formatName) {\n throw new Error(\n `Cannot detect config format for \"${rawPath}\". Provide explicit format option.`\n );\n }\n const format = getConfigFormat(formatName);\n\n const rawContent = await readFileIfExists(context.fs, targetPath);\n let preserveContent = rawContent;\n let current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n // Invalid file - backup and start fresh\n if (rawContent !== null && !context.dryRun) {\n await backupInvalidDocument(context, targetPath, rawContent);\n }\n current = {};\n preserveContent = null;\n }\n\n const value = resolveValue(mutation.value, options);\n if (!isConfigObject(value)) {\n throw new Error(`configMerge value must be an object for \"${rawPath}\".`);\n }\n\n // Keep prefix pruning on the same proto-safe object-write path as normal merges.\n let merged: ConfigObject;\n if (mutation.pruneByPrefix) {\n merged = mergeWithPruneByPrefix(current, value, mutation.pruneByPrefix);\n } else {\n merged = format.merge(current, value);\n }\n\n const serialized = serializeConfigUpdate(format, preserveContent, current, merged);\n const changed = serialized !== rawContent;\n\n if (changed && !context.dryRun) {\n await writeAtomically(context, targetPath, serialized);\n }\n\n return {\n outcome: {\n changed,\n effect: changed ? \"write\" : \"none\",\n detail: changed ? (rawContent === null ? \"create\" : \"update\") : \"noop\"\n },\n details\n };\n}\n\nasync function applyConfigPrune(\n mutation: Extract<Mutation, { kind: \"configPrune\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const rawContent = await readFileIfExists(context.fs, targetPath);\n if (rawContent === null) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n const formatName = mutation.format ?? detectFormat(rawPath);\n if (!formatName) {\n throw new Error(\n `Cannot detect config format for \"${rawPath}\". Provide explicit format option.`\n );\n }\n const format = getConfigFormat(formatName);\n\n let current: ConfigObject;\n try {\n current = format.parse(rawContent);\n } catch {\n // Invalid file - can't prune, leave as-is\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n // Check onlyIf guard\n if (mutation.onlyIf && !mutation.onlyIf(current, options)) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n const shape = resolveValue(mutation.shape, options);\n const { changed, result } = format.prune(current, shape);\n\n if (!changed) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n // Delete file if empty\n if (Object.keys(result).length === 0) {\n if (!context.dryRun) {\n await context.fs.unlink(targetPath);\n }\n return {\n outcome: { changed: true, effect: \"delete\", detail: \"delete\" },\n details\n };\n }\n\n const serialized = serializeConfigUpdate(format, rawContent, current, result);\n if (!context.dryRun) {\n await writeAtomically(context, targetPath, serialized);\n }\n\n return {\n outcome: { changed: true, effect: \"write\", detail: \"update\" },\n details\n };\n}\n\nasync function applyConfigTransform(\n mutation: Extract<Mutation, { kind: \"configTransform\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const formatName = mutation.format ?? detectFormat(rawPath);\n if (!formatName) {\n throw new Error(\n `Cannot detect config format for \"${rawPath}\". Provide explicit format option.`\n );\n }\n const format = getConfigFormat(formatName);\n\n const rawContent = await readFileIfExists(context.fs, targetPath);\n let preserveContent = rawContent;\n let current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n if (rawContent !== null && !context.dryRun) {\n await backupInvalidDocument(context, targetPath, rawContent);\n }\n current = {};\n preserveContent = null;\n }\n\n const { content: transformed, changed } = mutation.transform(current, options);\n\n if (!changed) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n // Delete file if null\n if (transformed === null) {\n if (rawContent === null) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n if (!context.dryRun) {\n await context.fs.unlink(targetPath);\n }\n return {\n outcome: { changed: true, effect: \"delete\", detail: \"delete\" },\n details\n };\n }\n\n const serialized = serializeConfigUpdate(format, preserveContent, current, transformed);\n const serializedChanged = serialized !== rawContent;\n if (!serializedChanged) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n await writeAtomically(context, targetPath, serialized);\n }\n\n return {\n outcome: {\n changed: true,\n effect: \"write\",\n detail: rawContent === null ? \"create\" : \"update\"\n },\n details\n };\n}\n\n// ============================================================================\n// Template Mutation Handlers\n// ============================================================================\n\nasync function applyTemplateWrite(\n mutation: Extract<Mutation, { kind: \"templateWrite\" }>,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n if (!context.templates) {\n throw new Error(\n \"Template mutations require a templates loader. \" +\n \"Provide templates function to runMutations context.\"\n );\n }\n\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const template = await context.templates(mutation.templateId);\n const templateContext = mutation.context\n ? resolveValue(mutation.context, options)\n : {};\n const rendered = renderTemplate(template, templateContext);\n\n const current = await readFileIfExists(context.fs, targetPath);\n const changed = current !== rendered;\n\n if (changed && !context.dryRun) {\n await writeAtomically(context, targetPath, rendered);\n }\n\n return {\n outcome: {\n changed,\n effect: changed ? \"write\" : \"none\",\n detail: changed ? (current === null ? \"create\" : \"update\") : \"noop\"\n },\n details\n };\n}\n\nasync function applyTemplateMerge(\n mutation: Extract<Mutation, { kind: \"templateMergeToml\" | \"templateMergeJson\" }>,\n context: MutationContext,\n options: MutationOptions,\n formatName: \"toml\" | \"json\"\n): Promise<{ outcome: MutationOutcome; details: MutationDetails }> {\n if (!context.templates) {\n throw new Error(\n \"Template mutations require a templates loader. \" +\n \"Provide templates function to runMutations context.\"\n );\n }\n\n const rawPath = resolveValue(mutation.target, options);\n const targetPath = resolvePath(rawPath, context.homeDir, context.pathMapper);\n\n const details: MutationDetails = {\n kind: mutation.kind,\n label: mutation.label ?? describeMutation(mutation.kind, targetPath),\n targetPath\n };\n\n const format = getConfigFormat(formatName);\n\n // Load and render template\n const template = await context.templates(mutation.templateId);\n const templateContext = mutation.context\n ? resolveValue(mutation.context, options)\n : {};\n const rendered = renderTemplate(template, templateContext);\n\n // Parse rendered template\n let templateDoc: ConfigObject;\n try {\n templateDoc = format.parse(rendered);\n } catch (error) {\n throw new Error(\n `Failed to parse rendered template \"${mutation.templateId}\" as ${formatName.toUpperCase()}: ${error}`,\n { cause: error }\n );\n }\n\n // Read and parse existing file\n const rawContent = await readFileIfExists(context.fs, targetPath);\n let current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n if (rawContent !== null && !context.dryRun) {\n await backupInvalidDocument(context, targetPath, rawContent);\n }\n current = {};\n }\n\n // Merge\n const merged = format.merge(current, templateDoc);\n const serialized = format.serialize(merged);\n const changed = serialized !== rawContent;\n\n if (changed && !context.dryRun) {\n await writeAtomically(context, targetPath, serialized);\n }\n\n return {\n outcome: {\n changed,\n effect: changed ? \"write\" : \"none\",\n detail: changed ? (rawContent === null ? \"create\" : \"update\") : \"noop\"\n },\n details\n };\n}\n", "export interface ColorSupportEnv {\n NO_COLOR?: string;\n FORCE_COLOR?: string;\n TERM?: string;\n}\n\nexport interface ColorSupportStream {\n isTTY?: boolean;\n}\n\nexport function supportsColor(\n env: ColorSupportEnv = process.env as ColorSupportEnv,\n stream: ColorSupportStream = process.stdout\n): boolean {\n if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== \"0\") {\n return true;\n }\n\n if (env.NO_COLOR !== undefined) {\n return false;\n }\n\n if (stream.isTTY !== true) {\n return false;\n }\n\n return typeof env.TERM === \"string\" && env.TERM.length > 0 && env.TERM !== \"dumb\";\n}\n", "import { supportsColor } from \"../internal/color-support.js\";\n\ntype AnsiStyleName =\n | \"reset\"\n | \"bold\"\n | \"dim\"\n | \"italic\"\n | \"underline\"\n | \"inverse\"\n | \"strikethrough\"\n | \"black\"\n | \"red\"\n | \"green\"\n | \"yellow\"\n | \"blue\"\n | \"magenta\"\n | \"cyan\"\n | \"white\"\n | \"gray\"\n | \"magentaBright\"\n | \"cyanBright\"\n | \"bgRed\"\n | \"bgGreen\"\n | \"bgYellow\"\n | \"bgBlue\"\n | \"bgMagenta\";\n\ninterface AnsiPair {\n open: string;\n}\n\nexport interface Color {\n (text: string): string;\n reset: Color;\n bold: Color;\n dim: Color;\n italic: Color;\n underline: Color;\n inverse: Color;\n strikethrough: Color;\n black: Color;\n red: Color;\n green: Color;\n yellow: Color;\n blue: Color;\n magenta: Color;\n cyan: Color;\n white: Color;\n gray: Color;\n magentaBright: Color;\n cyanBright: Color;\n bgRed: Color;\n bgGreen: Color;\n bgYellow: Color;\n bgBlue: Color;\n bgMagenta: Color;\n hex: (value: string) => Color;\n rgb: (red: number, green: number, blue: number) => Color;\n bgHex: (value: string) => Color;\n bgRgb: (red: number, green: number, blue: number) => Color;\n}\n\nconst reset = \"\\x1b[0m\";\n\nconst ansiStyles: Record<AnsiStyleName, AnsiPair> = {\n reset: { open: reset },\n bold: { open: \"\\x1b[1m\" },\n dim: { open: \"\\x1b[2m\" },\n italic: { open: \"\\x1b[3m\" },\n underline: { open: \"\\x1b[4m\" },\n inverse: { open: \"\\x1b[7m\" },\n strikethrough: { open: \"\\x1b[9m\" },\n black: { open: \"\\x1b[30m\" },\n red: { open: \"\\x1b[31m\" },\n green: { open: \"\\x1b[32m\" },\n yellow: { open: \"\\x1b[33m\" },\n blue: { open: \"\\x1b[34m\" },\n magenta: { open: \"\\x1b[35m\" },\n cyan: { open: \"\\x1b[36m\" },\n white: { open: \"\\x1b[37m\" },\n gray: { open: \"\\x1b[90m\" },\n magentaBright: { open: \"\\x1b[95m\" },\n cyanBright: { open: \"\\x1b[96m\" },\n bgRed: { open: \"\\x1b[41m\" },\n bgGreen: { open: \"\\x1b[42m\" },\n bgYellow: { open: \"\\x1b[43m\" },\n bgBlue: { open: \"\\x1b[44m\" },\n bgMagenta: { open: \"\\x1b[45m\" }\n};\n\nconst styleNames = Object.keys(ansiStyles) as AnsiStyleName[];\n\nfunction replaceAll(value: string, search: string, replacement: string): string {\n return value.split(search).join(replacement);\n}\n\nfunction applyStyles(text: string, styles: AnsiPair[]): string {\n if (!supportsColor() || styles.length === 0) {\n return text;\n }\n\n const open = styles.map((style) => style.open).join(\"\");\n const output = text.includes(reset) ? replaceAll(text, reset, `${reset}${open}`) : text;\n\n return `${open}${output}${reset}`;\n}\n\nfunction clampRgb(value: number): number {\n if (Number.isNaN(value)) {\n return 0;\n }\n\n return Math.min(255, Math.max(0, Math.round(value)));\n}\n\nfunction hexChannel(value: string, offset: number): number {\n return Number.parseInt(value.slice(offset, offset + 2), 16);\n}\n\nfunction normalizeHex(value: string): [number, number, number] {\n const normalized = value.startsWith(\"#\") ? value.slice(1) : value;\n\n if ((normalized.length !== 3 && normalized.length !== 6) ||\n Array.from(normalized).some((char) => !\"0123456789abcdefABCDEF\".includes(char))) {\n throw new Error(`Invalid hexadecimal color: ${value}`);\n }\n\n if (normalized.length === 3) {\n const red = normalized[0]!;\n const green = normalized[1]!;\n const blue = normalized[2]!;\n\n return [\n Number.parseInt(`${red}${red}`, 16),\n Number.parseInt(`${green}${green}`, 16),\n Number.parseInt(`${blue}${blue}`, 16)\n ];\n }\n\n return [\n hexChannel(normalized, 0),\n hexChannel(normalized, 2),\n hexChannel(normalized, 4)\n ];\n}\n\nfunction rgbStyle(red: number, green: number, blue: number): AnsiPair {\n return {\n open: `\\x1b[38;2;${clampRgb(red)};${clampRgb(green)};${clampRgb(blue)}m`\n };\n}\n\nfunction bgRgbStyle(red: number, green: number, blue: number): AnsiPair {\n return {\n open: `\\x1b[48;2;${clampRgb(red)};${clampRgb(green)};${clampRgb(blue)}m`\n };\n}\n\nfunction createColor(styles: AnsiPair[] = []): Color {\n const builder = ((text: string) => applyStyles(String(text), styles)) as Color;\n\n for (const name of styleNames) {\n Object.defineProperty(builder, name, {\n configurable: true,\n enumerable: true,\n get: () => createColor([...styles, ansiStyles[name]])\n });\n }\n\n builder.hex = (value: string) => {\n const [red, green, blue] = normalizeHex(value);\n return createColor([...styles, rgbStyle(red, green, blue)]);\n };\n\n builder.rgb = (red: number, green: number, blue: number) =>\n createColor([...styles, rgbStyle(red, green, blue)]);\n\n builder.bgHex = (value: string) => {\n const [red, green, blue] = normalizeHex(value);\n return createColor([...styles, bgRgbStyle(red, green, blue)]);\n };\n\n builder.bgRgb = (red: number, green: number, blue: number) =>\n createColor([...styles, bgRgbStyle(red, green, blue)]);\n\n return builder;\n}\n\nexport const color = createColor();\n", "export interface Brand {\n name: string;\n primary: string;\n}\n\nexport const brands: Record<string, Brand> = {\n purple: { name: \"purple\", primary: \"#a200ff\" },\n blue: { name: \"blue\", primary: \"#2f6fed\" },\n green: { name: \"green\", primary: \"#1f9d57\" }\n};\n", "import { brands } from \"../tokens/brand.js\";\n\nexport interface ThemeConfig {\n brand: string;\n label: string;\n}\n\nconst defaults: ThemeConfig = {\n brand: \"purple\",\n label: \"Poe\"\n};\n\nlet config: ThemeConfig = { ...defaults };\nlet revision = 0;\nlet brandConfigured = false;\n\nexport function configureTheme(patch: { brand?: string; label?: string }): void {\n if (patch.brand !== undefined && !Object.hasOwn(brands, patch.brand)) {\n throw new Error(`Unknown brand: ${patch.brand}`);\n }\n\n config = {\n brand: patch.brand ?? config.brand,\n label: patch.label ?? config.label\n };\n if (patch.brand !== undefined) {\n brandConfigured = true;\n }\n revision += 1;\n}\n\nexport function getThemeConfig(): ThemeConfig {\n return { ...config };\n}\n\nexport function getThemeRevision(): number {\n return revision;\n}\n\nexport function isThemeBrandConfigured(): boolean {\n return brandConfigured;\n}\n\nexport function resetTheme(): void {\n config = { ...defaults };\n brandConfigured = false;\n revision += 1;\n}\n", "import { color, type Color } from \"../components/color.js\";\nimport { getThemeConfig } from \"../internal/theme-state.js\";\nimport { brands, type Brand } from \"./brand.js\";\n\nexport const brand = brands.purple!.primary;\n\nexport type ThemeName = \"dark\" | \"light\";\n\nexport interface ThemeCellStyle {\n fg?: string;\n bold?: boolean;\n dim?: boolean;\n underline?: boolean;\n}\n\nexport interface ThemeCellStyles {\n accent: ThemeCellStyle;\n muted: ThemeCellStyle;\n success: ThemeCellStyle;\n warning: ThemeCellStyle;\n error: ThemeCellStyle;\n info: ThemeCellStyle;\n}\n\nexport interface ThemePalette {\n header: (text: string) => string;\n divider: (text: string) => string;\n prompt: (text: string) => string;\n number: (text: string) => string;\n intro: (text: string) => string;\n resolvedSymbol: string;\n errorSymbol: string;\n accent: (text: string) => string;\n muted: (text: string) => string;\n success: (text: string) => string;\n warning: (text: string) => string;\n error: (text: string) => string;\n info: (text: string) => string;\n badge: (text: string) => string;\n styles: ThemeCellStyles;\n}\n\nfunction withStyles(palette: Omit<ThemePalette, \"styles\">, styles: ThemeCellStyles): ThemePalette {\n return Object.defineProperty(palette, \"styles\", {\n value: styles,\n enumerable: false\n }) as ThemePalette;\n}\n\nfunction brandColor(activeBrand: Brand, purple: Color): Color {\n return activeBrand.name === \"purple\" ? purple : color.hex(activeBrand.primary);\n}\n\nfunction brandBackground(activeBrand: Brand, purple: Color): Color {\n return activeBrand.name === \"purple\" ? purple : color.bgHex(activeBrand.primary);\n}\n\nexport function createPalette(activeBrand: Brand, mode: ThemeName): ThemePalette {\n const isPurple = activeBrand.name === \"purple\";\n if (mode === \"light\") {\n const active = color.hex(activeBrand.primary);\n const prompt = isPurple ? color.hex(\"#006699\") : active;\n const number = isPurple ? color.hex(\"#0077cc\") : active;\n return withStyles(\n {\n header: (text: string) => active.bold(text),\n divider: (text: string) => color.hex(\"#666666\")(text),\n prompt: (text: string) => prompt.bold(text),\n number: (text: string) => number.bold(text),\n intro: (text: string) =>\n color.bgHex(activeBrand.primary).white(` ${getThemeConfig().label} - ${text} `),\n get resolvedSymbol() {\n return active(\"\u25C7\");\n },\n get errorSymbol() {\n return color.hex(\"#cc0000\")(\"\u25A0\");\n },\n accent: (text: string) => prompt.bold(text),\n muted: (text: string) => color.hex(\"#666666\")(text),\n success: (text: string) => color.hex(\"#008800\")(text),\n warning: (text: string) => color.hex(\"#cc6600\")(text),\n error: (text: string) => color.hex(\"#cc0000\")(text),\n info: (text: string) => active(text),\n badge: (text: string) => color.bgHex(\"#cc6600\").white(` ${text} `)\n },\n {\n accent: { fg: isPurple ? \"#006699\" : activeBrand.primary, bold: true },\n muted: { fg: \"#666666\" },\n success: { fg: \"#008800\" },\n warning: { fg: \"#cc6600\" },\n error: { fg: \"#cc0000\" },\n info: { fg: activeBrand.primary }\n }\n );\n }\n\n const active = brandColor(activeBrand, color.magenta);\n const activeBright = brandColor(activeBrand, color.magentaBright);\n const activeBackground = brandBackground(activeBrand, color.bgMagenta);\n const prompt = isPurple ? color.cyan : active;\n const number = isPurple ? color.cyanBright : active;\n return withStyles(\n {\n header: (text: string) => activeBright.bold(text),\n divider: (text: string) => color.dim(text),\n prompt: (text: string) => prompt(text),\n number: (text: string) => number(text),\n intro: (text: string) => activeBackground.white(` ${getThemeConfig().label} - ${text} `),\n get resolvedSymbol() {\n return active(\"\u25C7\");\n },\n get errorSymbol() {\n return color.red(\"\u25A0\");\n },\n accent: (text: string) => prompt(text),\n muted: (text: string) => color.dim(text),\n success: (text: string) => color.green(text),\n warning: (text: string) => color.yellow(text),\n error: (text: string) => color.red(text),\n info: (text: string) => active(text),\n badge: (text: string) => color.bgYellow.black(` ${text} `)\n },\n {\n accent: { fg: isPurple ? \"cyan\" : activeBrand.primary, bold: true },\n muted: { dim: true },\n success: { fg: \"green\" },\n warning: { fg: \"yellow\" },\n error: { fg: \"red\" },\n info: { fg: isPurple ? \"magenta\" : activeBrand.primary }\n }\n );\n}\n\nexport const dark = createPalette(brands.purple!, \"dark\");\nexport const light = createPalette(brands.purple!, \"light\");\n", "import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type OutputFormat = \"terminal\" | \"markdown\" | \"json\";\n\nconst VALID_FORMATS = new Set<OutputFormat>([\"terminal\", \"markdown\", \"json\"]);\nconst formatStorage = new AsyncLocalStorage<OutputFormat>();\n\nlet cached: OutputFormat | undefined;\n\nexport function resolveOutputFormat(\n env: { OUTPUT_FORMAT?: string } = process.env as { OUTPUT_FORMAT?: string }\n): OutputFormat {\n const scoped = formatStorage.getStore();\n if (scoped) {\n return scoped;\n }\n if (cached) {\n return cached;\n }\n const raw = env.OUTPUT_FORMAT?.toLowerCase();\n cached = VALID_FORMATS.has(raw as OutputFormat) ? (raw as OutputFormat) : \"terminal\";\n return cached;\n}\n\nexport function withOutputFormat<T>(format: OutputFormat, fn: () => T): T {\n return formatStorage.run(format, fn);\n}\n\nexport function resetOutputFormatCache(): void {\n cached = undefined;\n}\n", "import { getThemeConfig, getThemeRevision, isThemeBrandConfigured } from \"./theme-state.js\";\nimport { brands } from \"../tokens/brand.js\";\nimport { createPalette, dark, light, type ThemeName, type ThemePalette } from \"../tokens/colors.js\";\n\nexport interface ThemeEnv {\n POE_CODE_THEME?: string;\n POE_THEME?: string;\n POE_BRAND?: string;\n APPLE_INTERFACE_STYLE?: string;\n VSCODE_COLOR_THEME_KIND?: string;\n COLORFGBG?: string;\n}\n\nfunction detectThemeFromEnv(env: ThemeEnv): ThemeName | undefined {\n const apple = env.APPLE_INTERFACE_STYLE;\n if (typeof apple === \"string\") {\n return apple.toLowerCase() === \"dark\" ? \"dark\" : \"light\";\n }\n\n const vscodeKind = env.VSCODE_COLOR_THEME_KIND;\n if (typeof vscodeKind === \"string\") {\n const normalized = vscodeKind.toLowerCase();\n if (normalized.includes(\"light\")) {\n return \"light\";\n }\n if (normalized.includes(\"dark\")) {\n return \"dark\";\n }\n }\n\n const colorFGBG = env.COLORFGBG;\n if (typeof colorFGBG === \"string\") {\n const parts = colorFGBG.split(\";\").map((part) => Number.parseInt(part, 10));\n const background = parts.at(-1);\n if (Number.isFinite(background)) {\n return background! >= 8 ? \"light\" : \"dark\";\n }\n }\n\n return undefined;\n}\n\nexport function resolveThemeName(env: ThemeEnv = process.env as ThemeEnv): ThemeName {\n const raw = (env.POE_CODE_THEME ?? env.POE_THEME)?.toLowerCase();\n if (raw === \"light\" || raw === \"dark\") {\n return raw;\n }\n const detected = detectThemeFromEnv(env);\n if (detected) {\n return detected;\n }\n return \"dark\";\n}\n\nconst themeCache = new Map<string, ThemePalette>();\nlet cachedRevision = -1;\n\nexport function getTheme(env?: ThemeEnv): ThemePalette {\n const themeName = resolveThemeName(env);\n const config = getThemeConfig();\n const requestedBrand = env?.POE_BRAND?.toLowerCase();\n const activeBrandName =\n !isThemeBrandConfigured() && requestedBrand && Object.hasOwn(brands, requestedBrand)\n ? requestedBrand\n : config.brand;\n const revision = getThemeRevision();\n if (revision !== cachedRevision) {\n themeCache.clear();\n cachedRevision = revision;\n }\n const cacheKey = `${activeBrandName}:${themeName}`;\n const cachedTheme = themeCache.get(cacheKey);\n if (cachedTheme) {\n return cachedTheme;\n }\n const activeBrand = brands[activeBrandName]!;\n const theme =\n activeBrandName === \"purple\"\n ? themeName === \"light\"\n ? light\n : dark\n : createPalette(activeBrand, themeName);\n themeCache.set(cacheKey, theme);\n return theme;\n}\n\nexport function resetThemeCache(): void {\n themeCache.clear();\n cachedRevision = getThemeRevision();\n}\n", "import { color } from \"./color.js\";\nimport { resolveOutputFormat } from \"../internal/output-format.js\";\nimport { getTheme } from \"../internal/theme-detect.js\";\n\nexport const symbols = {\n get info(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"info\";\n if (format === \"markdown\") return \"(i)\";\n return color.magenta(\"\u25CF\");\n },\n get success(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"success\";\n if (format === \"markdown\") return \"[ok]\";\n return color.magenta(\"\u25C6\");\n },\n get resolved(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"resolved\";\n if (format === \"markdown\") return \">\";\n return getTheme().resolvedSymbol;\n },\n get errorResolved(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"error\";\n if (format === \"markdown\") return \"[!]\";\n return getTheme().errorSymbol;\n },\n get bar(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"\";\n if (format === \"markdown\") return \"|\";\n return \"\u2502\";\n },\n cornerTopRight: \"\u256E\",\n cornerBottomRight: \"\u256F\",\n get warning(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"warning\";\n if (format === \"markdown\") return \"[!]\";\n return \"\u25B2\";\n },\n get active(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"active\";\n if (format === \"markdown\") return \"[x]\";\n return \"\u25C6\";\n },\n get inactive(): string {\n const format = resolveOutputFormat();\n if (format === \"json\") return \"inactive\";\n if (format === \"markdown\") return \"[ ]\";\n return \"\u25CB\";\n }\n} as const;\n", "export function stripAnsi(value: string): string {\n let output = \"\";\n let index = 0;\n\n while (index < value.length) {\n const char = value[index];\n\n if (char === \"\\u001b\") {\n index = skipEscapeSequence(value, index);\n continue;\n }\n\n if (char === \"\\u009b\") {\n index = skipCsiSequence(value, index + 1);\n continue;\n }\n\n output += char;\n index += char.length;\n }\n\n return output;\n}\n\nfunction skipEscapeSequence(value: string, index: number): number {\n const next = value[index + 1];\n\n if (next === \"[\") {\n return skipCsiSequence(value, index + 2);\n }\n\n if (next === \"]\") {\n return skipOscSequence(value, index + 2);\n }\n\n return Math.min(value.length, index + 2);\n}\n\nfunction skipCsiSequence(value: string, index: number): number {\n while (index < value.length) {\n const codePoint = value.charCodeAt(index);\n index += 1;\n\n if (codePoint >= 0x40 && codePoint <= 0x7e) {\n break;\n }\n }\n\n return index;\n}\n\nfunction skipOscSequence(value: string, index: number): number {\n while (index < value.length) {\n if (value[index] === \"\\u0007\") {\n return index + 1;\n }\n\n if (value[index] === \"\\u001b\" && value[index + 1] === \"\\\\\") {\n return index + 2;\n }\n\n index += 1;\n }\n\n return index;\n}\n", "import { color } from \"../../components/color.js\";\nimport { symbols } from \"../../components/symbols.js\";\nimport { resolveOutputFormat } from \"../../internal/output-format.js\";\nimport { stripAnsi } from \"../../internal/strip-ansi.js\";\n\nexport interface LogMessageOptions {\n symbol?: string;\n secondarySymbol?: string;\n spacing?: number;\n withGuide?: boolean;\n}\n\nfunction renderMarkdownInline(value: string): string {\n return stripAnsi(value).replaceAll(\"\\r\\n\", \" \").replaceAll(\"\\n\", \" \").replaceAll(\"\\r\", \" \");\n}\n\nfunction writeTerminalMessage(\n msg: string,\n {\n symbol = color.gray(\"\u2502\"),\n secondarySymbol = color.gray(\"\u2502\"),\n spacing = 1,\n withGuide = true\n }: LogMessageOptions = {}\n): void {\n const lines: string[] = [];\n const showGuide = withGuide !== false;\n const contentLines = msg.split(\"\\n\");\n const prefix = showGuide ? `${symbol} ` : \"\";\n const continuationPrefix = showGuide ? `${secondarySymbol} ` : \"\";\n const emptyGuide = showGuide ? secondarySymbol : \"\";\n\n for (let index = 0; index < spacing; index += 1) {\n lines.push(emptyGuide);\n }\n\n if (contentLines.length === 0) {\n process.stdout.write(\"\\n\");\n return;\n }\n\n const [firstLine = \"\", ...continuationLines] = contentLines;\n if (firstLine.length > 0) {\n lines.push(`${prefix}${firstLine}`);\n } else {\n lines.push(showGuide ? symbol : \"\");\n }\n\n for (const line of continuationLines) {\n if (line.length > 0) {\n lines.push(`${continuationPrefix}${line}`);\n continue;\n }\n lines.push(emptyGuide);\n }\n\n process.stdout.write(`${lines.join(\"\\n\")}\\n`);\n}\n\nexport function message(msg: string, options?: LogMessageOptions): void {\n const format = resolveOutputFormat();\n if (format === \"markdown\") {\n process.stdout.write(`- ${renderMarkdownInline(msg)}\\n`);\n return;\n }\n if (format === \"json\") {\n process.stdout.write(\n `${JSON.stringify({ level: \"message\", message: stripAnsi(msg) })}\\n`\n );\n return;\n }\n\n writeTerminalMessage(msg, options);\n}\n\nexport function info(msg: string): void {\n const format = resolveOutputFormat();\n if (format === \"markdown\") {\n process.stdout.write(`- **info:** ${renderMarkdownInline(msg)}\\n`);\n return;\n }\n if (format === \"json\") {\n process.stdout.write(\n `${JSON.stringify({ level: \"info\", message: stripAnsi(msg) })}\\n`\n );\n return;\n }\n\n message(msg, { symbol: symbols.info });\n}\n\nexport function success(msg: string): void {\n const format = resolveOutputFormat();\n if (format === \"markdown\") {\n process.stdout.write(`- **success:** ${renderMarkdownInline(msg)}\\n`);\n return;\n }\n if (format === \"json\") {\n process.stdout.write(\n `${JSON.stringify({ level: \"success\", message: stripAnsi(msg) })}\\n`\n );\n return;\n }\n\n message(msg, { symbol: symbols.success });\n}\n\nexport function warn(msg: string): void {\n const format = resolveOutputFormat();\n if (format === \"markdown\") {\n process.stdout.write(`- **warning:** ${renderMarkdownInline(msg)}\\n`);\n return;\n }\n if (format === \"json\") {\n process.stdout.write(\n `${JSON.stringify({ level: \"warn\", message: stripAnsi(msg) })}\\n`\n );\n return;\n }\n\n message(msg, { symbol: color.yellow(\"\u25B2\") });\n}\n\nexport function error(msg: string): void {\n const format = resolveOutputFormat();\n if (format === \"markdown\") {\n process.stdout.write(`- **error:** ${renderMarkdownInline(msg)}\\n`);\n return;\n }\n if (format === \"json\") {\n process.stdout.write(\n `${JSON.stringify({ level: \"error\", message: stripAnsi(msg) })}\\n`\n );\n return;\n }\n\n message(msg, { symbol: color.red(\"\u25A0\") });\n}\n\nexport const log = {\n info,\n success,\n message,\n warn,\n error\n};\n", "import { color } from \"./color.js\";\nimport { log } from \"../prompts/primitives/log.js\";\nimport { symbols } from \"./symbols.js\";\n\nexport interface LoggerOutput {\n info(message: string): void;\n success(message: string): void;\n warn(message: string): void;\n error(message: string): void;\n resolved(label: string, value: string): void;\n errorResolved(label: string, value: string): void;\n message(message: string, symbol?: string): void;\n}\n\nexport function createLogger(emitter?: (message: string) => void): LoggerOutput {\n const emit = (\n level: \"info\" | \"success\" | \"warn\" | \"error\",\n message: string\n ): void => {\n if (emitter) {\n emitter(message);\n return;\n }\n if (level === \"success\") {\n log.success(message);\n return;\n }\n if (level === \"warn\") {\n log.warn(message);\n return;\n }\n if (level === \"error\") {\n log.error(message);\n return;\n }\n log.info(message);\n };\n\n return {\n info(message: string): void {\n emit(\"info\", message);\n },\n success(message: string): void {\n emit(\"success\", message);\n },\n warn(message: string): void {\n emit(\"warn\", message);\n },\n error(message: string): void {\n emit(\"error\", message);\n },\n resolved(label: string, value: string): void {\n if (emitter) {\n emitter(`${label}: ${value}`);\n return;\n }\n log.message(`${label}\\n ${value}`, { symbol: symbols.resolved });\n },\n errorResolved(label: string, value: string): void {\n if (emitter) {\n emitter(`${label}: ${value}`);\n return;\n }\n log.message(`${label}\\n ${value}`, { symbol: symbols.errorResolved });\n },\n message(message: string, symbol?: string): void {\n if (emitter) {\n emitter(message);\n return;\n }\n log.message(message, { symbol: symbol ?? color.gray(\"\u2502\") });\n }\n };\n}\n\nexport const logger = createLogger();\n", "import { text } from \"./text.js\";\n\nexport interface CommandInfo {\n name: string;\n description: string;\n}\n\nexport interface OptionInfo {\n flags: string;\n description: string;\n}\n\nexport interface FormatColumnsOptions {\n rows: Array<{ left: string; right: string }>;\n totalWidth?: number;\n minLeftWidth?: number;\n maxLeftWidth?: number;\n gap?: number;\n indent?: number;\n}\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nfunction normalizeInline(value: string): string {\n return value.replaceAll(\"\\r\\n\", \" \").replaceAll(\"\\n\", \" \").replaceAll(\"\\r\", \" \");\n}\n\nfunction readControlSequence(value: string, index: number): number | undefined {\n if (value[index] !== \"\\u001b\") {\n return undefined;\n }\n\n if (value[index + 1] === \"[\") {\n let nextIndex = index + 2;\n while (nextIndex < value.length) {\n const code = value.charCodeAt(nextIndex);\n nextIndex += 1;\n if (code >= 0x40 && code <= 0x7e) {\n return nextIndex;\n }\n }\n return value.length;\n }\n\n if (value[index + 1] === \"]\") {\n let nextIndex = index + 2;\n while (nextIndex < value.length) {\n if (value[nextIndex] === \"\\u0007\") {\n return nextIndex + 1;\n }\n if (value[nextIndex] === \"\\u001b\" && value[nextIndex + 1] === \"\\\\\") {\n return nextIndex + 2;\n }\n nextIndex += 1;\n }\n return value.length;\n }\n\n return index + 1;\n}\n\nfunction isWideCodePoint(codePoint: number): boolean {\n return (\n (codePoint >= 0x1100 && codePoint <= 0x115f) ||\n codePoint === 0x2329 ||\n codePoint === 0x232a ||\n (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f) ||\n (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||\n (codePoint >= 0xf900 && codePoint <= 0xfaff) ||\n (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||\n (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||\n (codePoint >= 0xff00 && codePoint <= 0xff60) ||\n (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||\n (codePoint >= 0x2600 && codePoint <= 0x27bf) ||\n (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||\n (codePoint >= 0x20000 && codePoint <= 0x3fffd)\n );\n}\n\nfunction clusterWidth(cluster: string): number {\n const codePoints = Array.from(cluster).map((char) => char.codePointAt(0) ?? 0);\n if (codePoints.some((codePoint) => codePoint === 0x200d || (codePoint >= 0xfe00 && codePoint <= 0xfe0f))) {\n return 2;\n }\n\n return codePoints.reduce((width, codePoint) => {\n if (codePoint === 0 || codePoint < 0x20 || (codePoint >= 0x7f && codePoint < 0xa0)) {\n return width;\n }\n return width + (isWideCodePoint(codePoint) ? 2 : 1);\n }, 0);\n}\n\nfunction visibleWidth(value: string): number {\n let width = 0;\n let index = 0;\n\n while (index < value.length) {\n const nextIndex = readControlSequence(value, index);\n if (nextIndex !== undefined) {\n index = nextIndex;\n continue;\n }\n\n const segment = graphemeSegmenter.segment(value.slice(index))[Symbol.iterator]().next().value as\n | Intl.SegmentData\n | undefined;\n const cluster = segment?.segment ?? \"\";\n width += clusterWidth(cluster);\n index += cluster.length || 1;\n }\n\n return width;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(Math.max(value, min), max);\n}\n\nfunction padEndVisible(value: string, width: number): string {\n return value + \" \".repeat(Math.max(0, width - visibleWidth(value)));\n}\n\nfunction isWhitespace(char: string | undefined): boolean {\n return char === \" \" || char === \"\\n\" || char === \"\\t\" || char === \"\\r\";\n}\n\nfunction splitWords(value: string): string[] {\n const words: string[] = [];\n let word = \"\";\n\n for (const char of value) {\n if (isWhitespace(char)) {\n if (word) {\n words.push(word);\n word = \"\";\n }\n continue;\n }\n word += char;\n }\n\n if (word) {\n words.push(word);\n }\n\n return words;\n}\n\nfunction wrapWords(value: string, width: number): string[] {\n const words = splitWords(value);\n if (words.length === 0) {\n return [\"\"];\n }\n\n const lines: string[] = [];\n let line = \"\";\n\n for (const word of words) {\n if (!line) {\n line = word;\n continue;\n }\n\n if (visibleWidth(line) + 1 + visibleWidth(word) <= width) {\n line += ` ${word}`;\n continue;\n }\n\n lines.push(line);\n line = word;\n }\n\n lines.push(line);\n return lines;\n}\n\nfunction validateLayoutValue(value: number, name: keyof Omit<FormatColumnsOptions, \"rows\">): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a finite non-negative number.`);\n }\n}\n\nexport function formatColumns(opts: FormatColumnsOptions): string {\n const rows = opts.rows.map((row) => ({\n left: normalizeInline(row.left),\n right: row.right\n }));\n if (rows.length === 0) {\n return \"\";\n }\n\n const totalWidth = opts.totalWidth ?? process.stdout.columns ?? 100;\n const minLeftWidth = opts.minLeftWidth ?? 12;\n const maxLeftWidth = opts.maxLeftWidth ?? 32;\n const gap = opts.gap ?? 3;\n const indent = opts.indent ?? 2;\n validateLayoutValue(totalWidth, \"totalWidth\");\n validateLayoutValue(minLeftWidth, \"minLeftWidth\");\n validateLayoutValue(maxLeftWidth, \"maxLeftWidth\");\n validateLayoutValue(gap, \"gap\");\n validateLayoutValue(indent, \"indent\");\n const maxLeftContentWidth = Math.max(...rows.map((row) => visibleWidth(row.left)));\n const leftWidth = clamp(maxLeftContentWidth + gap, minLeftWidth, maxLeftWidth);\n const rightWidth = Math.max(20, totalWidth - leftWidth - indent);\n const firstIndent = \" \".repeat(indent);\n const continuationIndent = \" \".repeat(indent + leftWidth);\n\n return rows\n .flatMap((row) => {\n if (row.right.length === 0) {\n return [`${firstIndent}${row.left}`];\n }\n\n const rightLines = wrapWords(row.right, rightWidth);\n if (visibleWidth(row.left) >= leftWidth) {\n return [\n `${firstIndent}${row.left}`,\n ...rightLines.map((line) => `${continuationIndent}${line}`)\n ];\n }\n const firstLine = `${firstIndent}${padEndVisible(row.left, leftWidth)}${rightLines[0]}`;\n const continuationLines = rightLines\n .slice(1)\n .map((line) => `${continuationIndent}${line}`);\n return [firstLine, ...continuationLines];\n })\n .join(\"\\n\");\n}\n\nexport function formatCommand(name: string, description: string): string {\n return formatColumns({\n rows: [{ left: text.command(name), right: description }]\n });\n}\n\nexport function formatUsage(command: string, args?: string): string {\n const argsStr = args ? ` ${text.argument(args)}` : \"\";\n return `${text.usageCommand(command)}${argsStr}`;\n}\n\nexport function formatOption(flags: string, description: string): string {\n return formatColumns({\n rows: [{ left: text.option(flags), right: description }]\n });\n}\n\nexport function formatCommandList(commands: CommandInfo[]): string {\n return formatColumns({\n rows: commands.map((cmd) => ({\n left: text.command(cmd.name),\n right: cmd.description\n }))\n });\n}\n\nexport function formatOptionList(options: OptionInfo[]): string {\n return formatColumns({\n rows: options.map((opt) => ({\n left: text.option(opt.flags),\n right: opt.description\n }))\n });\n}\n\nexport const helpFormatter = {\n formatColumns,\n formatCommand,\n formatUsage,\n formatOption,\n formatCommandList,\n formatOptionList\n} as const;\n", "import type { ThemePalette } from \"../tokens/colors.js\";\nimport { widths } from \"../tokens/widths.js\";\nimport { resolveOutputFormat } from \"../internal/output-format.js\";\nimport { stripAnsi } from \"../internal/strip-ansi.js\";\n\nexport interface TableColumn {\n name: string;\n title: string;\n alignment: \"left\" | \"right\";\n maxLen: number;\n}\n\nexport interface RenderTableOptions {\n theme: ThemePalette;\n columns: TableColumn[];\n rows: Record<string, string>[];\n variant?: \"table\" | \"detail\";\n maxWidth?: number;\n}\n\ntype TableAlignment = TableColumn[\"alignment\"] | \"center\";\n\ninterface ComputedColumn {\n name: string;\n title: string;\n alignment: TableAlignment;\n width: number;\n}\n\nconst reset = \"\\x1b[0m\";\nconst ellipsis = \"\u2026\";\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nfunction getCell(row: Record<string, string>, name: string): string {\n return Object.prototype.hasOwnProperty.call(row, name) ? row[name] ?? \"\" : \"\";\n}\n\nfunction renderMarkdownCell(value: string): string {\n return stripAnsi(value)\n .replaceAll(\"\\r\\n\", \" \")\n .replaceAll(\"\\n\", \" \")\n .replaceAll(\"\\r\", \" \")\n .replaceAll(\"|\", \"\\\\|\");\n}\n\nfunction isAnsiSequence(value: string, index: number): boolean {\n return value[index] === \"\\u001b\" && value[index + 1] === \"[\";\n}\n\nfunction readAnsiSequence(value: string, index: number): { sequence: string; nextIndex: number } {\n let nextIndex = index + 2;\n while (nextIndex < value.length && value[nextIndex] !== \"m\") {\n nextIndex += 1;\n }\n\n if (nextIndex < value.length) {\n nextIndex += 1;\n }\n\n return { sequence: value.slice(index, nextIndex), nextIndex };\n}\n\nfunction isCombiningCodePoint(codePoint: number): boolean {\n return (\n (codePoint >= 0x0300 && codePoint <= 0x036f) ||\n (codePoint >= 0x1ab0 && codePoint <= 0x1aff) ||\n (codePoint >= 0x1dc0 && codePoint <= 0x1dff) ||\n (codePoint >= 0x20d0 && codePoint <= 0x20ff) ||\n (codePoint >= 0xfe20 && codePoint <= 0xfe2f)\n );\n}\n\nfunction isWideCodePoint(codePoint: number): boolean {\n return (\n (codePoint >= 0x1100 && codePoint <= 0x115f) ||\n codePoint === 0x2329 ||\n codePoint === 0x232a ||\n (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f) ||\n (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||\n (codePoint >= 0xf900 && codePoint <= 0xfaff) ||\n (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||\n (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||\n (codePoint >= 0xff00 && codePoint <= 0xff60) ||\n (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||\n (codePoint >= 0x2600 && codePoint <= 0x27bf) ||\n (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||\n (codePoint >= 0x20000 && codePoint <= 0x3fffd)\n );\n}\n\nfunction isEmojiClusterCodePoint(codePoint: number): boolean {\n return (\n (codePoint >= 0x1f1e6 && codePoint <= 0x1f1ff) ||\n (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||\n (codePoint >= 0x2600 && codePoint <= 0x27bf)\n );\n}\n\nfunction codePointWidth(char: string): number {\n const codePoint = char.codePointAt(0) ?? 0;\n\n if (codePoint === 0 || codePoint < 0x20 || (codePoint >= 0x7f && codePoint < 0xa0)) {\n return 0;\n }\n\n if (\n codePoint === 0x200d ||\n (codePoint >= 0xfe00 && codePoint <= 0xfe0f) ||\n isCombiningCodePoint(codePoint)\n ) {\n return 0;\n }\n\n return isWideCodePoint(codePoint) ? 2 : 1;\n}\n\nfunction readPrintableCluster(value: string, index: number): string {\n const nextAnsiIndex = value.indexOf(\"\\u001b[\", index);\n const plainText = value.slice(index, nextAnsiIndex === -1 ? undefined : nextAnsiIndex);\n const firstSegment = graphemeSegmenter.segment(plainText)[Symbol.iterator]().next().value as\n | Intl.SegmentData\n | undefined;\n\n return firstSegment?.segment ?? Array.from(plainText)[0] ?? \"\";\n}\n\nfunction clusterWidth(cluster: string): number {\n const codePoints = Array.from(cluster).map((char) => char.codePointAt(0) ?? 0);\n const isEmojiCluster =\n codePoints.length > 1 &&\n codePoints.some(\n (codePoint) =>\n codePoint === 0x200d ||\n (codePoint >= 0xfe00 && codePoint <= 0xfe0f) ||\n isEmojiClusterCodePoint(codePoint)\n );\n\n if (isEmojiCluster) {\n return 2;\n }\n\n return codePoints.reduce((width, codePoint) => width + codePointWidth(String.fromCodePoint(codePoint)), 0);\n}\n\nfunction displayWidth(value: string): number {\n let width = 0;\n let index = 0;\n\n while (index < value.length) {\n if (isAnsiSequence(value, index)) {\n index = readAnsiSequence(value, index).nextIndex;\n continue;\n }\n\n const cluster = readPrintableCluster(value, index);\n width += clusterWidth(cluster);\n index += cluster.length;\n }\n\n return width;\n}\n\nfunction truncateToWidth(value: string, width: number): string {\n if (displayWidth(value) <= width) {\n return value;\n }\n\n if (width <= 0) {\n return \"\";\n }\n\n const targetWidth = width <= 1 ? 0 : width - displayWidth(ellipsis);\n let output = \"\";\n let currentWidth = 0;\n let index = 0;\n let sawAnsi = false;\n\n while (index < value.length) {\n if (isAnsiSequence(value, index)) {\n const ansi = readAnsiSequence(value, index);\n sawAnsi = true;\n output += ansi.sequence;\n index = ansi.nextIndex;\n continue;\n }\n\n const cluster = readPrintableCluster(value, index);\n const width = clusterWidth(cluster);\n if (currentWidth + width > targetWidth) {\n break;\n }\n\n output += cluster;\n currentWidth += width;\n index += cluster.length;\n }\n\n return `${output}${ellipsis}${sawAnsi ? reset : \"\"}`;\n}\n\nfunction padCell(value: string, width: number, alignment: TableAlignment): string {\n const visibleWidth = displayWidth(value);\n const padding = Math.max(0, width - visibleWidth);\n\n if (alignment === \"right\") {\n return `${\" \".repeat(padding)}${value}`;\n }\n\n if (alignment === \"center\") {\n const left = Math.floor(padding / 2);\n const right = padding - left;\n return `${\" \".repeat(left)}${value}${\" \".repeat(right)}`;\n }\n\n return `${value}${\" \".repeat(padding)}`;\n}\n\nfunction getAlignment(column: TableColumn): TableAlignment {\n const alignment = (column as { alignment: TableAlignment }).alignment;\n return alignment === \"right\" || alignment === \"center\" ? alignment : \"left\";\n}\n\nfunction getColumnWidth(column: TableColumn): number {\n if (!Number.isFinite(column.maxLen) || column.maxLen <= 0) {\n throw new Error(\"maxLen must be a positive finite number.\");\n }\n const configuredMin = (column as { minLen?: number }).minLen;\n const minWidth = Math.max(1, configuredMin ?? 1);\n return Math.max(minWidth, column.maxLen);\n}\n\nfunction computeColumns(columns: TableColumn[]): ComputedColumn[] {\n return columns.map((column) => ({\n name: column.name,\n title: column.title,\n alignment: getAlignment(column),\n width: getColumnWidth(column)\n }));\n}\n\nfunction renderBorder(\n columns: ComputedColumn[],\n theme: ThemePalette,\n parts: { left: string; mid: string; right: string }\n): string {\n const horizontal = theme.muted(\"\u2500\");\n const segments = columns.map((column) => horizontal.repeat(column.width + 2));\n return [\n theme.muted(parts.left),\n segments.join(theme.muted(parts.mid)),\n theme.muted(parts.right)\n ].join(\"\");\n}\n\nfunction renderTerminalRow(values: string[], columns: ComputedColumn[], theme: ThemePalette): string {\n const vertical = theme.muted(\"\u2502\");\n const cells = values.map((value, index) => {\n const column = columns[index]!;\n const truncated = truncateToWidth(value, column.width);\n return ` ${padCell(truncated, column.width, column.alignment)} `;\n });\n\n return `${vertical}${cells.join(vertical)}${vertical}`;\n}\n\nfunction wrapDetailValue(value: string, width: number): string[] {\n const lines: string[] = [];\n\n for (const paragraph of value.split(\"\\n\")) {\n let line = \"\";\n\n for (const rawWord of paragraph.split(\" \")) {\n const words: string[] = [];\n let word = rawWord;\n\n while (displayWidth(word) > width) {\n let chunk = \"\";\n let index = 0;\n\n while (index < word.length) {\n const cluster = readPrintableCluster(word, index);\n if (displayWidth(`${chunk}${cluster}`) > width) {\n break;\n }\n chunk += cluster;\n index += cluster.length;\n }\n\n words.push(chunk);\n word = word.slice(chunk.length);\n }\n\n words.push(word);\n\n for (const word of words) {\n if (line.length === 0) {\n line = word;\n continue;\n }\n\n if (displayWidth(`${line} ${word}`) <= width) {\n line = `${line} ${word}`;\n continue;\n }\n\n lines.push(line);\n line = word;\n }\n }\n\n lines.push(line);\n }\n\n return lines.length > 0 ? lines : [\"\"];\n}\n\nfunction renderTableTerminal(options: RenderTableOptions): string {\n const { theme, columns, rows } = options;\n const computedColumns = computeColumns(columns);\n if (options.variant === \"detail\") {\n const labelColumn = computedColumns[0];\n const valueColumn = computedColumns[1];\n if (!labelColumn || !valueColumn) {\n return \"\";\n }\n\n const detailLabelWidth = widths.helpColumn + 12;\n const labelWidth = Math.min(labelColumn.width, detailLabelWidth);\n const valueWidth = Math.max(20, (options.maxWidth ?? widths.maxLine) - labelWidth - 2);\n const continuation = \" \".repeat(labelWidth + 2);\n\n return rows\n .flatMap((row) => {\n const label = truncateToWidth(getCell(row, labelColumn.name), labelWidth);\n const values = wrapDetailValue(getCell(row, valueColumn.name), valueWidth);\n if (values.length === 1 && values[0] === \"\") {\n return [theme.header(label)];\n }\n return [\n `${theme.muted(padCell(label, labelWidth, \"left\"))} ${values[0] ?? \"\"}`,\n ...values.slice(1).map((value) => `${continuation}${value}`)\n ];\n })\n .join(\"\\n\");\n }\n\n const separatorOptions = options as { rowSeparator?: boolean; rowSeparators?: boolean };\n const includeRowSeparators =\n separatorOptions.rowSeparator === true || separatorOptions.rowSeparators === true;\n\n const top = renderBorder(computedColumns, theme, { left: \"\u250C\", mid: \"\u252C\", right: \"\u2510\" });\n const header = renderTerminalRow(\n computedColumns.map((column) => theme.header(column.title)),\n computedColumns,\n theme\n );\n const headerBottom = renderBorder(computedColumns, theme, { left: \"\u251C\", mid: \"\u253C\", right: \"\u2524\" });\n const bottom = renderBorder(computedColumns, theme, { left: \"\u2514\", mid: \"\u2534\", right: \"\u2518\" });\n\n const renderedRows: string[] = [];\n for (const [index, row] of rows.entries()) {\n if (includeRowSeparators && index > 0) {\n renderedRows.push(headerBottom);\n }\n renderedRows.push(\n renderTerminalRow(\n computedColumns.map((column) => getCell(row, column.name)),\n computedColumns,\n theme\n )\n );\n }\n\n return [top, header, headerBottom, ...renderedRows, bottom].join(\"\\n\");\n}\n\nfunction renderTableMarkdown(options: RenderTableOptions): string {\n const { columns, rows } = options;\n\n const header = `| ${columns.map((c) => renderMarkdownCell(c.title)).join(\" | \")} |`;\n const separator = `| ${columns\n .map((c) => {\n const alignment = getAlignment(c);\n if (alignment === \"right\") {\n return \"---:\";\n }\n if (alignment === \"center\") {\n return \":---:\";\n }\n return \":---\";\n })\n .join(\" | \")} |`;\n\n const dataRows = rows.map(\n (row) =>\n `| ${columns.map((c) => renderMarkdownCell(getCell(row, c.name))).join(\" | \")} |`\n );\n\n return [header, separator, ...dataRows].join(\"\\n\");\n}\n\nfunction renderTableJson(options: RenderTableOptions): string {\n const { columns, rows } = options;\n\n const cleaned = rows.map((row) => {\n const obj = Object.create(null) as Record<string, string>;\n for (const col of columns) {\n obj[col.name] = stripAnsi(getCell(row, col.name));\n }\n return obj;\n });\n\n return JSON.stringify(cleaned, null, 2);\n}\n\nexport function renderTable(options: RenderTableOptions): string {\n const format = resolveOutputFormat();\n switch (format) {\n case \"markdown\":\n return renderTableMarkdown(options);\n case \"json\":\n return renderTableJson(options);\n default:\n return renderTableTerminal(options);\n }\n}\n", "import stringWidth from \"fast-string-width\";\nimport { wrapAnsi } from \"fast-wrap-ansi\";\nimport type { ThemePalette } from \"../tokens/colors.js\";\nimport { widths } from \"../tokens/widths.js\";\n\nexport interface DetailCardRow {\n label: string;\n value: string;\n}\n\nexport interface DetailCardSection {\n title?: string;\n rows: DetailCardRow[];\n}\n\nexport interface RenderDetailCardOptions {\n theme: ThemePalette;\n title: string;\n subtitle?: string;\n badges?: string[];\n prose?: Array<{ title?: string; value: string }>;\n sections?: DetailCardSection[];\n width?: number;\n}\n\nfunction wrap(value: string, width: number): string[] {\n return wrapAnsi(value, Math.max(1, width), { hard: true, trim: true }).split(\"\\n\");\n}\n\nfunction renderRows(rows: DetailCardRow[], theme: ThemePalette, width: number): string[] {\n if (rows.length === 0) return [];\n const labelWidth = Math.max(...rows.map((row) => stringWidth(row.label)));\n const valueWidth = Math.max(20, width - labelWidth - 2);\n const continuation = \" \".repeat(labelWidth + 2);\n\n return rows.flatMap((row) => {\n const values = wrap(row.value, valueWidth);\n return [\n `${theme.muted(row.label.padEnd(labelWidth))} ${values[0] ?? \"\"}`,\n ...values.slice(1).map((value) => `${continuation}${value}`)\n ];\n });\n}\n\nexport function renderDetailCard(options: RenderDetailCardOptions): string {\n const width = options.width ?? widths.maxLine;\n const identity = [\n options.theme.header(options.title),\n options.subtitle ? options.theme.muted(options.subtitle) : undefined\n ]\n .filter((value): value is string => value !== undefined)\n .join(\" \");\n\n const hero = options.badges?.length\n ? `${identity}\\n${options.theme.muted(options.badges.map((badge) => badge[0] + badge.slice(1).toLowerCase()).join(\" \u00B7 \"))}`\n : identity;\n const blocks: string[] = [hero];\n for (const prose of options.prose ?? []) {\n blocks.push(\n prose.title\n ? [options.theme.header(prose.title), wrap(prose.value, width).join(\"\\n\")].join(\"\\n\")\n : wrap(prose.value, width).join(\"\\n\")\n );\n }\n\n for (const section of options.sections ?? []) {\n if (section.rows.length === 0) continue;\n const rows = renderRows(section.rows, options.theme, width);\n blocks.push(\n section.title ? [options.theme.header(section.title), ...rows].join(\"\\n\") : rows.join(\"\\n\")\n );\n }\n\n return blocks.join(\"\\n\\n\");\n}\n", "export type TemplateEscape = \"html\" | \"none\";\n\nexport interface RenderTemplateOptions {\n escape?: TemplateEscape;\n partials?: Record<string, string>;\n validate?: boolean;\n yield?: string;\n}\n\ntype Token =\n | { type: \"text\"; value: string; start: number }\n | { type: \"name\" | \"unescaped\"; name: string; raw: string }\n | { type: \"partial\"; name: string; indent: string }\n | {\n type: \"section\" | \"inverted\";\n name: string;\n children: Token[];\n rawStart: number;\n rawEnd: number;\n };\n\ninterface SectionFrame {\n token: Extract<Token, { type: \"section\" | \"inverted\" }>;\n parent: Token[];\n}\n\ninterface Context {\n view: unknown;\n parent?: Context;\n}\n\ntype Lambda = (...args: unknown[]) => unknown;\n\ninterface RenderState {\n escape: (value: string) => string;\n partials: Record<string, string>;\n partialStack: string[];\n preserveMissing: boolean;\n validate: boolean;\n}\n\nconst MAX_PARTIAL_DEPTH = 100;\n\nconst HTML_ESCAPE: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n \"/\": \"&#x2F;\",\n \"`\": \"&#x60;\",\n \"=\": \"&#x3D;\"\n};\n\nexport function renderTemplate(\n template: string,\n view: Record<string, unknown>,\n options: RenderTemplateOptions = {}\n): string {\n const prepared =\n options.yield === undefined\n ? template\n : resolveTemplatePartials(template, options.partials ?? {})\n .split(\"{{yield}}\")\n .join(options.yield);\n const tokens = parseTemplate(prepared);\n validatePartialReferences(tokens, options.partials ?? {}, []);\n if (options.validate === true) {\n const expanded = resolveTemplatePartials(prepared, options.partials ?? {});\n validateVariables(parseTemplate(expanded), { view });\n }\n const state: RenderState = {\n escape: options.escape === \"none\" ? String : escapeHtml,\n partials: options.partials ?? {},\n partialStack: [],\n preserveMissing: options.yield !== undefined && options.escape === \"none\",\n validate: options.validate === true\n };\n\n return renderTokens(tokens, { view }, prepared, state);\n}\n\nexport function getTemplatePartialNames(template: string): string[] {\n const names = new Set<string>();\n collectPartialNames(parseTemplate(template), names);\n return [...names];\n}\n\nexport function resolveTemplatePartials(\n template: string,\n partials: Record<string, string>\n): string {\n return expandTemplatePartials(template, partials, []);\n}\n\nfunction renderTemplateInContext(template: string, context: Context, state: RenderState): string {\n return renderTokens(parseTemplate(template), context, template, state);\n}\n\nfunction parseTemplate(template: string): Token[] {\n const root: Token[] = [];\n const stack: SectionFrame[] = [];\n let tokens = root;\n let index = 0;\n\n while (index < template.length) {\n const open = template.indexOf(\"{{\", index);\n if (open === -1) {\n appendText(tokens, template.slice(index), index);\n break;\n }\n\n appendText(tokens, template.slice(index, open), index);\n\n const parsed = parseTag(template, open);\n const standalone = getStandalone(template, open, parsed.end, parsed.kind);\n if (standalone !== undefined) {\n trimTextAfter(tokens, standalone.lineStart);\n }\n\n if (parsed.kind === \"comment\") {\n index = standalone?.nextIndex ?? parsed.end;\n continue;\n }\n\n if (parsed.kind === \"delimiter\") {\n throw new Error(\"Custom delimiters are not supported\");\n }\n\n if (parsed.kind === \"section\" || parsed.kind === \"inverted\") {\n const token: Token = {\n type: parsed.kind,\n name: parsed.name,\n children: [],\n rawStart: parsed.end,\n rawEnd: standalone?.lineStart ?? open\n };\n tokens.push(token);\n stack.push({ token, parent: tokens });\n tokens = token.children;\n index = standalone?.nextIndex ?? parsed.end;\n continue;\n }\n\n if (parsed.kind === \"partial\") {\n tokens.push({\n type: \"partial\",\n name: parsed.name,\n indent: standalone === undefined ? \"\" : template.slice(standalone.lineStart, open)\n });\n index = standalone?.nextIndex ?? parsed.end;\n continue;\n }\n\n if (parsed.kind === \"close\") {\n const frame = stack.pop();\n if (frame === undefined) {\n throw new Error(`Closing unopened section \"${parsed.name}\"`);\n }\n if (frame.token.name !== parsed.name) {\n throw new Error(`Unclosed section \"${frame.token.name}\" before closing \"${parsed.name}\"`);\n }\n frame.token.rawEnd = open;\n tokens = frame.parent;\n index = standalone?.nextIndex ?? parsed.end;\n continue;\n }\n\n tokens.push({ type: parsed.kind, name: parsed.name, raw: template.slice(open, parsed.end) });\n index = parsed.end;\n }\n\n const frame = stack.pop();\n if (frame !== undefined) {\n throw new Error(`Unclosed section \"${frame.token.name}\"`);\n }\n\n return root;\n}\n\nfunction parseTag(\n template: string,\n open: number\n): {\n kind:\n | \"name\"\n | \"unescaped\"\n | \"section\"\n | \"inverted\"\n | \"close\"\n | \"comment\"\n | \"partial\"\n | \"delimiter\";\n name: string;\n end: number;\n} {\n if (template.startsWith(\"{{{\", open)) {\n const close = template.indexOf(\"}}}\", open + 3);\n if (close === -1) {\n throw new Error(\"Unclosed unescaped tag\");\n }\n return { kind: \"unescaped\", name: template.slice(open + 3, close).trim(), end: close + 3 };\n }\n\n const close = template.indexOf(\"}}\", open + 2);\n if (close === -1) {\n throw new Error(\"Unclosed tag\");\n }\n\n const raw = template.slice(open + 2, close).trim();\n const sigil = raw[0];\n const name = sigil === undefined ? \"\" : raw.slice(1).trim();\n const end = close + 2;\n\n if (sigil === \"#\") return { kind: \"section\", name, end };\n if (sigil === \"^\") return { kind: \"inverted\", name, end };\n if (sigil === \"/\") return { kind: \"close\", name, end };\n if (sigil === \"!\") return { kind: \"comment\", name, end };\n if (sigil === \"&\") return { kind: \"unescaped\", name, end };\n if (sigil === \">\") return { kind: \"partial\", name, end };\n if (sigil === \"=\" && raw.endsWith(\"=\")) return { kind: \"delimiter\", name, end };\n\n return { kind: \"name\", name: raw, end };\n}\n\nfunction getStandalone(\n template: string,\n tagStart: number,\n tagEnd: number,\n kind: ReturnType<typeof parseTag>[\"kind\"]\n): { lineStart: number; nextIndex: number } | undefined {\n if (![\"section\", \"inverted\", \"close\", \"comment\", \"partial\", \"delimiter\"].includes(kind)) {\n return undefined;\n }\n\n const lineStart = template.lastIndexOf(\"\\n\", tagStart - 1) + 1;\n if (!isWhitespace(template.slice(lineStart, tagStart))) {\n return undefined;\n }\n\n let cursor = tagEnd;\n while (cursor < template.length && (template[cursor] === \" \" || template[cursor] === \"\\t\")) {\n cursor += 1;\n }\n\n if (template.startsWith(\"\\r\\n\", cursor)) {\n return { lineStart, nextIndex: cursor + 2 };\n }\n\n if (template[cursor] === \"\\n\") {\n return { lineStart, nextIndex: cursor + 1 };\n }\n\n if (cursor === template.length) {\n return { lineStart, nextIndex: cursor };\n }\n\n return undefined;\n}\n\nfunction renderTokens(\n tokens: Token[],\n context: Context,\n template: string,\n state: RenderState\n): string {\n let output = \"\";\n\n for (const token of tokens) {\n switch (token.type) {\n case \"text\":\n output += token.value;\n continue;\n\n case \"name\":\n case \"unescaped\": {\n const result = lookup(context, token.name);\n if (!result.hit || result.value == null) {\n if (state.validate) {\n throw new Error(`Template variable \"${token.name}\" not found.`);\n }\n if (state.preserveMissing) {\n output += token.raw;\n }\n continue;\n }\n const rendered = String(result.value);\n output += token.type === \"name\" ? state.escape(rendered) : rendered;\n continue;\n }\n\n case \"partial\": {\n if (!Object.hasOwn(state.partials, token.name)) {\n throw new Error(`Partial \"${token.name}\" not found.`);\n }\n if (state.partialStack.includes(token.name)) {\n throw new Error(\n `Circular partial reference detected: ${[...state.partialStack, token.name].join(\" -> \")}.`\n );\n }\n if (state.partialStack.length >= MAX_PARTIAL_DEPTH) {\n throw new Error(`Maximum partial depth exceeded (${MAX_PARTIAL_DEPTH}).`);\n }\n\n const partial = indentPartial(state.partials[token.name], token.indent);\n output += renderTokens(parseTemplate(partial), context, partial, {\n ...state,\n partialStack: [...state.partialStack, token.name]\n });\n continue;\n }\n\n case \"inverted\": {\n const result = lookup(context, token.name);\n if (!result.hit && state.validate) {\n throw new Error(`Template variable \"${token.name}\" not found.`);\n }\n const value = result.value;\n if (!value || (Array.isArray(value) && value.length === 0)) {\n output += renderTokens(token.children, context, template, state);\n }\n continue;\n }\n\n case \"section\": {\n const result = lookup(context, token.name);\n if (!result.hit && state.validate) {\n throw new Error(`Template variable \"${token.name}\" not found.`);\n }\n const value = result.value;\n if (!value) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n output += renderTokens(token.children, pushContext(context, item), template, state);\n }\n continue;\n }\n\n if (typeof value === \"function\") {\n const raw = template.slice(token.rawStart, token.rawEnd);\n const rendered = (value as Lambda).call(context.view, raw, (nextTemplate: string) =>\n renderTemplateInContext(nextTemplate, context, state)\n );\n if (rendered != null) {\n output += String(rendered);\n }\n continue;\n }\n\n if (typeof value === \"object\" || typeof value === \"string\" || typeof value === \"number\") {\n output += renderTokens(token.children, pushContext(context, value), template, state);\n continue;\n }\n\n output += renderTokens(token.children, context, template, state);\n }\n }\n }\n\n return output;\n}\n\nfunction lookup(context: Context, name: string): { hit: boolean; value: unknown } {\n if (name === \".\") {\n return { hit: true, value: callLambda(context.view, context.view) };\n }\n\n let cursor: Context | undefined = context;\n while (cursor !== undefined) {\n const result = name.includes(\".\")\n ? lookupDotted(cursor.view, name)\n : lookupName(cursor.view, name);\n\n if (result.hit) {\n return { hit: true, value: callLambda(result.value, cursor.view) };\n }\n\n cursor = cursor.parent;\n }\n\n return { hit: false, value: undefined };\n}\n\nfunction collectPartialNames(tokens: Token[], names: Set<string>): void {\n for (const token of tokens) {\n if (token.type === \"partial\") {\n names.add(token.name);\n continue;\n }\n if (token.type === \"section\" || token.type === \"inverted\") {\n collectPartialNames(token.children, names);\n }\n }\n}\n\nfunction validateVariables(tokens: Token[], context: Context): void {\n for (const token of tokens) {\n if (token.type === \"text\" || token.type === \"partial\") {\n continue;\n }\n if (token.type === \"name\" || token.type === \"unescaped\") {\n if (!lookup(context, token.name).hit) {\n throw new Error(`Template variable \"${token.name}\" not found.`);\n }\n continue;\n }\n if (token.type !== \"section\" && token.type !== \"inverted\") {\n continue;\n }\n\n const result = lookup(context, token.name);\n if (!result.hit) {\n throw new Error(`Template variable \"${token.name}\" not found.`);\n }\n if (Array.isArray(result.value) && result.value.length > 0) {\n for (const item of result.value) {\n validateVariables(token.children, pushContext(context, item));\n }\n continue;\n }\n if (\n typeof result.value === \"object\" && result.value !== null ||\n typeof result.value === \"string\" ||\n typeof result.value === \"number\"\n ) {\n validateVariables(token.children, pushContext(context, result.value));\n continue;\n }\n\n validateVariables(token.children, context);\n }\n}\n\nfunction validatePartialReferences(\n tokens: Token[],\n partials: Record<string, string>,\n partialStack: string[]\n): void {\n for (const token of tokens) {\n if (token.type === \"section\" || token.type === \"inverted\") {\n validatePartialReferences(token.children, partials, partialStack);\n continue;\n }\n if (token.type !== \"partial\") {\n continue;\n }\n if (!Object.hasOwn(partials, token.name)) {\n throw new Error(`Partial \"${token.name}\" not found.`);\n }\n if (partialStack.includes(token.name)) {\n throw new Error(\n `Circular partial reference detected: ${[...partialStack, token.name].join(\" -> \")}.`\n );\n }\n if (partialStack.length >= MAX_PARTIAL_DEPTH) {\n throw new Error(`Maximum partial depth exceeded (${MAX_PARTIAL_DEPTH}).`);\n }\n\n validatePartialReferences(parseTemplate(partials[token.name]), partials, [\n ...partialStack,\n token.name\n ]);\n }\n}\n\nfunction indentPartial(partial: string, indent: string): string {\n if (indent === \"\") {\n return partial;\n }\n\n return partial\n .split(\"\\n\")\n .map((line) => (line === \"\" ? \"\" : `${indent}${line}`))\n .join(\"\\n\");\n}\n\nfunction expandTemplatePartials(\n template: string,\n partials: Record<string, string>,\n partialStack: string[]\n): string {\n let output = \"\";\n let index = 0;\n\n while (index < template.length) {\n const open = template.indexOf(\"{{\", index);\n if (open === -1) {\n output += template.slice(index);\n break;\n }\n\n const parsed = parseTag(template, open);\n if (parsed.kind !== \"partial\") {\n output += template.slice(index, parsed.end);\n index = parsed.end;\n continue;\n }\n\n if (!Object.hasOwn(partials, parsed.name)) {\n throw new Error(`Partial \"${parsed.name}\" not found.`);\n }\n if (partialStack.includes(parsed.name)) {\n throw new Error(\n `Circular partial reference detected: ${[...partialStack, parsed.name].join(\" -> \")}.`\n );\n }\n if (partialStack.length >= MAX_PARTIAL_DEPTH) {\n throw new Error(`Maximum partial depth exceeded (${MAX_PARTIAL_DEPTH}).`);\n }\n\n const standalone = getStandalone(template, open, parsed.end, parsed.kind);\n const beforePartial =\n standalone === undefined\n ? template.slice(index, open)\n : template.slice(index, standalone.lineStart);\n const indent = standalone === undefined ? \"\" : template.slice(standalone.lineStart, open);\n const partial = indentPartial(partials[parsed.name], indent);\n output +=\n beforePartial + expandTemplatePartials(partial, partials, [...partialStack, parsed.name]);\n index = standalone?.nextIndex ?? parsed.end;\n }\n\n return output;\n}\n\nfunction lookupName(view: unknown, name: string): { hit: boolean; value: unknown } {\n if (!isPropertyContainer(view) || !hasProperty(view, name)) {\n return { hit: false, value: undefined };\n }\n\n return { hit: true, value: view[name] };\n}\n\nfunction lookupDotted(view: unknown, name: string): { hit: boolean; value: unknown } {\n const parts = name.split(\".\");\n let value = view;\n\n for (const part of parts) {\n if (!isPropertyContainer(value) || !hasProperty(value, part)) {\n return { hit: false, value: undefined };\n }\n value = Object(value)[part as keyof typeof value];\n }\n\n return { hit: true, value };\n}\n\nfunction callLambda(value: unknown, view: unknown): unknown {\n return typeof value === \"function\" ? (value as Lambda).call(view) : value;\n}\n\nfunction pushContext(parent: Context, view: unknown): Context {\n return { view, parent };\n}\n\nfunction appendText(tokens: Token[], value: string, start: number): void {\n if (value === \"\") {\n return;\n }\n\n const previous = tokens[tokens.length - 1];\n if (previous?.type === \"text\") {\n previous.value += value;\n return;\n }\n\n tokens.push({ type: \"text\", value, start });\n}\n\nfunction trimTextAfter(tokens: Token[], lineStart: number): void {\n const previous = tokens[tokens.length - 1];\n if (previous?.type !== \"text\") {\n return;\n }\n\n const keep = Math.max(0, lineStart - previous.start);\n previous.value = previous.value.slice(0, keep);\n if (previous.value === \"\") {\n tokens.pop();\n }\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"'`=/]/g, (char) => HTML_ESCAPE[char] ?? char);\n}\n\nfunction isWhitespace(value: string): boolean {\n return value.trim() === \"\";\n}\n\nfunction isPropertyContainer(value: unknown): value is Record<string, unknown> {\n return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n\nfunction hasProperty(value: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(value, key);\n}\n", "import { spawn } from \"node:child_process\";\nimport process from \"node:process\";\n\ninterface BrowserProcess {\n once(event: \"error\", listener: (error: Error) => void): this;\n once(event: \"close\", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n unref(): void;\n}\n\ntype SpawnBrowserProcess = (\n command: string,\n args: string[],\n options: { detached: true; stdio: \"ignore\" }\n) => BrowserProcess;\n\nexport interface OpenExternalOptions {\n platform?: NodeJS.Platform;\n spawnProcess?: SpawnBrowserProcess;\n}\n\nexport async function openExternal(url: string, options: OpenExternalOptions = {}): Promise<void> {\n const parsed = new URL(url);\n const { command, args } = browserCommand(parsed.href, options.platform ?? process.platform);\n await launchBrowser(command, args, options.spawnProcess ?? spawn);\n}\n\nfunction browserCommand(url: string, platform: NodeJS.Platform): { command: string; args: string[] } {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [url] };\n }\n\n if (platform === \"win32\") {\n return { command: \"rundll32.exe\", args: [\"url.dll,FileProtocolHandler\", url] };\n }\n\n return { command: \"xdg-open\", args: [url] };\n}\n\nfunction launchBrowser(\n command: string,\n args: string[],\n spawnProcess: SpawnBrowserProcess\n): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawnProcess(command, args, { detached: true, stdio: \"ignore\" });\n\n child.once(\"error\", reject);\n child.once(\"close\", (code, signal) => {\n if (code !== 0) {\n const reason = code === null ? `signal ${signal ?? \"unknown\"}` : `code ${code}`;\n reject(new Error(`Browser launcher exited with ${reason}`));\n return;\n }\n\n child.unref();\n resolve();\n });\n });\n}\n", "import { LineCounter, parse, parseDocument } from \"yaml\";\nimport { inspectFrontmatterBlock, splitFrontmatterBlock } from \"./fences.js\";\n\nexport interface ParsedFrontmatter {\n frontmatter: Record<string, unknown>;\n body: string;\n}\n\nexport interface ParsedFrontmatterDocument extends ParsedFrontmatter {\n errors: readonly { message: string; pos?: [number, number] }[];\n lineCounter: LineCounter;\n}\n\nexport interface ParseFrontmatterOptions {\n uniqueKeys?: boolean;\n}\n\nexport class FrontmatterParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FrontmatterParseError\";\n }\n}\n\nexport function parseFrontmatter(\n source: string,\n options: ParseFrontmatterOptions = {}\n): ParsedFrontmatter {\n const split = splitFrontmatter(source);\n\n if (split.raw === undefined) {\n return {\n frontmatter: {},\n body: split.body\n };\n }\n\n return {\n frontmatter: parseYamlFrontmatter(split.raw, options),\n body: split.body\n };\n}\n\nexport function parseFrontmatterDocument(\n source: string,\n options: ParseFrontmatterOptions = {}\n): ParsedFrontmatterDocument {\n const split = inspectFrontmatterBlock(source);\n const lineCounter = createSourceLineCounter(source);\n\n if (split.kind === \"body\") {\n return {\n frontmatter: {},\n body: split.body,\n errors: [],\n lineCounter\n };\n }\n\n if (split.kind === \"missing-closing-fence\") {\n return {\n frontmatter: {},\n body: split.body,\n errors: [{ message: split.message, pos: [split.position, split.position] }],\n lineCounter\n };\n }\n\n const yamlLineCounter = new LineCounter();\n const normalizedYaml = normalizeYamlLineEndings(split.raw);\n const document = parseDocument(normalizedYaml, {\n lineCounter: yamlLineCounter,\n prettyErrors: false,\n uniqueKeys: options.uniqueKeys ?? false\n });\n const errors = document.errors.map((error) => ({\n message: error.message,\n ...(error.pos === undefined\n ? {}\n : { pos: translateYamlErrorPosition(error.pos as [number, number], split) })\n }));\n\n if (errors.length > 0) {\n return {\n frontmatter: {},\n body: split.body,\n errors,\n lineCounter\n };\n }\n\n try {\n return {\n frontmatter: normalizeYamlFrontmatter(document.toJSON()),\n body: split.body,\n errors,\n lineCounter\n };\n } catch (error) {\n if (error instanceof FrontmatterParseError) {\n return {\n frontmatter: {},\n body: split.body,\n errors: [{ message: error.message }],\n lineCounter\n };\n }\n\n throw error;\n }\n}\n\nfunction createSourceLineCounter(source: string): LineCounter {\n const lineCounter = new LineCounter();\n lineCounter.addNewLine(0);\n\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n\n if (character === \"\\n\") {\n lineCounter.addNewLine(index + 1);\n continue;\n }\n\n if (character === \"\\r\") {\n lineCounter.addNewLine(index + (source[index + 1] === \"\\n\" ? 2 : 1));\n if (source[index + 1] === \"\\n\") {\n index += 1;\n }\n }\n }\n\n return lineCounter;\n}\n\nfunction translateYamlErrorPosition(\n pos: [number, number],\n split: { raw: string; rawStart: number }\n): [number, number] {\n return pos.map((offset) => split.rawStart + normalizeYamlErrorOffset(split.raw, offset)) as [\n number,\n number\n ];\n}\n\nfunction normalizeYamlErrorOffset(raw: string, offset: number): number {\n if (offset >= raw.length && endsWithLineBreak(raw)) {\n return findPreviousLineStart(raw, raw.length);\n }\n\n return offset;\n}\n\nfunction endsWithLineBreak(value: string): boolean {\n return value.endsWith(\"\\n\") || value.endsWith(\"\\r\");\n}\n\nfunction findPreviousLineStart(value: string, end: number): number {\n let index = end - 1;\n\n if (value[index] === \"\\n\") {\n index -= 1;\n }\n\n if (value[index] === \"\\r\") {\n index -= 1;\n }\n\n while (index >= 0) {\n const character = value[index];\n\n if (character === \"\\n\" || character === \"\\r\") {\n return index + 1;\n }\n\n index -= 1;\n }\n\n return 0;\n}\n\nfunction splitFrontmatter(source: string): { raw?: string; body: string } {\n try {\n return splitFrontmatterBlock(source);\n } catch (error) {\n if (error instanceof Error) {\n throw new FrontmatterParseError(error.message);\n }\n\n throw error;\n }\n}\n\nfunction parseYamlFrontmatter(\n yamlBlock: string,\n options: ParseFrontmatterOptions\n): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = parse(normalizeYamlLineEndings(yamlBlock), {\n uniqueKeys: options.uniqueKeys ?? false\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown YAML parse error\";\n throw new FrontmatterParseError(`Invalid YAML frontmatter: ${message}`);\n }\n\n return normalizeYamlFrontmatter(parsed);\n}\n\nfunction normalizeYamlLineEndings(value: string): string {\n if (!value.includes(\"\\r\")) {\n return value;\n }\n\n let normalized = \"\";\n\n for (let index = 0; index < value.length; index += 1) {\n const character = value[index];\n\n if (character !== \"\\r\") {\n normalized += character;\n continue;\n }\n\n if (value[index + 1] === \"\\n\") {\n normalized += \"\\r\\n\";\n index += 1;\n continue;\n }\n\n normalized += \"\\n\";\n }\n\n return normalized;\n}\n\nfunction normalizeYamlFrontmatter(value: unknown): Record<string, unknown> {\n if (value === null || value === undefined) {\n return {};\n }\n\n if (!isPlainRecord(value)) {\n throw new FrontmatterParseError(\"YAML frontmatter must parse to an object.\");\n }\n\n return normalizeYamlValue(value) as Record<string, unknown>;\n}\n\nfunction normalizeYamlValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => normalizeYamlValue(item));\n }\n\n if (!isPlainRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = {};\n\n for (const [key, entryValue] of Object.entries(value)) {\n Object.defineProperty(normalized, key, {\n configurable: true,\n enumerable: true,\n value: normalizeYamlValue(entryValue),\n writable: true\n });\n }\n\n return normalized;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (!isRecord(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n", "import { stringify } from \"yaml\";\nimport { FrontmatterParseError } from \"./parse.js\";\n\nexport function stringifyFrontmatter(frontmatter: Record<string, unknown>, body: string): string {\n try {\n assertFrontmatterRoot(frontmatter);\n assertAcyclic(frontmatter);\n return `---\\n${stringify(frontmatter, { aliasDuplicateObjects: false }).trimEnd()}\\n---\\n${body}`;\n } catch (error) {\n if (error instanceof FrontmatterParseError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : \"Unknown YAML stringify error\";\n throw new FrontmatterParseError(`Invalid YAML frontmatter: ${message}`);\n }\n}\n\nfunction assertFrontmatterRoot(value: unknown): asserts value is Record<string, unknown> {\n if (!isPlainRecord(value)) {\n throw new FrontmatterParseError(\"YAML frontmatter must parse to an object.\");\n }\n}\n\nfunction assertAcyclic(value: unknown, seen: WeakSet<object> = new WeakSet()): void {\n if (typeof value !== \"object\" || value === null) {\n return;\n }\n\n if (seen.has(value)) {\n throw new FrontmatterParseError(\"Cannot stringify cyclic frontmatter.\");\n }\n\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n assertAcyclic(item, seen);\n }\n } else {\n for (const item of Object.values(value)) {\n assertAcyclic(item, seen);\n }\n }\n\n seen.delete(value);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n", "const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport function graphemes(value: string): string[] {\n return Array.from(graphemeSegmenter.segment(value), ({ segment }) => segment);\n}\n\nexport function displayWidth(value: string, startColumn = 0): number {\n let column = startColumn;\n\n for (const segment of graphemes(value)) {\n if (segment === \"\\t\") {\n column += 8 - (column % 8);\n continue;\n }\n\n column += graphemeWidth(segment);\n }\n\n return column - startColumn;\n}\n\nexport function expandTabs(value: string, startColumn = 0): string {\n let column = startColumn;\n let expanded = \"\";\n\n for (const segment of graphemes(value)) {\n if (segment === \"\\t\") {\n const spaces = 8 - (column % 8);\n expanded += \" \".repeat(spaces);\n column += spaces;\n continue;\n }\n\n expanded += segment;\n column += graphemeWidth(segment);\n }\n\n return expanded;\n}\n\nexport function graphemeWidth(segment: string): number {\n const codePoint = segment.codePointAt(0);\n\n if (codePoint === undefined || isZeroWidthCodePoint(codePoint)) {\n return 0;\n }\n\n return isWideCodePoint(codePoint) || isFlagSegment(segment) ? 2 : 1;\n}\n\nfunction isZeroWidthCodePoint(codePoint: number): boolean {\n return (codePoint >= 0x0300 && codePoint <= 0x036f)\n || (codePoint >= 0x1ab0 && codePoint <= 0x1aff)\n || (codePoint >= 0x1dc0 && codePoint <= 0x1dff)\n || (codePoint >= 0x20d0 && codePoint <= 0x20ff)\n || (codePoint >= 0xfe20 && codePoint <= 0xfe2f);\n}\n\nfunction isFlagSegment(segment: string): boolean {\n const codePoints = [...segment].map((character) => character.codePointAt(0));\n return codePoints.length === 2\n && codePoints.every(\n (codePoint) => codePoint !== undefined && codePoint >= 0x1f1e6 && codePoint <= 0x1f1ff\n );\n}\n\nfunction isWideCodePoint(codePoint: number): boolean {\n return (\n (codePoint >= 0x1100 && codePoint <= 0x115f)\n || codePoint === 0x2329\n || codePoint === 0x232a\n || (codePoint >= 0x2e80 && codePoint <= 0x303e)\n || (codePoint >= 0x3041 && codePoint <= 0x33bf)\n || (codePoint >= 0x3400 && codePoint <= 0x4dbf)\n || (codePoint >= 0x4e00 && codePoint <= 0xa4cf)\n || (codePoint >= 0xa960 && codePoint <= 0xa97f)\n || (codePoint >= 0xac00 && codePoint <= 0xd7af)\n || (codePoint >= 0xf900 && codePoint <= 0xfaff)\n || (codePoint >= 0xfe10 && codePoint <= 0xfe19)\n || (codePoint >= 0xfe30 && codePoint <= 0xfe6f)\n || (codePoint >= 0xff00 && codePoint <= 0xff60)\n || (codePoint >= 0xffe0 && codePoint <= 0xffe6)\n || (codePoint >= 0x1b000 && codePoint <= 0x1b0ff)\n || codePoint === 0x1f004\n || codePoint === 0x1f0cf\n || (codePoint >= 0x1f200 && codePoint <= 0x1fffd)\n || (codePoint >= 0x20000 && codePoint <= 0x2fffd)\n || (codePoint >= 0x30000 && codePoint <= 0x3fffd)\n );\n}\n", "import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type AcpLineWriter = (line: string) => void;\n\nconst storage = new AsyncLocalStorage<AcpLineWriter>();\n\nconst defaultWriter: AcpLineWriter = (line) => {\n process.stdout.write(`${line}\\n`);\n};\n\n/**\n * Return the writer active in the current async context, or the default\n * stdout writer if none is bound.\n */\nexport function getAcpWriter(): AcpLineWriter {\n return storage.getStore() ?? defaultWriter;\n}\n\n/**\n * Run `fn` with `writer` bound as the active ACP line writer. All calls to\n * `renderAgentMessage`, `renderToolStart`, `renderAcpEvent`, etc. made inside\n * `fn` (or async work awaited from `fn`) will go through `writer` instead of\n * writing to `process.stdout`.\n */\nexport function withAcpWriter<T>(writer: AcpLineWriter, fn: () => Promise<T>): Promise<T> {\n return storage.run(writer, fn);\n}\n", "import readline from \"node:readline\";\nimport { PassThrough } from \"node:stream\";\nimport { cellToAnsi } from \"./buffer.js\";\nimport type { Cell } from \"./types.js\";\n\nexport type KeypressEvent = {\n name?: string;\n ch?: string;\n ctrl: boolean;\n meta: boolean;\n shift: boolean;\n};\n\nexport type TerminalDriver = {\n enterRawMode(): void;\n exitRawMode(): void;\n enterAltScreen(): void;\n exitAltScreen(): void;\n disableLineWrap(): void;\n enableLineWrap(): void;\n hideCursor(): void;\n showCursor(): void;\n moveTo(x: number, y: number): void;\n write(text: string): void;\n flush(changes: Array<{ x: number; y: number; cell: Cell }>): void;\n getSize(): { cols: number; rows: number };\n onResize(handler: () => void): () => void;\n onKeypress(handler: (key: KeypressEvent) => void): () => void;\n destroy(): void;\n};\n\ntype ReadlineKey = {\n sequence?: string;\n name?: string;\n ctrl?: boolean;\n meta?: boolean;\n shift?: boolean;\n};\n\ntype KeypressInput = NodeJS.ReadableStream & {\n on(event: \"keypress\", listener: (str: string | undefined, key: ReadlineKey) => void): KeypressInput;\n off(event: \"keypress\", listener: (str: string | undefined, key: ReadlineKey) => void): KeypressInput;\n};\n\ntype TerminalInput = NodeJS.ReadStream & KeypressInput & {\n setRawMode?: (mode: boolean) => void;\n};\n\ntype TerminalOutput = NodeJS.WriteStream & {\n columns?: number;\n rows?: number;\n on(event: \"resize\", listener: () => void): TerminalOutput;\n off(event: \"resize\", listener: () => void): TerminalOutput;\n};\n\nexport function createTerminalDriver(opts?: {\n stdin?: NodeJS.ReadStream;\n stdout?: NodeJS.WriteStream;\n}): TerminalDriver {\n const stdin = (opts?.stdin ?? process.stdin) as TerminalInput;\n const stdout = (opts?.stdout ?? process.stdout) as TerminalOutput;\n const resizeListeners = new Set<() => void>();\n const keypressListeners = new Set<(str: string | undefined, key: ReadlineKey) => void>();\n let rawMode = false;\n let altScreen = false;\n let lineWrapEnabled = true;\n let cursorHidden = false;\n let destroyed = false;\n\n readline.emitKeypressEvents(stdin);\n\n function enterRawMode(): void {\n if (destroyed || rawMode) {\n return;\n }\n\n stdin.setRawMode?.(true);\n stdin.resume();\n rawMode = true;\n }\n\n function exitRawMode(): void {\n if (destroyed || !rawMode) {\n return;\n }\n\n stdin.setRawMode?.(false);\n stdin.pause();\n rawMode = false;\n }\n\n function enterAltScreen(): void {\n if (destroyed || altScreen) {\n return;\n }\n\n write(\"\\u001b[?1049h\");\n altScreen = true;\n }\n\n function exitAltScreen(): void {\n if (destroyed || !altScreen) {\n return;\n }\n\n write(\"\\u001b[?1049l\");\n altScreen = false;\n }\n\n function disableLineWrap(): void {\n if (destroyed || !lineWrapEnabled) {\n return;\n }\n\n write(\"\\u001b[?7l\");\n lineWrapEnabled = false;\n }\n\n function enableLineWrap(): void {\n if (destroyed || lineWrapEnabled) {\n return;\n }\n\n write(\"\\u001b[?7h\");\n lineWrapEnabled = true;\n }\n\n function hideCursor(): void {\n if (destroyed || cursorHidden) {\n return;\n }\n\n write(\"\\u001b[?25l\");\n cursorHidden = true;\n }\n\n function showCursor(): void {\n if (destroyed || !cursorHidden) {\n return;\n }\n\n write(\"\\u001b[?25h\");\n cursorHidden = false;\n }\n\n function moveTo(x: number, y: number): void {\n if (destroyed) {\n return;\n }\n\n write(cursorPositionAnsi(x, y));\n }\n\n function write(text: string): void {\n if (destroyed || text.length === 0) {\n return;\n }\n\n stdout.write(text);\n }\n\n function flush(changes: Array<{ x: number; y: number; cell: Cell }>): void {\n if (destroyed || changes.length === 0) {\n return;\n }\n\n let output = \"\";\n\n for (const change of changes) {\n output += `${cursorPositionAnsi(change.x, change.y)}${cellToAnsi(change.cell)}`;\n }\n\n write(output);\n }\n\n function getSize(): { cols: number; rows: number } {\n return {\n cols: normalizeSize(stdout.columns),\n rows: normalizeSize(stdout.rows)\n };\n }\n\n function onResize(handler: () => void): () => void {\n if (destroyed) {\n return () => {};\n }\n\n const listener = () => {\n handler();\n };\n\n resizeListeners.add(listener);\n stdout.on(\"resize\", listener);\n\n return () => {\n if (!resizeListeners.delete(listener)) {\n return;\n }\n\n stdout.off(\"resize\", listener);\n };\n }\n\n function onKeypress(handler: (key: KeypressEvent) => void): () => void {\n if (destroyed) {\n return () => {};\n }\n\n const listener = (str: string | undefined, key: ReadlineKey) => {\n const event = toKeypressEvent(str, key);\n if (event !== undefined) {\n handler(event);\n }\n };\n\n keypressListeners.add(listener);\n stdin.on(\"keypress\", listener);\n\n return () => {\n if (!keypressListeners.delete(listener)) {\n return;\n }\n\n stdin.off(\"keypress\", listener);\n };\n }\n\n function destroy(): void {\n if (destroyed) {\n return;\n }\n\n for (const listener of keypressListeners) {\n stdin.off(\"keypress\", listener);\n }\n keypressListeners.clear();\n\n for (const listener of resizeListeners) {\n stdout.off(\"resize\", listener);\n }\n resizeListeners.clear();\n\n exitRawMode();\n enableLineWrap();\n exitAltScreen();\n showCursor();\n destroyed = true;\n }\n\n return {\n enterRawMode,\n exitRawMode,\n enterAltScreen,\n exitAltScreen,\n disableLineWrap,\n enableLineWrap,\n hideCursor,\n showCursor,\n moveTo,\n write,\n flush,\n getSize,\n onResize,\n onKeypress,\n destroy\n };\n}\n\nexport function parseKeypress(data: Buffer): KeypressEvent | undefined {\n if (data.length === 0) {\n return undefined;\n }\n\n const stream = new PassThrough();\n const stdin = stream as unknown as KeypressInput;\n let event: KeypressEvent | undefined;\n\n readline.emitKeypressEvents(stdin);\n stdin.on(\"keypress\", (str, key) => {\n event = toKeypressEvent(str, key);\n });\n stream.emit(\"data\", data);\n stream.destroy();\n\n return event;\n}\n\nfunction toKeypressEvent(str: string | undefined, key: ReadlineKey | undefined): KeypressEvent | undefined {\n const controlCharacter = controlCharacterToKeypress(key?.sequence);\n if (controlCharacter !== undefined) {\n return controlCharacter;\n }\n\n const ctrl = key?.ctrl ?? false;\n const meta = key?.meta ?? false;\n const shift = key?.shift ?? false;\n const ch = extractPrintableCharacter(str, key?.sequence);\n\n if (ch !== undefined) {\n return { ch, ctrl, meta, shift };\n }\n\n if (key?.name === undefined) {\n return undefined;\n }\n\n return {\n name: key.name,\n ctrl,\n meta,\n shift\n };\n}\n\nfunction extractPrintableCharacter(str: string | undefined, sequence: string | undefined): string | undefined {\n if (isPrintableCharacter(str)) {\n return str;\n }\n\n if (isSinglePrintableSequence(sequence)) {\n return sequence;\n }\n\n if (sequence === undefined || sequence.length <= 1 || sequence[0] !== \"\\u001b\") {\n return undefined;\n }\n\n const candidate = sequence.slice(1);\n return isPrintableCharacter(candidate) ? candidate : undefined;\n}\n\nfunction isSinglePrintableSequence(value: string | undefined): boolean {\n if (value === undefined || Array.from(value).length !== 1) {\n return false;\n }\n\n const codePoint = value.codePointAt(0);\n return codePoint !== undefined && codePoint >= 0x20 && codePoint !== 0x7f;\n}\n\nfunction isPrintableCharacter(value: string | undefined): value is string {\n if (value === undefined || Array.from(value).length !== 1) {\n return false;\n }\n\n const codePoint = value.codePointAt(0);\n return codePoint !== undefined && codePoint >= 0x20 && codePoint !== 0x7f;\n}\n\nfunction controlCharacterToKeypress(sequence: string | undefined): KeypressEvent | undefined {\n if (sequence === \"\\u001f\") {\n return { ch: \"/\", ctrl: true, meta: false, shift: false };\n }\n\n if (sequence !== undefined && sequence.length === 1) {\n const code = sequence.charCodeAt(0);\n if (code >= 1 && code <= 26 && code !== 9 && code !== 10 && code !== 13) {\n return {\n name: String.fromCharCode(code + 96),\n ctrl: true,\n meta: false,\n shift: false\n };\n }\n }\n\n return undefined;\n}\n\nfunction cursorPositionAnsi(x: number, y: number): string {\n return `\\u001b[${normalizeCoordinate(y) + 1};${normalizeCoordinate(x) + 1}H`;\n}\n\nfunction normalizeCoordinate(value: number): number {\n return Math.max(0, Math.floor(value));\n}\n\nfunction normalizeSize(value: number | undefined): number {\n if (value === undefined || !Number.isFinite(value)) {\n return 0;\n }\n\n return Math.max(0, Math.floor(value));\n}\n", "import { resolveBindings, type ResolvedBindings } from \"./keymap.js\";\n\nexport type Tone = \"success\" | \"warning\" | \"error\" | \"info\" | \"muted\";\n\nexport interface Row {\n id: string;\n title: string;\n subtitle?: string;\n badge?: { text: string; tone?: Tone };\n group?: string; // grouped rendering; rows with same group cluster under a header\n}\n\nexport interface DetailItem {\n id: string;\n title?: string; // absent => item fills pane with no cursor / no selection chrome\n subtitle?: string;\n badge?: { text: string; tone?: Tone };\n render: (ctx: DetailCtx) => string | Promise<string>;\n renderedContent?: string;\n}\n\nexport interface Detail<R> {\n items: (row: Row, ctx: DetailCtx) => Promise<DetailItem[]>;\n actions?: Action<R>[]; // run against the focused detail item\n}\n\nexport interface DetailCtx { width: number; height: number; signal: AbortSignal; row: Row }\n\nexport interface Action<R> {\n id: string;\n label: string | (() => string); // function form re-evaluated when state changes\n key?: string | string[];\n predicate?: (ctx: ActionContext<R>) => boolean;\n handler: (ctx: ActionContext<R>) => void | Promise<void>;\n destructive?: boolean;\n primary?: boolean; // bound to Enter\n showInFooter?: boolean; // default true\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ActionContext<R> {\n row: Row; // currently highlighted left-pane row\n rows: Row[]; // multi-select; falls back to [row] if no selection\n item?: DetailItem; // populated for actions declared under detail.actions\n filter: string;\n refresh: () => Promise<void>;\n suspendAnd: <T>(fn: () => Promise<T>) => Promise<T>;\n toast: (msg: string, tone?: Tone) => void;\n confirm: (prompt: string) => Promise<boolean>;\n exit: (after?: () => void | Promise<void>) => void;\n}\n\nexport interface ReorderContext {\n refresh: () => Promise<void>;\n toast: (msg: string, tone?: Tone) => void;\n}\n\nexport interface ExplorerConfig<R> {\n title: string;\n rows: () => Promise<Row[]>;\n refresh?: () => Promise<void>;\n detail: Detail<R>;\n actions: Action<R>[];\n reorder?: { onReorder: (orderedIds: string[], ctx?: ReorderContext) => void | Promise<void> };\n multiSelect?: boolean;\n keybindOverrides?: Record<string, string | string[]>;\n emptyHint?: string;\n initialFilter?: string;\n}\n\nexport const REGION_HEADER = 1 << 0;\nexport const REGION_LIST = 1 << 1;\nexport const REGION_DETAIL = 1 << 2;\nexport const REGION_FOOTER = 1 << 3;\nexport const REGION_MODAL = 1 << 4;\nexport const REGION_TOAST = 1 << 5;\nexport const REGION_ALL =\n REGION_HEADER |\n REGION_LIST |\n REGION_DETAIL |\n REGION_FOOTER |\n REGION_MODAL |\n REGION_TOAST;\n\nexport type Dirty = number;\n\nexport type ExplorerLayoutMode =\n | \"wide\"\n | \"medium\"\n | \"narrow-vertical\"\n | \"narrow-list-only\"\n | \"too-narrow\";\n\nexport interface ExplorerSize {\n cols: number;\n rows: number;\n}\n\nexport interface ExplorerState {\n title: string;\n emptyHint: string;\n rows: Row[];\n filtered: number[];\n matchPositions: Map<number, number[]>;\n cursor: number;\n filter: string;\n filterFocused: boolean;\n focused: \"list\" | \"detail\";\n detail: {\n rowId: string | null;\n items: DetailItem[] | null;\n cursor: number;\n scroll: number;\n token: number;\n loading: boolean;\n };\n selected: Set<string>;\n multiSelect: boolean;\n modal:\n | null\n | { kind: \"help\" }\n | { kind: \"confirm\"; action: Action<unknown>; rows: Row[]; resolver: (ok: boolean) => void }\n | { kind: \"palette\"; query: string; cursor: number };\n toast: { message: string; tone: Tone; expiresAt: number } | null;\n dirty: Dirty;\n size: ExplorerSize;\n layout: ExplorerLayoutMode;\n bindings: ResolvedBindings;\n actionState: Map<string, ActionStateEntry>;\n}\n\nexport interface ActionStateEntry {\n available: boolean;\n label: string;\n running?: boolean;\n action?: Action<unknown>;\n source?: \"row\" | \"detail\";\n}\n\nexport function createInitialState<R>(\n config: ExplorerConfig<R>,\n size: ExplorerSize\n): ExplorerState {\n const normalizedSize = {\n cols: normalizeSize(size.cols),\n rows: normalizeSize(size.rows)\n };\n const multiSelect = config.multiSelect ?? true;\n\n return {\n title: config.title,\n emptyHint: config.emptyHint ?? \"No detail\",\n rows: [],\n filtered: [],\n matchPositions: new Map(),\n cursor: 0,\n filter: config.initialFilter ?? \"\",\n filterFocused: false,\n focused: \"list\",\n detail: {\n rowId: null,\n items: null,\n cursor: 0,\n scroll: 0,\n token: 0,\n loading: false\n },\n selected: new Set(),\n multiSelect,\n modal: null,\n toast: null,\n dirty: REGION_ALL,\n size: normalizedSize,\n layout: resolveExplorerLayoutMode(normalizedSize.cols),\n bindings: resolveBindings(config),\n actionState: createInitialActionState(config)\n };\n}\n\nfunction createInitialActionState<R>(\n config: ExplorerConfig<R>\n): Map<string, ActionStateEntry> {\n const state = new Map<string, ActionStateEntry>();\n\n for (const [source, actions] of [[\"row\", config.actions], [\"detail\", config.detail.actions ?? []]] as const) {\n for (const action of actions) {\n if (state.has(action.id)) {\n throw new Error(`Duplicate explorer action id: ${action.id}`);\n }\n\n state.set(action.id, {\n available: true,\n label: typeof action.label === \"function\" ? action.id : action.label,\n action: action as Action<unknown>,\n source\n });\n }\n }\n\n return state;\n}\n\nexport function resolveExplorerLayoutMode(cols: number): ExplorerLayoutMode {\n if (cols < 40) {\n return \"too-narrow\";\n }\n\n if (cols < 80) {\n return \"narrow-list-only\";\n }\n\n if (cols < 100) {\n return \"narrow-vertical\";\n }\n\n if (cols < 120) {\n return \"medium\";\n }\n\n return \"wide\";\n}\n\nfunction normalizeSize(value: number): number {\n if (!Number.isFinite(value)) {\n return 0;\n }\n\n return Math.max(0, Math.floor(value));\n}\n", "import { color } from \"../../components/color.js\";\nimport type { PromptStateName } from \"./core.js\";\n\nfunction supportsUnicode(): boolean {\n if (!process.platform.startsWith(\"win\")) {\n return process.env.TERM !== \"linux\";\n }\n\n return Boolean(\n process.env.CI ||\n process.env.WT_SESSION ||\n process.env.TERMINUS_SUBLIME ||\n process.env.ConEmuTask === \"{cmd::Cmder}\" ||\n process.env.TERM_PROGRAM === \"Terminus-Sublime\" ||\n process.env.TERM_PROGRAM === \"vscode\" ||\n process.env.TERM === \"xterm-256color\" ||\n process.env.TERM === \"alacritty\" ||\n process.env.TERMINAL_EMULATOR === \"JetBrains-JediTerm\"\n );\n}\n\nexport const UNICODE = supportsUnicode();\n\nfunction glyph(unicode: string, ascii: string): string {\n return UNICODE ? unicode : ascii;\n}\n\nexport const GLYPHS = {\n stepActive: glyph(\"\u25C6\", \"*\"),\n stepCancel: glyph(\"\u25A0\", \"x\"),\n stepError: glyph(\"\u25B2\", \"x\"),\n stepSubmit: glyph(\"\u25C7\", \"o\"),\n barStart: glyph(\"\u250C\", \"T\"),\n bar: glyph(\"\u2502\", \"|\"),\n barEnd: glyph(\"\u2514\", \"-\"),\n radioActive: glyph(\"\u25CF\", \">\"),\n radioInactive: glyph(\"\u25CB\", \" \"),\n checkboxActive: glyph(\"\u25FB\", \"[ ]\"),\n checkboxSelected: glyph(\"\u25FC\", \"[+]\"),\n checkboxInactive: glyph(\"\u25FB\", \"[ ]\"),\n passwordMask: glyph(\"\u2022\", \"*\"),\n ellipsis: \"...\"\n} as const;\n\nexport function symbol(state: PromptStateName): string {\n if (state === \"cancel\") return color.red(GLYPHS.stepCancel);\n if (state === \"error\") return color.yellow(GLYPHS.stepError);\n if (state === \"submit\") return color.green(GLYPHS.stepSubmit);\n return color.cyan(GLYPHS.stepActive);\n}\n\nexport function symbolBar(state: PromptStateName): string {\n if (state === \"cancel\") return color.red(GLYPHS.bar);\n if (state === \"error\") return color.yellow(GLYPHS.bar);\n if (state === \"submit\") return color.green(GLYPHS.bar);\n return color.cyan(GLYPHS.bar);\n}\n", "import { EventEmitter } from \"node:events\";\nimport * as readline from \"node:readline\";\nimport { CANCEL } from \"./cancel-symbol.js\";\nimport { mapKey, type Action } from \"./keys.js\";\nimport { wrapFrame } from \"./wrap.js\";\n\nconst cursor = {\n hide: \"\\x1b[?25l\",\n show: \"\\x1b[?25h\",\n move: (x: number, y: number) => {\n let output = \"\";\n if (x < 0) output += `\\x1b[${-x}D`;\n if (x > 0) output += `\\x1b[${x}C`;\n if (y < 0) output += `\\x1b[${-y}A`;\n if (y > 0) output += `\\x1b[${y}B`;\n return output;\n }\n};\n\nconst erase = {\n down: \"\\x1b[J\"\n};\n\nexport type PromptStateName = \"initial\" | \"active\" | \"submit\" | \"cancel\" | \"error\";\n\nexport interface PromptState<Value> {\n state: PromptStateName;\n value: Value | undefined;\n error: string;\n cursor: number;\n userInput: string;\n}\n\nexport interface PromptOptions<Value> {\n render: (state: Prompt<Value>) => string;\n initialValue?: Value;\n initialUserInput?: string;\n validate?: (value: Value | undefined) => string | Error | undefined;\n signal?: AbortSignal;\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\ntype InputStream = NodeJS.ReadableStream & {\n isTTY?: boolean;\n setRawMode?: (enabled: boolean) => void;\n unpipe?: () => void;\n};\n\ntype KeyMeta = {\n name?: string;\n ctrl?: boolean;\n};\n\nexport class Prompt<Value> extends EventEmitter {\n state: PromptStateName = \"initial\";\n value: Value | undefined;\n error = \"\";\n userInput = \"\";\n protected _cursor = 0;\n protected input: InputStream;\n protected output: NodeJS.WritableStream;\n private readonly renderFrame: (state: Prompt<Value>) => string;\n private readonly validate?: (value: Value | undefined) => string | Error | undefined;\n private readonly signal?: AbortSignal;\n private readonly trackValue: boolean;\n private previousFrame = \"\";\n private readlineInterface?: readline.Interface;\n private abortListener?: () => void;\n private closed = false;\n\n constructor(opts: PromptOptions<Value>, trackValue = true) {\n super();\n this.input = (opts.input ?? process.stdin) as InputStream;\n this.output = opts.output ?? process.stdout;\n this.renderFrame = opts.render;\n this.validate = opts.validate;\n this.signal = opts.signal;\n this.value = opts.initialValue;\n this.trackValue = trackValue;\n this.userInput = opts.initialUserInput ?? \"\";\n this._cursor = this.userInput.length;\n }\n\n get cursor(): number {\n return this._cursor;\n }\n\n prompt(): Promise<Value | typeof CANCEL> {\n if (this.signal?.aborted) {\n this.state = \"cancel\";\n return Promise.resolve(CANCEL);\n }\n\n if (this.input.isTTY !== true) {\n return this.promptNonTty();\n }\n\n return new Promise((resolve) => {\n const onSubmit = (value: Value | undefined) => resolve(value as Value);\n const onCancel = () => resolve(CANCEL);\n this.once(\"submit\", onSubmit);\n this.once(\"cancel\", onCancel);\n\n this.abortListener = () => {\n this.state = \"cancel\";\n this.emit(\"finalize\");\n this.render();\n this.close();\n };\n this.signal?.addEventListener(\"abort\", this.abortListener, { once: true });\n\n this.readlineInterface = readline.createInterface({\n input: this.input,\n output: undefined,\n tabSize: 2,\n prompt: \"\",\n escapeCodeTimeout: 50,\n terminal: true\n });\n readline.emitKeypressEvents(this.input, this.readlineInterface);\n this.readlineInterface.prompt();\n this.input.on(\"keypress\", this.onKeypress);\n if (this.input.setRawMode) {\n this.input.setRawMode(true);\n }\n this.output.on(\"resize\", this.render);\n this.render();\n });\n }\n\n protected promptNonTty(): Promise<Value | typeof CANCEL> {\n return Promise.reject(new Error(\"Interactive prompt requires a TTY. Set POE_NO_PROMPT=1 to accept defaults non-interactively.\"));\n }\n\n protected readNonTtyLine(): Promise<string> {\n return new Promise((resolve) => {\n const rl = readline.createInterface({ input: this.input, terminal: false });\n let settled = false;\n\n const settle = (value: string) => {\n if (settled) {\n return;\n }\n settled = true;\n rl.close();\n resolve(value);\n };\n\n rl.once(\"line\", settle);\n rl.once(\"close\", () => settle(rl.line));\n });\n }\n\n protected setValue(value: Value | undefined): void {\n this.value = value;\n this.emit(\"value\", value);\n }\n\n protected setError(message: string): void {\n this.error = message;\n }\n\n protected setUserInput(value: string): void {\n this.userInput = value;\n this._cursor = Math.min(this._cursor, this.userInput.length);\n this.emit(\"userInput\", this.userInput);\n }\n\n protected clearUserInput(): void {\n this.userInput = \"\";\n this._cursor = 0;\n this.emit(\"userInput\", this.userInput);\n }\n\n private readonly onKeypress = (char: string | undefined, key: KeyMeta = {}) => {\n let action = mapKey(key.name, char);\n if (this.trackValue && char && char >= \" \" && key.name !== \"return\" && key.name !== \"enter\" && key.name !== \"escape\") {\n action = undefined;\n }\n\n if (this.trackValue && action !== \"enter\") {\n this.updateTrackedInput(char, key, action);\n }\n\n if (this.state === \"error\") {\n this.state = \"active\";\n this.error = \"\";\n }\n\n if (!this.trackValue && action) {\n this.emit(\"cursor\", action);\n } else if (this.trackValue && action && action !== \"enter\") {\n this.emit(\"cursor\", action);\n }\n\n if (char && /^[yn]$/i.test(char)) {\n this.emit(\"confirm\", char.toLowerCase() === \"y\");\n }\n\n if (char) {\n this.emit(\"key\", char.toLowerCase(), key);\n }\n\n if (action === \"enter\") {\n const error = this.validate?.(this.value);\n if (error) {\n this.error = error instanceof Error ? error.message : error;\n this.state = \"error\";\n } else {\n this.state = \"submit\";\n }\n }\n\n if (action === \"cancel\") {\n this.state = \"cancel\";\n }\n\n if (this.state === \"submit\" || this.state === \"cancel\") {\n this.emit(\"finalize\");\n }\n\n this.render();\n\n if (this.state === \"submit\" || this.state === \"cancel\") {\n this.close();\n }\n };\n\n private updateTrackedInput(char: string | undefined, key: KeyMeta, action: Action | undefined): void {\n if (key.ctrl) {\n if (key.name === \"a\") {\n this._cursor = 0;\n return;\n }\n if (key.name === \"e\") {\n this._cursor = this.userInput.length;\n return;\n }\n if (key.name === \"u\") {\n this.userInput = this.userInput.slice(this._cursor);\n this._cursor = 0;\n this.emit(\"userInput\", this.userInput);\n return;\n }\n if (key.name === \"k\") {\n this.userInput = this.userInput.slice(0, this._cursor);\n this.emit(\"userInput\", this.userInput);\n return;\n }\n }\n\n if (action === \"left\") {\n this._cursor = Math.max(0, this._cursor - 1);\n return;\n }\n if (action === \"right\") {\n this._cursor = Math.min(this.userInput.length, this._cursor + 1);\n return;\n }\n if (action === \"cancel\" || action === \"up\" || action === \"down\" || action === \"space\") {\n return;\n }\n if (key.name === \"backspace\" || char === \"\\b\" || char === \"\\x7f\") {\n if (this._cursor > 0) {\n this.userInput = `${this.userInput.slice(0, this._cursor - 1)}${this.userInput.slice(this._cursor)}`;\n this._cursor -= 1;\n this.emit(\"userInput\", this.userInput);\n }\n return;\n }\n if (key.name === \"delete\") {\n if (this._cursor < this.userInput.length) {\n this.userInput = `${this.userInput.slice(0, this._cursor)}${this.userInput.slice(this._cursor + 1)}`;\n this.emit(\"userInput\", this.userInput);\n }\n return;\n }\n if (!char || char < \" \" || key.ctrl) {\n return;\n }\n\n this.userInput = `${this.userInput.slice(0, this._cursor)}${char}${this.userInput.slice(this._cursor)}`;\n this._cursor += char.length;\n this.emit(\"userInput\", this.userInput);\n }\n\n protected readonly render = () => {\n if (this.closed) {\n return;\n }\n\n const frame = wrapFrame(this.output, this.renderFrame(this) ?? \"\");\n if (frame === this.previousFrame) {\n return;\n }\n\n if (!this.previousFrame) {\n this.output.write(`${cursor.hide}${frame}`);\n this.previousFrame = frame;\n if (this.state === \"initial\") {\n this.state = \"active\";\n }\n return;\n }\n\n const previousLineCount = this.previousFrame.split(\"\\n\").length - 1;\n this.output.write(`${cursor.move(-999, -previousLineCount)}${erase.down}${frame}`);\n this.previousFrame = frame;\n };\n\n protected close(): void {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.input.removeListener(\"keypress\", this.onKeypress);\n this.output.removeListener(\"resize\", this.render);\n if (this.abortListener) {\n this.signal?.removeEventListener(\"abort\", this.abortListener);\n }\n this.output.write(`${cursor.show}\\n`);\n if (!process.platform.startsWith(\"win\") && this.input.setRawMode) {\n this.input.setRawMode(false);\n }\n this.readlineInterface?.close();\n this.input.unpipe?.();\n\n if (this.state === \"cancel\") {\n this.emit(\"cancel\");\n } else {\n this.emit(\"submit\", this.value);\n }\n this.removeAllListeners();\n }\n}\n", "import { wrapAnsi } from \"fast-wrap-ansi\";\nimport stringWidth from \"fast-string-width\";\n\ninterface StreamSize {\n columns?: number;\n rows?: number;\n}\n\nexport function getColumns(output: NodeJS.WritableStream): number {\n return Math.max(1, (output as StreamSize).columns ?? 80);\n}\n\nexport function getRows(output: NodeJS.WritableStream): number {\n return Math.max(1, (output as StreamSize).rows ?? 20);\n}\n\nexport function wrapTextWithPrefix(\n output: NodeJS.WritableStream,\n text: string,\n prefix: string,\n startPrefix = prefix\n): string {\n const width = Math.max(1, getColumns(output) - stringWidth(prefix));\n return wrapAnsi(text, width, { hard: true, trim: false })\n .split(\"\\n\")\n .map((line, index) => `${index === 0 ? startPrefix : prefix}${line}`)\n .join(\"\\n\");\n}\n\nexport function wrapFrame(output: NodeJS.WritableStream, frame: string): string {\n return wrapAnsi(frame, getColumns(output), { hard: true, trim: false });\n}\n", "import { color } from \"../../components/color.js\";\nimport { GLYPHS } from \"./glyphs.js\";\nimport { getColumns, getRows } from \"./wrap.js\";\nimport { wrapAnsi } from \"fast-wrap-ansi\";\n\nexport interface PaginationOptions<Option> {\n cursor: number;\n options: Option[];\n style: (option: Option, active: boolean) => string;\n output: NodeJS.WritableStream;\n maxItems?: number;\n columnPadding?: number;\n rowPadding?: number;\n}\n\nfunction countLines(values: string[]): number {\n return values.reduce((sum, value) => sum + value.split(\"\\n\").length, 0);\n}\n\nfunction trimToRows(values: string[], cursorOffset: number, rows: number, hasTop: boolean, hasBottom: boolean): string[] {\n const output = [...values];\n while (countLines(output) > rows && output.length > 1) {\n const removeFromTop = hasTop && cursorOffset > 0;\n const removeFromBottom = hasBottom && cursorOffset < output.length - 1;\n if (removeFromTop) {\n output.shift();\n cursorOffset -= 1;\n } else if (removeFromBottom) {\n output.pop();\n } else {\n output.pop();\n }\n }\n return output;\n}\n\nexport function limitOptions<Option>(opts: PaginationOptions<Option>): string[] {\n const {\n cursor,\n options,\n style,\n output,\n maxItems = Number.POSITIVE_INFINITY,\n columnPadding = 0,\n rowPadding = 4\n } = opts;\n\n if (options.length === 0) {\n return [];\n }\n\n const columns = Math.max(1, getColumns(output) - columnPadding);\n const rowBudget = Math.max(getRows(output) - rowPadding, 0);\n const visibleCount = Math.max(Math.min(maxItems, rowBudget), 5);\n const cappedVisibleCount = Math.min(visibleCount, options.length);\n let start = 0;\n\n if (cursor >= cappedVisibleCount - 3) {\n start = Math.max(Math.min(cursor - cappedVisibleCount + 3, options.length - cappedVisibleCount), 0);\n }\n\n const hasTopMarker = cappedVisibleCount < options.length && start > 0;\n const hasBottomMarker = cappedVisibleCount < options.length && start + cappedVisibleCount < options.length;\n const visible = options\n .slice(start, start + cappedVisibleCount)\n .map((option, index) => wrapAnsi(style(option, start + index === cursor), columns, { hard: true, trim: false }));\n const trimmed = trimToRows(\n visible,\n Math.max(cursor - start, 0),\n Math.max(rowBudget - Number(hasTopMarker) - Number(hasBottomMarker), 1),\n hasTopMarker,\n hasBottomMarker\n );\n\n if (hasTopMarker) {\n trimmed.unshift(color.dim(GLYPHS.ellipsis));\n }\n if (hasBottomMarker) {\n trimmed.push(color.dim(GLYPHS.ellipsis));\n }\n\n return trimmed;\n}\n", "import { color } from \"../components/color.js\";\nimport { symbols } from \"../components/symbols.js\";\nimport { resolveOutputFormat } from \"../internal/output-format.js\";\n\nexport const SPINNER_FRAMES = Object.freeze([\"\u25D2\", \"\u25D0\", \"\u25D3\", \"\u25D1\"] as const);\n\nexport interface SpinnerFrameOptions {\n frame?: number;\n message: string;\n timer?: string;\n}\n\nexport function renderSpinnerFrame(options: SpinnerFrameOptions): string {\n const format = resolveOutputFormat();\n\n if (format === \"markdown\") {\n return `- ${renderMarkdownInline(options.message)}${options.timer ? ` [${renderMarkdownInline(options.timer)}]` : \"\"}...\\n`;\n }\n\n if (format === \"json\") {\n return `${JSON.stringify({\n type: \"spinner\",\n state: \"running\",\n message: options.message,\n ...(options.timer ? { timer: options.timer } : {})\n })}\\n`;\n }\n\n const frame = options.frame ?? 0;\n const index = ((frame % SPINNER_FRAMES.length) + SPINNER_FRAMES.length) % SPINNER_FRAMES.length;\n const spinnerChar = color.magenta(SPINNER_FRAMES[index]);\n const timerSuffix = options.timer ? color.dim(` [${options.timer}]`) : \"\";\n const bar = color.gray(symbols.bar);\n\n return `${spinnerChar} ${options.message}${timerSuffix}\\n${bar}`;\n}\n\nexport interface SpinnerStoppedOptions {\n message: string;\n code?: number;\n timer?: string;\n subtext?: string;\n}\n\nfunction renderMarkdownInline(value: string): string {\n return value.replaceAll(\"\\r\\n\", \" \").replaceAll(\"\\n\", \" \").replaceAll(\"\\r\", \" \");\n}\n\nexport function renderSpinnerStopped(options: SpinnerStoppedOptions): string {\n const format = resolveOutputFormat();\n\n if (format === \"markdown\") {\n return `- ${renderMarkdownInline(options.message)}${options.timer ? ` [${renderMarkdownInline(options.timer)}]` : \"\"}\\n`;\n }\n\n if (format === \"json\") {\n return `${JSON.stringify({\n type: \"spinner\",\n state: \"stopped\",\n message: options.message,\n code: options.code ?? 0,\n ...(options.timer ? { timer: options.timer } : {}),\n ...(options.subtext ? { subtext: options.subtext } : {})\n })}\\n`;\n }\n\n const code = options.code ?? 0;\n const symbol = code === 0 ? color.green(\"\u25C6\") : color.red(\"\u25A0\");\n const timerSuffix = options.timer ? color.dim(` [${options.timer}]`) : \"\";\n const bar = color.gray(symbols.bar);\n\n let output = `${symbol} ${options.message}${timerSuffix}`;\n if (options.subtext) {\n output += `\\n${bar} ${color.dim(options.subtext)}`;\n }\n return output;\n}\n", "import * as jsonc from \"jsonc-parser\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.js\";\nimport { cloneConfigObject, hasConfigEntry, setConfigEntry } from \"./object.js\";\n\nfunction isConfigObject(value: unknown): value is ConfigObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction detectIndent(content: string): string {\n const match = content.match(/^[\\t ]+/m);\n if (match) {\n return match[0];\n }\n return \" \";\n}\n\nfunction parse(content: string): ConfigObject {\n if (!content || content.trim() === \"\") {\n return {};\n }\n const errors: jsonc.ParseError[] = [];\n const parsed = jsonc.parse(content, errors, {\n allowTrailingComma: true,\n disallowComments: false\n });\n if (errors.length > 0) {\n throw new Error(`JSON parse error: ${jsonc.printParseErrorCode(errors[0].error)}`);\n }\n if (parsed === null || parsed === undefined) {\n return {};\n }\n if (!isConfigObject(parsed)) {\n throw new Error(\"Expected JSON object.\");\n }\n return cloneConfigObject(parsed);\n}\n\nfunction serialize(obj: ConfigObject): string {\n return `${JSON.stringify(obj, null, 2)}\\n`;\n}\n\nfunction merge(base: ConfigObject, patch: ConfigObject): ConfigObject {\n const result = cloneConfigObject(base);\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = hasConfigEntry(result, key) ? result[key] : undefined;\n if (isConfigObject(existing) && isConfigObject(value)) {\n setConfigEntry(result, key, merge(existing, value));\n continue;\n }\n setConfigEntry(result, key, value as ConfigValue);\n }\n return result;\n}\n\nfunction configValuesEqual(left: ConfigValue | undefined, right: ConfigValue | undefined): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction prune(\n obj: ConfigObject,\n shape: ConfigObject\n): { changed: boolean; result: ConfigObject } {\n let changed = false;\n const result = cloneConfigObject(obj);\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!hasConfigEntry(result, key)) {\n continue;\n }\n\n const current = result[key];\n\n // Empty object pattern means \"delete this key entirely\"\n if (isConfigObject(pattern) && Object.keys(pattern).length === 0) {\n delete result[key];\n changed = true;\n continue;\n }\n\n // Non-empty object pattern with object current: recurse\n if (isConfigObject(pattern) && isConfigObject(current)) {\n const { changed: childChanged, result: childResult } = prune(\n current,\n pattern\n );\n if (childChanged) {\n changed = true;\n }\n if (Object.keys(childResult).length === 0) {\n delete result[key];\n } else {\n setConfigEntry(result, key, childResult);\n }\n continue;\n }\n\n if (isConfigObject(pattern) && Object.keys(pattern).length > 0) {\n continue;\n }\n\n delete result[key];\n changed = true;\n }\n\n return { changed, result };\n}\n\n/**\n * Modify JSON content at a specific path while preserving comments and formatting.\n * Uses jsonc-parser's modify() for targeted updates.\n *\n * @param content - The original JSON content (may include comments)\n * @param path - JSON path array, e.g. [\"mcpServers\", \"my-server\"]\n * @param value - The value to set (or undefined to remove)\n * @returns The modified JSON content with comments preserved\n */\nfunction modifyAtPath(\n content: string,\n path: (string | number)[],\n value: ConfigValue | undefined\n): string {\n const indent = detectIndent(content);\n const formattingOptions: jsonc.FormattingOptions = {\n tabSize: indent === \"\\t\" ? 1 : indent.length,\n insertSpaces: indent !== \"\\t\",\n eol: \"\\n\"\n };\n\n const edits = jsonc.modify(content, path, value, { formattingOptions });\n let result = jsonc.applyEdits(content, edits);\n\n if (!result.endsWith(\"\\n\")) {\n result += \"\\n\";\n }\n\n return result;\n}\n\n/**\n * Merge a patch into JSON content while preserving comments and formatting.\n * Uses jsonc.modify() for each top-level key to preserve existing comments.\n *\n * @param content - The original JSON content (may include comments)\n * @param patch - Object with values to merge\n * @returns The modified JSON content with comments preserved\n */\nfunction mergePreservingComments(\n content: string,\n patch: ConfigObject\n): string {\n const current = parse(content);\n return serializeUpdate(content || \"{}\", current, merge(current, patch));\n}\n\n/**\n * Remove a key from JSON content while preserving comments and formatting.\n *\n * @param content - The original JSON content\n * @param path - JSON path array to the key to remove\n * @returns The modified JSON content with comments preserved\n */\nfunction removeAtPath(content: string, path: (string | number)[]): string {\n return modifyAtPath(content, path, undefined);\n}\n\nfunction serializeUpdate(\n content: string,\n current: ConfigObject,\n next: ConfigObject\n): string {\n let result = content || \"{}\";\n result = applyObjectUpdate(result, [], current, next);\n\n if (!result.endsWith(\"\\n\")) {\n result += \"\\n\";\n }\n\n return result;\n}\n\nfunction applyObjectUpdate(\n content: string,\n path: (string | number)[],\n current: ConfigObject,\n next: ConfigObject\n): string {\n let result = content;\n\n for (const key of Object.keys(current)) {\n if (!hasConfigEntry(next, key)) {\n result = removeAtPath(result, [...path, key]);\n }\n }\n\n for (const [key, nextValue] of Object.entries(next)) {\n const nextPath = [...path, key];\n const hasCurrent = hasConfigEntry(current, key);\n const currentValue = hasCurrent ? current[key] : undefined;\n\n if (hasCurrent && isConfigObject(currentValue) && isConfigObject(nextValue)) {\n result = applyObjectUpdate(result, nextPath, currentValue, nextValue);\n continue;\n }\n\n if (!hasCurrent || !configValuesEqual(currentValue, nextValue)) {\n result = modifyAtPath(result, nextPath, nextValue as ConfigValue);\n }\n }\n\n return result;\n}\n\nexport {\n detectIndent,\n modifyAtPath,\n mergePreservingComments,\n removeAtPath,\n serializeUpdate\n};\n\nexport const jsonFormat: ConfigFormat = {\n parse,\n serialize,\n serializeUpdate,\n merge,\n prune\n};\n", "import type { ConfigObject, ConfigValue } from \"../types.js\";\n\nexport function cloneConfigObject(value: ConfigObject): ConfigObject {\n const result: ConfigObject = {};\n for (const [key, entry] of Object.entries(value)) {\n setConfigEntry(result, key, cloneConfigValue(entry));\n }\n return result;\n}\n\nexport function setConfigEntry(target: ConfigObject, key: string, value: ConfigValue): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value\n });\n}\n\nexport function hasConfigEntry(target: ConfigObject, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(target, key);\n}\n\nfunction cloneConfigValue(value: ConfigValue): ConfigValue {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneConfigValue(entry));\n }\n if (value && typeof value === \"object\" && !(value instanceof Date)) {\n return cloneConfigObject(value as ConfigObject);\n }\n return value;\n}\n", "import { parse as parseToml, stringify as stringifyToml } from \"smol-toml\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.js\";\nimport { cloneConfigObject, hasConfigEntry, setConfigEntry } from \"./object.js\";\n\nfunction isConfigObject(value: unknown): value is ConfigObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parse(content: string): ConfigObject {\n if (!content || content.trim() === \"\") {\n return {};\n }\n const parsed = parseToml(content);\n if (!isConfigObject(parsed)) {\n throw new Error(\"Expected TOML document to be a table.\");\n }\n return cloneConfigObject(parsed as ConfigObject);\n}\n\nfunction serialize(obj: ConfigObject): string {\n const serialized = stringifyToml(obj);\n return serialized.endsWith(\"\\n\") ? serialized : `${serialized}\\n`;\n}\n\nfunction merge(base: ConfigObject, patch: ConfigObject): ConfigObject {\n const result = cloneConfigObject(base);\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = hasConfigEntry(result, key) ? result[key] : undefined;\n if (isConfigObject(existing) && isConfigObject(value)) {\n setConfigEntry(result, key, merge(existing, value));\n continue;\n }\n setConfigEntry(result, key, value as ConfigValue);\n }\n return result;\n}\n\nfunction prune(\n obj: ConfigObject,\n shape: ConfigObject\n): { changed: boolean; result: ConfigObject } {\n let changed = false;\n const result = cloneConfigObject(obj);\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!hasConfigEntry(result, key)) {\n continue;\n }\n\n const current = result[key];\n\n // Empty object pattern means \"delete this key entirely\"\n if (isConfigObject(pattern) && Object.keys(pattern).length === 0) {\n delete result[key];\n changed = true;\n continue;\n }\n\n // Non-empty object pattern with object current: recurse\n if (isConfigObject(pattern) && isConfigObject(current)) {\n const { changed: childChanged, result: childResult } = prune(\n current,\n pattern\n );\n if (childChanged) {\n changed = true;\n }\n if (Object.keys(childResult).length === 0) {\n delete result[key];\n } else {\n setConfigEntry(result, key, childResult);\n }\n continue;\n }\n\n if (!isConfigObject(pattern) || Object.keys(pattern).length === 0) {\n delete result[key];\n changed = true;\n }\n }\n\n return { changed, result };\n}\n\nexport const tomlFormat: ConfigFormat = {\n parse,\n serialize,\n merge,\n prune\n};\n", "import { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.js\";\nimport { cloneConfigObject, hasConfigEntry, setConfigEntry } from \"./object.js\";\n\nfunction isConfigObject(value: unknown): value is ConfigObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parse(content: string): ConfigObject {\n if (!content || content.trim() === \"\") {\n return {};\n }\n const parsed = parseYaml(content);\n if (parsed === null || parsed === undefined) {\n return {};\n }\n if (!isConfigObject(parsed)) {\n throw new Error(\"Expected YAML object.\");\n }\n return cloneConfigObject(parsed);\n}\n\nfunction serialize(obj: ConfigObject): string {\n const serialized = stringifyYaml(obj);\n return serialized.endsWith(\"\\n\") ? serialized : `${serialized}\\n`;\n}\n\nfunction merge(base: ConfigObject, patch: ConfigObject): ConfigObject {\n const result = cloneConfigObject(base);\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = hasConfigEntry(result, key) ? result[key] : undefined;\n if (isConfigObject(existing) && isConfigObject(value)) {\n setConfigEntry(result, key, merge(existing, value));\n continue;\n }\n setConfigEntry(result, key, value as ConfigValue);\n }\n return result;\n}\n\nfunction prune(\n obj: ConfigObject,\n shape: ConfigObject\n): { changed: boolean; result: ConfigObject } {\n let changed = false;\n const result = cloneConfigObject(obj);\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!hasConfigEntry(result, key)) {\n continue;\n }\n\n const current = result[key];\n\n if (isConfigObject(pattern) && Object.keys(pattern).length === 0) {\n delete result[key];\n changed = true;\n continue;\n }\n\n if (isConfigObject(pattern) && isConfigObject(current)) {\n const { changed: childChanged, result: childResult } = prune(current, pattern);\n if (childChanged) {\n changed = true;\n }\n if (Object.keys(childResult).length === 0) {\n delete result[key];\n } else {\n setConfigEntry(result, key, childResult);\n }\n continue;\n }\n\n if (!isConfigObject(pattern) || Object.keys(pattern).length === 0) {\n delete result[key];\n changed = true;\n }\n }\n\n return { changed, result };\n}\n\nexport const yamlFormat: ConfigFormat = {\n parse,\n serialize,\n merge,\n prune\n};\n", "import type { ConfigFormat } from \"../types.js\";\nimport { jsonFormat } from \"./json.js\";\nimport { tomlFormat } from \"./toml.js\";\nimport { yamlFormat } from \"./yaml.js\";\n\nexport type FormatName = \"json\" | \"toml\" | \"yaml\";\n\nconst formatRegistry: Record<FormatName, ConfigFormat> = {\n json: jsonFormat,\n toml: tomlFormat,\n yaml: yamlFormat\n};\n\nconst extensionMap: Record<string, FormatName> = {\n \".json\": \"json\",\n \".toml\": \"toml\",\n \".yaml\": \"yaml\",\n \".yml\": \"yaml\"\n};\n\n/**\n * Get a format handler by path (auto-detect from extension) or explicit format name.\n */\nexport function getConfigFormat(pathOrFormat: string): ConfigFormat {\n // Check if it's an explicit format name\n if (Object.prototype.hasOwnProperty.call(formatRegistry, pathOrFormat)) {\n return formatRegistry[pathOrFormat as FormatName];\n }\n\n // Try to detect from extension\n const ext = getExtension(pathOrFormat);\n const formatName = extensionMap[ext];\n\n if (!formatName) {\n throw new Error(\n `Unsupported config format. Cannot detect format from \"${pathOrFormat}\". ` +\n `Supported extensions: ${Object.keys(extensionMap).join(\", \")}. ` +\n `Supported format names: ${Object.keys(formatRegistry).join(\", \")}.`\n );\n }\n\n return formatRegistry[formatName];\n}\n\n/**\n * Detect format name from a file path.\n */\nexport function detectFormat(path: string): FormatName | undefined {\n const ext = getExtension(path);\n return extensionMap[ext];\n}\n\nfunction getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1) {\n return \"\";\n }\n return path.slice(lastDot).toLowerCase();\n}\n\nexport { jsonFormat } from \"./json.js\";\nexport { tomlFormat } from \"./toml.js\";\nexport { yamlFormat } from \"./yaml.js\";\n", "import path from \"node:path\";\nimport type { PathMapper } from \"../types.js\";\n\n/**\n * Expand ~ shortcut to the provided home directory.\n */\nexport function expandHome(targetPath: string, homeDir: string): string {\n if (!targetPath?.startsWith(\"~\")) {\n return targetPath;\n }\n\n // Handle ~./ -> ~/.\n if (targetPath.startsWith(\"~./\")) {\n targetPath = `~/.${targetPath.slice(3)}`;\n }\n\n let remainder = targetPath.slice(1);\n\n // Remove leading slash or backslash\n if (remainder.startsWith(\"/\") || remainder.startsWith(\"\\\\\")) {\n remainder = remainder.slice(1);\n } else if (remainder.startsWith(\".\")) {\n // Handle ~/.\n remainder = remainder.slice(1);\n if (remainder.startsWith(\"/\") || remainder.startsWith(\"\\\\\")) {\n remainder = remainder.slice(1);\n }\n }\n\n return remainder.length === 0 ? homeDir : path.join(homeDir, remainder);\n}\n\n/**\n * Validate that a path is home-relative (starts with ~).\n * Throws if the path is not home-relative.\n */\nexport function validateHomePath(targetPath: string): void {\n if (typeof targetPath !== \"string\" || targetPath.length === 0) {\n throw new Error(\"Target path must be a non-empty string.\");\n }\n\n if (!targetPath.startsWith(\"~\")) {\n throw new Error(\n `All target paths must be home-relative (start with ~). Received: \"${targetPath}\"`\n );\n }\n}\n\n/**\n * Resolve a path with optional path mapping for isolated configurations.\n * 1. Validates the path starts with ~\n * 2. Expands ~ to home directory\n * 3. If pathMapper is provided, maps the directory portion and reconstructs the path\n */\nexport function resolvePath(\n rawPath: string,\n homeDir: string,\n pathMapper?: PathMapper\n): string {\n validateHomePath(rawPath);\n const expanded = expandHome(rawPath, homeDir);\n const canonicalHome = path.resolve(homeDir);\n const canonicalExpanded = path.resolve(expanded);\n const relative = path.relative(canonicalHome, canonicalExpanded);\n if (relative === \"..\" || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new Error(`Target path resolves outside home directory: \"${rawPath}\"`);\n }\n\n if (!pathMapper) {\n return canonicalExpanded;\n }\n\n // Map the directory portion\n const rawDirectory = path.dirname(expanded);\n const mappedDirectory = pathMapper.mapTargetDirectory({\n targetDirectory: rawDirectory\n });\n const filename = path.basename(expanded);\n\n return filename.length === 0 ? mappedDirectory : path.join(mappedDirectory, filename);\n}\n", "export function hasOwnErrorCode(\n error: unknown,\n code: string,\n): error is NodeJS.ErrnoException {\n return (\n typeof error === \"object\" &&\n error !== null &&\n Object.prototype.hasOwnProperty.call(error, \"code\") &&\n (error as { code?: unknown }).code === code\n );\n}\n", "import type { FileSystem } from \"./types.js\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\n\n/**\n * Check if an error is a \"file not found\" (ENOENT) error.\n */\nexport function isNotFound(error: unknown): boolean {\n return hasOwnErrorCode(error, \"ENOENT\");\n}\n\n/**\n * Read a file if it exists, returning null if not found.\n */\nexport async function readFileIfExists(\n fs: FileSystem,\n target: string\n): Promise<string | null> {\n try {\n return await fs.readFile(target, \"utf8\");\n } catch (error) {\n if (isNotFound(error)) {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Check if a path exists (file or directory).\n */\nexport async function pathExists(\n fs: FileSystem,\n target: string\n): Promise<boolean> {\n try {\n await fs.stat(target);\n return true;\n } catch (error) {\n if (isNotFound(error)) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Create an ISO timestamp safe for use in filenames.\n * Replaces colons and dots with dashes.\n */\nexport function createTimestamp(): string {\n return new Date().toISOString().replaceAll(\":\", \"-\").replaceAll(\".\", \"-\");\n}\n", "import type {\n Mutation,\n MutationContext,\n MutationDetails,\n MutationResult,\n MutationOptions\n} from \"../types.js\";\nimport { applyMutation, resolveMutationDetails } from \"./apply-mutation.js\";\n\n/**\n * Execute an array of mutations in order.\n *\n * All dependencies must be injected - no defaults, no globals.\n */\nexport async function runMutations(\n mutations: Mutation[],\n context: MutationContext,\n options?: MutationOptions\n): Promise<MutationResult> {\n const effects: MutationResult[\"effects\"] = [];\n let anyChanged = false;\n const resolverOptions = options ?? {};\n\n for (const mutation of mutations) {\n const { outcome } = await executeMutation(\n mutation,\n context,\n resolverOptions\n );\n effects.push(outcome);\n if (outcome.changed) {\n anyChanged = true;\n }\n }\n\n return {\n changed: anyChanged,\n effects\n };\n}\n\nasync function executeMutation(\n mutation: Mutation,\n context: MutationContext,\n options: MutationOptions\n): Promise<{ outcome: MutationResult[\"effects\"][number]; details: MutationDetails }> {\n const pendingDetails = resolveMutationDetails(mutation, context, options);\n\n // Call onStart observer\n context.observers?.onStart?.(pendingDetails);\n\n try {\n const { outcome, details } = await applyMutation(mutation, context, options);\n\n // Call onComplete observer\n context.observers?.onComplete?.(details, outcome);\n\n return { outcome, details };\n } catch (error) {\n // Call onError observer\n context.observers?.onError?.(pendingDetails, error);\n\n // Re-throw the error\n throw error;\n }\n}\n", "export function hasOwnErrorCode(error: unknown, code: string): boolean {\n return (\n error instanceof Error &&\n Object.prototype.hasOwnProperty.call(error, \"code\") &&\n (error as { code?: unknown }).code === code\n );\n}\n", "import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { TemplateLoader } from \"@poe-code/config-mutations\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\n\nconst TEMPLATE_IDS = [\"poe-generate.md\", \"terminal-pilot.md\"] as const;\ntype TemplateId = (typeof TEMPLATE_IDS)[number];\n\nconst cache = new Map<TemplateId, string>();\n\nasync function pathExists(target: string): Promise<boolean> {\n try {\n await stat(target);\n return true;\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nasync function findPackageRoot(entryFilePath: string): Promise<string> {\n let current = path.dirname(entryFilePath);\n while (true) {\n if (await pathExists(path.join(current, \"package.json\"))) {\n return current;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n throw new Error(\"Unable to locate package root for agent-skill-config templates.\");\n }\n current = parent;\n }\n}\n\nasync function resolveTemplatePath(templateId: TemplateId): Promise<string> {\n const packageRoot = await findPackageRoot(fileURLToPath(import.meta.url));\n const candidates = [\n path.join(packageRoot, \"src\", \"templates\", templateId),\n path.join(packageRoot, \"dist\", \"templates\", templateId),\n path.join(packageRoot, \"dist\", \"templates\", \"skill\", templateId)\n ];\n\n for (const candidate of candidates) {\n if (await pathExists(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(`Template not found: ${templateId}`);\n}\n\nfunction isKnownTemplate(templateId: string): templateId is TemplateId {\n return (TEMPLATE_IDS as readonly string[]).includes(templateId);\n}\n\nexport async function loadTemplate(templateId: string): Promise<string> {\n if (!isKnownTemplate(templateId)) {\n throw new Error(`Template not found: ${templateId}`);\n }\n\n const cached = cache.get(templateId);\n if (cached !== undefined) {\n return cached;\n }\n\n const resolved = await resolveTemplatePath(templateId);\n const content = await readFile(resolved, \"utf8\");\n cache.set(templateId, content);\n return content;\n}\n\nexport function createTemplateLoader(): TemplateLoader {\n return loadTemplate;\n}\n", "import { fileMutation, runMutations, templateMutation } from \"@poe-code/config-mutations\";\nimport { resolveAgentSupport } from \"./configs.js\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\nimport { createTemplateLoader } from \"./templates.js\";\nimport type { ApplyOptions, SkillFile } from \"./types.js\";\n\nexport class UnsupportedAgentError extends Error {\n constructor(agentId: string) {\n super(`Unsupported agent: ${agentId}`);\n this.name = \"UnsupportedAgentError\";\n }\n}\n\nfunction toHomeRelative(localSkillDir: string): string {\n if (localSkillDir.startsWith(\"~/\") || localSkillDir === \"~\") {\n return localSkillDir;\n }\n\n const normalized = localSkillDir.startsWith(\"./\")\n ? localSkillDir.slice(2)\n : localSkillDir;\n\n return `~/${normalized}`;\n}\n\nconst bundledSkillTemplateIds = [\"poe-generate.md\"] as const;\n\nasync function pathExists(fs: ApplyOptions[\"fs\"], targetPath: string): Promise<boolean> {\n try {\n await fs.stat(targetPath);\n return true;\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nexport async function configure(agentId: string, options: ApplyOptions): Promise<void> {\n const support = resolveAgentSupport(agentId);\n if (support.status !== \"supported\") {\n throw new UnsupportedAgentError(agentId);\n }\n\n const scope = options.scope ?? \"global\";\n const config = support.config!;\n\n const skillDir =\n scope === \"global\" ? config.globalSkillDir : toHomeRelative(config.localSkillDir);\n const homeDir = scope === \"global\" ? options.homeDir : options.cwd;\n const templateLoader = createTemplateLoader();\n\n for (const templateId of bundledSkillTemplateIds) {\n const targetPath = `${scope === \"global\" ? options.homeDir : options.cwd}/${skillDir.slice(2)}/${templateId}`;\n if (await pathExists(options.fs, targetPath)) {\n const existing = await options.fs.readFile(targetPath, \"utf8\");\n if (existing !== (await templateLoader(templateId))) {\n throw new Error(`Skill already exists: ${targetPath}`);\n }\n }\n }\n\n await runMutations(\n [\n fileMutation.ensureDirectory({\n path: skillDir,\n label: `Ensure directory ${skillDir}`\n }),\n ...bundledSkillTemplateIds.map((templateId) =>\n templateMutation.write({\n target: `${skillDir}/${templateId}`,\n templateId,\n label: `Write bundled skill ${templateId} to ${skillDir}`\n })\n )\n ],\n {\n fs: options.fs,\n homeDir,\n dryRun: options.dryRun,\n observers: options.observers,\n templates: templateLoader\n }\n );\n}\n\nexport async function unconfigure(\n agentId: string,\n options: ApplyOptions & { force?: boolean }\n): Promise<void> {\n const support = resolveAgentSupport(agentId);\n if (support.status !== \"supported\") {\n throw new UnsupportedAgentError(agentId);\n }\n\n const scope = options.scope ?? \"global\";\n const config = support.config!;\n\n const skillDir =\n scope === \"global\" ? config.globalSkillDir : toHomeRelative(config.localSkillDir);\n const homeDir = scope === \"global\" ? options.homeDir : options.cwd;\n const templateLoader = createTemplateLoader();\n const removeBundledSkills = [];\n\n for (const templateId of bundledSkillTemplateIds) {\n const targetPath = `${scope === \"global\" ? options.homeDir : options.cwd}/${skillDir.slice(2)}/${templateId}`;\n if (await pathExists(options.fs, targetPath)) {\n const existing = await options.fs.readFile(targetPath, \"utf8\");\n if (existing === (await templateLoader(templateId))) {\n removeBundledSkills.push(\n fileMutation.remove({\n target: `${skillDir}/${templateId}`,\n label: `Remove bundled skill ${templateId} from ${skillDir}`\n })\n );\n }\n }\n }\n\n await runMutations(\n [\n ...removeBundledSkills,\n fileMutation.removeDirectory({\n path: skillDir,\n force: options.force,\n label: `Remove skills directory ${skillDir}`\n })\n ],\n {\n fs: options.fs,\n homeDir,\n dryRun: options.dryRun,\n observers: options.observers\n }\n );\n}\n\nexport type InstallSkillOptions = {\n fs: ApplyOptions[\"fs\"];\n cwd: string;\n homeDir: string;\n scope: ApplyOptions[\"scope\"];\n dryRun?: boolean;\n observers?: ApplyOptions[\"observers\"];\n};\n\nexport type InstallSkillResult = {\n skillPath: string;\n displayPath: string;\n};\n\nconst SKILL_TEMPLATE_ID = \"__skill_content__\";\n\n/**\n * Install a skill for an agent.\n * Creates folder structure: skillDir/<skill.name>/SKILL.md\n */\nexport async function installSkill(\n agentId: string,\n skill: SkillFile,\n options: InstallSkillOptions\n): Promise<InstallSkillResult> {\n const support = resolveAgentSupport(agentId);\n if (support.status !== \"supported\") {\n throw new UnsupportedAgentError(agentId);\n }\n\n const scope = options.scope ?? \"local\";\n const config = support.config!;\n\n if (\n skill.name.length === 0 ||\n skill.name !== skill.name.trim() ||\n skill.name === \".\" ||\n skill.name === \"..\" ||\n skill.name.includes(\"/\") ||\n skill.name.includes(\"\\\\\") ||\n skill.name.includes(\"\\n\") ||\n skill.name.includes(\"\\r\")\n ) {\n throw new Error(`Invalid skill name: ${skill.name}`);\n }\n\n // Use home-relative paths for mutations (same pattern as configure/unconfigure)\n const skillDir =\n scope === \"global\" ? config.globalSkillDir : toHomeRelative(config.localSkillDir);\n const skillFolderPath = `${skillDir}/${skill.name}`;\n const skillFilePath = `${skillFolderPath}/SKILL.md`;\n const displayPath = `${scope === \"global\" ? config.globalSkillDir : config.localSkillDir}/${skill.name}/SKILL.md`;\n const absoluteSkillPath = `${scope === \"global\" ? options.homeDir : options.cwd}/${skillFilePath.slice(2)}`;\n\n if (await pathExists(options.fs, absoluteSkillPath)) {\n throw new Error(`Skill already exists: ${displayPath}`);\n }\n\n await runMutations(\n [\n fileMutation.ensureDirectory({\n path: skillFolderPath,\n label: `Ensure skill directory ${skill.name}`\n }),\n templateMutation.write({\n target: skillFilePath,\n templateId: SKILL_TEMPLATE_ID,\n label: `Write skill ${skill.name}`\n })\n ],\n {\n fs: options.fs,\n homeDir: scope === \"global\" ? options.homeDir : options.cwd,\n dryRun: options.dryRun,\n observers: options.observers,\n templates: async (templateId) => {\n if (templateId === SKILL_TEMPLATE_ID) {\n return skill.content;\n }\n throw new Error(`Unknown template: ${templateId}`);\n }\n }\n );\n\n return { skillPath: absoluteSkillPath, displayPath };\n}\n", "import * as fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getAgentConfig, resolveAgentSupport, resolveSkillDir } from \"./configs.js\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\n\nexport interface SkillSource {\n kind: \"resolved\";\n ref: string;\n name: string;\n sourceAgentId?: string;\n sourcePath: string;\n scope: \"project\" | \"user\";\n}\n\nexport type SkillResolutionFailure =\n | { kind: \"malformed\"; ref: string }\n | { kind: \"unknown-agent\"; ref: string; agentInput: string }\n | { kind: \"not-found\"; ref: string; searchedPaths: string[] };\n\nexport type SkillResolution = SkillSource | SkillResolutionFailure;\n\ninterface SearchTier {\n scope: \"project\" | \"user\";\n sourcePath: string;\n}\n\nfunction isMalformedSegment(segment: string): boolean {\n return (\n segment.length === 0 ||\n segment !== segment.trim() ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"\\n\") ||\n segment.includes(\"\\r\")\n );\n}\n\nfunction isDirectory(targetPath: string): boolean {\n try {\n return fs.statSync(targetPath).isDirectory();\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\") || hasOwnErrorCode(error, \"ENOTDIR\")) {\n return false;\n }\n throw error;\n }\n}\n\nfunction findSkill(\n ref: string,\n name: string,\n tiers: SearchTier[],\n sourceAgentId?: string\n): SkillResolution {\n for (const tier of tiers) {\n if (isDirectory(tier.sourcePath)) {\n return {\n kind: \"resolved\",\n ref,\n name,\n ...(sourceAgentId ? { sourceAgentId } : {}),\n sourcePath: tier.sourcePath,\n scope: tier.scope\n };\n }\n }\n\n return {\n kind: \"not-found\",\n ref,\n searchedPaths: tiers.map((tier) => tier.sourcePath)\n };\n}\n\nexport function resolveSkillReference(ref: string, cwd: string, homeDir: string): SkillResolution {\n const slashIndex = ref.indexOf(\"/\");\n const hasPrefix = slashIndex !== -1;\n\n if (\n ref.length === 0 ||\n ref !== ref.trim() ||\n (hasPrefix && ref.indexOf(\"/\", slashIndex + 1) !== -1)\n ) {\n return { kind: \"malformed\", ref };\n }\n\n if (!hasPrefix) {\n if (isMalformedSegment(ref)) {\n return { kind: \"malformed\", ref };\n }\n\n const tiers: SearchTier[] = [\n {\n scope: \"project\",\n sourcePath: path.resolve(cwd, \".poe-code/skills\", ref)\n },\n {\n scope: \"user\",\n sourcePath: path.resolve(homeDir, \".poe-code/skills\", ref)\n }\n ];\n\n return findSkill(ref, ref, tiers);\n }\n\n const agentInput = ref.slice(0, slashIndex);\n const name = ref.slice(slashIndex + 1);\n if (isMalformedSegment(agentInput) || isMalformedSegment(name)) {\n return { kind: \"malformed\", ref };\n }\n\n const support = resolveAgentSupport(agentInput);\n if (support.status !== \"supported\" || !support.id) {\n return { kind: \"unknown-agent\", ref, agentInput };\n }\n\n const config = getAgentConfig(support.id);\n if (!config) {\n return { kind: \"unknown-agent\", ref, agentInput };\n }\n\n const tiers: SearchTier[] = [\n {\n scope: \"project\",\n sourcePath: path.resolve(resolveSkillDir(config, \"local\", cwd), name)\n },\n {\n scope: \"user\",\n sourcePath: path.resolve(resolveSkillDir(config, \"global\", cwd, homeDir), name)\n }\n ];\n\n return findSkill(ref, name, tiers, support.id);\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport path from \"node:path\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\n\nexport type GitDirRunner = (cwd: string) => string | undefined;\n\nconst defaultMarkerPrefix = \"poe-code-spawn-skills\";\n\nfunction defaultGitDirRunner(cwd: string): string | undefined {\n try {\n return execFileSync(\"git\", [\"rev-parse\", \"--git-dir\"], {\n cwd,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"]\n }).trim();\n } catch {\n return undefined;\n }\n}\n\nlet gitDirRunner: GitDirRunner = defaultGitDirRunner;\n\nexport function setGitDirRunnerForTest(runner: GitDirRunner): () => void {\n const previous = gitDirRunner;\n gitDirRunner = runner;\n return () => {\n gitDirRunner = previous;\n };\n}\n\nfunction resolveExcludePath(cwd: string): string | undefined {\n const gitDir = gitDirRunner(cwd);\n if (gitDir === undefined || gitDir.length === 0) {\n return undefined;\n }\n\n return path.join(path.isAbsolute(gitDir) ? gitDir : path.resolve(cwd, gitDir), \"info/exclude\");\n}\n\nfunction markers(runId: string, markerPrefix: string): { begin: string; end: string } {\n return {\n begin: `# ${markerPrefix}:${runId} begin`,\n end: `# ${markerPrefix}:${runId} end`\n };\n}\n\nfunction assertSingleLine(value: string, label: string): void {\n if (value.includes(\"\\n\") || value.includes(\"\\r\")) {\n throw new Error(`${label} must be a single line`);\n }\n}\n\nfunction readExcludeFile(excludePath: string): string | undefined {\n try {\n return fs.readFileSync(excludePath, \"utf8\");\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return undefined;\n }\n throw error;\n }\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return hasOwnErrorCode(error, \"EEXIST\");\n}\n\nfunction assertNoSymbolicLink(targetPath: string): void {\n const parsed = path.parse(path.resolve(targetPath));\n let current = parsed.root;\n\n for (const segment of path.resolve(targetPath).slice(parsed.root.length).split(path.sep)) {\n if (segment.length === 0) {\n continue;\n }\n current = path.join(current, segment);\n try {\n if (fs.lstatSync(current).isSymbolicLink()) {\n throw new Error(`Refusing to update Git exclude path through symbolic link: ${current}`);\n }\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return;\n }\n throw error;\n }\n }\n}\n\nfunction writeExcludeFile(excludePath: string, content: string): void {\n assertNoSymbolicLink(excludePath);\n fs.mkdirSync(path.dirname(excludePath), { recursive: true });\n assertNoSymbolicLink(excludePath);\n const tempPath = `${excludePath}.poe-code-${process.pid}-${randomUUID()}.tmp`;\n let tempCreated = false;\n try {\n assertNoSymbolicLink(tempPath);\n fs.writeFileSync(tempPath, content, { encoding: \"utf8\", flag: \"wx\" });\n tempCreated = true;\n fs.renameSync(tempPath, excludePath);\n } catch (error) {\n if (tempCreated || !isAlreadyExistsError(error)) {\n try {\n fs.rmSync(tempPath, { force: true });\n } catch (cleanupError) {\n void cleanupError;\n }\n }\n throw error;\n }\n}\n\nfunction removeBlock(content: string, runId: string, markerPrefix: string): string {\n const { begin, end } = markers(runId, markerPrefix);\n const lines = content.split(\"\\n\");\n const result: string[] = [];\n\n for (let index = 0; index < lines.length; index += 1) {\n if (lines[index] === begin) {\n const endIndex = lines.indexOf(end, index + 1);\n if (endIndex !== -1) {\n index = endIndex;\n continue;\n }\n }\n\n result.push(lines[index]);\n }\n\n return result.join(\"\\n\");\n}\n\nfunction appendBlock(\n content: string | undefined,\n runId: string,\n entries: string[],\n markerPrefix: string\n): string {\n const { begin, end } = markers(runId, markerPrefix);\n const existing = content ?? \"\";\n const prefix = existing.length === 0 || existing.endsWith(\"\\n\") ? existing : `${existing}\\n`;\n return `${prefix}${[begin, ...entries, end, \"\"].join(\"\\n\")}`;\n}\n\nfunction nextBlockId(content: string | undefined, runId: string, markerPrefix: string): string {\n if (content === undefined || !content.includes(markers(runId, markerPrefix).begin)) {\n return runId;\n }\n\n let suffix = 1;\n while (content.includes(markers(`${runId}:${suffix}`, markerPrefix).begin)) {\n suffix += 1;\n }\n return `${runId}:${suffix}`;\n}\n\nexport function appendExcludeBlock(\n cwd: string,\n runId: string,\n entries: string[],\n opts?: { markerPrefix?: string }\n): string | undefined {\n assertSingleLine(runId, \"runId\");\n assertSingleLine(opts?.markerPrefix ?? defaultMarkerPrefix, \"markerPrefix\");\n for (const entry of entries) {\n assertSingleLine(entry, \"exclude entry\");\n }\n const excludePath = resolveExcludePath(cwd);\n if (excludePath === undefined) {\n return undefined;\n }\n\n assertNoSymbolicLink(excludePath);\n const content = readExcludeFile(excludePath);\n const markerPrefix = opts?.markerPrefix ?? defaultMarkerPrefix;\n const blockId = nextBlockId(content, runId, markerPrefix);\n writeExcludeFile(excludePath, appendBlock(content, blockId, entries, markerPrefix));\n return blockId;\n}\n\nexport function removeExcludeBlock(\n cwd: string,\n runId: string,\n opts?: { markerPrefix?: string }\n): void {\n assertSingleLine(runId, \"runId\");\n assertSingleLine(opts?.markerPrefix ?? defaultMarkerPrefix, \"markerPrefix\");\n const excludePath = resolveExcludePath(cwd);\n if (excludePath === undefined) {\n return;\n }\n\n const content = readExcludeFile(excludePath);\n if (content === undefined) {\n return;\n }\n\n writeExcludeFile(excludePath, removeBlock(content, runId, opts?.markerPrefix ?? defaultMarkerPrefix));\n}\n", "import * as fs from \"node:fs\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport {\n getAgentConfig,\n resolveAgentSupport,\n resolveSkillDir,\n supportedAgents\n} from \"./configs.js\";\nimport { hasOwnErrorCode } from \"./error-codes.js\";\nimport { appendExcludeBlock, removeExcludeBlock } from \"./git-exclude.js\";\nimport { resolveSkillReference, type SkillResolutionFailure } from \"./resolve-skill-reference.js\";\n\nexport interface BridgeEntry {\n ref: string;\n sourcePath: string;\n targetPath: string;\n createdParents: string[];\n}\n\nexport type BridgeWarningKind =\n | \"local-collision\"\n | \"global-collision\"\n | \"self-reference\"\n | \"intra-batch-collision\";\n\nexport interface BridgeWarning {\n kind: BridgeWarningKind;\n ref: string;\n sourcePath: string;\n conflictingPath: string;\n message: string;\n}\n\nexport interface BridgeManifest {\n spawnAgentId: string;\n cwd: string;\n runId: string;\n excludeBlockId?: string;\n entries: BridgeEntry[];\n warnings: BridgeWarning[];\n}\n\ninterface ActiveTarget {\n createdParents: string[];\n fingerprint: string;\n sourceFingerprint: string;\n sourcePath: string;\n references: number;\n token: string;\n}\n\ninterface ManifestState {\n excludeBlockId?: string;\n cleaned?: boolean;\n}\n\nconst activeTargets = new Map<string, ActiveTarget>();\nconst manifestStates = new WeakMap<BridgeManifest, ManifestState>();\nconst ownershipFileName = \".poe-code-bridge-owner\";\n\ntype ResolvedSkill = Extract<ReturnType<typeof resolveSkillReference>, { kind: \"resolved\" }>;\n\ninterface ResolvedBridgeSource {\n ref: string;\n source: ResolvedSkill;\n targetPath: string;\n globalTargetPath: string;\n}\n\nfunction pathExists(targetPath: string): boolean {\n try {\n fs.statSync(targetPath);\n return true;\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nfunction assertNoSymbolicLinkUnder(rootPath: string, targetPath: string): void {\n const root = path.resolve(rootPath);\n const target = path.resolve(targetPath);\n const relative = path.relative(root, target);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Refusing to bridge skills outside root ${root}: ${target}`);\n }\n\n let current = root;\n const segments = relative.length === 0 ? [] : relative.split(path.sep);\n\n for (const segment of segments) {\n if (segment.length === 0) {\n continue;\n }\n current = path.join(current, segment);\n try {\n if (fs.lstatSync(current).isSymbolicLink()) {\n throw new Error(`Refusing to bridge skills through symbolic link: ${current}`);\n }\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return;\n }\n throw error;\n }\n }\n}\n\nfunction isDirectory(targetPath: string): boolean {\n try {\n return fs.statSync(targetPath).isDirectory();\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nfunction formatResolutionFailureError(failures: SkillResolutionFailure[]): Error {\n const malformed = failures.filter((failure) => failure.kind === \"malformed\");\n const unknownAgent = failures.filter((failure) => failure.kind === \"unknown-agent\");\n const notFound = failures.filter((failure) => failure.kind === \"not-found\");\n const lines = [\n `Failed to bridge active skills: ${failures.length} skill reference(s) could not be resolved.`\n ];\n\n if (malformed.length > 0) {\n lines.push(\"\", \"Malformed skill references:\");\n for (const failure of malformed) {\n lines.push(`- ${failure.ref}`);\n }\n lines.push('Expected syntax: \"<name>\" or \"<agentId>/<name>\".');\n }\n\n if (unknownAgent.length > 0) {\n lines.push(\"\", \"Unknown agent references:\");\n for (const failure of unknownAgent) {\n lines.push(`- ${failure.ref} (agent token: ${failure.agentInput})`);\n }\n lines.push(`Supported agents: ${supportedAgents.join(\", \")}.`);\n }\n\n if (notFound.length > 0) {\n lines.push(\"\", \"Not found skill references.\");\n for (const failure of notFound) {\n lines.push(`- ${failure.ref}`);\n lines.push(\" searched paths:\");\n for (const searchedPath of failure.searchedPaths) {\n lines.push(` - ${searchedPath}`);\n }\n }\n }\n\n return new Error(lines.join(\"\\n\"));\n}\n\nfunction copyDirectory(sourcePath: string, targetPath: string): void {\n fs.mkdirSync(targetPath, { recursive: true });\n for (const dirent of fs.readdirSync(sourcePath, { withFileTypes: true })) {\n const childSource = path.join(sourcePath, dirent.name);\n const childTarget = path.join(targetPath, dirent.name);\n\n if (dirent.isSymbolicLink()) {\n throw new Error(`Refusing to bridge skill containing symbolic link: ${childSource}`);\n }\n\n if (dirent.isDirectory()) {\n copyDirectory(childSource, childTarget);\n continue;\n }\n\n if (dirent.isFile()) {\n fs.copyFileSync(childSource, childTarget);\n continue;\n }\n\n throw new Error(`Refusing to bridge unsupported filesystem entry: ${childSource}`);\n }\n}\n\nfunction directoryFingerprint(targetPath: string): string {\n const hash = createHash(\"sha256\");\n\n function visit(currentPath: string, relativePath: string): void {\n const stats = fs.lstatSync(currentPath);\n if (stats.isSymbolicLink()) {\n throw new Error(`Refusing to inspect bridged skill through symbolic link: ${currentPath}`);\n }\n if (stats.isDirectory()) {\n hash.update(`d:${relativePath}\\n`);\n for (const name of fs.readdirSync(currentPath).sort()) {\n visit(path.join(currentPath, name), path.join(relativePath, name));\n }\n return;\n }\n if (stats.isFile()) {\n hash.update(`f:${relativePath}\\n`);\n hash.update(fs.readFileSync(currentPath));\n return;\n }\n throw new Error(`Refusing to bridge unsupported filesystem entry: ${currentPath}`);\n }\n\n visit(targetPath, \".\");\n return hash.digest(\"hex\");\n}\n\nfunction ownershipPath(targetPath: string): string {\n return path.join(targetPath, ownershipFileName);\n}\n\nfunction hasOwnershipToken(targetPath: string, token: string): boolean {\n try {\n return fs.readFileSync(ownershipPath(targetPath), \"utf8\") === token;\n } catch (error) {\n if (hasOwnErrorCode(error, \"ENOENT\")) {\n return false;\n }\n throw error;\n }\n}\n\nfunction collectMissingParents(targetPath: string): string[] {\n const parents: string[] = [];\n let current = path.dirname(targetPath);\n\n while (!pathExists(current)) {\n parents.push(current);\n const parent = path.dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n\n return parents.reverse();\n}\n\nfunction removeDirectoryIfEmpty(targetPath: string): void {\n try {\n fs.rmdirSync(targetPath);\n } catch (error) {\n if (\n hasOwnErrorCode(error, \"ENOENT\") ||\n hasOwnErrorCode(error, \"ENOTEMPTY\") ||\n hasOwnErrorCode(error, \"EEXIST\")\n ) {\n return;\n }\n throw error;\n }\n}\n\nfunction removeTarget(targetPath: string): void {\n fs.rmSync(targetPath, { recursive: true, force: true });\n}\n\nfunction rollbackEntries(entries: BridgeEntry[]): void {\n for (const entry of [...entries].reverse()) {\n const activeTarget = activeTargets.get(entry.targetPath);\n if (activeTarget && activeTarget.references > 1) {\n activeTarget.references -= 1;\n continue;\n }\n activeTargets.delete(entry.targetPath);\n removeTarget(entry.targetPath);\n for (const parent of [...(activeTarget?.createdParents ?? entry.createdParents)].reverse()) {\n removeDirectoryIfEmpty(parent);\n }\n }\n}\n\nfunction toCwdRelative(cwd: string, targetPath: string): string {\n return path.relative(cwd, targetPath);\n}\n\nfunction warning(\n kind: BridgeWarningKind,\n ref: string,\n sourcePath: string,\n conflictingPath: string\n): BridgeWarning {\n const messages: Record<BridgeWarningKind, string> = {\n \"intra-batch-collision\": `Skipping ${ref}: an earlier bridged skill already targets ${conflictingPath}.`,\n \"local-collision\": `Skipping ${ref}: local skill already exists at ${conflictingPath}.`,\n \"global-collision\": `Skipping ${ref}: global skill already exists at ${conflictingPath}.`,\n \"self-reference\": `Skipping ${ref}: spawning agent already sees this native skill at ${conflictingPath}.`\n };\n\n return {\n kind,\n ref,\n sourcePath,\n conflictingPath,\n message: messages[kind]\n };\n}\n\nexport function bridgeActiveSkills(\n spawnAgentId: string,\n cwd: string,\n refs: string[],\n homeDir: string,\n runId: string\n): BridgeManifest {\n const spawnConfig = getAgentConfig(spawnAgentId);\n const spawnSupport = resolveAgentSupport(spawnAgentId);\n if (!spawnConfig || spawnSupport.status !== \"supported\" || !spawnSupport.id) {\n throw new Error(\n `Unsupported spawn agent \"${spawnAgentId}\". Supported agents: ${supportedAgents.join(\", \")}.`\n );\n }\n\n const targetDir = resolveSkillDir(spawnConfig, \"local\", cwd);\n const globalTargetDir = resolveSkillDir(spawnConfig, \"global\", cwd, homeDir);\n const resolutions = refs.map((ref) => resolveSkillReference(ref, cwd, homeDir));\n const failures = resolutions.filter(\n (resolution): resolution is SkillResolutionFailure => resolution.kind !== \"resolved\"\n );\n if (failures.length > 0) {\n throw formatResolutionFailureError(failures);\n }\n\n const sources: ResolvedBridgeSource[] = resolutions.map((source, index) => ({\n ref: refs[index]!,\n source: source as ResolvedSkill,\n targetPath: path.resolve(targetDir, (source as ResolvedSkill).name),\n globalTargetPath: path.resolve(globalTargetDir, (source as ResolvedSkill).name)\n }));\n\n const entries: BridgeEntry[] = [];\n const warnings: BridgeWarning[] = [];\n const claimedTargets = new Set<string>();\n\n try {\n for (const item of sources) {\n if (claimedTargets.has(item.targetPath)) {\n warnings.push(\n warning(\"intra-batch-collision\", item.ref, item.source.sourcePath, item.targetPath)\n );\n continue;\n }\n\n if (item.source.sourceAgentId === spawnSupport.id) {\n warnings.push(\n warning(\"self-reference\", item.ref, item.source.sourcePath, item.source.sourcePath)\n );\n continue;\n }\n\n const activeTarget = activeTargets.get(item.targetPath);\n if (activeTarget && pathExists(item.targetPath)) {\n if (activeTarget.sourcePath === item.source.sourcePath) {\n const sourceRoot = item.source.scope === \"project\" ? cwd : homeDir;\n assertNoSymbolicLinkUnder(sourceRoot, item.source.sourcePath);\n const sourceFingerprint = directoryFingerprint(item.source.sourcePath);\n if (\n sourceFingerprint === activeTarget.sourceFingerprint &&\n hasOwnershipToken(item.targetPath, activeTarget.token) &&\n directoryFingerprint(item.targetPath) === activeTarget.fingerprint\n ) {\n activeTarget.references += 1;\n claimedTargets.add(item.targetPath);\n entries.push({\n ref: item.ref,\n sourcePath: item.source.sourcePath,\n targetPath: item.targetPath,\n createdParents: []\n });\n continue;\n }\n\n warnings.push(\n warning(\"local-collision\", item.ref, item.source.sourcePath, item.targetPath)\n );\n continue;\n }\n activeTargets.delete(item.targetPath);\n }\n\n if (pathExists(item.targetPath)) {\n warnings.push(\n warning(\"local-collision\", item.ref, item.source.sourcePath, item.targetPath)\n );\n continue;\n }\n\n if (isDirectory(item.globalTargetPath)) {\n warnings.push(\n warning(\"global-collision\", item.ref, item.source.sourcePath, item.globalTargetPath)\n );\n continue;\n }\n\n const sourceRoot = item.source.scope === \"project\" ? cwd : homeDir;\n assertNoSymbolicLinkUnder(sourceRoot, item.source.sourcePath);\n const sourceFingerprint = directoryFingerprint(item.source.sourcePath);\n const createdParents = collectMissingParents(item.targetPath);\n assertNoSymbolicLinkUnder(cwd, path.dirname(item.targetPath));\n fs.mkdirSync(path.dirname(item.targetPath), { recursive: true });\n const token = randomUUID();\n try {\n copyDirectory(item.source.sourcePath, item.targetPath);\n fs.writeFileSync(ownershipPath(item.targetPath), token, \"utf8\");\n const fingerprint = directoryFingerprint(item.targetPath);\n claimedTargets.add(item.targetPath);\n entries.push({\n ref: item.ref,\n sourcePath: item.source.sourcePath,\n targetPath: item.targetPath,\n createdParents\n });\n activeTargets.set(item.targetPath, {\n createdParents,\n fingerprint,\n sourceFingerprint,\n sourcePath: item.source.sourcePath,\n references: 1,\n token\n });\n } catch (error) {\n removeTarget(item.targetPath);\n for (const parent of [...createdParents].reverse()) {\n removeDirectoryIfEmpty(parent);\n }\n throw error;\n }\n }\n\n let excludeBlockId: string | undefined;\n if (entries.length > 0) {\n excludeBlockId = appendExcludeBlock(\n cwd,\n runId,\n entries.map((entry) => toCwdRelative(cwd, entry.targetPath))\n );\n }\n\n const manifest = {\n spawnAgentId,\n cwd,\n runId,\n ...(excludeBlockId !== undefined && excludeBlockId !== runId ? { excludeBlockId } : {}),\n entries,\n warnings\n };\n manifestStates.set(manifest, { excludeBlockId });\n return manifest;\n } catch (error) {\n rollbackEntries(entries);\n throw error;\n }\n}\n\nexport function cleanupBridgedSkills(manifest: BridgeManifest): void {\n const state = manifestStates.get(manifest);\n if (state?.cleaned) {\n return;\n }\n removeExcludeBlock(\n manifest.cwd,\n state?.excludeBlockId ?? manifest.excludeBlockId ?? manifest.runId\n );\n for (const entry of manifest.entries) {\n const activeTarget = activeTargets.get(entry.targetPath);\n if (!activeTarget) {\n continue;\n }\n if (activeTarget.references > 1) {\n activeTarget.references -= 1;\n continue;\n }\n activeTargets.delete(entry.targetPath);\n if (\n pathExists(entry.targetPath) &&\n hasOwnershipToken(entry.targetPath, activeTarget.token) &&\n directoryFingerprint(entry.targetPath) === activeTarget.fingerprint\n ) {\n removeTarget(entry.targetPath);\n for (const parent of [...activeTarget.createdParents].reverse()) {\n removeDirectoryIfEmpty(parent);\n }\n }\n }\n if (state) {\n state.cleaned = true;\n }\n}\n"],
5
+ "mappings": ";AACA,YAAYA,SAAQ;AACpB,YAAYC,SAAQ;AACpB,YAAYC,WAAU;;;ACHtB,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACCV,IAAM,kBAAmC;AAAA,EAC9C,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS,CAAC,QAAQ;AAAA,EAClB,YAAY;AAAA,EACZ,WAAW,CAAC,oBAAoB;AAAA,EAChC,aAAa;AAAA,IACX,KAAK;AAAA,MACH,8BAA8B;AAAA,IAChC;AAAA,EACF;AAAA,EACA,YAAY;AAAA,EACZ,UAAU;AAAA,IACR,QAAQ;AAAA,MACN,MAAM;AAAA,MACN,OAAO;AAAA,IACT;AAAA,EACF;AACF;;;ACpBO,IAAM,qBAAsC;AAAA,EACjD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,MACN,MAAM;AAAA,M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"number", "text", "config", "revision", "symbol", "spacing", "message", "symbol", "graphemeSegmenter", "frame", "close", "lookup", "lookup", "process", "graphemeSegmenter", "AsyncLocalStorage", "readline", "wrapAnsi", "stringWidth", "wrapAnsi", "parse", "path", "path", "parse", "isConfigObject", "parse", "serialize", "merge", "prune", "isConfigObject", "parse", "serialize", "merge", "prune", "path", "path", "error", "error", "fs", "error", "path", "isConfigObject", "stat", "backup", "fs", "error", "hasOwnErrorCode", "error", "path", "pathExists", "fs", "error", "hasOwnErrorCode", "config", "pathExists", "path", "randomUUID", "fs", "path", "fs", "randomUUID", "path", "installSkill"]
7
+ }