terminal-pilot 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cli.js +66 -103
  2. package/dist/cli.js.map +4 -4
  3. package/dist/commands/close-session.js +33 -81
  4. package/dist/commands/close-session.js.map +3 -3
  5. package/dist/commands/create-session.js +33 -81
  6. package/dist/commands/create-session.js.map +3 -3
  7. package/dist/commands/fill.js +33 -81
  8. package/dist/commands/fill.js.map +3 -3
  9. package/dist/commands/get-session.js +33 -81
  10. package/dist/commands/get-session.js.map +3 -3
  11. package/dist/commands/index.js +41 -92
  12. package/dist/commands/index.js.map +4 -4
  13. package/dist/commands/install.js +2 -5
  14. package/dist/commands/install.js.map +4 -4
  15. package/dist/commands/installer.js +2 -5
  16. package/dist/commands/installer.js.map +4 -4
  17. package/dist/commands/list-sessions.js +33 -81
  18. package/dist/commands/list-sessions.js.map +3 -3
  19. package/dist/commands/press-key.js +33 -81
  20. package/dist/commands/press-key.js.map +3 -3
  21. package/dist/commands/read-history.js +33 -81
  22. package/dist/commands/read-history.js.map +3 -3
  23. package/dist/commands/read-screen.js +33 -81
  24. package/dist/commands/read-screen.js.map +3 -3
  25. package/dist/commands/resize.js +33 -81
  26. package/dist/commands/resize.js.map +3 -3
  27. package/dist/commands/runtime.js +33 -81
  28. package/dist/commands/runtime.js.map +3 -3
  29. package/dist/commands/screenshot.js +33 -81
  30. package/dist/commands/screenshot.js.map +3 -3
  31. package/dist/commands/send-signal.js +33 -81
  32. package/dist/commands/send-signal.js.map +3 -3
  33. package/dist/commands/type.js +33 -81
  34. package/dist/commands/type.js.map +3 -3
  35. package/dist/commands/uninstall.js +1 -4
  36. package/dist/commands/uninstall.js.map +4 -4
  37. package/dist/commands/wait-for-exit.js +33 -81
  38. package/dist/commands/wait-for-exit.js.map +3 -3
  39. package/dist/commands/wait-for.js +33 -81
  40. package/dist/commands/wait-for.js.map +3 -3
  41. package/dist/index.js +33 -81
  42. package/dist/index.js.map +3 -3
  43. package/dist/terminal-pilot.js +33 -81
  44. package/dist/terminal-pilot.js.map +3 -3
  45. package/dist/terminal-session.js +33 -81
  46. package/dist/terminal-session.js.map +3 -3
  47. package/dist/testing/cli-repl.js +66 -103
  48. package/dist/testing/cli-repl.js.map +4 -4
  49. package/dist/testing/qa-cli.js +66 -103
  50. package/dist/testing/qa-cli.js.map +4 -4
  51. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../agent-skill-config/src/configs.ts", "../../../agent-defs/src/agents/claude-code.ts", "../../../agent-defs/src/agents/claude-desktop.ts", "../../../agent-defs/src/agents/codex.ts", "../../../agent-defs/src/agents/opencode.ts", "../../../agent-defs/src/agents/kimi.ts", "../../../agent-defs/src/registry.ts", "../../../config-mutations/src/mutations/file-mutation.ts", "../../../config-mutations/src/mutations/template-mutation.ts", "../../../config-mutations/src/execution/apply-mutation.ts", "../../../config-mutations/src/formats/json.ts", "../../../config-mutations/src/formats/toml.ts", "../../../config-mutations/src/formats/index.ts", "../../../config-mutations/src/execution/path-utils.ts", "../../../config-mutations/src/fs-utils.ts", "../../../config-mutations/src/execution/run-mutations.ts", "../../../config-mutations/src/template/render.ts", "../../../agent-skill-config/src/templates.ts", "../../../agent-skill-config/src/apply.ts", "../../../cmdkit/src/index.ts", "../../../cmdkit-schema/src/index.ts", "../../src/commands/installer.ts", "../../src/commands/install.ts"],
4
- "sourcesContent": ["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 opencode: {\n globalSkillDir: \"~/.config/opencode/skills\",\n localSkillDir: \".opencode/skills\"\n }\n};\n\nexport const supportedAgents = 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 };\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): string {\n if (!targetPath?.startsWith(\"~\")) {\n return targetPath;\n }\n\n if (targetPath === \"~\") {\n return os.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 ? os.homedir() : path.join(os.homedir(), remainder);\n}\n\nexport function resolveSkillDir(\n config: AgentSkillConfig,\n scope: SkillScope,\n cwd: string\n): string {\n if (scope === \"global\") {\n return path.resolve(expandHome(config.globalSkillDir));\n }\n\n return path.resolve(cwd, config.localSkillDir);\n}\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 configPath: \"~/.claude/settings.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: \"~/.claude/settings.json\",\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 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 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 configPath: \"~/.config/opencode/config.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 configPath: \"~/.kimi/config.toml\",\n branding: {\n colors: {\n dark: \"#7B68EE\",\n light: \"#6A5ACD\"\n }\n }\n};\n", "import type { AgentDefinition } from \"./types.js\";\nimport {\n claudeCodeAgent,\n claudeDesktopAgent,\n codexAgent,\n openCodeAgent,\n kimiAgent\n} from \"./agents/index.js\";\n\nexport const allAgents: AgentDefinition[] = [\n claudeCodeAgent,\n claudeDesktopAgent,\n codexAgent,\n openCodeAgent,\n kimiAgent\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.toLowerCase());\n}\n", "import type {\n EnsureDirectoryMutation,\n RemoveDirectoryMutation,\n RemoveFileMutation,\n ChmodMutation,\n BackupMutation,\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 /** 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 label: options.label\n };\n}\n\nexport const fileMutation = {\n ensureDirectory,\n remove,\n removeDirectory,\n chmod,\n backup\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 Mustache.render() */\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 Mustache.render() */\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 Mustache.render() */\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 Mustache from \"mustache\";\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 { resolvePath } from \"./path-utils.js\";\nimport {\n isNotFound,\n readFileIfExists,\n pathExists,\n createTimestamp\n} from \"../fs-utils.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 fs: FileSystem,\n targetPath: string,\n content: string\n): Promise<void> {\n const backupPath = createInvalidDocumentBackupPath(targetPath);\n await fs.writeFile(backupPath, content, { encoding: \"utf8\" });\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 \"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 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 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: ConfigObject = { ...base };\n const prefixMap = pruneByPrefix ?? {};\n\n for (const [key, value] of Object.entries(patch)) {\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 result[key] = { ...pruned, ...value };\n } else {\n result[key] = mergeWithPruneByPrefix(\n current,\n value as ConfigObject,\n prefixMap\n );\n }\n continue;\n }\n result[key] = value;\n }\n return result;\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 \"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 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 && !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 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 const content = await readFileIfExists(context.fs, targetPath);\n if (content === null) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n const backupPath = `${targetPath}.backup-${createTimestamp()}`;\n await context.fs.writeFile(backupPath, content, { encoding: \"utf8\" });\n }\n\n return {\n outcome: { changed: true, effect: \"copy\", detail: \"backup\" },\n details\n };\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 current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n // Invalid file - backup and start fresh\n if (rawContent !== null) {\n await backupInvalidDocument(context.fs, targetPath, rawContent);\n }\n current = {};\n }\n\n const value = resolveValue(mutation.value, options);\n\n // Use mergeWithPruneByPrefix for TOML files with pruneByPrefix option\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 = format.serialize(merged);\n const changed = serialized !== rawContent;\n\n if (changed && !context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 = format.serialize(result);\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n if (rawContent !== null) {\n await backupInvalidDocument(context.fs, targetPath, rawContent);\n }\n current = {};\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 = format.serialize(transformed);\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 = Mustache.render(template, templateContext);\n\n const existed = await pathExists(context.fs, targetPath);\n\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, rendered, { encoding: \"utf8\" });\n }\n\n return {\n outcome: {\n changed: true,\n effect: \"write\",\n detail: existed ? \"update\" : \"create\"\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 = Mustache.render(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) {\n await backupInvalidDocument(context.fs, 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 context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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", "import * as jsonc from \"jsonc-parser\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.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 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: ConfigObject = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = result[key];\n if (isConfigObject(existing) && isConfigObject(value)) {\n result[key] = merge(existing, value);\n continue;\n }\n 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: ConfigObject = { ...obj };\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!(key in result)) {\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 result[key] = childResult;\n }\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 let result = content || \"{}\";\n\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n result = modifyAtPath(result, [key], value);\n }\n\n return result;\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\nexport { detectIndent, modifyAtPath, mergePreservingComments, removeAtPath };\n\nexport const jsonFormat: ConfigFormat = {\n parse,\n serialize,\n merge,\n prune\n};\n", "import { parse as parseToml, stringify as stringifyToml } from \"smol-toml\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.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 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: ConfigObject = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = result[key];\n if (isConfigObject(existing) && isConfigObject(value)) {\n result[key] = merge(existing, value);\n continue;\n }\n 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: ConfigObject = { ...obj };\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!(key in result)) {\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 result[key] = childResult;\n }\n continue;\n }\n\n delete result[key];\n changed = true;\n }\n\n return { changed, result };\n}\n\nexport const tomlFormat: 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\";\n\nexport type FormatName = \"json\" | \"toml\";\n\nconst formatRegistry: Record<FormatName, ConfigFormat> = {\n json: jsonFormat,\n toml: tomlFormat\n};\n\nconst extensionMap: Record<string, FormatName> = {\n \".json\": \"json\",\n \".toml\": \"toml\"\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 (pathOrFormat in formatRegistry) {\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\";\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\n if (!pathMapper) {\n return expanded;\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", "import type { FileSystem } from \"./types.js\";\n\n/**\n * Check if an error is a \"file not found\" (ENOENT) error.\n */\nexport function isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === \"ENOENT\"\n );\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 MutationResult,\n MutationOptions\n} from \"../types.js\";\nimport { applyMutation } 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: { kind: string; label: string; targetPath?: string } }> {\n // Call onStart observer\n context.observers?.onStart?.({\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind,\n targetPath: undefined // Will be resolved during apply\n });\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?.(\n {\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind,\n targetPath: undefined\n },\n error\n );\n\n // Re-throw the error\n throw error;\n }\n}\n", "import Mustache from \"mustache\";\n\nexport type TemplateVariables = Record<string, string | number | boolean | string[]>;\n\n// Disable HTML escaping - we're rendering prompts, not HTML\nconst originalEscape = Mustache.escape;\n\n/**\n * Render a mustache template with the given variables.\n * Arrays are automatically joined with newlines.\n * HTML escaping is disabled.\n */\nexport function renderTemplate(\n template: string,\n variables: TemplateVariables\n): string {\n // Pre-process variables to handle arrays\n const processed: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (Array.isArray(value)) {\n processed[key] = value.join(\"\\n\");\n } else {\n processed[key] = value;\n }\n }\n\n // Temporarily disable HTML escaping\n Mustache.escape = (text: string) => text;\n try {\n return Mustache.render(template, processed);\n } finally {\n Mustache.escape = originalEscape;\n }\n}\n", "import type { TemplateLoader } from \"@poe-code/config-mutations\";\nimport { readFile } from \"node:fs/promises\";\n\nconst TEMPLATE_NAMES = [\"poe-generate.md\", \"terminal-pilot.md\"] as const;\n\nlet templatesCache: Record<string, string> | null = null;\n\nasync function getTemplates(): Promise<Record<string, string>> {\n if (templatesCache) {\n return templatesCache;\n }\n const entries = await Promise.all(\n TEMPLATE_NAMES.map(async (name) => {\n const url = new URL(`./templates/${name}`, import.meta.url);\n return [name, await readFile(url, \"utf8\")] as const;\n })\n );\n templatesCache = Object.fromEntries(entries);\n return templatesCache;\n}\n\nexport async function loadTemplate(templateId: string): Promise<string> {\n const templates = await getTemplates();\n const template = templates[templateId];\n if (!template) {\n throw new Error(`Template not found: ${templateId}`);\n }\n return template;\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 { 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\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\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: createTemplateLoader()\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\n await runMutations(\n [\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 // 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\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: skillFilePath, displayPath };\n}\n", "import { fileURLToPath } from \"node:url\";\nimport type { ObjectSchema, Static } from \"@poe-code/cmdkit-schema\";\nimport type { LoggerOutput, RenderTableOptions, ThemePalette } from \"@poe-code/design-system\";\n\nconst commandConfigSymbol = Symbol(\"cmdkit.command.config\");\nconst groupConfigSymbol = Symbol(\"cmdkit.group.config\");\nconst commandSourcePathSymbol = Symbol(\"cmdkit.command.sourcePath\");\n\ntype ScopeValue = \"cli\" | \"mcp\" | \"sdk\";\ntype AnyObjectSchema = ObjectSchema<Record<string, never>>;\ntype EmptyServices = Record<string, never>;\ntype ScopeInput = readonly Scope[] | undefined;\n\nexport type Scope = ScopeValue;\n\nexport interface SecretDefinition {\n env: string;\n description?: string;\n optional?: boolean;\n}\n\nexport type SecretDeclarations = Record<string, SecretDefinition>;\n\ntype OptionalSecretKeys<TSecrets extends SecretDeclarations> = {\n [TKey in keyof TSecrets]: TSecrets[TKey] extends { optional: true } ? TKey : never;\n}[keyof TSecrets];\n\ntype RequiredSecretKeys<TSecrets extends SecretDeclarations> = Exclude<\n keyof TSecrets,\n OptionalSecretKeys<TSecrets>\n>;\n\nexport type InferSecrets<TSecrets extends SecretDeclarations | undefined> =\n TSecrets extends SecretDeclarations\n ? { [TKey in RequiredSecretKeys<TSecrets>]: string } & {\n [TKey in OptionalSecretKeys<TSecrets>]?: string;\n }\n : Record<string, never>;\n\nexport interface HandlerFs {\n readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n writeFile(path: string, contents: string): Promise<void>;\n exists(path: string): Promise<boolean>;\n}\n\nexport interface HandlerEnv {\n get(key: string): string | undefined;\n}\n\nexport interface RenderPrimitives {\n logger: LoggerOutput;\n renderTable(options: RenderTableOptions): string;\n getTheme(): ThemePalette;\n note(message: string, title?: string): void;\n}\n\nexport interface CheckResult {\n ok: boolean;\n message?: string;\n}\n\nexport type GroupCheckContext<TServices extends object = EmptyServices> = TServices & {\n params?: unknown;\n secrets?: Record<string, string | undefined>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport type CommandCheckContext<\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TServices extends object = EmptyServices,\n> = TServices & {\n params?: Static<TParamsSchema>;\n secrets?: InferSecrets<TSecrets>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport interface Requires<TContext = unknown> {\n auth?: boolean;\n apiVersion?: string;\n check?: (ctx: TContext) => Promise<CheckResult>;\n}\n\nexport interface Renderers<TResult> {\n rich?: (result: TResult, primitives: RenderPrimitives) => void;\n markdown?: (result: TResult, primitives: RenderPrimitives) => string;\n json?: (result: TResult, primitives: RenderPrimitives) => unknown;\n}\n\nexport type HandlerContext<\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TServices extends object = EmptyServices,\n> = TServices & {\n params: Static<TParamsSchema>;\n secrets: InferSecrets<TSecrets>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport interface CommandConfig<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n> {\n name: string;\n description?: string;\n aliases?: string[];\n positional?: string[];\n params: TParamsSchema;\n secrets?: TSecrets;\n scope?: Scope[];\n confirm?: boolean;\n requires?: Requires<CommandCheckContext<TParamsSchema, TSecrets, TServices>>;\n handler: (ctx: HandlerContext<TParamsSchema, TSecrets, TServices>) => Promise<TResult>;\n render?: Renderers<TResult>;\n}\n\nexport interface Command<\n TServices extends object = EmptyServices,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TResult = unknown,\n> {\n kind: \"command\";\n name: string;\n description?: string;\n aliases: string[];\n positional: string[];\n params: TParamsSchema;\n secrets: SecretDeclarations;\n scope: Scope[];\n confirm: boolean;\n requires?: Requires<any>;\n handler: (ctx: HandlerContext<TParamsSchema, TSecrets, TServices>) => Promise<TResult>;\n render?: Renderers<TResult>;\n}\n\nexport interface GroupConfig<TServices extends object> {\n name: string;\n description?: string;\n aliases?: string[];\n scope?: Scope[];\n secrets?: SecretDeclarations;\n requires?: Requires<GroupCheckContext<TServices>>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\nexport interface Group<TServices extends object = EmptyServices> {\n kind: \"group\";\n name: string;\n description?: string;\n aliases: string[];\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\nexport type CommandNode<TServices extends object = EmptyServices> =\n | Command<TServices, any, any, any>\n | Group<TServices>;\n\nexport interface CommandTypeInfo<\n TName extends string = string,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TResult = unknown,\n TOwnScope extends ScopeInput = ScopeInput,\n> {\n name: TName;\n params: TParamsSchema;\n result: TResult;\n ownScope: TOwnScope;\n}\n\nexport interface GroupTypeInfo<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TChildren extends readonly unknown[] = readonly CommandNode<TServices>[],\n TOwnScope extends ScopeInput = ScopeInput,\n> {\n name: TName;\n children: TChildren;\n ownScope: TOwnScope;\n}\n\ntype TypedCommandMetadata<\n TName extends string,\n TParamsSchema extends ObjectSchema<any>,\n TResult,\n TOwnScope extends ScopeInput,\n> = {\n readonly __cmdkitCommandTypeInfo: CommandTypeInfo<TName, TParamsSchema, TResult, TOwnScope>;\n};\n\ntype TypedGroupMetadata<\n TServices extends object,\n TName extends string,\n TChildren extends readonly unknown[],\n TOwnScope extends ScopeInput,\n> = {\n readonly __cmdkitGroupTypeInfo: GroupTypeInfo<TServices, TName, TChildren, TOwnScope>;\n};\n\ninterface InternalCommandConfig {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n sourcePath?: string;\n}\n\ninterface InternalGroupConfig<TServices extends object> {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\ninterface InheritedMetadata {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n}\n\nexport class UserError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UserError\";\n }\n}\n\nexport interface CommandRequirementOptions {\n apiVersion?: string;\n authEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nfunction cloneScope(scope: Scope[] | undefined): Scope[] | undefined {\n return scope === undefined ? undefined : [...scope];\n}\n\nfunction cloneSecretDefinition(secret: SecretDefinition): SecretDefinition {\n return {\n env: secret.env,\n description: secret.description,\n optional: secret.optional,\n };\n}\n\nfunction cloneSecrets(secrets: SecretDeclarations | undefined): SecretDeclarations {\n if (secrets === undefined) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(secrets).map(([key, secret]) => [key, cloneSecretDefinition(secret)])\n );\n}\n\nfunction cloneRequires<TContext>(requires: Requires<TContext> | undefined): Requires<TContext> | undefined {\n if (requires === undefined) {\n return undefined;\n }\n\n return {\n auth: requires.auth,\n apiVersion: requires.apiVersion,\n check: requires.check,\n };\n}\n\nfunction parseStackPath(candidate: string): string | undefined {\n if (candidate.startsWith(\"file://\")) {\n try {\n return fileURLToPath(candidate);\n } catch {\n return undefined;\n }\n }\n\n if (candidate.startsWith(\"/\")) {\n return candidate;\n }\n\n return undefined;\n}\n\nfunction extractStackPath(line: string): string | undefined {\n const trimmed = line.trim();\n const fileIndex = trimmed.indexOf(\"file://\");\n\n if (fileIndex >= 0) {\n const location = trimmed.slice(fileIndex);\n const separatorIndex = location.lastIndexOf(\":\");\n const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(\":\", separatorIndex - 1) : -1;\n const candidate =\n separatorIndex >= 0 && previousSeparatorIndex >= 0\n ? location.slice(0, previousSeparatorIndex)\n : location;\n\n return parseStackPath(candidate);\n }\n\n const slashIndex = trimmed.indexOf(\"/\");\n if (slashIndex < 0) {\n return undefined;\n }\n\n const location = trimmed.slice(slashIndex);\n const separatorIndex = location.lastIndexOf(\":\");\n const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(\":\", separatorIndex - 1) : -1;\n const candidate =\n separatorIndex >= 0 && previousSeparatorIndex >= 0\n ? location.slice(0, previousSeparatorIndex)\n : location;\n\n return parseStackPath(candidate);\n}\n\nfunction inferCommandSourcePath(): string | undefined {\n const stack = new Error().stack;\n\n if (typeof stack !== \"string\") {\n return undefined;\n }\n\n for (const line of stack.split(\"\\n\").slice(1)) {\n const candidate = extractStackPath(line);\n\n if (candidate === undefined) {\n continue;\n }\n\n if (\n candidate.includes(\"/packages/cmdkit/src/index.ts\") ||\n candidate.includes(\"/packages/cmdkit/dist/index.js\")\n ) {\n continue;\n }\n\n return candidate;\n }\n\n return undefined;\n}\n\nfunction composeChecks(\n parentCheck: Requires<any>[\"check\"] | undefined,\n childCheck: Requires<any>[\"check\"] | undefined\n): Requires<any>[\"check\"] | undefined {\n if (parentCheck === undefined) {\n return childCheck;\n }\n\n if (childCheck === undefined) {\n return parentCheck;\n }\n\n return async (ctx) => {\n const parentResult = await parentCheck(ctx);\n if (!parentResult.ok) {\n return parentResult;\n }\n\n return childCheck(ctx);\n };\n}\n\nfunction mergeRequires(parent: Requires<any> | undefined, child: Requires<any> | undefined): Requires<any> | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n const merged: Requires<any> = {\n auth: child?.auth ?? parent?.auth,\n apiVersion: child?.apiVersion ?? parent?.apiVersion,\n check: composeChecks(parent?.check, child?.check),\n };\n\n if (\n merged.auth === undefined &&\n merged.apiVersion === undefined &&\n merged.check === undefined\n ) {\n return undefined;\n }\n\n return merged;\n}\n\nfunction parseSimpleSemver(value: string): [number, number, number] | undefined {\n const parts = value.split(\".\");\n if (parts.length !== 3) {\n return undefined;\n }\n\n const parsed = parts.map((part) => {\n if (part.length === 0) {\n return Number.NaN;\n }\n\n for (const char of part) {\n if (char < \"0\" || char > \"9\") {\n return Number.NaN;\n }\n }\n\n return Number(part);\n });\n\n if (parsed.some((part) => !Number.isInteger(part) || part < 0)) {\n return undefined;\n }\n\n return parsed as [number, number, number];\n}\n\nfunction parseMinimumApiVersion(requirement: string): [number, number, number] | undefined {\n if (!requirement.startsWith(\">=\")) {\n return undefined;\n }\n\n return parseSimpleSemver(requirement.slice(2).trim());\n}\n\nfunction compareSemver(left: [number, number, number], right: [number, number, number]): number {\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] === right[index]) {\n continue;\n }\n\n return left[index]! > right[index]! ? 1 : -1;\n }\n\n return 0;\n}\n\nexport function resolveCommandSecrets(\n command: Command<any, any, any, any>,\n env: Record<string, string | undefined> = process.env\n): Record<string, string | undefined> {\n const secrets: Record<string, string | undefined> = {};\n\n for (const [name, secret] of Object.entries(command.secrets)) {\n const value = env[secret.env];\n\n if (value === undefined && secret.optional !== true) {\n const details = secret.description ? `\\n ${secret.description}` : \"\";\n throw new UserError(`Error: Missing required secret ${secret.env}${details}`);\n }\n\n secrets[name] = value;\n }\n\n return secrets;\n}\n\nexport async function assertCommandRequirements(\n command: Command<any, any, any, any>,\n context: GroupCheckContext<any>,\n options: CommandRequirementOptions = {}\n): Promise<void> {\n const requires = command.requires;\n if (requires === undefined) {\n return;\n }\n\n const env = options.env ?? process.env;\n const authEnvVar = options.authEnvVar ?? \"POE_API_KEY\";\n\n if (requires.auth === true && env[authEnvVar] === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires authentication.\\n Run 'poe-code login' first.`\n );\n }\n\n if (requires.apiVersion !== undefined) {\n const minimumVersion = parseMinimumApiVersion(requires.apiVersion);\n if (minimumVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" has invalid apiVersion requirement \"${requires.apiVersion}\". Expected format \">=X.Y.Z\".`\n );\n }\n\n if (options.apiVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but no runner API version was provided.`\n );\n }\n\n const runnerVersion = parseSimpleSemver(options.apiVersion);\n if (runnerVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but runner API version \"${options.apiVersion}\" is not valid semver.`\n );\n }\n\n if (compareSemver(runnerVersion, minimumVersion) < 0) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but runner API version is ${options.apiVersion}.`\n );\n }\n }\n\n const checkResult = await requires.check?.(context);\n if (checkResult && !checkResult.ok) {\n throw new UserError(checkResult.message ?? \"Command precondition failed.\");\n }\n}\n\nfunction mergeSecrets(parent: SecretDeclarations, child: SecretDeclarations): SecretDeclarations {\n return cloneSecrets({\n ...parent,\n ...child,\n });\n}\n\nfunction resolveCommandScope(ownScope: Scope[] | undefined, inheritedScope: Scope[] | undefined): Scope[] {\n return cloneScope(ownScope ?? inheritedScope) ?? [\"cli\", \"sdk\"];\n}\n\nfunction resolveGroupScope(ownScope: Scope[] | undefined, inheritedScope: Scope[] | undefined): Scope[] | undefined {\n return cloneScope(ownScope ?? inheritedScope);\n}\n\nfunction createBaseCommand<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n>(\n config: CommandConfig<TServices, TParamsSchema, TSecrets, TResult>\n): Command<TServices, TParamsSchema, TSecrets, TResult> {\n const command: Command<TServices, TParamsSchema, TSecrets, TResult> = {\n kind: \"command\",\n name: config.name,\n description: config.description,\n aliases: [...(config.aliases ?? [])],\n positional: [...(config.positional ?? [])],\n params: config.params,\n secrets: cloneSecrets(config.secrets),\n scope: resolveCommandScope(config.scope, undefined),\n confirm: config.confirm ?? false,\n requires: cloneRequires(config.requires),\n handler: config.handler,\n render: config.render,\n };\n\n Object.defineProperty(command, commandConfigSymbol, {\n value: {\n scope: cloneScope(config.scope),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n sourcePath: inferCommandSourcePath(),\n } satisfies InternalCommandConfig,\n });\n\n return command;\n}\n\nfunction createBaseGroup<TServices extends object>(config: GroupConfig<TServices>): Group<TServices> {\n const group: Group<TServices> = {\n kind: \"group\",\n name: config.name,\n description: config.description,\n aliases: [...(config.aliases ?? [])],\n scope: resolveGroupScope(config.scope, undefined),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n children: [],\n default: undefined,\n };\n\n Object.defineProperty(group, groupConfigSymbol, {\n value: {\n scope: cloneScope(config.scope),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n children: [...config.children],\n default: config.default,\n } satisfies InternalGroupConfig<TServices>,\n });\n\n return group;\n}\n\nfunction getInternalCommandConfig(command: Command<any, any, any, any>): InternalCommandConfig {\n return (command as Command<any, any, any, any> & { [commandConfigSymbol]: InternalCommandConfig })[\n commandConfigSymbol\n ];\n}\n\nfunction getInternalGroupConfig<TServices extends object>(group: Group<TServices>): InternalGroupConfig<TServices> {\n return (group as Group<TServices> & { [groupConfigSymbol]: InternalGroupConfig<TServices> })[\n groupConfigSymbol\n ];\n}\n\nfunction materializeCommand<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n>(\n command: Command<TServices, TParamsSchema, TSecrets, TResult>,\n inherited: InheritedMetadata\n): Command<TServices, TParamsSchema, TSecrets, TResult> {\n const internal = getInternalCommandConfig(command);\n\n const materialized: Command<TServices, TParamsSchema, TSecrets, TResult> = {\n kind: \"command\",\n name: command.name,\n description: command.description,\n aliases: [...command.aliases],\n positional: [...command.positional],\n params: command.params,\n secrets: mergeSecrets(inherited.secrets, internal.secrets),\n scope: resolveCommandScope(internal.scope, inherited.scope),\n confirm: command.confirm,\n requires: mergeRequires(inherited.requires, internal.requires),\n handler: command.handler,\n render: command.render,\n };\n\n Object.defineProperty(materialized, commandConfigSymbol, {\n value: {\n scope: cloneScope(internal.scope),\n secrets: cloneSecrets(internal.secrets),\n requires: cloneRequires(internal.requires),\n sourcePath: internal.sourcePath,\n } satisfies InternalCommandConfig,\n });\n\n Object.defineProperty(materialized, commandSourcePathSymbol, {\n value: internal.sourcePath,\n });\n\n return materialized;\n}\n\nfunction materializeGroup<TServices extends object>(\n group: Group<TServices>,\n inherited: InheritedMetadata\n): Group<TServices> {\n const internal = getInternalGroupConfig(group);\n const scope = resolveGroupScope(internal.scope, inherited.scope);\n const secrets = mergeSecrets(inherited.secrets, internal.secrets);\n const requires = mergeRequires(inherited.requires, internal.requires);\n const materializedChildren = internal.children.map((child) =>\n materializeNode(child, {\n scope,\n secrets,\n requires,\n })\n );\n\n let defaultChild: Command<TServices, any, any, any> | undefined;\n\n if (internal.default !== undefined) {\n const defaultIndex = internal.children.indexOf(internal.default);\n\n if (defaultIndex === -1) {\n throw new UserError(`Default command \"${internal.default.name}\" must be listed in children.`);\n }\n\n const resolvedDefault = materializedChildren[defaultIndex];\n if (resolvedDefault?.kind !== \"command\") {\n throw new UserError(`Default child \"${internal.default.name}\" must be a command.`);\n }\n\n defaultChild = resolvedDefault;\n }\n\n const materialized: Group<TServices> = {\n kind: \"group\",\n name: group.name,\n description: group.description,\n aliases: [...group.aliases],\n scope,\n secrets,\n requires,\n children: materializedChildren,\n default: defaultChild,\n };\n\n Object.defineProperty(materialized, groupConfigSymbol, {\n value: {\n scope: cloneScope(internal.scope),\n secrets: cloneSecrets(internal.secrets),\n requires: cloneRequires(internal.requires),\n children: [...internal.children],\n default: internal.default,\n } satisfies InternalGroupConfig<TServices>,\n });\n\n return materialized;\n}\n\nfunction materializeNode<TServices extends object>(\n node: CommandNode<TServices>,\n inherited: InheritedMetadata\n): CommandNode<TServices> {\n if (node.kind === \"command\") {\n return materializeCommand(node, inherited);\n }\n\n return materializeGroup(node, inherited);\n}\n\nexport function defineCommand<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TResult = unknown,\n TOwnScope extends ScopeInput = undefined,\n>(\n config: Omit<CommandConfig<TServices, TParamsSchema, TSecrets, TResult>, \"name\" | \"scope\"> & {\n name: TName;\n scope?: TOwnScope;\n }\n): Command<TServices, TParamsSchema, TSecrets, TResult> &\n TypedCommandMetadata<TName, TParamsSchema, TResult, TOwnScope> {\n return materializeCommand(createBaseCommand(config as CommandConfig<TServices, TParamsSchema, TSecrets, TResult>), {\n scope: undefined,\n secrets: {},\n requires: undefined,\n }) as Command<TServices, TParamsSchema, TSecrets, TResult> &\n TypedCommandMetadata<TName, TParamsSchema, TResult, TOwnScope>;\n}\n\nexport function defineGroup<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TChildren extends readonly unknown[] = readonly CommandNode<TServices>[],\n TOwnScope extends ScopeInput = undefined,\n>(\n config: Omit<GroupConfig<TServices>, \"name\" | \"children\" | \"scope\"> & {\n name: TName;\n children: TChildren & readonly CommandNode<TServices>[];\n scope?: TOwnScope;\n }\n): Group<TServices> & TypedGroupMetadata<TServices, TName, TChildren, TOwnScope> {\n return materializeGroup(createBaseGroup(config as unknown as GroupConfig<TServices>), {\n scope: undefined,\n secrets: {},\n requires: undefined,\n }) as Group<TServices> & TypedGroupMetadata<TServices, TName, TChildren, TOwnScope>;\n}\n\nexport function getCommandSourcePath(command: Command<any, any, any, any>): string | undefined {\n return (command as Command<any, any, any, any> & { [commandSourcePathSymbol]?: string })[\n commandSourcePathSymbol\n ];\n}\n\nexport { S, toJsonSchema } from \"@poe-code/cmdkit-schema\";\nexport type { AnySchema, ArraySchema, BooleanSchema, EnumSchema, JsonSchema, NumberSchema, ObjectSchema, OptionalSchema, Static, StringSchema } from \"@poe-code/cmdkit-schema\";\n", "type JsonSchemaType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\ntype SchemaKind =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"enum\"\n | \"array\"\n | \"object\"\n | \"optional\";\ntype EnumValue = string | number | boolean;\ntype NonEmptyReadonlyArray<T> = readonly [T, ...T[]];\ntype ObjectShape = Record<string, AnySchema>;\ntype OptionalKeys<TShape extends ObjectShape> = {\n [TKey in keyof TShape]: TShape[TKey] extends OptionalSchema<any> ? TKey : never;\n}[keyof TShape];\ntype RequiredKeys<TShape extends ObjectShape> = Exclude<keyof TShape, OptionalKeys<TShape>>;\n\ntype PropertyStatic<TSchema extends AnySchema> = TSchema extends OptionalSchema<infer TInner>\n ? Static<TInner>\n : Static<TSchema>;\n\ntype InferObject<TShape extends ObjectShape> = {\n [TKey in RequiredKeys<TShape>]: PropertyStatic<TShape[TKey]>;\n} & {\n [TKey in OptionalKeys<TShape>]?: PropertyStatic<TShape[TKey]>;\n};\n\ntype SchemaOptions<TDefault> = {\n description?: string;\n default?: TDefault;\n short?: string;\n};\n\ninterface SchemaBase<TKind extends SchemaKind, TStatic> {\n readonly kind: TKind;\n readonly description?: string;\n readonly default?: TStatic;\n readonly short?: string;\n readonly __static?: TStatic;\n}\n\nexport interface JsonSchema {\n type?: JsonSchemaType;\n description?: string;\n default?: unknown;\n enum?: ReadonlyArray<EnumValue>;\n items?: JsonSchema;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n}\n\nexport type StringSchema = SchemaBase<\"string\", string>;\n\nexport type NumberSchema = SchemaBase<\"number\", number>;\n\nexport type BooleanSchema = SchemaBase<\"boolean\", boolean>;\n\nexport interface EnumSchema<TValues extends NonEmptyReadonlyArray<EnumValue>>\n extends SchemaBase<\"enum\", TValues[number]> {\n readonly values: TValues;\n readonly labels?: Partial<Record<string, string>>;\n readonly loadOptions?: () => Array<{ label: string; value: string }> | Promise<Array<{ label: string; value: string }>>;\n}\n\nexport interface ArraySchema<TItem extends AnySchema>\n extends SchemaBase<\"array\", Array<Static<TItem>>> {\n readonly item: TItem;\n}\n\nexport interface ObjectSchema<TShape extends ObjectShape>\n extends SchemaBase<\"object\", InferObject<TShape>> {\n readonly shape: TShape;\n}\n\nexport interface OptionalSchema<TInner extends AnySchema>\n extends SchemaBase<\"optional\", Static<TInner> | undefined> {\n readonly inner: TInner;\n}\n\nexport type AnySchema =\n | StringSchema\n | NumberSchema\n | BooleanSchema\n | EnumSchema<NonEmptyReadonlyArray<EnumValue>>\n | ArraySchema<AnySchema>\n | ObjectSchema<ObjectShape>\n | OptionalSchema<AnySchema>;\n\nexport type Static<TSchema extends AnySchema> = TSchema extends SchemaBase<any, infer TStatic>\n ? TStatic\n : never;\n\nfunction withMetadata<TSchema extends AnySchema>(\n schema: TSchema,\n jsonSchema: JsonSchema\n): JsonSchema {\n if (schema.description !== undefined) {\n jsonSchema.description = schema.description;\n }\n\n if (schema.default !== undefined) {\n jsonSchema.default = schema.default;\n }\n\n return jsonSchema;\n}\n\nfunction getEnumJsonType(values: ReadonlyArray<EnumValue>): JsonSchemaType | undefined {\n const [firstValue] = values;\n\n if (firstValue === undefined) {\n return undefined;\n }\n\n const firstType = typeof firstValue;\n const isSinglePrimitiveType = values.every((value) => typeof value === firstType);\n\n if (!isSinglePrimitiveType) {\n return undefined;\n }\n\n if (firstType === \"string\" || firstType === \"number\" || firstType === \"boolean\") {\n return firstType;\n }\n\n return undefined;\n}\n\nfunction isOptionalSchema(schema: AnySchema): schema is OptionalSchema<AnySchema> {\n return schema.kind === \"optional\";\n}\n\nfunction assertValidEnumValues(values: ReadonlyArray<EnumValue>): void {\n if (values.length === 0) {\n throw new Error(\"Enum schema requires at least one value\");\n }\n\n const uniqueValues = new Set(values);\n\n if (uniqueValues.size !== values.length) {\n throw new Error(\"Enum schema values must be unique\");\n }\n}\n\nfunction unwrapOptional(schema: AnySchema): Exclude<AnySchema, OptionalSchema<AnySchema>> {\n if (isOptionalSchema(schema)) {\n return unwrapOptional(schema.inner);\n }\n\n return schema;\n}\n\nexport const S = {\n String(options: SchemaOptions<string> = {}): StringSchema {\n return {\n kind: \"string\",\n ...options,\n };\n },\n\n Number(options: SchemaOptions<number> = {}): NumberSchema {\n return {\n kind: \"number\",\n ...options,\n };\n },\n\n Boolean(options: SchemaOptions<boolean> = {}): BooleanSchema {\n return {\n kind: \"boolean\",\n ...options,\n };\n },\n\n Enum<const TValues extends NonEmptyReadonlyArray<EnumValue>>(\n values: TValues,\n options: SchemaOptions<TValues[number]> & {\n labels?: Partial<Record<string, string>>;\n loadOptions?: () => Array<{ label: string; value: string }> | Promise<Array<{ label: string; value: string }>>;\n } = {}\n ): EnumSchema<TValues> {\n assertValidEnumValues(values);\n\n return {\n kind: \"enum\",\n values,\n ...options,\n };\n },\n\n Array<TItem extends AnySchema>(\n item: TItem,\n options: SchemaOptions<Array<Static<TItem>>> = {}\n ): ArraySchema<TItem> {\n return {\n kind: \"array\",\n item,\n ...options,\n };\n },\n\n Object<const TShape extends ObjectShape>(shape: TShape): ObjectSchema<TShape> {\n return {\n kind: \"object\",\n shape,\n };\n },\n\n Optional<TInner extends AnySchema>(inner: TInner): OptionalSchema<TInner> {\n return {\n kind: \"optional\",\n inner,\n };\n },\n} as const;\n\nexport function toJsonSchema(schema: AnySchema): JsonSchema {\n const unwrappedSchema = unwrapOptional(schema);\n\n switch (unwrappedSchema.kind) {\n case \"string\":\n return withMetadata(unwrappedSchema, { type: \"string\" });\n\n case \"number\":\n return withMetadata(unwrappedSchema, { type: \"number\" });\n\n case \"boolean\":\n return withMetadata(unwrappedSchema, { type: \"boolean\" });\n\n case \"enum\": {\n const jsonSchema: JsonSchema = {\n enum: [...unwrappedSchema.values],\n };\n const enumType = getEnumJsonType(unwrappedSchema.values);\n\n if (enumType !== undefined) {\n jsonSchema.type = enumType;\n }\n\n return withMetadata(unwrappedSchema, jsonSchema);\n }\n\n case \"array\":\n return withMetadata(unwrappedSchema, {\n type: \"array\",\n items: toJsonSchema(unwrappedSchema.item),\n });\n\n case \"object\": {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n for (const [key, propertySchema] of Object.entries(unwrappedSchema.shape)) {\n properties[key] = toJsonSchema(propertySchema);\n\n if (!isOptionalSchema(propertySchema)) {\n required.push(key);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n }\n}\n", "import os from \"node:os\";\nimport path from \"node:path\";\nimport * as nodeFs from \"node:fs/promises\";\nimport { readFile } from \"node:fs/promises\";\nimport { UserError } from \"@poe-code/cmdkit\";\nimport {\n getAgentConfig,\n resolveAgentSupport as resolveSkillAgentSupport,\n supportedAgents as skillSupportedAgents\n} from \"@poe-code/agent-skill-config\";\n\nexport type TerminalPilotInstallerFileSystem = {\n readFile(path: string, encoding: \"utf8\"): Promise<string>;\n writeFile(\n path: string,\n content: string,\n options?: { encoding: \"utf8\" }\n ): Promise<void>;\n mkdir(path: string, options?: { recursive: boolean }): Promise<void>;\n unlink(path: string): Promise<void>;\n rm?(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n stat(path: string): Promise<{ mode?: number }>;\n readdir(path: string): Promise<string[]>;\n chmod?(path: string, mode: number): Promise<void>;\n};\n\nexport type TerminalPilotInstallScope = \"global\" | \"local\";\nexport type TerminalPilotInstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport const DEFAULT_INSTALL_AGENT = \"claude-code\";\nexport const DEFAULT_INSTALL_SCOPE: TerminalPilotInstallScope = \"local\";\nexport const TERMINAL_PILOT_SKILL_NAME = \"terminal-pilot\";\nexport const installableAgents = skillSupportedAgents;\n\nexport type TerminalPilotInstallerServices = {\n fs?: TerminalPilotInstallerFileSystem;\n cwd?: string;\n homeDir?: string;\n platform?: TerminalPilotInstallerPlatform;\n};\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n\nexport function resolveInstallerServices(\n installer: TerminalPilotInstallerServices | undefined\n): Required<TerminalPilotInstallerServices> {\n return {\n fs: installer?.fs ?? (nodeFs as TerminalPilotInstallerFileSystem),\n cwd: installer?.cwd ?? process.cwd(),\n homeDir: installer?.homeDir ?? os.homedir(),\n platform: installer?.platform ?? (process.platform as TerminalPilotInstallerPlatform)\n };\n}\n\nfunction throwUnsupportedAgent(agent: string): never {\n throw new UserError(`Unsupported agent: ${agent}`);\n}\n\nexport function resolveInstallableAgent(agent: string): string {\n const skillSupport = resolveSkillAgentSupport(agent);\n\n if (\n skillSupport.status !== \"supported\" ||\n !skillSupport.id\n ) {\n throwUnsupportedAgent(agent);\n }\n\n return skillSupport.id;\n}\n\nexport function resolveInstallScope(input: {\n local?: boolean;\n global?: boolean;\n}): TerminalPilotInstallScope {\n if (input.local && input.global) {\n throw new UserError(\"Use either --local or --global, not both.\");\n }\n\n if (input.local) {\n return \"local\";\n }\n\n if (input.global) {\n return \"global\";\n }\n\n return DEFAULT_INSTALL_SCOPE;\n}\n\nlet terminalPilotTemplateCache: string | undefined;\n\nexport async function loadTerminalPilotTemplate(): Promise<string> {\n if (terminalPilotTemplateCache !== undefined) {\n return terminalPilotTemplateCache;\n }\n\n const candidates = [\n new URL(\"./templates/terminal-pilot.md\", import.meta.url),\n new URL(\"../templates/terminal-pilot.md\", import.meta.url),\n new URL(\"../../../agent-skill-config/src/templates/terminal-pilot.md\", import.meta.url)\n ];\n\n for (const candidate of candidates) {\n try {\n terminalPilotTemplateCache = await readFile(candidate, \"utf8\");\n return terminalPilotTemplateCache;\n } catch (error) {\n if (!isNotFoundError(error)) {\n throw error;\n }\n }\n }\n\n throw new UserError(\"terminal-pilot skill template is missing.\");\n}\n\nfunction resolveHomeRelativePath(targetPath: string, homeDir: string): string {\n if (targetPath === \"~\") {\n return homeDir;\n }\n\n if (targetPath.startsWith(\"~/\")) {\n return path.join(homeDir, targetPath.slice(2));\n }\n\n return targetPath;\n}\n\nexport function getSkillFolderWithHome(\n agent: string,\n scope: TerminalPilotInstallScope,\n cwd: string,\n homeDir: string\n): {\n displayPath: string;\n fullPath: string;\n} {\n const config = getAgentConfig(agent);\n\n if (!config) {\n throwUnsupportedAgent(agent);\n }\n\n return {\n displayPath: path.join(\n scope === \"global\" ? config.globalSkillDir : config.localSkillDir,\n TERMINAL_PILOT_SKILL_NAME\n ),\n fullPath: path.join(\n scope === \"global\"\n ? resolveHomeRelativePath(config.globalSkillDir, homeDir)\n : path.resolve(cwd, config.localSkillDir),\n TERMINAL_PILOT_SKILL_NAME\n )\n };\n}\n\nexport async function removeSkillFolder(\n fs: TerminalPilotInstallerFileSystem,\n folderPath: string\n): Promise<boolean> {\n try {\n await fs.stat(folderPath);\n } catch (error) {\n if (isNotFoundError(error)) {\n return false;\n }\n throw error;\n }\n\n if (typeof fs.rm !== \"function\") {\n throw new UserError(\"The configured filesystem does not support removing directories.\");\n }\n\n await fs.rm(folderPath, { recursive: true, force: true });\n return true;\n}\n", "import { installSkill } from \"@poe-code/agent-skill-config\";\nimport { defineCommand, S } from \"@poe-code/cmdkit\";\nimport type { TerminalPilotCommandServices } from \"./runtime.js\";\nimport {\n DEFAULT_INSTALL_AGENT,\n installableAgents,\n loadTerminalPilotTemplate,\n resolveInstallScope,\n resolveInstallableAgent,\n resolveInstallerServices,\n TERMINAL_PILOT_SKILL_NAME\n} from \"./installer.js\";\n\nconst params = S.Object({\n agent: S.Enum(installableAgents as [string, ...string[]], {\n description: \"Agent to install terminal-pilot for\",\n default: DEFAULT_INSTALL_AGENT\n }),\n local: S.Optional(S.Boolean({ description: \"Install the skill in the current project\" })),\n global: S.Optional(S.Boolean({ description: \"Install the skill in the user home directory\" }))\n});\n\nexport const install = defineCommand<\n TerminalPilotCommandServices,\n \"install\",\n typeof params,\n undefined,\n {\n agent: string;\n scope: \"local\" | \"global\";\n skillPath: string;\n },\n readonly [\"cli\"]\n>({\n name: \"install\",\n description: \"Install the terminal-pilot CLI skill.\",\n scope: [\"cli\"],\n positional: [\"agent\"],\n params,\n handler: async ({ params, terminalPilotInstaller }) => {\n const services = resolveInstallerServices(terminalPilotInstaller);\n const agent = resolveInstallableAgent(params.agent);\n const scope = resolveInstallScope(params);\n const template = await loadTerminalPilotTemplate();\n\n const skillResult = await installSkill(\n agent,\n {\n name: TERMINAL_PILOT_SKILL_NAME,\n content: template\n },\n {\n fs: services.fs,\n cwd: services.cwd,\n homeDir: services.homeDir,\n scope\n }\n );\n\n return {\n agent,\n scope,\n skillPath: skillResult.displayPath\n };\n }\n});\n"],
5
- "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,SAAS,EAAE,QAAQ,EAAE,aAAa,2CAA2C,CAAC,CAAC;AAAA,EACxF,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,+CAA+C,CAAC,CAAC;AAC/F,CAAC;AAEM,IAAM,UAAU,cAWrB;AAAA,EACA,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO,CAAC,KAAK;AAAA,EACb,YAAY,CAAC,OAAO;AAAA,EACpB;AAAA,EACA,SAAS,OAAO,EAAE,QAAAC,SAAQ,uBAAuB,MAAM;AACrD,UAAM,WAAW,yBAAyB,sBAAsB;AAChE,UAAM,QAAQ,wBAAwBA,QAAO,KAAK;AAClD,UAAM,QAAQ,oBAAoBA,OAAM;AACxC,UAAM,WAAW,MAAM,0BAA0B;AAEjD,UAAM,cAAc,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,MACA;AAAA,QACE,IAAI,SAAS;AAAA,QACb,KAAK,SAAS;AAAA,QACd,SAAS,SAAS;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,WAAW,YAAY;AAAA,IACzB;AAAA,EACF;AACF,CAAC;",
6
- "names": ["parse", "parse", "isConfigObject", "parse", "serialize", "merge", "prune", "path", "path", "isConfigObject", "Mustache", "location", "separatorIndex", "previousSeparatorIndex", "candidate", "os", "path", "readFile", "os", "readFile", "params"]
3
+ "sources": ["../../../agent-skill-config/src/configs.ts", "../../../agent-defs/src/agents/claude-code.ts", "../../../agent-defs/src/agents/claude-desktop.ts", "../../../agent-defs/src/agents/codex.ts", "../../../agent-defs/src/agents/opencode.ts", "../../../agent-defs/src/agents/kimi.ts", "../../../agent-defs/src/registry.ts", "../../../config-mutations/src/mutations/file-mutation.ts", "../../../config-mutations/src/mutations/template-mutation.ts", "../../../config-mutations/src/execution/apply-mutation.ts", "../../../config-mutations/src/formats/json.ts", "../../../config-mutations/src/formats/toml.ts", "../../../config-mutations/src/formats/index.ts", "../../../config-mutations/src/execution/path-utils.ts", "../../../config-mutations/src/fs-utils.ts", "../../../config-mutations/src/execution/run-mutations.ts", "../../../config-mutations/src/template/render.ts", "../../../agent-skill-config/src/apply.ts", "../../../cmdkit/src/index.ts", "../../../cmdkit-schema/src/index.ts", "../../src/commands/installer.ts", "../../src/commands/install.ts"],
4
+ "sourcesContent": ["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 opencode: {\n globalSkillDir: \"~/.config/opencode/skills\",\n localSkillDir: \".opencode/skills\"\n }\n};\n\nexport const supportedAgents = 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 };\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): string {\n if (!targetPath?.startsWith(\"~\")) {\n return targetPath;\n }\n\n if (targetPath === \"~\") {\n return os.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 ? os.homedir() : path.join(os.homedir(), remainder);\n}\n\nexport function resolveSkillDir(\n config: AgentSkillConfig,\n scope: SkillScope,\n cwd: string\n): string {\n if (scope === \"global\") {\n return path.resolve(expandHome(config.globalSkillDir));\n }\n\n return path.resolve(cwd, config.localSkillDir);\n}\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 configPath: \"~/.claude/settings.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: \"~/.claude/settings.json\",\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 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 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 configPath: \"~/.config/opencode/config.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 configPath: \"~/.kimi/config.toml\",\n branding: {\n colors: {\n dark: \"#7B68EE\",\n light: \"#6A5ACD\"\n }\n }\n};\n", "import type { AgentDefinition } from \"./types.js\";\nimport {\n claudeCodeAgent,\n claudeDesktopAgent,\n codexAgent,\n openCodeAgent,\n kimiAgent\n} from \"./agents/index.js\";\n\nexport const allAgents: AgentDefinition[] = [\n claudeCodeAgent,\n claudeDesktopAgent,\n codexAgent,\n openCodeAgent,\n kimiAgent\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.toLowerCase());\n}\n", "import type {\n EnsureDirectoryMutation,\n RemoveDirectoryMutation,\n RemoveFileMutation,\n ChmodMutation,\n BackupMutation,\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 /** 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 label: options.label\n };\n}\n\nexport const fileMutation = {\n ensureDirectory,\n remove,\n removeDirectory,\n chmod,\n backup\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 Mustache.render() */\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 Mustache.render() */\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 Mustache.render() */\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 Mustache from \"mustache\";\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 { resolvePath } from \"./path-utils.js\";\nimport {\n isNotFound,\n readFileIfExists,\n pathExists,\n createTimestamp\n} from \"../fs-utils.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 fs: FileSystem,\n targetPath: string,\n content: string\n): Promise<void> {\n const backupPath = createInvalidDocumentBackupPath(targetPath);\n await fs.writeFile(backupPath, content, { encoding: \"utf8\" });\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 \"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 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 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: ConfigObject = { ...base };\n const prefixMap = pruneByPrefix ?? {};\n\n for (const [key, value] of Object.entries(patch)) {\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 result[key] = { ...pruned, ...value };\n } else {\n result[key] = mergeWithPruneByPrefix(\n current,\n value as ConfigObject,\n prefixMap\n );\n }\n continue;\n }\n result[key] = value;\n }\n return result;\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 \"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 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 && !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 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 const content = await readFileIfExists(context.fs, targetPath);\n if (content === null) {\n return {\n outcome: { changed: false, effect: \"none\", detail: \"noop\" },\n details\n };\n }\n\n if (!context.dryRun) {\n const backupPath = `${targetPath}.backup-${createTimestamp()}`;\n await context.fs.writeFile(backupPath, content, { encoding: \"utf8\" });\n }\n\n return {\n outcome: { changed: true, effect: \"copy\", detail: \"backup\" },\n details\n };\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 current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n // Invalid file - backup and start fresh\n if (rawContent !== null) {\n await backupInvalidDocument(context.fs, targetPath, rawContent);\n }\n current = {};\n }\n\n const value = resolveValue(mutation.value, options);\n\n // Use mergeWithPruneByPrefix for TOML files with pruneByPrefix option\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 = format.serialize(merged);\n const changed = serialized !== rawContent;\n\n if (changed && !context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 = format.serialize(result);\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 current: ConfigObject;\n try {\n current = rawContent === null ? {} : format.parse(rawContent);\n } catch {\n if (rawContent !== null) {\n await backupInvalidDocument(context.fs, targetPath, rawContent);\n }\n current = {};\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 = format.serialize(transformed);\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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 = Mustache.render(template, templateContext);\n\n const existed = await pathExists(context.fs, targetPath);\n\n if (!context.dryRun) {\n await context.fs.writeFile(targetPath, rendered, { encoding: \"utf8\" });\n }\n\n return {\n outcome: {\n changed: true,\n effect: \"write\",\n detail: existed ? \"update\" : \"create\"\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 = Mustache.render(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) {\n await backupInvalidDocument(context.fs, 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 context.fs.writeFile(targetPath, serialized, { encoding: \"utf8\" });\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", "import * as jsonc from \"jsonc-parser\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.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 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: ConfigObject = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = result[key];\n if (isConfigObject(existing) && isConfigObject(value)) {\n result[key] = merge(existing, value);\n continue;\n }\n 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: ConfigObject = { ...obj };\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!(key in result)) {\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 result[key] = childResult;\n }\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 let result = content || \"{}\";\n\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n result = modifyAtPath(result, [key], value);\n }\n\n return result;\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\nexport { detectIndent, modifyAtPath, mergePreservingComments, removeAtPath };\n\nexport const jsonFormat: ConfigFormat = {\n parse,\n serialize,\n merge,\n prune\n};\n", "import { parse as parseToml, stringify as stringifyToml } from \"smol-toml\";\nimport type { ConfigFormat, ConfigObject, ConfigValue } from \"../types.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 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: ConfigObject = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const existing = result[key];\n if (isConfigObject(existing) && isConfigObject(value)) {\n result[key] = merge(existing, value);\n continue;\n }\n 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: ConfigObject = { ...obj };\n\n for (const [key, pattern] of Object.entries(shape)) {\n if (!(key in result)) {\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 result[key] = childResult;\n }\n continue;\n }\n\n delete result[key];\n changed = true;\n }\n\n return { changed, result };\n}\n\nexport const tomlFormat: 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\";\n\nexport type FormatName = \"json\" | \"toml\";\n\nconst formatRegistry: Record<FormatName, ConfigFormat> = {\n json: jsonFormat,\n toml: tomlFormat\n};\n\nconst extensionMap: Record<string, FormatName> = {\n \".json\": \"json\",\n \".toml\": \"toml\"\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 (pathOrFormat in formatRegistry) {\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\";\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\n if (!pathMapper) {\n return expanded;\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", "import type { FileSystem } from \"./types.js\";\n\n/**\n * Check if an error is a \"file not found\" (ENOENT) error.\n */\nexport function isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === \"ENOENT\"\n );\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 MutationResult,\n MutationOptions\n} from \"../types.js\";\nimport { applyMutation } 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: { kind: string; label: string; targetPath?: string } }> {\n // Call onStart observer\n context.observers?.onStart?.({\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind,\n targetPath: undefined // Will be resolved during apply\n });\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?.(\n {\n kind: mutation.kind,\n label: mutation.label ?? mutation.kind,\n targetPath: undefined\n },\n error\n );\n\n // Re-throw the error\n throw error;\n }\n}\n", "import Mustache from \"mustache\";\n\nexport type TemplateVariables = Record<string, string | number | boolean | string[]>;\n\n// Disable HTML escaping - we're rendering prompts, not HTML\nconst originalEscape = Mustache.escape;\n\n/**\n * Render a mustache template with the given variables.\n * Arrays are automatically joined with newlines.\n * HTML escaping is disabled.\n */\nexport function renderTemplate(\n template: string,\n variables: TemplateVariables\n): string {\n // Pre-process variables to handle arrays\n const processed: Record<string, string | number | boolean> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (Array.isArray(value)) {\n processed[key] = value.join(\"\\n\");\n } else {\n processed[key] = value;\n }\n }\n\n // Temporarily disable HTML escaping\n Mustache.escape = (text: string) => text;\n try {\n return Mustache.render(template, processed);\n } finally {\n Mustache.escape = originalEscape;\n }\n}\n", "import { fileMutation, runMutations, templateMutation } from \"@poe-code/config-mutations\";\nimport { resolveAgentSupport } from \"./configs.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\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\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: createTemplateLoader()\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\n await runMutations(\n [\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 // 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\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: skillFilePath, displayPath };\n}\n", "import { fileURLToPath } from \"node:url\";\nimport type { ObjectSchema, Static } from \"@poe-code/cmdkit-schema\";\nimport type { LoggerOutput, RenderTableOptions, ThemePalette } from \"@poe-code/design-system\";\n\nconst commandConfigSymbol = Symbol(\"cmdkit.command.config\");\nconst groupConfigSymbol = Symbol(\"cmdkit.group.config\");\nconst commandSourcePathSymbol = Symbol(\"cmdkit.command.sourcePath\");\n\ntype ScopeValue = \"cli\" | \"mcp\" | \"sdk\";\ntype AnyObjectSchema = ObjectSchema<Record<string, never>>;\ntype EmptyServices = Record<string, never>;\ntype ScopeInput = readonly Scope[] | undefined;\n\nexport type Scope = ScopeValue;\n\nexport interface SecretDefinition {\n env: string;\n description?: string;\n optional?: boolean;\n}\n\nexport type SecretDeclarations = Record<string, SecretDefinition>;\n\ntype OptionalSecretKeys<TSecrets extends SecretDeclarations> = {\n [TKey in keyof TSecrets]: TSecrets[TKey] extends { optional: true } ? TKey : never;\n}[keyof TSecrets];\n\ntype RequiredSecretKeys<TSecrets extends SecretDeclarations> = Exclude<\n keyof TSecrets,\n OptionalSecretKeys<TSecrets>\n>;\n\nexport type InferSecrets<TSecrets extends SecretDeclarations | undefined> =\n TSecrets extends SecretDeclarations\n ? { [TKey in RequiredSecretKeys<TSecrets>]: string } & {\n [TKey in OptionalSecretKeys<TSecrets>]?: string;\n }\n : Record<string, never>;\n\nexport interface HandlerFs {\n readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n writeFile(path: string, contents: string): Promise<void>;\n exists(path: string): Promise<boolean>;\n}\n\nexport interface HandlerEnv {\n get(key: string): string | undefined;\n}\n\nexport interface RenderPrimitives {\n logger: LoggerOutput;\n renderTable(options: RenderTableOptions): string;\n getTheme(): ThemePalette;\n note(message: string, title?: string): void;\n}\n\nexport interface CheckResult {\n ok: boolean;\n message?: string;\n}\n\nexport type GroupCheckContext<TServices extends object = EmptyServices> = TServices & {\n params?: unknown;\n secrets?: Record<string, string | undefined>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport type CommandCheckContext<\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TServices extends object = EmptyServices,\n> = TServices & {\n params?: Static<TParamsSchema>;\n secrets?: InferSecrets<TSecrets>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport interface Requires<TContext = unknown> {\n auth?: boolean;\n apiVersion?: string;\n check?: (ctx: TContext) => Promise<CheckResult>;\n}\n\nexport interface Renderers<TResult> {\n rich?: (result: TResult, primitives: RenderPrimitives) => void;\n markdown?: (result: TResult, primitives: RenderPrimitives) => string;\n json?: (result: TResult, primitives: RenderPrimitives) => unknown;\n}\n\nexport type HandlerContext<\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TServices extends object = EmptyServices,\n> = TServices & {\n params: Static<TParamsSchema>;\n secrets: InferSecrets<TSecrets>;\n fetch: typeof globalThis.fetch;\n fs: HandlerFs;\n env: HandlerEnv;\n progress(message: string): void;\n};\n\nexport interface CommandConfig<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n> {\n name: string;\n description?: string;\n aliases?: string[];\n positional?: string[];\n params: TParamsSchema;\n secrets?: TSecrets;\n scope?: Scope[];\n confirm?: boolean;\n requires?: Requires<CommandCheckContext<TParamsSchema, TSecrets, TServices>>;\n handler: (ctx: HandlerContext<TParamsSchema, TSecrets, TServices>) => Promise<TResult>;\n render?: Renderers<TResult>;\n}\n\nexport interface Command<\n TServices extends object = EmptyServices,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TResult = unknown,\n> {\n kind: \"command\";\n name: string;\n description?: string;\n aliases: string[];\n positional: string[];\n params: TParamsSchema;\n secrets: SecretDeclarations;\n scope: Scope[];\n confirm: boolean;\n requires?: Requires<any>;\n handler: (ctx: HandlerContext<TParamsSchema, TSecrets, TServices>) => Promise<TResult>;\n render?: Renderers<TResult>;\n}\n\nexport interface GroupConfig<TServices extends object> {\n name: string;\n description?: string;\n aliases?: string[];\n scope?: Scope[];\n secrets?: SecretDeclarations;\n requires?: Requires<GroupCheckContext<TServices>>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\nexport interface Group<TServices extends object = EmptyServices> {\n kind: \"group\";\n name: string;\n description?: string;\n aliases: string[];\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\nexport type CommandNode<TServices extends object = EmptyServices> =\n | Command<TServices, any, any, any>\n | Group<TServices>;\n\nexport interface CommandTypeInfo<\n TName extends string = string,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TResult = unknown,\n TOwnScope extends ScopeInput = ScopeInput,\n> {\n name: TName;\n params: TParamsSchema;\n result: TResult;\n ownScope: TOwnScope;\n}\n\nexport interface GroupTypeInfo<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TChildren extends readonly unknown[] = readonly CommandNode<TServices>[],\n TOwnScope extends ScopeInput = ScopeInput,\n> {\n name: TName;\n children: TChildren;\n ownScope: TOwnScope;\n}\n\ntype TypedCommandMetadata<\n TName extends string,\n TParamsSchema extends ObjectSchema<any>,\n TResult,\n TOwnScope extends ScopeInput,\n> = {\n readonly __cmdkitCommandTypeInfo: CommandTypeInfo<TName, TParamsSchema, TResult, TOwnScope>;\n};\n\ntype TypedGroupMetadata<\n TServices extends object,\n TName extends string,\n TChildren extends readonly unknown[],\n TOwnScope extends ScopeInput,\n> = {\n readonly __cmdkitGroupTypeInfo: GroupTypeInfo<TServices, TName, TChildren, TOwnScope>;\n};\n\ninterface InternalCommandConfig {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n sourcePath?: string;\n}\n\ninterface InternalGroupConfig<TServices extends object> {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n children: Array<CommandNode<TServices>>;\n default?: Command<TServices, any, any, any>;\n}\n\ninterface InheritedMetadata {\n scope?: Scope[];\n secrets: SecretDeclarations;\n requires?: Requires<any>;\n}\n\nexport class UserError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UserError\";\n }\n}\n\nexport interface CommandRequirementOptions {\n apiVersion?: string;\n authEnvVar?: string;\n env?: Record<string, string | undefined>;\n}\n\nfunction cloneScope(scope: Scope[] | undefined): Scope[] | undefined {\n return scope === undefined ? undefined : [...scope];\n}\n\nfunction cloneSecretDefinition(secret: SecretDefinition): SecretDefinition {\n return {\n env: secret.env,\n description: secret.description,\n optional: secret.optional,\n };\n}\n\nfunction cloneSecrets(secrets: SecretDeclarations | undefined): SecretDeclarations {\n if (secrets === undefined) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(secrets).map(([key, secret]) => [key, cloneSecretDefinition(secret)])\n );\n}\n\nfunction cloneRequires<TContext>(requires: Requires<TContext> | undefined): Requires<TContext> | undefined {\n if (requires === undefined) {\n return undefined;\n }\n\n return {\n auth: requires.auth,\n apiVersion: requires.apiVersion,\n check: requires.check,\n };\n}\n\nfunction parseStackPath(candidate: string): string | undefined {\n if (candidate.startsWith(\"file://\")) {\n try {\n return fileURLToPath(candidate);\n } catch {\n return undefined;\n }\n }\n\n if (candidate.startsWith(\"/\")) {\n return candidate;\n }\n\n return undefined;\n}\n\nfunction extractStackPath(line: string): string | undefined {\n const trimmed = line.trim();\n const fileIndex = trimmed.indexOf(\"file://\");\n\n if (fileIndex >= 0) {\n const location = trimmed.slice(fileIndex);\n const separatorIndex = location.lastIndexOf(\":\");\n const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(\":\", separatorIndex - 1) : -1;\n const candidate =\n separatorIndex >= 0 && previousSeparatorIndex >= 0\n ? location.slice(0, previousSeparatorIndex)\n : location;\n\n return parseStackPath(candidate);\n }\n\n const slashIndex = trimmed.indexOf(\"/\");\n if (slashIndex < 0) {\n return undefined;\n }\n\n const location = trimmed.slice(slashIndex);\n const separatorIndex = location.lastIndexOf(\":\");\n const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(\":\", separatorIndex - 1) : -1;\n const candidate =\n separatorIndex >= 0 && previousSeparatorIndex >= 0\n ? location.slice(0, previousSeparatorIndex)\n : location;\n\n return parseStackPath(candidate);\n}\n\nfunction inferCommandSourcePath(): string | undefined {\n const stack = new Error().stack;\n\n if (typeof stack !== \"string\") {\n return undefined;\n }\n\n for (const line of stack.split(\"\\n\").slice(1)) {\n const candidate = extractStackPath(line);\n\n if (candidate === undefined) {\n continue;\n }\n\n if (\n candidate.includes(\"/packages/cmdkit/src/index.ts\") ||\n candidate.includes(\"/packages/cmdkit/dist/index.js\")\n ) {\n continue;\n }\n\n return candidate;\n }\n\n return undefined;\n}\n\nfunction composeChecks(\n parentCheck: Requires<any>[\"check\"] | undefined,\n childCheck: Requires<any>[\"check\"] | undefined\n): Requires<any>[\"check\"] | undefined {\n if (parentCheck === undefined) {\n return childCheck;\n }\n\n if (childCheck === undefined) {\n return parentCheck;\n }\n\n return async (ctx) => {\n const parentResult = await parentCheck(ctx);\n if (!parentResult.ok) {\n return parentResult;\n }\n\n return childCheck(ctx);\n };\n}\n\nfunction mergeRequires(parent: Requires<any> | undefined, child: Requires<any> | undefined): Requires<any> | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n const merged: Requires<any> = {\n auth: child?.auth ?? parent?.auth,\n apiVersion: child?.apiVersion ?? parent?.apiVersion,\n check: composeChecks(parent?.check, child?.check),\n };\n\n if (\n merged.auth === undefined &&\n merged.apiVersion === undefined &&\n merged.check === undefined\n ) {\n return undefined;\n }\n\n return merged;\n}\n\nfunction parseSimpleSemver(value: string): [number, number, number] | undefined {\n const parts = value.split(\".\");\n if (parts.length !== 3) {\n return undefined;\n }\n\n const parsed = parts.map((part) => {\n if (part.length === 0) {\n return Number.NaN;\n }\n\n for (const char of part) {\n if (char < \"0\" || char > \"9\") {\n return Number.NaN;\n }\n }\n\n return Number(part);\n });\n\n if (parsed.some((part) => !Number.isInteger(part) || part < 0)) {\n return undefined;\n }\n\n return parsed as [number, number, number];\n}\n\nfunction parseMinimumApiVersion(requirement: string): [number, number, number] | undefined {\n if (!requirement.startsWith(\">=\")) {\n return undefined;\n }\n\n return parseSimpleSemver(requirement.slice(2).trim());\n}\n\nfunction compareSemver(left: [number, number, number], right: [number, number, number]): number {\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] === right[index]) {\n continue;\n }\n\n return left[index]! > right[index]! ? 1 : -1;\n }\n\n return 0;\n}\n\nexport function resolveCommandSecrets(\n command: Command<any, any, any, any>,\n env: Record<string, string | undefined> = process.env\n): Record<string, string | undefined> {\n const secrets: Record<string, string | undefined> = {};\n\n for (const [name, secret] of Object.entries(command.secrets)) {\n const value = env[secret.env];\n\n if (value === undefined && secret.optional !== true) {\n const details = secret.description ? `\\n ${secret.description}` : \"\";\n throw new UserError(`Error: Missing required secret ${secret.env}${details}`);\n }\n\n secrets[name] = value;\n }\n\n return secrets;\n}\n\nexport async function assertCommandRequirements(\n command: Command<any, any, any, any>,\n context: GroupCheckContext<any>,\n options: CommandRequirementOptions = {}\n): Promise<void> {\n const requires = command.requires;\n if (requires === undefined) {\n return;\n }\n\n const env = options.env ?? process.env;\n const authEnvVar = options.authEnvVar ?? \"POE_API_KEY\";\n\n if (requires.auth === true && env[authEnvVar] === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires authentication.\\n Run 'poe-code login' first.`\n );\n }\n\n if (requires.apiVersion !== undefined) {\n const minimumVersion = parseMinimumApiVersion(requires.apiVersion);\n if (minimumVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" has invalid apiVersion requirement \"${requires.apiVersion}\". Expected format \">=X.Y.Z\".`\n );\n }\n\n if (options.apiVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but no runner API version was provided.`\n );\n }\n\n const runnerVersion = parseSimpleSemver(options.apiVersion);\n if (runnerVersion === undefined) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but runner API version \"${options.apiVersion}\" is not valid semver.`\n );\n }\n\n if (compareSemver(runnerVersion, minimumVersion) < 0) {\n throw new UserError(\n `Error: Command \"${command.name}\" requires API version ${requires.apiVersion}, but runner API version is ${options.apiVersion}.`\n );\n }\n }\n\n const checkResult = await requires.check?.(context);\n if (checkResult && !checkResult.ok) {\n throw new UserError(checkResult.message ?? \"Command precondition failed.\");\n }\n}\n\nfunction mergeSecrets(parent: SecretDeclarations, child: SecretDeclarations): SecretDeclarations {\n return cloneSecrets({\n ...parent,\n ...child,\n });\n}\n\nfunction resolveCommandScope(ownScope: Scope[] | undefined, inheritedScope: Scope[] | undefined): Scope[] {\n return cloneScope(ownScope ?? inheritedScope) ?? [\"cli\", \"sdk\"];\n}\n\nfunction resolveGroupScope(ownScope: Scope[] | undefined, inheritedScope: Scope[] | undefined): Scope[] | undefined {\n return cloneScope(ownScope ?? inheritedScope);\n}\n\nfunction createBaseCommand<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n>(\n config: CommandConfig<TServices, TParamsSchema, TSecrets, TResult>\n): Command<TServices, TParamsSchema, TSecrets, TResult> {\n const command: Command<TServices, TParamsSchema, TSecrets, TResult> = {\n kind: \"command\",\n name: config.name,\n description: config.description,\n aliases: [...(config.aliases ?? [])],\n positional: [...(config.positional ?? [])],\n params: config.params,\n secrets: cloneSecrets(config.secrets),\n scope: resolveCommandScope(config.scope, undefined),\n confirm: config.confirm ?? false,\n requires: cloneRequires(config.requires),\n handler: config.handler,\n render: config.render,\n };\n\n Object.defineProperty(command, commandConfigSymbol, {\n value: {\n scope: cloneScope(config.scope),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n sourcePath: inferCommandSourcePath(),\n } satisfies InternalCommandConfig,\n });\n\n return command;\n}\n\nfunction createBaseGroup<TServices extends object>(config: GroupConfig<TServices>): Group<TServices> {\n const group: Group<TServices> = {\n kind: \"group\",\n name: config.name,\n description: config.description,\n aliases: [...(config.aliases ?? [])],\n scope: resolveGroupScope(config.scope, undefined),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n children: [],\n default: undefined,\n };\n\n Object.defineProperty(group, groupConfigSymbol, {\n value: {\n scope: cloneScope(config.scope),\n secrets: cloneSecrets(config.secrets),\n requires: cloneRequires(config.requires),\n children: [...config.children],\n default: config.default,\n } satisfies InternalGroupConfig<TServices>,\n });\n\n return group;\n}\n\nfunction getInternalCommandConfig(command: Command<any, any, any, any>): InternalCommandConfig {\n return (command as Command<any, any, any, any> & { [commandConfigSymbol]: InternalCommandConfig })[\n commandConfigSymbol\n ];\n}\n\nfunction getInternalGroupConfig<TServices extends object>(group: Group<TServices>): InternalGroupConfig<TServices> {\n return (group as Group<TServices> & { [groupConfigSymbol]: InternalGroupConfig<TServices> })[\n groupConfigSymbol\n ];\n}\n\nfunction materializeCommand<\n TServices extends object,\n TParamsSchema extends ObjectSchema<any>,\n TSecrets extends SecretDeclarations | undefined,\n TResult,\n>(\n command: Command<TServices, TParamsSchema, TSecrets, TResult>,\n inherited: InheritedMetadata\n): Command<TServices, TParamsSchema, TSecrets, TResult> {\n const internal = getInternalCommandConfig(command);\n\n const materialized: Command<TServices, TParamsSchema, TSecrets, TResult> = {\n kind: \"command\",\n name: command.name,\n description: command.description,\n aliases: [...command.aliases],\n positional: [...command.positional],\n params: command.params,\n secrets: mergeSecrets(inherited.secrets, internal.secrets),\n scope: resolveCommandScope(internal.scope, inherited.scope),\n confirm: command.confirm,\n requires: mergeRequires(inherited.requires, internal.requires),\n handler: command.handler,\n render: command.render,\n };\n\n Object.defineProperty(materialized, commandConfigSymbol, {\n value: {\n scope: cloneScope(internal.scope),\n secrets: cloneSecrets(internal.secrets),\n requires: cloneRequires(internal.requires),\n sourcePath: internal.sourcePath,\n } satisfies InternalCommandConfig,\n });\n\n Object.defineProperty(materialized, commandSourcePathSymbol, {\n value: internal.sourcePath,\n });\n\n return materialized;\n}\n\nfunction materializeGroup<TServices extends object>(\n group: Group<TServices>,\n inherited: InheritedMetadata\n): Group<TServices> {\n const internal = getInternalGroupConfig(group);\n const scope = resolveGroupScope(internal.scope, inherited.scope);\n const secrets = mergeSecrets(inherited.secrets, internal.secrets);\n const requires = mergeRequires(inherited.requires, internal.requires);\n const materializedChildren = internal.children.map((child) =>\n materializeNode(child, {\n scope,\n secrets,\n requires,\n })\n );\n\n let defaultChild: Command<TServices, any, any, any> | undefined;\n\n if (internal.default !== undefined) {\n const defaultIndex = internal.children.indexOf(internal.default);\n\n if (defaultIndex === -1) {\n throw new UserError(`Default command \"${internal.default.name}\" must be listed in children.`);\n }\n\n const resolvedDefault = materializedChildren[defaultIndex];\n if (resolvedDefault?.kind !== \"command\") {\n throw new UserError(`Default child \"${internal.default.name}\" must be a command.`);\n }\n\n defaultChild = resolvedDefault;\n }\n\n const materialized: Group<TServices> = {\n kind: \"group\",\n name: group.name,\n description: group.description,\n aliases: [...group.aliases],\n scope,\n secrets,\n requires,\n children: materializedChildren,\n default: defaultChild,\n };\n\n Object.defineProperty(materialized, groupConfigSymbol, {\n value: {\n scope: cloneScope(internal.scope),\n secrets: cloneSecrets(internal.secrets),\n requires: cloneRequires(internal.requires),\n children: [...internal.children],\n default: internal.default,\n } satisfies InternalGroupConfig<TServices>,\n });\n\n return materialized;\n}\n\nfunction materializeNode<TServices extends object>(\n node: CommandNode<TServices>,\n inherited: InheritedMetadata\n): CommandNode<TServices> {\n if (node.kind === \"command\") {\n return materializeCommand(node, inherited);\n }\n\n return materializeGroup(node, inherited);\n}\n\nexport function defineCommand<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TParamsSchema extends ObjectSchema<any> = AnyObjectSchema,\n TSecrets extends SecretDeclarations | undefined = undefined,\n TResult = unknown,\n TOwnScope extends ScopeInput = undefined,\n>(\n config: Omit<CommandConfig<TServices, TParamsSchema, TSecrets, TResult>, \"name\" | \"scope\"> & {\n name: TName;\n scope?: TOwnScope;\n }\n): Command<TServices, TParamsSchema, TSecrets, TResult> &\n TypedCommandMetadata<TName, TParamsSchema, TResult, TOwnScope> {\n return materializeCommand(createBaseCommand(config as CommandConfig<TServices, TParamsSchema, TSecrets, TResult>), {\n scope: undefined,\n secrets: {},\n requires: undefined,\n }) as Command<TServices, TParamsSchema, TSecrets, TResult> &\n TypedCommandMetadata<TName, TParamsSchema, TResult, TOwnScope>;\n}\n\nexport function defineGroup<\n TServices extends object = EmptyServices,\n TName extends string = string,\n TChildren extends readonly unknown[] = readonly CommandNode<TServices>[],\n TOwnScope extends ScopeInput = undefined,\n>(\n config: Omit<GroupConfig<TServices>, \"name\" | \"children\" | \"scope\"> & {\n name: TName;\n children: TChildren & readonly CommandNode<TServices>[];\n scope?: TOwnScope;\n }\n): Group<TServices> & TypedGroupMetadata<TServices, TName, TChildren, TOwnScope> {\n return materializeGroup(createBaseGroup(config as unknown as GroupConfig<TServices>), {\n scope: undefined,\n secrets: {},\n requires: undefined,\n }) as Group<TServices> & TypedGroupMetadata<TServices, TName, TChildren, TOwnScope>;\n}\n\nexport function getCommandSourcePath(command: Command<any, any, any, any>): string | undefined {\n return (command as Command<any, any, any, any> & { [commandSourcePathSymbol]?: string })[\n commandSourcePathSymbol\n ];\n}\n\nexport { S, toJsonSchema } from \"@poe-code/cmdkit-schema\";\nexport type { AnySchema, ArraySchema, BooleanSchema, EnumSchema, JsonSchema, NumberSchema, ObjectSchema, OptionalSchema, Static, StringSchema } from \"@poe-code/cmdkit-schema\";\n", "type JsonSchemaType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\ntype SchemaKind =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"enum\"\n | \"array\"\n | \"object\"\n | \"optional\";\ntype EnumValue = string | number | boolean;\ntype NonEmptyReadonlyArray<T> = readonly [T, ...T[]];\ntype ObjectShape = Record<string, AnySchema>;\ntype OptionalKeys<TShape extends ObjectShape> = {\n [TKey in keyof TShape]: TShape[TKey] extends OptionalSchema<any> ? TKey : never;\n}[keyof TShape];\ntype RequiredKeys<TShape extends ObjectShape> = Exclude<keyof TShape, OptionalKeys<TShape>>;\n\ntype PropertyStatic<TSchema extends AnySchema> = TSchema extends OptionalSchema<infer TInner>\n ? Static<TInner>\n : Static<TSchema>;\n\ntype InferObject<TShape extends ObjectShape> = {\n [TKey in RequiredKeys<TShape>]: PropertyStatic<TShape[TKey]>;\n} & {\n [TKey in OptionalKeys<TShape>]?: PropertyStatic<TShape[TKey]>;\n};\n\ntype SchemaOptions<TDefault> = {\n description?: string;\n default?: TDefault;\n short?: string;\n};\n\ninterface SchemaBase<TKind extends SchemaKind, TStatic> {\n readonly kind: TKind;\n readonly description?: string;\n readonly default?: TStatic;\n readonly short?: string;\n readonly __static?: TStatic;\n}\n\nexport interface JsonSchema {\n type?: JsonSchemaType;\n description?: string;\n default?: unknown;\n enum?: ReadonlyArray<EnumValue>;\n items?: JsonSchema;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n}\n\nexport type StringSchema = SchemaBase<\"string\", string>;\n\nexport type NumberSchema = SchemaBase<\"number\", number>;\n\nexport type BooleanSchema = SchemaBase<\"boolean\", boolean>;\n\nexport interface EnumSchema<TValues extends NonEmptyReadonlyArray<EnumValue>>\n extends SchemaBase<\"enum\", TValues[number]> {\n readonly values: TValues;\n readonly labels?: Partial<Record<string, string>>;\n readonly loadOptions?: () => Array<{ label: string; value: string }> | Promise<Array<{ label: string; value: string }>>;\n}\n\nexport interface ArraySchema<TItem extends AnySchema>\n extends SchemaBase<\"array\", Array<Static<TItem>>> {\n readonly item: TItem;\n}\n\nexport interface ObjectSchema<TShape extends ObjectShape>\n extends SchemaBase<\"object\", InferObject<TShape>> {\n readonly shape: TShape;\n}\n\nexport interface OptionalSchema<TInner extends AnySchema>\n extends SchemaBase<\"optional\", Static<TInner> | undefined> {\n readonly inner: TInner;\n}\n\nexport type AnySchema =\n | StringSchema\n | NumberSchema\n | BooleanSchema\n | EnumSchema<NonEmptyReadonlyArray<EnumValue>>\n | ArraySchema<AnySchema>\n | ObjectSchema<ObjectShape>\n | OptionalSchema<AnySchema>;\n\nexport type Static<TSchema extends AnySchema> = TSchema extends SchemaBase<any, infer TStatic>\n ? TStatic\n : never;\n\nfunction withMetadata<TSchema extends AnySchema>(\n schema: TSchema,\n jsonSchema: JsonSchema\n): JsonSchema {\n if (schema.description !== undefined) {\n jsonSchema.description = schema.description;\n }\n\n if (schema.default !== undefined) {\n jsonSchema.default = schema.default;\n }\n\n return jsonSchema;\n}\n\nfunction getEnumJsonType(values: ReadonlyArray<EnumValue>): JsonSchemaType | undefined {\n const [firstValue] = values;\n\n if (firstValue === undefined) {\n return undefined;\n }\n\n const firstType = typeof firstValue;\n const isSinglePrimitiveType = values.every((value) => typeof value === firstType);\n\n if (!isSinglePrimitiveType) {\n return undefined;\n }\n\n if (firstType === \"string\" || firstType === \"number\" || firstType === \"boolean\") {\n return firstType;\n }\n\n return undefined;\n}\n\nfunction isOptionalSchema(schema: AnySchema): schema is OptionalSchema<AnySchema> {\n return schema.kind === \"optional\";\n}\n\nfunction assertValidEnumValues(values: ReadonlyArray<EnumValue>): void {\n if (values.length === 0) {\n throw new Error(\"Enum schema requires at least one value\");\n }\n\n const uniqueValues = new Set(values);\n\n if (uniqueValues.size !== values.length) {\n throw new Error(\"Enum schema values must be unique\");\n }\n}\n\nfunction unwrapOptional(schema: AnySchema): Exclude<AnySchema, OptionalSchema<AnySchema>> {\n if (isOptionalSchema(schema)) {\n return unwrapOptional(schema.inner);\n }\n\n return schema;\n}\n\nexport const S = {\n String(options: SchemaOptions<string> = {}): StringSchema {\n return {\n kind: \"string\",\n ...options,\n };\n },\n\n Number(options: SchemaOptions<number> = {}): NumberSchema {\n return {\n kind: \"number\",\n ...options,\n };\n },\n\n Boolean(options: SchemaOptions<boolean> = {}): BooleanSchema {\n return {\n kind: \"boolean\",\n ...options,\n };\n },\n\n Enum<const TValues extends NonEmptyReadonlyArray<EnumValue>>(\n values: TValues,\n options: SchemaOptions<TValues[number]> & {\n labels?: Partial<Record<string, string>>;\n loadOptions?: () => Array<{ label: string; value: string }> | Promise<Array<{ label: string; value: string }>>;\n } = {}\n ): EnumSchema<TValues> {\n assertValidEnumValues(values);\n\n return {\n kind: \"enum\",\n values,\n ...options,\n };\n },\n\n Array<TItem extends AnySchema>(\n item: TItem,\n options: SchemaOptions<Array<Static<TItem>>> = {}\n ): ArraySchema<TItem> {\n return {\n kind: \"array\",\n item,\n ...options,\n };\n },\n\n Object<const TShape extends ObjectShape>(shape: TShape): ObjectSchema<TShape> {\n return {\n kind: \"object\",\n shape,\n };\n },\n\n Optional<TInner extends AnySchema>(inner: TInner): OptionalSchema<TInner> {\n return {\n kind: \"optional\",\n inner,\n };\n },\n} as const;\n\nexport function toJsonSchema(schema: AnySchema): JsonSchema {\n const unwrappedSchema = unwrapOptional(schema);\n\n switch (unwrappedSchema.kind) {\n case \"string\":\n return withMetadata(unwrappedSchema, { type: \"string\" });\n\n case \"number\":\n return withMetadata(unwrappedSchema, { type: \"number\" });\n\n case \"boolean\":\n return withMetadata(unwrappedSchema, { type: \"boolean\" });\n\n case \"enum\": {\n const jsonSchema: JsonSchema = {\n enum: [...unwrappedSchema.values],\n };\n const enumType = getEnumJsonType(unwrappedSchema.values);\n\n if (enumType !== undefined) {\n jsonSchema.type = enumType;\n }\n\n return withMetadata(unwrappedSchema, jsonSchema);\n }\n\n case \"array\":\n return withMetadata(unwrappedSchema, {\n type: \"array\",\n items: toJsonSchema(unwrappedSchema.item),\n });\n\n case \"object\": {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n for (const [key, propertySchema] of Object.entries(unwrappedSchema.shape)) {\n properties[key] = toJsonSchema(propertySchema);\n\n if (!isOptionalSchema(propertySchema)) {\n required.push(key);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n }\n}\n", "import os from \"node:os\";\nimport path from \"node:path\";\nimport * as nodeFs from \"node:fs/promises\";\nimport { readFile } from \"node:fs/promises\";\nimport { UserError } from \"@poe-code/cmdkit\";\nimport {\n getAgentConfig,\n resolveAgentSupport as resolveSkillAgentSupport,\n supportedAgents as skillSupportedAgents\n} from \"@poe-code/agent-skill-config\";\n\nexport type TerminalPilotInstallerFileSystem = {\n readFile(path: string, encoding: \"utf8\"): Promise<string>;\n writeFile(\n path: string,\n content: string,\n options?: { encoding: \"utf8\" }\n ): Promise<void>;\n mkdir(path: string, options?: { recursive: boolean }): Promise<void>;\n unlink(path: string): Promise<void>;\n rm?(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n stat(path: string): Promise<{ mode?: number }>;\n readdir(path: string): Promise<string[]>;\n chmod?(path: string, mode: number): Promise<void>;\n};\n\nexport type TerminalPilotInstallScope = \"global\" | \"local\";\nexport type TerminalPilotInstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport const DEFAULT_INSTALL_AGENT = \"claude-code\";\nexport const DEFAULT_INSTALL_SCOPE: TerminalPilotInstallScope = \"local\";\nexport const TERMINAL_PILOT_SKILL_NAME = \"terminal-pilot\";\nexport const installableAgents = skillSupportedAgents;\n\nexport type TerminalPilotInstallerServices = {\n fs?: TerminalPilotInstallerFileSystem;\n cwd?: string;\n homeDir?: string;\n platform?: TerminalPilotInstallerPlatform;\n};\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n\nexport function resolveInstallerServices(\n installer: TerminalPilotInstallerServices | undefined\n): Required<TerminalPilotInstallerServices> {\n return {\n fs: installer?.fs ?? (nodeFs as TerminalPilotInstallerFileSystem),\n cwd: installer?.cwd ?? process.cwd(),\n homeDir: installer?.homeDir ?? os.homedir(),\n platform: installer?.platform ?? (process.platform as TerminalPilotInstallerPlatform)\n };\n}\n\nfunction throwUnsupportedAgent(agent: string): never {\n throw new UserError(`Unsupported agent: ${agent}`);\n}\n\nexport function resolveInstallableAgent(agent: string): string {\n const skillSupport = resolveSkillAgentSupport(agent);\n\n if (\n skillSupport.status !== \"supported\" ||\n !skillSupport.id\n ) {\n throwUnsupportedAgent(agent);\n }\n\n return skillSupport.id;\n}\n\nexport function resolveInstallScope(input: {\n local?: boolean;\n global?: boolean;\n}): TerminalPilotInstallScope {\n if (input.local && input.global) {\n throw new UserError(\"Use either --local or --global, not both.\");\n }\n\n if (input.local) {\n return \"local\";\n }\n\n if (input.global) {\n return \"global\";\n }\n\n return DEFAULT_INSTALL_SCOPE;\n}\n\nlet terminalPilotTemplateCache: string | undefined;\n\nexport async function loadTerminalPilotTemplate(): Promise<string> {\n if (terminalPilotTemplateCache !== undefined) {\n return terminalPilotTemplateCache;\n }\n\n const candidates = [\n new URL(\"./templates/terminal-pilot.md\", import.meta.url),\n new URL(\"../templates/terminal-pilot.md\", import.meta.url),\n new URL(\"../../../agent-skill-config/src/templates/terminal-pilot.md\", import.meta.url)\n ];\n\n for (const candidate of candidates) {\n try {\n terminalPilotTemplateCache = await readFile(candidate, \"utf8\");\n return terminalPilotTemplateCache;\n } catch (error) {\n if (!isNotFoundError(error)) {\n throw error;\n }\n }\n }\n\n throw new UserError(\"terminal-pilot skill template is missing.\");\n}\n\nfunction resolveHomeRelativePath(targetPath: string, homeDir: string): string {\n if (targetPath === \"~\") {\n return homeDir;\n }\n\n if (targetPath.startsWith(\"~/\")) {\n return path.join(homeDir, targetPath.slice(2));\n }\n\n return targetPath;\n}\n\nexport function getSkillFolderWithHome(\n agent: string,\n scope: TerminalPilotInstallScope,\n cwd: string,\n homeDir: string\n): {\n displayPath: string;\n fullPath: string;\n} {\n const config = getAgentConfig(agent);\n\n if (!config) {\n throwUnsupportedAgent(agent);\n }\n\n return {\n displayPath: path.join(\n scope === \"global\" ? config.globalSkillDir : config.localSkillDir,\n TERMINAL_PILOT_SKILL_NAME\n ),\n fullPath: path.join(\n scope === \"global\"\n ? resolveHomeRelativePath(config.globalSkillDir, homeDir)\n : path.resolve(cwd, config.localSkillDir),\n TERMINAL_PILOT_SKILL_NAME\n )\n };\n}\n\nexport async function removeSkillFolder(\n fs: TerminalPilotInstallerFileSystem,\n folderPath: string\n): Promise<boolean> {\n try {\n await fs.stat(folderPath);\n } catch (error) {\n if (isNotFoundError(error)) {\n return false;\n }\n throw error;\n }\n\n if (typeof fs.rm !== \"function\") {\n throw new UserError(\"The configured filesystem does not support removing directories.\");\n }\n\n await fs.rm(folderPath, { recursive: true, force: true });\n return true;\n}\n", "import { installSkill } from \"@poe-code/agent-skill-config\";\nimport { defineCommand, S } from \"@poe-code/cmdkit\";\nimport type { TerminalPilotCommandServices } from \"./runtime.js\";\nimport {\n DEFAULT_INSTALL_AGENT,\n installableAgents,\n loadTerminalPilotTemplate,\n resolveInstallScope,\n resolveInstallableAgent,\n resolveInstallerServices,\n TERMINAL_PILOT_SKILL_NAME\n} from \"./installer.js\";\n\nconst params = S.Object({\n agent: S.Enum(installableAgents as [string, ...string[]], {\n description: \"Agent to install terminal-pilot for\",\n default: DEFAULT_INSTALL_AGENT\n }),\n local: S.Optional(S.Boolean({ description: \"Install the skill in the current project\" })),\n global: S.Optional(S.Boolean({ description: \"Install the skill in the user home directory\" }))\n});\n\nexport const install = defineCommand<\n TerminalPilotCommandServices,\n \"install\",\n typeof params,\n undefined,\n {\n agent: string;\n scope: \"local\" | \"global\";\n skillPath: string;\n },\n readonly [\"cli\"]\n>({\n name: \"install\",\n description: \"Install the terminal-pilot CLI skill.\",\n scope: [\"cli\"],\n positional: [\"agent\"],\n params,\n handler: async ({ params, terminalPilotInstaller }) => {\n const services = resolveInstallerServices(terminalPilotInstaller);\n const agent = resolveInstallableAgent(params.agent);\n const scope = resolveInstallScope(params);\n const template = await loadTerminalPilotTemplate();\n\n const skillResult = await installSkill(\n agent,\n {\n name: TERMINAL_PILOT_SKILL_NAME,\n content: template\n },\n {\n fs: services.fs,\n cwd: services.cwd,\n homeDir: services.homeDir,\n scope\n }\n );\n\n return {\n agent,\n scope,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AAO,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,2CAA2C,CAAC,CAAC;AAAA,EACxF,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,+CAA+C,CAAC,CAAC;AAC/F,CAAC;AAEM,IAAM,UAAU,cAWrB;AAAA,EACA,MAAM;AAAA,EACN,aAAa;AAAA,EACb,OAAO,CAAC,KAAK;AAAA,EACb,YAAY,CAAC,OAAO;AAAA,EACpB;AAAA,EACA,SAAS,OAAO,EAAE,QAAAC,SAAQ,uBAAuB,MAAM;AACrD,UAAM,WAAW,yBAAyB,sBAAsB;AAChE,UAAM,QAAQ,wBAAwBA,QAAO,KAAK;AAClD,UAAM,QAAQ,oBAAoBA,OAAM;AACxC,UAAM,WAAW,MAAM,0BAA0B;AAEjD,UAAM,cAAc,MAAM;AAAA,MACxB;AAAA,MACA;AAAA,QACE,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,MACA;AAAA,QACE,IAAI,SAAS;AAAA,QACb,KAAK,SAAS;AAAA,QACd,SAAS,SAAS;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,WAAW,YAAY;AAAA,IACzB;AAAA,EACF;AACF,CAAC;",
6
+ "names": ["parse", "parse", "isConfigObject", "parse", "serialize", "merge", "prune", "path", "path", "isConfigObject", "Mustache", "location", "separatorIndex", "previousSeparatorIndex", "candidate", "os", "path", "os", "params"]
7
7
  }