@mariozechner/pi-coding-agent 0.54.2 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,EAAc,KAAK,EAAE,MAAM,wCAAwC,CAAC;AA4C3E,mEAAmE;AACnE,MAAM,wCAAwC,GAA6B;IAC1E,WAAW;IACX,OAAO;IACP,MAAM;IACN,SAAS;IACT,oBAAoB;IACpB,mBAAmB;IACnB,oBAAoB;IACpB,aAAa;IACb,aAAa;IACb,gBAAgB;IAChB,gBAAgB;IAChB,UAAU;IACV,QAAQ;IACR,eAAe;IACf,cAAc;IACd,MAAM;IACN,iBAAiB;CACjB,CAAC;AAIF,MAAM,uBAAuB,GAAG,CAAC,oBAAiD,EAAsB,EAAE,CAAC;IAC1G,MAAM,kBAAkB,GAAG,EAAwB,CAAC;IACpD,KAAK,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,oBAAoB,CAAC,EAAE,CAAC;QACnE,MAAM,SAAS,GAAG,MAAmB,CAAC;QACtC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACpD,MAAM,gBAAgB,GAAG,wCAAwC,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QACtF,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;YAC3B,MAAM,aAAa,GAAG,GAAG,CAAC,WAAW,EAAW,CAAC;YACjD,kBAAkB,CAAC,aAAa,CAAC,GAAG;gBACnC,MAAM,EAAE,SAAS;gBACjB,gBAAgB,EAAE,gBAAgB;aAClC,CAAC;QACH,CAAC;IACF,CAAC;IACD,OAAO,kBAAkB,CAAC;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AE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;oBAC9F,MAAM,MAAM,GAAG,CAAC,MAAM,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAiC,CAAC;oBAC3E,IAAI,MAAM,EAAE,MAAM,KAAK,SAAS;wBAAE,OAAO,MAAM,CAAC;oBAChD,IAAI,MAAM,EAAE,MAAM,KAAK,WAAW,EAAE,CAAC;wBACpC,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC;wBAC1B,aAAa,GAAG,MAAM,CAAC,MAAM,IAAI,aAAa,CAAC;oBAChD,CAAC;gBACF,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACd,IAAI,CAAC,SAAS,CAAC;wBACd,aAAa,EAAE,GAAG,CAAC,IAAI;wBACvB,KAAK,EAAE,OAAO;wBACd,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;wBACvD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;qBACnD,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,WAAW,KAAK,IAAI,IAAI,aAAa,KAAK,MAAM;YACtD,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE;YACnE,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Model } from \"@mariozechner/pi-ai\";\nimport type { KeyId } from \"@mariozechner/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { ResourceDiagnostic } from \"../diagnostics.js\";\nimport type { KeyAction, KeybindingsConfig } from \"../keybindings.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageRenderer,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.js\";\n\n// Keybindings for these actions cannot be overridden by extensions\nconst RESERVED_ACTIONS_FOR_EXTENSION_CONFLICTS: ReadonlyArray<KeyAction> = [\n\t\"interrupt\",\n\t\"clear\",\n\t\"exit\",\n\t\"suspend\",\n\t\"cycleThinkingLevel\",\n\t\"cycleModelForward\",\n\t\"cycleModelBackward\",\n\t\"selectModel\",\n\t\"expandTools\",\n\t\"toggleThinking\",\n\t\"externalEditor\",\n\t\"followUp\",\n\t\"submit\",\n\t\"selectConfirm\",\n\t\"selectCancel\",\n\t\"copy\",\n\t\"deleteToLineEnd\",\n];\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { action: KeyAction; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (effectiveKeybindings: Required<KeybindingsConfig>): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [action, keys] of Object.entries(effectiveKeybindings)) {\n\t\tconst keyAction = action as KeyAction;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = RESERVED_ACTIONS_FOR_EXTENSION_CONFLICTS.includes(keyAction);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\taction: keyAction,\n\t\t\t\trestrictOverride: restrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (entryId: string) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (sessionPath: string) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(extensionRunner: ExtensionRunner | undefined): Promise<boolean> {\n\tif (extensionRunner?.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit({\n\t\t\ttype: \"session_shutdown\",\n\t\t});\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\tsetEditorComponent: () => {},\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(actions: ExtensionActions, contextActions: ExtensionContextActions): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\n\t\t// Process provider registrations queued during extension loading\n\t\tfor (const { name, config } of this.runtime.pendingProviderRegistrations) {\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions. */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst tools: RegisteredTool[] = [];\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\ttools.push(tool);\n\t\t\t}\n\t\t}\n\t\treturn tools;\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tallFlags.set(name, flag);\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(effectiveKeybindings: Required<KeybindingsConfig>): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(effectiveKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.action} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetRegisteredCommands(reserved?: Set<string>): RegisteredCommand[] {\n\t\tthis.commandDiagnostics = [];\n\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tif (reserved?.has(command.name)) {\n\t\t\t\t\tconst message = `Extension command '${command.name}' from ${ext.path} conflicts with built-in commands. Skipping.`;\n\t\t\t\t\tthis.commandDiagnostics.push({ type: \"warning\", message, path: ext.path });\n\t\t\t\t\tif (!this.hasUI()) {\n\t\t\t\t\t\tconsole.warn(message);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tcommands.push(command);\n\t\t\t}\n\t\t}\n\t\treturn commands;\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetRegisteredCommandsWithPaths(): Array<{ command: RegisteredCommand; extensionPath: string }> {\n\t\tconst result: Array<{ command: RegisteredCommand; extensionPath: string }> = [];\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tresult.push({ command, extensionPath: ext.path });\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetCommand(name: string): RegisteredCommand | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst command = ext.commands.get(name);\n\t\t\tif (command) {\n\t\t\t\treturn command;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tui: this.uiContext,\n\t\t\thasUI: this.hasUI(),\n\t\t\tcwd: this.cwd,\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this.modelRegistry,\n\t\t\tget model() {\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tisIdle: () => this.isIdleFn(),\n\t\t\tabort: () => this.abortFn(),\n\t\t\thasPendingMessages: () => this.hasPendingMessagesFn(),\n\t\t\tshutdown: () => this.shutdownHandler(),\n\t\t\tgetContextUsage: () => this.getContextUsageFn(),\n\t\t\tcompact: (options) => this.compactFn(options),\n\t\t\tgetSystemPrompt: () => this.getSystemPromptFn(),\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\treturn {\n\t\t\t...this.createContext(),\n\t\t\twaitForIdle: () => this.waitForIdleFn(),\n\t\t\tnewSession: (options) => this.newSessionHandler(options),\n\t\t\tfork: (entryId) => this.forkHandler(entryId),\n\t\t\tnavigateTree: (targetId, options) => this.navigateTreeHandler(targetId, options),\n\t\t\tswitchSession: (sessionPath) => this.switchSessionHandler(sessionPath),\n\t\t\treload: () => this.reloadHandler(),\n\t\t};\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(text: string, images: ImageContent[] | undefined, source: InputSource): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = { type: \"input\", text: currentText, images: currentImages, source };\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,EAAc,KAAK,EAAE,MAAM,wCAAwC,CAAC;AA4C3E,mEAAmE;AACnE,MAAM,wCAAwC,GAA6B;IAC1E,WAAW;IACX,OAAO;IACP,MAAM;IACN,SAAS;IACT,oBAAoB;IACpB,mB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AC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;qBACnD,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,WAAW,KAAK,IAAI,IAAI,aAAa,KAAK,MAAM;YACtD,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE;YACnE,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@mariozechner/pi-agent-core\";\nimport type { ImageContent, Model } from \"@mariozechner/pi-ai\";\nimport type { KeyId } from \"@mariozechner/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.js\";\nimport type { ResourceDiagnostic } from \"../diagnostics.js\";\nimport type { KeyAction, KeybindingsConfig } from \"../keybindings.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport type { SessionManager } from \"../session-manager.js\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageRenderer,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.js\";\n\n// Keybindings for these actions cannot be overridden by extensions\nconst RESERVED_ACTIONS_FOR_EXTENSION_CONFLICTS: ReadonlyArray<KeyAction> = [\n\t\"interrupt\",\n\t\"clear\",\n\t\"exit\",\n\t\"suspend\",\n\t\"cycleThinkingLevel\",\n\t\"cycleModelForward\",\n\t\"cycleModelBackward\",\n\t\"selectModel\",\n\t\"expandTools\",\n\t\"toggleThinking\",\n\t\"externalEditor\",\n\t\"followUp\",\n\t\"submit\",\n\t\"selectConfirm\",\n\t\"selectCancel\",\n\t\"copy\",\n\t\"deleteToLineEnd\",\n];\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { action: KeyAction; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (effectiveKeybindings: Required<KeybindingsConfig>): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [action, keys] of Object.entries(effectiveKeybindings)) {\n\t\tconst keyAction = action as KeyAction;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = RESERVED_ACTIONS_FOR_EXTENSION_CONFLICTS.includes(keyAction);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\taction: keyAction,\n\t\t\t\trestrictOverride: restrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeAgentStartEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (entryId: string) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (sessionPath: string) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(extensionRunner: ExtensionRunner | undefined): Promise<boolean> {\n\tif (extensionRunner?.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit({\n\t\t\ttype: \"session_shutdown\",\n\t\t});\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\tsetEditorComponent: () => {},\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(actions: ExtensionActions, contextActions: ExtensionContextActions): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\n\t\t// Process provider registrations queued during extension loading\n\t\tfor (const { name, config } of this.runtime.pendingProviderRegistrations) {\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map<string, RegisteredTool>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(effectiveKeybindings: Required<KeybindingsConfig>): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(effectiveKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.action} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetRegisteredCommands(reserved?: Set<string>): RegisteredCommand[] {\n\t\tthis.commandDiagnostics = [];\n\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst commandOwners = new Map<string, string>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tif (reserved?.has(command.name)) {\n\t\t\t\t\tconst message = `Extension command '${command.name}' from ${ext.path} conflicts with built-in commands. Skipping.`;\n\t\t\t\t\tthis.commandDiagnostics.push({ type: \"warning\", message, path: ext.path });\n\t\t\t\t\tif (!this.hasUI()) {\n\t\t\t\t\t\tconsole.warn(message);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst existingOwner = commandOwners.get(command.name);\n\t\t\t\tif (existingOwner) {\n\t\t\t\t\tconst message = `Extension command '${command.name}' from ${ext.path} conflicts with ${existingOwner}. Skipping.`;\n\t\t\t\t\tthis.commandDiagnostics.push({ type: \"warning\", message, path: ext.path });\n\t\t\t\t\tif (!this.hasUI()) {\n\t\t\t\t\t\tconsole.warn(message);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tcommandOwners.set(command.name, ext.path);\n\t\t\t\tcommands.push(command);\n\t\t\t}\n\t\t}\n\t\treturn commands;\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetRegisteredCommandsWithPaths(): Array<{ command: RegisteredCommand; extensionPath: string }> {\n\t\tconst result: Array<{ command: RegisteredCommand; extensionPath: string }> = [];\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tresult.push({ command, extensionPath: ext.path });\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tgetCommand(name: string): RegisteredCommand | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst command = ext.commands.get(name);\n\t\t\tif (command) {\n\t\t\t\treturn command;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tui: this.uiContext,\n\t\t\thasUI: this.hasUI(),\n\t\t\tcwd: this.cwd,\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: this.modelRegistry,\n\t\t\tget model() {\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tisIdle: () => this.isIdleFn(),\n\t\t\tabort: () => this.abortFn(),\n\t\t\thasPendingMessages: () => this.hasPendingMessagesFn(),\n\t\t\tshutdown: () => this.shutdownHandler(),\n\t\t\tgetContextUsage: () => this.getContextUsageFn(),\n\t\t\tcompact: (options) => this.compactFn(options),\n\t\t\tgetSystemPrompt: () => this.getSystemPromptFn(),\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\treturn {\n\t\t\t...this.createContext(),\n\t\t\twaitForIdle: () => this.waitForIdleFn(),\n\t\t\tnewSession: (options) => this.newSessionHandler(options),\n\t\t\tfork: (entryId) => this.forkHandler(entryId),\n\t\t\tnavigateTree: (targetId, options) => this.navigateTreeHandler(targetId, options),\n\t\t\tswitchSession: (sessionPath) => this.switchSessionHandler(sessionPath),\n\t\t\treload: () => this.reloadHandler(),\n\t\t};\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(text: string, images: ImageContent[] | undefined, source: InputSource): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = { type: \"input\", text: currentText, images: currentImages, source };\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"package-manager.d.ts","sourceRoot":"","sources":["../../src/core/package-manager.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE5E,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,WAAW,CAAC;IACnB,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,YAAY,CAAC;CACvB;AAED,MAAM,WAAW,aAAa;I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,yBAAyB;YAUzB,SAAS;IAOvB,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,uBAAuB;IAiD/B,OAAO,CAAC,uBAAuB;IAsB/B,OAAO,CAAC,kBAAkB;IA0B1B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,kBAAkB;IAoB1B,OAAO,CAAC,+BAA+B;IAMvC,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,0BAA0B;IA4HlC,OAAO,CAAC,qBAAqB;IAmB7B,OAAO,CAAC,YAAY;IAkBpB,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,UAAU;IAkBlB,OAAO,CAAC,cAAc;CAWtB","sourcesContent":["import { spawn, spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport ignore from \"ignore\";\nimport { minimatch } from \"minimatch\";\nimport { CONFIG_DIR_NAME } from \"../config.js\";\nimport { type GitSource, parseGitUrl } from \"../utils/git.js\";\nimport type { PackageSource, SettingsManager } from \"./settings-manager.js\";\n\nexport interface PathMetadata {\n\tsource: string;\n\tscope: SourceScope;\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\nexport interface ResolvedResource {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n}\n\nexport interface ResolvedPaths {\n\textensions: ResolvedResource[];\n\tskills: ResolvedResource[];\n\tprompts: ResolvedResource[];\n\tthemes: ResolvedResource[];\n}\n\nexport type MissingSourceAction = \"install\" | \"skip\" | \"error\";\n\nexport interface ProgressEvent {\n\ttype: \"start\" | \"progress\" | \"complete\" | \"error\";\n\taction: \"install\" | \"remove\" | \"update\" | \"clone\" | \"pull\";\n\tsource: string;\n\tmessage?: string;\n}\n\nexport type ProgressCallback = (event: ProgressEvent) => void;\n\nexport interface PackageManager {\n\tresolve(onMissing?: (source: string) => Promise<MissingSourceAction>): Promise<ResolvedPaths>;\n\tinstall(source: string, options?: { local?: boolean }): Promise<void>;\n\tremove(source: string, options?: { local?: boolean }): Promise<void>;\n\tupdate(source?: string): Promise<void>;\n\tresolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise<ResolvedPaths>;\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean;\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean;\n\tsetProgressCallback(callback: ProgressCallback | undefined): void;\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined;\n}\n\ninterface PackageManagerOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n}\n\ntype SourceScope = \"user\" | \"project\" | \"temporary\";\n\ntype NpmSource = {\n\ttype: \"npm\";\n\tspec: string;\n\tname: string;\n\tpinned: boolean;\n};\n\ntype LocalSource = {\n\ttype: \"local\";\n\tpath: string;\n};\n\ntype ParsedSource = NpmSource | GitSource | LocalSource;\n\ninterface PiManifest {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ninterface ResourceAccumulator {\n\textensions: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tskills: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tprompts: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tthemes: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n}\n\ninterface PackageFilter {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\nconst RESOURCE_TYPES: ResourceType[] = [\"extensions\", \"skills\", \"prompts\", \"themes\"];\n\nconst FILE_PATTERNS: Record<ResourceType, RegExp> = {\n\textensions: /\\.(ts|js)$/,\n\tskills: /\\.md$/,\n\tprompts: /\\.md$/,\n\tthemes: /\\.json$/,\n};\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nfunction isPattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\") || s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction splitPatterns(entries: string[]): { plain: string[]; patterns: string[] } {\n\tconst plain: string[] = [];\n\tconst patterns: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (isPattern(entry)) {\n\t\t\tpatterns.push(entry);\n\t\t} else {\n\t\t\tplain.push(entry);\n\t\t}\n\t}\n\treturn { plain, patterns };\n}\n\nfunction collectFiles(\n\tdir: string,\n\tfilePattern: RegExp,\n\tskipNodeModules = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst files: string[] = [];\n\tif (!existsSync(dir)) return files;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (skipNodeModules && entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tfiles.push(...collectFiles(fullPath, filePattern, skipNodeModules, ig, root));\n\t\t\t} else if (isFile && filePattern.test(entry.name)) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn files;\n}\n\nfunction collectSkillEntries(\n\tdir: string,\n\tincludeRootFiles = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tentries.push(...collectSkillEntries(fullPath, false, ig, root));\n\t\t\t} else if (isFile) {\n\t\t\t\tconst isRootMd = includeRootFiles && entry.name.endsWith(\".md\");\n\t\t\t\tconst isSkillMd = !includeRootFiles && entry.name === \"SKILL.md\";\n\t\t\t\tif (isRootMd || isSkillMd) {\n\t\t\t\t\tentries.push(fullPath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoSkillEntries(dir: string, includeRootFiles = true): string[] {\n\treturn collectSkillEntries(dir, includeRootFiles);\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\nfunction collectAncestorAgentsSkillDirs(startDir: string): string[] {\n\tconst skillDirs: string[] = [];\n\tconst resolvedStartDir = resolve(startDir);\n\tconst gitRepoRoot = findGitRepoRoot(resolvedStartDir);\n\n\tlet dir = resolvedStartDir;\n\twhile (true) {\n\t\tskillDirs.push(join(dir, \".agents\", \"skills\"));\n\t\tif (gitRepoRoot && dir === gitRepoRoot) {\n\t\t\tbreak;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\tbreak;\n\t\t}\n\t\tdir = parent;\n\t}\n\n\treturn skillDirs;\n}\n\nfunction collectAutoPromptEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoThemeEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".json\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction readPiManifestFile(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\treturn pkg.pi ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = join(dir, \"package.json\");\n\tif (existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifestFile(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = resolve(dir, extPath);\n\t\t\t\tif (existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst indexTs = join(dir, \"index.ts\");\n\tconst indexJs = join(dir, \"index.js\");\n\tif (existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\nfunction collectAutoExtensionEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\t// First check if this directory itself has explicit extension entries (package.json or index)\n\tconst rootEntries = resolveExtensionEntries(dir);\n\tif (rootEntries) {\n\t\treturn rootEntries;\n\t}\n\n\t// Otherwise, discover extensions from directory contents\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isFile && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".js\"))) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t} else if (isDir) {\n\t\t\t\tconst resolvedEntries = resolveExtensionEntries(fullPath);\n\t\t\t\tif (resolvedEntries) {\n\t\t\t\t\tentries.push(...resolvedEntries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\n/**\n * Collect resource files from a directory based on resource type.\n * Extensions use smart discovery (index.ts in subdirs), others use recursive collection.\n */\nfunction collectResourceFiles(dir: string, resourceType: ResourceType): string[] {\n\tif (resourceType === \"skills\") {\n\t\treturn collectSkillEntries(dir);\n\t}\n\tif (resourceType === \"extensions\") {\n\t\treturn collectAutoExtensionEntries(dir);\n\t}\n\treturn collectFiles(dir, FILE_PATTERNS[resourceType]);\n}\n\nfunction matchesAnyPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst rel = relative(baseDir, filePath);\n\tconst name = basename(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? relative(baseDir, parentDir!) : undefined;\n\tconst parentName = isSkillFile ? basename(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tif (minimatch(rel, pattern) || minimatch(name, pattern) || minimatch(filePath, pattern)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn minimatch(parentRel!, pattern) || minimatch(parentName!, pattern) || minimatch(parentDir!, pattern);\n\t});\n}\n\nfunction normalizeExactPattern(pattern: string): string {\n\tif (pattern.startsWith(\"./\") || pattern.startsWith(\".\\\\\")) {\n\t\treturn pattern.slice(2);\n\t}\n\treturn pattern;\n}\n\nfunction matchesAnyExactPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tif (patterns.length === 0) return false;\n\tconst rel = relative(baseDir, filePath);\n\tconst name = basename(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? relative(baseDir, parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalized = normalizeExactPattern(pattern);\n\t\tif (normalized === rel || normalized === filePath) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn normalized === parentRel || normalized === parentDir;\n\t});\n}\n\nfunction getOverridePatterns(entries: string[]): string[] {\n\treturn entries.filter((pattern) => pattern.startsWith(\"!\") || pattern.startsWith(\"+\") || pattern.startsWith(\"-\"));\n}\n\nfunction isEnabledByOverrides(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst overrides = getOverridePatterns(patterns);\n\tconst excludes = overrides.filter((pattern) => pattern.startsWith(\"!\")).map((pattern) => pattern.slice(1));\n\tconst forceIncludes = overrides.filter((pattern) => pattern.startsWith(\"+\")).map((pattern) => pattern.slice(1));\n\tconst forceExcludes = overrides.filter((pattern) => pattern.startsWith(\"-\")).map((pattern) => pattern.slice(1));\n\n\tlet enabled = true;\n\tif (excludes.length > 0 && matchesAnyPattern(filePath, excludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\tif (forceIncludes.length > 0 && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\tenabled = true;\n\t}\n\tif (forceExcludes.length > 0 && matchesAnyExactPattern(filePath, forceExcludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\treturn enabled;\n}\n\n/**\n * Apply patterns to paths and return a Set of enabled paths.\n * Pattern types:\n * - Plain patterns: include matching paths\n * - `!pattern`: exclude matching paths\n * - `+path`: force-include exact path (overrides exclusions)\n * - `-path`: force-exclude exact path (overrides force-includes)\n */\nfunction applyPatterns(allPaths: string[], patterns: string[], baseDir: string): Set<string> {\n\tconst includes: string[] = [];\n\tconst excludes: string[] = [];\n\tconst forceIncludes: string[] = [];\n\tconst forceExcludes: string[] = [];\n\n\tfor (const p of patterns) {\n\t\tif (p.startsWith(\"+\")) {\n\t\t\tforceIncludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"-\")) {\n\t\t\tforceExcludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"!\")) {\n\t\t\texcludes.push(p.slice(1));\n\t\t} else {\n\t\t\tincludes.push(p);\n\t\t}\n\t}\n\n\t// Step 1: Apply includes (or all if no includes)\n\tlet result: string[];\n\tif (includes.length === 0) {\n\t\tresult = [...allPaths];\n\t} else {\n\t\tresult = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir));\n\t}\n\n\t// Step 2: Apply excludes\n\tif (excludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir));\n\t}\n\n\t// Step 3: Force-include (add back from allPaths, overriding exclusions)\n\tif (forceIncludes.length > 0) {\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\t\t\tresult.push(filePath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Step 4: Force-exclude (remove even if included or force-included)\n\tif (forceExcludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir));\n\t}\n\n\treturn new Set(result);\n}\n\nexport class DefaultPackageManager implements PackageManager {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate globalNpmRoot: string | undefined;\n\tprivate progressCallback: ProgressCallback | undefined;\n\n\tconstructor(options: PackageManagerOptions) {\n\t\tthis.cwd = options.cwd;\n\t\tthis.agentDir = options.agentDir;\n\t\tthis.settingsManager = options.settingsManager;\n\t}\n\n\tsetProgressCallback(callback: ProgressCallback | undefined): void {\n\t\tthis.progressCallback = callback;\n\t}\n\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst normalizedSource = this.normalizePackageSourceForSettings(source, scope);\n\t\tconst exists = currentPackages.some((existing) => this.packageSourcesMatch(existing, source, scope));\n\t\tif (exists) {\n\t\t\treturn false;\n\t\t}\n\t\tconst nextPackages = [...currentPackages, normalizedSource];\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst nextPackages = currentPackages.filter((existing) => !this.packageSourcesMatch(existing, source, scope));\n\t\tconst changed = nextPackages.length !== currentPackages.length;\n\t\tif (!changed) {\n\t\t\treturn false;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tconst path = this.getNpmInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tconst path = this.getGitInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"local\") {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\tconst path = this.resolvePathFromBase(parsed.path, baseDir);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate emitProgress(event: ProgressEvent): void {\n\t\tthis.progressCallback?.(event);\n\t}\n\n\tprivate async withProgress(\n\t\taction: ProgressEvent[\"action\"],\n\t\tsource: string,\n\t\tmessage: string,\n\t\toperation: () => Promise<void>,\n\t): Promise<void> {\n\t\tthis.emitProgress({ type: \"start\", action, source, message });\n\t\ttry {\n\t\t\tawait operation();\n\t\t\tthis.emitProgress({ type: \"complete\", action, source });\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tthis.emitProgress({ type: \"error\", action, source, message: errorMessage });\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync resolve(onMissing?: (source: string) => Promise<MissingSourceAction>): Promise<ResolvedPaths> {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\n\t\t// Collect all packages with scope\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\n\t\t// Dedupe: project scope wins over global for same package identity\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tawait this.resolvePackageSources(packageSources, accumulator, onMissing);\n\n\t\tconst globalBaseDir = this.agentDir;\n\t\tconst projectBaseDir = join(this.cwd, CONFIG_DIR_NAME);\n\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tconst globalEntries = (globalSettings[resourceType] ?? []) as string[];\n\t\t\tconst projectEntries = (projectSettings[resourceType] ?? []) as string[];\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tglobalEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"user\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tglobalBaseDir,\n\t\t\t);\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tprojectEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"project\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tthis.addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir);\n\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync resolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise<ResolvedPaths> {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst scope: SourceScope = options?.temporary ? \"temporary\" : options?.local ? \"project\" : \"user\";\n\t\tconst packageSources = sources.map((source) => ({ pkg: source as PackageSource, scope }));\n\t\tawait this.resolvePackageSources(packageSources, accumulator);\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync install(source: string, options?: { local?: boolean }): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tawait this.withProgress(\"install\", source, `Installing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.installGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst resolved = this.resolvePath(parsed.path);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\tthrow new Error(`Path does not exist: ${resolved}`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported install source: ${source}`);\n\t\t});\n\t}\n\n\tasync remove(source: string, options?: { local?: boolean }): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tawait this.withProgress(\"remove\", source, `Removing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.uninstallNpm(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.removeGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported remove source: ${source}`);\n\t\t});\n\t}\n\n\tasync update(source?: string): Promise<void> {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst identity = source ? this.getPackageIdentity(source) : undefined;\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"user\") !== identity) continue;\n\t\t\tawait this.updateSourceForScope(sourceStr, \"user\");\n\t\t}\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"project\") !== identity) continue;\n\t\t\tawait this.updateSourceForScope(sourceStr, \"project\");\n\t\t}\n\t}\n\n\tprivate async updateSourceForScope(source: string, scope: SourceScope): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tif (parsed.pinned) return;\n\t\t\tawait this.withProgress(\"update\", source, `Updating ${source}...`, async () => {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tif (parsed.pinned) return;\n\t\t\tawait this.withProgress(\"update\", source, `Updating ${source}...`, async () => {\n\t\t\t\tawait this.updateGit(parsed, scope);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async resolvePackageSources(\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t\taccumulator: ResourceAccumulator,\n\t\tonMissing?: (source: string) => Promise<MissingSourceAction>,\n\t): Promise<void> {\n\t\tfor (const { pkg, scope } of sources) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconst filter = typeof pkg === \"object\" ? pkg : undefined;\n\t\t\tconst parsed = this.parseSource(sourceStr);\n\t\t\tconst metadata: PathMetadata = { source: sourceStr, scope, origin: \"package\" };\n\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\t\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata, baseDir);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst installMissing = async (): Promise<boolean> => {\n\t\t\t\tif (!onMissing) {\n\t\t\t\t\tawait this.installParsedSource(parsed, scope);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconst action = await onMissing(sourceStr);\n\t\t\t\tif (action === \"skip\") return false;\n\t\t\t\tif (action === \"error\") throw new Error(`Missing source: ${sourceStr}`);\n\t\t\t\tawait this.installParsedSource(parsed, scope);\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tconst installedPath = this.getNpmInstallPath(parsed, scope);\n\t\t\t\tconst needsInstall = !existsSync(installedPath) || (await this.npmNeedsUpdate(parsed, installedPath));\n\t\t\t\tif (needsInstall) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, scope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t} else if (scope === \"temporary\" && !parsed.pinned) {\n\t\t\t\t\tawait this.refreshTemporaryGitSource(parsed, sourceStr);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveLocalExtensionSource(\n\t\tsource: LocalSource,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tconst resolved = this.resolvePathFromBase(source.path, baseDir);\n\t\tif (!existsSync(resolved)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolved);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tmetadata.baseDir = dirname(resolved);\n\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tmetadata.baseDir = resolved;\n\t\t\t\tconst resources = this.collectPackageResources(resolved, accumulator, filter, metadata);\n\t\t\t\tif (!resources) {\n\t\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async installParsedSource(parsed: ParsedSource, scope: SourceScope): Promise<void> {\n\t\tif (parsed.type === \"npm\") {\n\t\t\tawait this.installNpm(parsed, scope, scope === \"temporary\");\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tawait this.installGit(parsed, scope);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate getPackageSourceString(pkg: PackageSource): string {\n\t\treturn typeof pkg === \"string\" ? pkg : pkg.source;\n\t}\n\n\tprivate getSourceMatchKeyForInput(source: string): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\tprivate getSourceMatchKeyForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t}\n\n\tprivate packageSourcesMatch(existing: PackageSource, inputSource: string, scope: SourceScope): boolean {\n\t\tconst left = this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing), scope);\n\t\tconst right = this.getSourceMatchKeyForInput(inputSource);\n\t\treturn left === right;\n\t}\n\n\tprivate normalizePackageSourceForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type !== \"local\") {\n\t\t\treturn source;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\tconst resolved = this.resolvePath(parsed.path);\n\t\tconst rel = relative(baseDir, resolved);\n\t\treturn rel || \".\";\n\t}\n\n\tprivate parseSource(source: string): ParsedSource {\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\tconst spec = source.slice(\"npm:\".length).trim();\n\t\t\tconst { name, version } = this.parseNpmSpec(spec);\n\t\t\treturn {\n\t\t\t\ttype: \"npm\",\n\t\t\t\tspec,\n\t\t\t\tname,\n\t\t\t\tpinned: Boolean(version),\n\t\t\t};\n\t\t}\n\n\t\tconst trimmed = source.trim();\n\t\tconst isWindowsAbsolutePath = /^[A-Za-z]:[\\\\/]|^\\\\\\\\/.test(trimmed);\n\t\tconst isLocalPathLike =\n\t\t\ttrimmed.startsWith(\".\") ||\n\t\t\ttrimmed.startsWith(\"/\") ||\n\t\t\ttrimmed === \"~\" ||\n\t\t\ttrimmed.startsWith(\"~/\") ||\n\t\t\tisWindowsAbsolutePath;\n\t\tif (isLocalPathLike) {\n\t\t\treturn { type: \"local\", path: source };\n\t\t}\n\n\t\t// Try parsing as git URL\n\t\tconst gitParsed = parseGitUrl(source);\n\t\tif (gitParsed) {\n\t\t\treturn gitParsed;\n\t\t}\n\n\t\treturn { type: \"local\", path: source };\n\t}\n\n\t/**\n\t * Check if an npm package needs to be updated.\n\t * - For unpinned packages: check if registry has a newer version\n\t * - For pinned packages: check if installed version matches the pinned version\n\t */\n\tprivate async npmNeedsUpdate(source: NpmSource, installedPath: string): Promise<boolean> {\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) return true;\n\n\t\tconst { version: pinnedVersion } = this.parseNpmSpec(source.spec);\n\t\tif (pinnedVersion) {\n\t\t\t// Pinned: check if installed matches pinned (exact match for now)\n\t\t\treturn installedVersion !== pinnedVersion;\n\t\t}\n\n\t\t// Unpinned: check registry for latest version\n\t\ttry {\n\t\t\tconst latestVersion = await this.getLatestNpmVersion(source.name);\n\t\t\treturn latestVersion !== installedVersion;\n\t\t} catch {\n\t\t\t// If we can't check registry, assume it's fine\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate getInstalledNpmVersion(installedPath: string): string | undefined {\n\t\tconst packageJsonPath = join(installedPath, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) return undefined;\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { version?: string };\n\t\t\treturn pkg.version;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async getLatestNpmVersion(packageName: string): Promise<string> {\n\t\tconst response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);\n\t\tif (!response.ok) throw new Error(`Failed to fetch npm registry: ${response.status}`);\n\t\tconst data = (await response.json()) as { version: string };\n\t\treturn data.version;\n\t}\n\n\t/**\n\t * Get a unique identity for a package, ignoring version/ref.\n\t * Used to detect when the same package is in both global and project settings.\n\t * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs\n\t * for the same repository are treated as identical.\n\t */\n\tprivate getPackageIdentity(source: string, scope?: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\t// Use host/path for identity to normalize SSH and HTTPS\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tif (scope) {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\t/**\n\t * Dedupe packages: if same package identity appears in both global and project,\n\t * keep only the project one (project wins).\n\t */\n\tprivate dedupePackages(\n\t\tpackages: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): Array<{ pkg: PackageSource; scope: SourceScope }> {\n\t\tconst seen = new Map<string, { pkg: PackageSource; scope: SourceScope }>();\n\n\t\tfor (const entry of packages) {\n\t\t\tconst sourceStr = typeof entry.pkg === \"string\" ? entry.pkg : entry.pkg.source;\n\t\t\tconst identity = this.getPackageIdentity(sourceStr, entry.scope);\n\n\t\t\tconst existing = seen.get(identity);\n\t\t\tif (!existing) {\n\t\t\t\tseen.set(identity, entry);\n\t\t\t} else if (entry.scope === \"project\" && existing.scope === \"user\") {\n\t\t\t\t// Project wins over user\n\t\t\t\tseen.set(identity, entry);\n\t\t\t}\n\t\t\t// If existing is project and new is global, keep existing (project)\n\t\t\t// If both are same scope, keep first one\n\t\t}\n\n\t\treturn Array.from(seen.values());\n\t}\n\n\tprivate parseNpmSpec(spec: string): { name: string; version?: string } {\n\t\tconst match = spec.match(/^(@?[^@]+(?:\\/[^@]+)?)(?:@(.+))?$/);\n\t\tif (!match) {\n\t\t\treturn { name: spec };\n\t\t}\n\t\tconst name = match[1] ?? spec;\n\t\tconst version = match[2];\n\t\treturn { name, version };\n\t}\n\n\tprivate async installNpm(source: NpmSource, scope: SourceScope, temporary: boolean): Promise<void> {\n\t\tif (scope === \"user\" && !temporary) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\", \"-g\", source.spec]);\n\t\t\treturn;\n\t\t}\n\t\tconst installRoot = this.getNpmInstallRoot(scope, temporary);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runCommand(\"npm\", [\"install\", source.spec, \"--prefix\", installRoot]);\n\t}\n\n\tprivate async uninstallNpm(source: NpmSource, scope: SourceScope): Promise<void> {\n\t\tif (scope === \"user\") {\n\t\t\tawait this.runCommand(\"npm\", [\"uninstall\", \"-g\", source.name]);\n\t\t\treturn;\n\t\t}\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tif (!existsSync(installRoot)) {\n\t\t\treturn;\n\t\t}\n\t\tawait this.runCommand(\"npm\", [\"uninstall\", source.name, \"--prefix\", installRoot]);\n\t}\n\n\tprivate async installGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (existsSync(targetDir)) {\n\t\t\treturn;\n\t\t}\n\t\tconst gitRoot = this.getGitInstallRoot(scope);\n\t\tif (gitRoot) {\n\t\t\tthis.ensureGitIgnore(gitRoot);\n\t\t}\n\t\tmkdirSync(dirname(targetDir), { recursive: true });\n\n\t\tawait this.runCommand(\"git\", [\"clone\", source.repo, targetDir]);\n\t\tif (source.ref) {\n\t\t\tawait this.runCommand(\"git\", [\"checkout\", source.ref], { cwd: targetDir });\n\t\t}\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\"], { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async updateGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) {\n\t\t\tawait this.installGit(source, scope);\n\t\t\treturn;\n\t\t}\n\n\t\t// Fetch latest from remote (handles force-push by getting new history)\n\t\tawait this.runCommand(\"git\", [\"fetch\", \"--prune\", \"origin\"], { cwd: targetDir });\n\n\t\t// Reset to tracking branch. Fall back to origin/HEAD when no upstream is configured.\n\t\ttry {\n\t\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"@{upstream}\"], { cwd: targetDir });\n\t\t} catch {\n\t\t\tawait this.runCommand(\"git\", [\"remote\", \"set-head\", \"origin\", \"-a\"], { cwd: targetDir }).catch(() => {});\n\t\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"origin/HEAD\"], { cwd: targetDir });\n\t\t}\n\n\t\t// Clean untracked files (extensions should be pristine)\n\t\tawait this.runCommand(\"git\", [\"clean\", \"-fdx\"], { cwd: targetDir });\n\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\"], { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async refreshTemporaryGitSource(source: GitSource, sourceStr: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.withProgress(\"pull\", sourceStr, `Refreshing ${sourceStr}...`, async () => {\n\t\t\t\tawait this.updateGit(source, \"temporary\");\n\t\t\t});\n\t\t} catch {\n\t\t\t// Keep cached temporary checkout if refresh fails.\n\t\t}\n\t}\n\n\tprivate async removeGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) return;\n\t\trmSync(targetDir, { recursive: true, force: true });\n\t\tthis.pruneEmptyGitParents(targetDir, this.getGitInstallRoot(scope));\n\t}\n\n\tprivate pruneEmptyGitParents(targetDir: string, installRoot: string | undefined): void {\n\t\tif (!installRoot) return;\n\t\tconst resolvedRoot = resolve(installRoot);\n\t\tlet current = dirname(targetDir);\n\t\twhile (current.startsWith(resolvedRoot) && current !== resolvedRoot) {\n\t\t\tif (!existsSync(current)) {\n\t\t\t\tcurrent = dirname(current);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst entries = readdirSync(current);\n\t\t\tif (entries.length > 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trmSync(current, { recursive: true, force: true });\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent = dirname(current);\n\t\t}\n\t}\n\n\tprivate ensureNpmProject(installRoot: string): void {\n\t\tif (!existsSync(installRoot)) {\n\t\t\tmkdirSync(installRoot, { recursive: true });\n\t\t}\n\t\tthis.ensureGitIgnore(installRoot);\n\t\tconst packageJsonPath = join(installRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\tconst pkgJson = { name: \"pi-extensions\", private: true };\n\t\t\twriteFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2), \"utf-8\");\n\t\t}\n\t}\n\n\tprivate ensureGitIgnore(dir: string): void {\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\tconst ignorePath = join(dir, \".gitignore\");\n\t\tif (!existsSync(ignorePath)) {\n\t\t\twriteFileSync(ignorePath, \"*\\n!.gitignore\\n\", \"utf-8\");\n\t\t}\n\t}\n\n\tprivate getNpmInstallRoot(scope: SourceScope, temporary: boolean): string {\n\t\tif (temporary) {\n\t\t\treturn this.getTemporaryDir(\"npm\");\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\");\n\t\t}\n\t\treturn join(this.getGlobalNpmRoot(), \"..\");\n\t}\n\n\tprivate getGlobalNpmRoot(): string {\n\t\tif (this.globalNpmRoot) {\n\t\t\treturn this.globalNpmRoot;\n\t\t}\n\t\tconst result = this.runCommandSync(\"npm\", [\"root\", \"-g\"]);\n\t\tthis.globalNpmRoot = result.trim();\n\t\treturn this.globalNpmRoot;\n\t}\n\n\tprivate getNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn join(this.getTemporaryDir(\"npm\"), \"node_modules\", source.name);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\", \"node_modules\", source.name);\n\t\t}\n\t\treturn join(this.getGlobalNpmRoot(), source.name);\n\t}\n\n\tprivate getGitInstallPath(source: GitSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn this.getTemporaryDir(`git-${source.host}`, source.path);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\", source.host, source.path);\n\t\t}\n\t\treturn join(this.agentDir, \"git\", source.host, source.path);\n\t}\n\n\tprivate getGitInstallRoot(scope: SourceScope): string | undefined {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\");\n\t\t}\n\t\treturn join(this.agentDir, \"git\");\n\t}\n\n\tprivate getTemporaryDir(prefix: string, suffix?: string): string {\n\t\tconst hash = createHash(\"sha256\")\n\t\t\t.update(`${prefix}-${suffix ?? \"\"}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 8);\n\t\treturn join(tmpdir(), \"pi-extensions\", prefix, hash, suffix ?? \"\");\n\t}\n\n\tprivate getBaseDirForScope(scope: SourceScope): string {\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME);\n\t\t}\n\t\tif (scope === \"user\") {\n\t\t\treturn this.agentDir;\n\t\t}\n\t\treturn this.cwd;\n\t}\n\n\tprivate resolvePath(input: string): string {\n\t\tconst trimmed = input.trim();\n\t\tif (trimmed === \"~\") return homedir();\n\t\tif (trimmed.startsWith(\"~/\")) return join(homedir(), trimmed.slice(2));\n\t\tif (trimmed.startsWith(\"~\")) return join(homedir(), trimmed.slice(1));\n\t\treturn resolve(this.cwd, trimmed);\n\t}\n\n\tprivate resolvePathFromBase(input: string, baseDir: string): string {\n\t\tconst trimmed = input.trim();\n\t\tif (trimmed === \"~\") return homedir();\n\t\tif (trimmed.startsWith(\"~/\")) return join(homedir(), trimmed.slice(2));\n\t\tif (trimmed.startsWith(\"~\")) return join(homedir(), trimmed.slice(1));\n\t\treturn resolve(baseDir, trimmed);\n\t}\n\n\tprivate collectPackageResources(\n\t\tpackageRoot: string,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t): boolean {\n\t\tif (filter) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst patterns = filter[resourceType as keyof PackageFilter];\n\t\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\t\tif (patterns !== undefined) {\n\t\t\t\t\tthis.applyPackageFilter(packageRoot, patterns, resourceType, target, metadata);\n\t\t\t\t} else {\n\t\t\t\t\tthis.collectDefaultResources(packageRoot, resourceType, target, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tif (manifest) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst entries = manifest[resourceType as keyof PiManifest];\n\t\t\t\tthis.addManifestEntries(\n\t\t\t\t\tentries,\n\t\t\t\t\tpackageRoot,\n\t\t\t\t\tresourceType,\n\t\t\t\t\tthis.getTargetMap(accumulator, resourceType),\n\t\t\t\t\tmetadata,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tlet hasAnyDir = false;\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst dir = join(packageRoot, resourceType);\n\t\t\tif (existsSync(dir)) {\n\t\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\t\tfor (const f of files) {\n\t\t\t\t\tthis.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true);\n\t\t\t\t}\n\t\t\t\thasAnyDir = true;\n\t\t\t}\n\t\t}\n\t\treturn hasAnyDir;\n\t}\n\n\tprivate collectDefaultResources(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries) {\n\t\t\tthis.addManifestEntries(entries, packageRoot, resourceType, target, metadata);\n\t\t\treturn;\n\t\t}\n\t\tconst dir = join(packageRoot, resourceType);\n\t\tif (existsSync(dir)) {\n\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyPackageFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\n\t\tif (userPatterns.length === 0) {\n\t\t\t// Empty array explicitly disables all resources of this type\n\t\t\tfor (const f of allFiles) {\n\t\t\t\tthis.addResource(target, f, metadata, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Apply user patterns\n\t\tconst enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot);\n\n\t\tfor (const f of allFiles) {\n\t\t\tconst enabled = enabledByUser.has(f);\n\t\t\tthis.addResource(target, f, metadata, enabled);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all files from a package for a resource type, applying manifest patterns.\n\t * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files\n\t * that pass the manifest's own patterns.\n\t */\n\tprivate collectManifestFiles(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t): { allFiles: string[]; enabledByManifest: Set<string> } {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries && entries.length > 0) {\n\t\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, packageRoot, resourceType);\n\t\t\tconst manifestPatterns = entries.filter(isPattern);\n\t\t\tconst enabledByManifest =\n\t\t\t\tmanifestPatterns.length > 0 ? applyPatterns(allFiles, manifestPatterns, packageRoot) : new Set(allFiles);\n\t\t\treturn { allFiles: Array.from(enabledByManifest), enabledByManifest };\n\t\t}\n\n\t\tconst conventionDir = join(packageRoot, resourceType);\n\t\tif (!existsSync(conventionDir)) {\n\t\t\treturn { allFiles: [], enabledByManifest: new Set() };\n\t\t}\n\t\tconst allFiles = collectResourceFiles(conventionDir, resourceType);\n\t\treturn { allFiles, enabledByManifest: new Set(allFiles) };\n\t}\n\n\tprivate readPiManifest(packageRoot: string): PiManifest | null {\n\t\tconst packageJsonPath = join(packageRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\t\treturn pkg.pi ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate addManifestEntries(\n\t\tentries: string[] | undefined,\n\t\troot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (!entries) return;\n\n\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, root, resourceType);\n\t\tconst patterns = entries.filter(isPattern);\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, root);\n\n\t\tfor (const f of allFiles) {\n\t\t\tif (enabledPaths.has(f)) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate collectFilesFromManifestEntries(entries: string[], root: string, resourceType: ResourceType): string[] {\n\t\tconst plain = entries.filter((entry) => !isPattern(entry));\n\t\tconst resolved = plain.map((entry) => resolve(root, entry));\n\t\treturn this.collectFilesFromPaths(resolved, resourceType);\n\t}\n\n\tprivate resolveLocalEntries(\n\t\tentries: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tif (entries.length === 0) return;\n\n\t\t// Collect all files from plain entries (non-pattern entries)\n\t\tconst { plain, patterns } = splitPatterns(entries);\n\t\tconst resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir));\n\t\tconst allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType);\n\n\t\t// Determine which files are enabled based on patterns\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, baseDir);\n\n\t\t// Add all files with their enabled state\n\t\tfor (const f of allFiles) {\n\t\t\tthis.addResource(target, f, metadata, enabledPaths.has(f));\n\t\t}\n\t}\n\n\tprivate addAutoDiscoveredResources(\n\t\taccumulator: ResourceAccumulator,\n\t\tglobalSettings: ReturnType<SettingsManager[\"getGlobalSettings\"]>,\n\t\tprojectSettings: ReturnType<SettingsManager[\"getProjectSettings\"]>,\n\t\tglobalBaseDir: string,\n\t\tprojectBaseDir: string,\n\t): void {\n\t\tconst userMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"user\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: globalBaseDir,\n\t\t};\n\t\tconst projectMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"project\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: projectBaseDir,\n\t\t};\n\n\t\tconst userOverrides = {\n\t\t\textensions: (globalSettings.extensions ?? []) as string[],\n\t\t\tskills: (globalSettings.skills ?? []) as string[],\n\t\t\tprompts: (globalSettings.prompts ?? []) as string[],\n\t\t\tthemes: (globalSettings.themes ?? []) as string[],\n\t\t};\n\t\tconst projectOverrides = {\n\t\t\textensions: (projectSettings.extensions ?? []) as string[],\n\t\t\tskills: (projectSettings.skills ?? []) as string[],\n\t\t\tprompts: (projectSettings.prompts ?? []) as string[],\n\t\t\tthemes: (projectSettings.themes ?? []) as string[],\n\t\t};\n\n\t\tconst userDirs = {\n\t\t\textensions: join(globalBaseDir, \"extensions\"),\n\t\t\tskills: join(globalBaseDir, \"skills\"),\n\t\t\tprompts: join(globalBaseDir, \"prompts\"),\n\t\t\tthemes: join(globalBaseDir, \"themes\"),\n\t\t};\n\t\tconst projectDirs = {\n\t\t\textensions: join(projectBaseDir, \"extensions\"),\n\t\t\tskills: join(projectBaseDir, \"skills\"),\n\t\t\tprompts: join(projectBaseDir, \"prompts\"),\n\t\t\tthemes: join(projectBaseDir, \"themes\"),\n\t\t};\n\t\tconst userAgentsSkillsDir = join(homedir(), \".agents\", \"skills\");\n\t\tconst projectAgentsSkillDirs = collectAncestorAgentsSkillDirs(this.cwd);\n\n\t\tconst addResources = (\n\t\t\tresourceType: ResourceType,\n\t\t\tpaths: string[],\n\t\t\tmetadata: PathMetadata,\n\t\t\toverrides: string[],\n\t\t\tbaseDir: string,\n\t\t) => {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst enabled = isEnabledByOverrides(path, overrides, baseDir);\n\t\t\t\tthis.addResource(target, path, metadata, enabled);\n\t\t\t}\n\t\t};\n\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(userDirs.extensions),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.extensions,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\t[...collectAutoSkillEntries(userDirs.skills), ...collectAutoSkillEntries(userAgentsSkillsDir)],\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(userDirs.prompts),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.prompts,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(userDirs.themes),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.themes,\n\t\t\tglobalBaseDir,\n\t\t);\n\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(projectDirs.extensions),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.extensions,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\t[\n\t\t\t\t...collectAutoSkillEntries(projectDirs.skills),\n\t\t\t\t...projectAgentsSkillDirs.flatMap((dir) => collectAutoSkillEntries(dir)),\n\t\t\t],\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.skills,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(projectDirs.prompts),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.prompts,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(projectDirs.themes),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.themes,\n\t\t\tprojectBaseDir,\n\t\t);\n\t}\n\n\tprivate collectFilesFromPaths(paths: string[], resourceType: ResourceType): string[] {\n\t\tconst files: string[] = [];\n\t\tfor (const p of paths) {\n\t\t\tif (!existsSync(p)) continue;\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(p);\n\t\t\t\tif (stats.isFile()) {\n\t\t\t\t\tfiles.push(p);\n\t\t\t\t} else if (stats.isDirectory()) {\n\t\t\t\t\tfiles.push(...collectResourceFiles(p, resourceType));\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tprivate getTargetMap(\n\t\taccumulator: ResourceAccumulator,\n\t\tresourceType: ResourceType,\n\t): Map<string, { metadata: PathMetadata; enabled: boolean }> {\n\t\tswitch (resourceType) {\n\t\t\tcase \"extensions\":\n\t\t\t\treturn accumulator.extensions;\n\t\t\tcase \"skills\":\n\t\t\t\treturn accumulator.skills;\n\t\t\tcase \"prompts\":\n\t\t\t\treturn accumulator.prompts;\n\t\t\tcase \"themes\":\n\t\t\t\treturn accumulator.themes;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown resource type: ${resourceType}`);\n\t\t}\n\t}\n\n\tprivate addResource(\n\t\tmap: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tpath: string,\n\t\tmetadata: PathMetadata,\n\t\tenabled: boolean,\n\t): void {\n\t\tif (!path) return;\n\t\tif (!map.has(path)) {\n\t\t\tmap.set(path, { metadata, enabled });\n\t\t}\n\t}\n\n\tprivate createAccumulator(): ResourceAccumulator {\n\t\treturn {\n\t\t\textensions: new Map(),\n\t\t\tskills: new Map(),\n\t\t\tprompts: new Map(),\n\t\t\tthemes: new Map(),\n\t\t};\n\t}\n\n\tprivate toResolvedPaths(accumulator: ResourceAccumulator): ResolvedPaths {\n\t\tconst toResolved = (entries: Map<string, { metadata: PathMetadata; enabled: boolean }>): ResolvedResource[] => {\n\t\t\treturn Array.from(entries.entries()).map(([path, { metadata, enabled }]) => ({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t}));\n\t\t};\n\n\t\treturn {\n\t\t\textensions: toResolved(accumulator.extensions),\n\t\t\tskills: toResolved(accumulator.skills),\n\t\t\tprompts: toResolved(accumulator.prompts),\n\t\t\tthemes: toResolved(accumulator.themes),\n\t\t};\n\t}\n\n\tprivate runCommand(command: string, args: string[], options?: { cwd?: string }): Promise<void> {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = spawn(command, args, {\n\t\t\t\tcwd: options?.cwd,\n\t\t\t\tstdio: \"inherit\",\n\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t});\n\t\t\tchild.on(\"error\", reject);\n\t\t\tchild.on(\"exit\", (code) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise();\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommandSync(command: string, args: string[]): string {\n\t\tconst result = spawnSync(command, args, {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tshell: process.platform === \"win32\",\n\t\t});\n\t\tif (result.status !== 0) {\n\t\t\tthrow new Error(`Failed to run ${command} ${args.join(\" \")}: ${result.stderr || result.stdout}`);\n\t\t}\n\t\treturn (result.stdout || result.stderr || \"\").trim();\n\t}\n}\n"]}
1
+ {"version":3,"file":"package-manager.d.ts","sourceRoot":"","sources":["../../src/core/package-manager.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE5E,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,WAAW,CAAC;IACnB,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IACh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B;YAYhB,mBAAmB;IAOjC;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;IAgB1B;;;OAGG;IACH,OAAO,CAAC,cAAc;IAuBtB,OAAO,CAAC,YAAY;YAUN,UAAU;YAUV,YAAY;YAYZ,UAAU;YAqBV,SAAS;YA2BT,yBAAyB;YAUzB,SAAS;IAOvB,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,kBAAkB;IAU1B,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,uBAAuB;IAiD/B,OAAO,CAAC,uBAAuB;IAsB/B,OAAO,CAAC,kBAAkB;IA0B1B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,kBAAkB;IAoB1B,OAAO,CAAC,+BAA+B;IAMvC,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,0BAA0B;IA4HlC,OAAO,CAAC,qBAAqB;IAmB7B,OAAO,CAAC,YAAY;IAkBpB,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,UAAU;IAkBlB,OAAO,CAAC,cAAc;CAWtB","sourcesContent":["import { spawn, spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport ignore from \"ignore\";\nimport { minimatch } from \"minimatch\";\nimport { CONFIG_DIR_NAME } from \"../config.js\";\nimport { type GitSource, parseGitUrl } from \"../utils/git.js\";\nimport type { PackageSource, SettingsManager } from \"./settings-manager.js\";\n\nexport interface PathMetadata {\n\tsource: string;\n\tscope: SourceScope;\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\nexport interface ResolvedResource {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n}\n\nexport interface ResolvedPaths {\n\textensions: ResolvedResource[];\n\tskills: ResolvedResource[];\n\tprompts: ResolvedResource[];\n\tthemes: ResolvedResource[];\n}\n\nexport type MissingSourceAction = \"install\" | \"skip\" | \"error\";\n\nexport interface ProgressEvent {\n\ttype: \"start\" | \"progress\" | \"complete\" | \"error\";\n\taction: \"install\" | \"remove\" | \"update\" | \"clone\" | \"pull\";\n\tsource: string;\n\tmessage?: string;\n}\n\nexport type ProgressCallback = (event: ProgressEvent) => void;\n\nexport interface PackageManager {\n\tresolve(onMissing?: (source: string) => Promise<MissingSourceAction>): Promise<ResolvedPaths>;\n\tinstall(source: string, options?: { local?: boolean }): Promise<void>;\n\tremove(source: string, options?: { local?: boolean }): Promise<void>;\n\tupdate(source?: string): Promise<void>;\n\tresolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise<ResolvedPaths>;\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean;\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean;\n\tsetProgressCallback(callback: ProgressCallback | undefined): void;\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined;\n}\n\ninterface PackageManagerOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n}\n\ntype SourceScope = \"user\" | \"project\" | \"temporary\";\n\ntype NpmSource = {\n\ttype: \"npm\";\n\tspec: string;\n\tname: string;\n\tpinned: boolean;\n};\n\ntype LocalSource = {\n\ttype: \"local\";\n\tpath: string;\n};\n\ntype ParsedSource = NpmSource | GitSource | LocalSource;\n\ninterface PiManifest {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ninterface ResourceAccumulator {\n\textensions: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tskills: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tprompts: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n\tthemes: Map<string, { metadata: PathMetadata; enabled: boolean }>;\n}\n\ninterface PackageFilter {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\nconst RESOURCE_TYPES: ResourceType[] = [\"extensions\", \"skills\", \"prompts\", \"themes\"];\n\nconst FILE_PATTERNS: Record<ResourceType, RegExp> = {\n\textensions: /\\.(ts|js)$/,\n\tskills: /\\.md$/,\n\tprompts: /\\.md$/,\n\tthemes: /\\.json$/,\n};\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nfunction isPattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\") || s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction splitPatterns(entries: string[]): { plain: string[]; patterns: string[] } {\n\tconst plain: string[] = [];\n\tconst patterns: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (isPattern(entry)) {\n\t\t\tpatterns.push(entry);\n\t\t} else {\n\t\t\tplain.push(entry);\n\t\t}\n\t}\n\treturn { plain, patterns };\n}\n\nfunction collectFiles(\n\tdir: string,\n\tfilePattern: RegExp,\n\tskipNodeModules = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst files: string[] = [];\n\tif (!existsSync(dir)) return files;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (skipNodeModules && entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tfiles.push(...collectFiles(fullPath, filePattern, skipNodeModules, ig, root));\n\t\t\t} else if (isFile && filePattern.test(entry.name)) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn files;\n}\n\nfunction collectSkillEntries(\n\tdir: string,\n\tincludeRootFiles = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tentries.push(...collectSkillEntries(fullPath, false, ig, root));\n\t\t\t} else if (isFile) {\n\t\t\t\tconst isRootMd = includeRootFiles && entry.name.endsWith(\".md\");\n\t\t\t\tconst isSkillMd = !includeRootFiles && entry.name === \"SKILL.md\";\n\t\t\t\tif (isRootMd || isSkillMd) {\n\t\t\t\t\tentries.push(fullPath);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoSkillEntries(dir: string, includeRootFiles = true): string[] {\n\treturn collectSkillEntries(dir, includeRootFiles);\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\nfunction collectAncestorAgentsSkillDirs(startDir: string): string[] {\n\tconst skillDirs: string[] = [];\n\tconst resolvedStartDir = resolve(startDir);\n\tconst gitRepoRoot = findGitRepoRoot(resolvedStartDir);\n\n\tlet dir = resolvedStartDir;\n\twhile (true) {\n\t\tskillDirs.push(join(dir, \".agents\", \"skills\"));\n\t\tif (gitRepoRoot && dir === gitRepoRoot) {\n\t\t\tbreak;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\tbreak;\n\t\t}\n\t\tdir = parent;\n\t}\n\n\treturn skillDirs;\n}\n\nfunction collectAutoPromptEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoThemeEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".json\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction readPiManifestFile(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\treturn pkg.pi ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = join(dir, \"package.json\");\n\tif (existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifestFile(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = resolve(dir, extPath);\n\t\t\t\tif (existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst indexTs = join(dir, \"index.ts\");\n\tconst indexJs = join(dir, \"index.js\");\n\tif (existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\nfunction collectAutoExtensionEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\t// First check if this directory itself has explicit extension entries (package.json or index)\n\tconst rootEntries = resolveExtensionEntries(dir);\n\tif (rootEntries) {\n\t\treturn rootEntries;\n\t}\n\n\t// Otherwise, discover extensions from directory contents\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isFile && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".js\"))) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t} else if (isDir) {\n\t\t\t\tconst resolvedEntries = resolveExtensionEntries(fullPath);\n\t\t\t\tif (resolvedEntries) {\n\t\t\t\t\tentries.push(...resolvedEntries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\n/**\n * Collect resource files from a directory based on resource type.\n * Extensions use smart discovery (index.ts in subdirs), others use recursive collection.\n */\nfunction collectResourceFiles(dir: string, resourceType: ResourceType): string[] {\n\tif (resourceType === \"skills\") {\n\t\treturn collectSkillEntries(dir);\n\t}\n\tif (resourceType === \"extensions\") {\n\t\treturn collectAutoExtensionEntries(dir);\n\t}\n\treturn collectFiles(dir, FILE_PATTERNS[resourceType]);\n}\n\nfunction matchesAnyPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst rel = relative(baseDir, filePath);\n\tconst name = basename(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? relative(baseDir, parentDir!) : undefined;\n\tconst parentName = isSkillFile ? basename(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tif (minimatch(rel, pattern) || minimatch(name, pattern) || minimatch(filePath, pattern)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn minimatch(parentRel!, pattern) || minimatch(parentName!, pattern) || minimatch(parentDir!, pattern);\n\t});\n}\n\nfunction normalizeExactPattern(pattern: string): string {\n\tif (pattern.startsWith(\"./\") || pattern.startsWith(\".\\\\\")) {\n\t\treturn pattern.slice(2);\n\t}\n\treturn pattern;\n}\n\nfunction matchesAnyExactPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tif (patterns.length === 0) return false;\n\tconst rel = relative(baseDir, filePath);\n\tconst name = basename(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? relative(baseDir, parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalized = normalizeExactPattern(pattern);\n\t\tif (normalized === rel || normalized === filePath) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn normalized === parentRel || normalized === parentDir;\n\t});\n}\n\nfunction getOverridePatterns(entries: string[]): string[] {\n\treturn entries.filter((pattern) => pattern.startsWith(\"!\") || pattern.startsWith(\"+\") || pattern.startsWith(\"-\"));\n}\n\nfunction isEnabledByOverrides(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst overrides = getOverridePatterns(patterns);\n\tconst excludes = overrides.filter((pattern) => pattern.startsWith(\"!\")).map((pattern) => pattern.slice(1));\n\tconst forceIncludes = overrides.filter((pattern) => pattern.startsWith(\"+\")).map((pattern) => pattern.slice(1));\n\tconst forceExcludes = overrides.filter((pattern) => pattern.startsWith(\"-\")).map((pattern) => pattern.slice(1));\n\n\tlet enabled = true;\n\tif (excludes.length > 0 && matchesAnyPattern(filePath, excludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\tif (forceIncludes.length > 0 && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\tenabled = true;\n\t}\n\tif (forceExcludes.length > 0 && matchesAnyExactPattern(filePath, forceExcludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\treturn enabled;\n}\n\n/**\n * Apply patterns to paths and return a Set of enabled paths.\n * Pattern types:\n * - Plain patterns: include matching paths\n * - `!pattern`: exclude matching paths\n * - `+path`: force-include exact path (overrides exclusions)\n * - `-path`: force-exclude exact path (overrides force-includes)\n */\nfunction applyPatterns(allPaths: string[], patterns: string[], baseDir: string): Set<string> {\n\tconst includes: string[] = [];\n\tconst excludes: string[] = [];\n\tconst forceIncludes: string[] = [];\n\tconst forceExcludes: string[] = [];\n\n\tfor (const p of patterns) {\n\t\tif (p.startsWith(\"+\")) {\n\t\t\tforceIncludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"-\")) {\n\t\t\tforceExcludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"!\")) {\n\t\t\texcludes.push(p.slice(1));\n\t\t} else {\n\t\t\tincludes.push(p);\n\t\t}\n\t}\n\n\t// Step 1: Apply includes (or all if no includes)\n\tlet result: string[];\n\tif (includes.length === 0) {\n\t\tresult = [...allPaths];\n\t} else {\n\t\tresult = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir));\n\t}\n\n\t// Step 2: Apply excludes\n\tif (excludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir));\n\t}\n\n\t// Step 3: Force-include (add back from allPaths, overriding exclusions)\n\tif (forceIncludes.length > 0) {\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\t\t\tresult.push(filePath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Step 4: Force-exclude (remove even if included or force-included)\n\tif (forceExcludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir));\n\t}\n\n\treturn new Set(result);\n}\n\nexport class DefaultPackageManager implements PackageManager {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate globalNpmRoot: string | undefined;\n\tprivate progressCallback: ProgressCallback | undefined;\n\n\tconstructor(options: PackageManagerOptions) {\n\t\tthis.cwd = options.cwd;\n\t\tthis.agentDir = options.agentDir;\n\t\tthis.settingsManager = options.settingsManager;\n\t}\n\n\tsetProgressCallback(callback: ProgressCallback | undefined): void {\n\t\tthis.progressCallback = callback;\n\t}\n\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst normalizedSource = this.normalizePackageSourceForSettings(source, scope);\n\t\tconst exists = currentPackages.some((existing) => this.packageSourcesMatch(existing, source, scope));\n\t\tif (exists) {\n\t\t\treturn false;\n\t\t}\n\t\tconst nextPackages = [...currentPackages, normalizedSource];\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst nextPackages = currentPackages.filter((existing) => !this.packageSourcesMatch(existing, source, scope));\n\t\tconst changed = nextPackages.length !== currentPackages.length;\n\t\tif (!changed) {\n\t\t\treturn false;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tconst path = this.getNpmInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tconst path = this.getGitInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"local\") {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\tconst path = this.resolvePathFromBase(parsed.path, baseDir);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate emitProgress(event: ProgressEvent): void {\n\t\tthis.progressCallback?.(event);\n\t}\n\n\tprivate async withProgress(\n\t\taction: ProgressEvent[\"action\"],\n\t\tsource: string,\n\t\tmessage: string,\n\t\toperation: () => Promise<void>,\n\t): Promise<void> {\n\t\tthis.emitProgress({ type: \"start\", action, source, message });\n\t\ttry {\n\t\t\tawait operation();\n\t\t\tthis.emitProgress({ type: \"complete\", action, source });\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tthis.emitProgress({ type: \"error\", action, source, message: errorMessage });\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync resolve(onMissing?: (source: string) => Promise<MissingSourceAction>): Promise<ResolvedPaths> {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\n\t\t// Collect all packages with scope (project first so cwd resources win collisions)\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\n\t\t// Dedupe: project scope wins over global for same package identity\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tawait this.resolvePackageSources(packageSources, accumulator, onMissing);\n\n\t\tconst globalBaseDir = this.agentDir;\n\t\tconst projectBaseDir = join(this.cwd, CONFIG_DIR_NAME);\n\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tconst globalEntries = (globalSettings[resourceType] ?? []) as string[];\n\t\t\tconst projectEntries = (projectSettings[resourceType] ?? []) as string[];\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tprojectEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"project\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tglobalEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"user\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tglobalBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tthis.addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir);\n\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync resolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise<ResolvedPaths> {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst scope: SourceScope = options?.temporary ? \"temporary\" : options?.local ? \"project\" : \"user\";\n\t\tconst packageSources = sources.map((source) => ({ pkg: source as PackageSource, scope }));\n\t\tawait this.resolvePackageSources(packageSources, accumulator);\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync install(source: string, options?: { local?: boolean }): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tawait this.withProgress(\"install\", source, `Installing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.installGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst resolved = this.resolvePath(parsed.path);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\tthrow new Error(`Path does not exist: ${resolved}`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported install source: ${source}`);\n\t\t});\n\t}\n\n\tasync remove(source: string, options?: { local?: boolean }): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tawait this.withProgress(\"remove\", source, `Removing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.uninstallNpm(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.removeGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported remove source: ${source}`);\n\t\t});\n\t}\n\n\tasync update(source?: string): Promise<void> {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst identity = source ? this.getPackageIdentity(source) : undefined;\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"user\") !== identity) continue;\n\t\t\tawait this.updateSourceForScope(sourceStr, \"user\");\n\t\t}\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"project\") !== identity) continue;\n\t\t\tawait this.updateSourceForScope(sourceStr, \"project\");\n\t\t}\n\t}\n\n\tprivate async updateSourceForScope(source: string, scope: SourceScope): Promise<void> {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tif (parsed.pinned) return;\n\t\t\tawait this.withProgress(\"update\", source, `Updating ${source}...`, async () => {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tif (parsed.pinned) return;\n\t\t\tawait this.withProgress(\"update\", source, `Updating ${source}...`, async () => {\n\t\t\t\tawait this.updateGit(parsed, scope);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async resolvePackageSources(\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t\taccumulator: ResourceAccumulator,\n\t\tonMissing?: (source: string) => Promise<MissingSourceAction>,\n\t): Promise<void> {\n\t\tfor (const { pkg, scope } of sources) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconst filter = typeof pkg === \"object\" ? pkg : undefined;\n\t\t\tconst parsed = this.parseSource(sourceStr);\n\t\t\tconst metadata: PathMetadata = { source: sourceStr, scope, origin: \"package\" };\n\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\t\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata, baseDir);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst installMissing = async (): Promise<boolean> => {\n\t\t\t\tif (!onMissing) {\n\t\t\t\t\tawait this.installParsedSource(parsed, scope);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconst action = await onMissing(sourceStr);\n\t\t\t\tif (action === \"skip\") return false;\n\t\t\t\tif (action === \"error\") throw new Error(`Missing source: ${sourceStr}`);\n\t\t\t\tawait this.installParsedSource(parsed, scope);\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tconst installedPath = this.getNpmInstallPath(parsed, scope);\n\t\t\t\tconst needsInstall = !existsSync(installedPath) || (await this.npmNeedsUpdate(parsed, installedPath));\n\t\t\t\tif (needsInstall) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, scope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t} else if (scope === \"temporary\" && !parsed.pinned) {\n\t\t\t\t\tawait this.refreshTemporaryGitSource(parsed, sourceStr);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveLocalExtensionSource(\n\t\tsource: LocalSource,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tconst resolved = this.resolvePathFromBase(source.path, baseDir);\n\t\tif (!existsSync(resolved)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolved);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tmetadata.baseDir = dirname(resolved);\n\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tmetadata.baseDir = resolved;\n\t\t\t\tconst resources = this.collectPackageResources(resolved, accumulator, filter, metadata);\n\t\t\t\tif (!resources) {\n\t\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async installParsedSource(parsed: ParsedSource, scope: SourceScope): Promise<void> {\n\t\tif (parsed.type === \"npm\") {\n\t\t\tawait this.installNpm(parsed, scope, scope === \"temporary\");\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tawait this.installGit(parsed, scope);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate getPackageSourceString(pkg: PackageSource): string {\n\t\treturn typeof pkg === \"string\" ? pkg : pkg.source;\n\t}\n\n\tprivate getSourceMatchKeyForInput(source: string): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\tprivate getSourceMatchKeyForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t}\n\n\tprivate packageSourcesMatch(existing: PackageSource, inputSource: string, scope: SourceScope): boolean {\n\t\tconst left = this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing), scope);\n\t\tconst right = this.getSourceMatchKeyForInput(inputSource);\n\t\treturn left === right;\n\t}\n\n\tprivate normalizePackageSourceForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type !== \"local\") {\n\t\t\treturn source;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\tconst resolved = this.resolvePath(parsed.path);\n\t\tconst rel = relative(baseDir, resolved);\n\t\treturn rel || \".\";\n\t}\n\n\tprivate parseSource(source: string): ParsedSource {\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\tconst spec = source.slice(\"npm:\".length).trim();\n\t\t\tconst { name, version } = this.parseNpmSpec(spec);\n\t\t\treturn {\n\t\t\t\ttype: \"npm\",\n\t\t\t\tspec,\n\t\t\t\tname,\n\t\t\t\tpinned: Boolean(version),\n\t\t\t};\n\t\t}\n\n\t\tconst trimmed = source.trim();\n\t\tconst isWindowsAbsolutePath = /^[A-Za-z]:[\\\\/]|^\\\\\\\\/.test(trimmed);\n\t\tconst isLocalPathLike =\n\t\t\ttrimmed.startsWith(\".\") ||\n\t\t\ttrimmed.startsWith(\"/\") ||\n\t\t\ttrimmed === \"~\" ||\n\t\t\ttrimmed.startsWith(\"~/\") ||\n\t\t\tisWindowsAbsolutePath;\n\t\tif (isLocalPathLike) {\n\t\t\treturn { type: \"local\", path: source };\n\t\t}\n\n\t\t// Try parsing as git URL\n\t\tconst gitParsed = parseGitUrl(source);\n\t\tif (gitParsed) {\n\t\t\treturn gitParsed;\n\t\t}\n\n\t\treturn { type: \"local\", path: source };\n\t}\n\n\t/**\n\t * Check if an npm package needs to be updated.\n\t * - For unpinned packages: check if registry has a newer version\n\t * - For pinned packages: check if installed version matches the pinned version\n\t */\n\tprivate async npmNeedsUpdate(source: NpmSource, installedPath: string): Promise<boolean> {\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) return true;\n\n\t\tconst { version: pinnedVersion } = this.parseNpmSpec(source.spec);\n\t\tif (pinnedVersion) {\n\t\t\t// Pinned: check if installed matches pinned (exact match for now)\n\t\t\treturn installedVersion !== pinnedVersion;\n\t\t}\n\n\t\t// Unpinned: check registry for latest version\n\t\ttry {\n\t\t\tconst latestVersion = await this.getLatestNpmVersion(source.name);\n\t\t\treturn latestVersion !== installedVersion;\n\t\t} catch {\n\t\t\t// If we can't check registry, assume it's fine\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate getInstalledNpmVersion(installedPath: string): string | undefined {\n\t\tconst packageJsonPath = join(installedPath, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) return undefined;\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { version?: string };\n\t\t\treturn pkg.version;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async getLatestNpmVersion(packageName: string): Promise<string> {\n\t\tconst response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);\n\t\tif (!response.ok) throw new Error(`Failed to fetch npm registry: ${response.status}`);\n\t\tconst data = (await response.json()) as { version: string };\n\t\treturn data.version;\n\t}\n\n\t/**\n\t * Get a unique identity for a package, ignoring version/ref.\n\t * Used to detect when the same package is in both global and project settings.\n\t * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs\n\t * for the same repository are treated as identical.\n\t */\n\tprivate getPackageIdentity(source: string, scope?: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\t// Use host/path for identity to normalize SSH and HTTPS\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tif (scope) {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\t/**\n\t * Dedupe packages: if same package identity appears in both global and project,\n\t * keep only the project one (project wins).\n\t */\n\tprivate dedupePackages(\n\t\tpackages: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): Array<{ pkg: PackageSource; scope: SourceScope }> {\n\t\tconst seen = new Map<string, { pkg: PackageSource; scope: SourceScope }>();\n\n\t\tfor (const entry of packages) {\n\t\t\tconst sourceStr = typeof entry.pkg === \"string\" ? entry.pkg : entry.pkg.source;\n\t\t\tconst identity = this.getPackageIdentity(sourceStr, entry.scope);\n\n\t\t\tconst existing = seen.get(identity);\n\t\t\tif (!existing) {\n\t\t\t\tseen.set(identity, entry);\n\t\t\t} else if (entry.scope === \"project\" && existing.scope === \"user\") {\n\t\t\t\t// Project wins over user\n\t\t\t\tseen.set(identity, entry);\n\t\t\t}\n\t\t\t// If existing is project and new is global, keep existing (project)\n\t\t\t// If both are same scope, keep first one\n\t\t}\n\n\t\treturn Array.from(seen.values());\n\t}\n\n\tprivate parseNpmSpec(spec: string): { name: string; version?: string } {\n\t\tconst match = spec.match(/^(@?[^@]+(?:\\/[^@]+)?)(?:@(.+))?$/);\n\t\tif (!match) {\n\t\t\treturn { name: spec };\n\t\t}\n\t\tconst name = match[1] ?? spec;\n\t\tconst version = match[2];\n\t\treturn { name, version };\n\t}\n\n\tprivate async installNpm(source: NpmSource, scope: SourceScope, temporary: boolean): Promise<void> {\n\t\tif (scope === \"user\" && !temporary) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\", \"-g\", source.spec]);\n\t\t\treturn;\n\t\t}\n\t\tconst installRoot = this.getNpmInstallRoot(scope, temporary);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runCommand(\"npm\", [\"install\", source.spec, \"--prefix\", installRoot]);\n\t}\n\n\tprivate async uninstallNpm(source: NpmSource, scope: SourceScope): Promise<void> {\n\t\tif (scope === \"user\") {\n\t\t\tawait this.runCommand(\"npm\", [\"uninstall\", \"-g\", source.name]);\n\t\t\treturn;\n\t\t}\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tif (!existsSync(installRoot)) {\n\t\t\treturn;\n\t\t}\n\t\tawait this.runCommand(\"npm\", [\"uninstall\", source.name, \"--prefix\", installRoot]);\n\t}\n\n\tprivate async installGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (existsSync(targetDir)) {\n\t\t\treturn;\n\t\t}\n\t\tconst gitRoot = this.getGitInstallRoot(scope);\n\t\tif (gitRoot) {\n\t\t\tthis.ensureGitIgnore(gitRoot);\n\t\t}\n\t\tmkdirSync(dirname(targetDir), { recursive: true });\n\n\t\tawait this.runCommand(\"git\", [\"clone\", source.repo, targetDir]);\n\t\tif (source.ref) {\n\t\t\tawait this.runCommand(\"git\", [\"checkout\", source.ref], { cwd: targetDir });\n\t\t}\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\"], { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async updateGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) {\n\t\t\tawait this.installGit(source, scope);\n\t\t\treturn;\n\t\t}\n\n\t\t// Fetch latest from remote (handles force-push by getting new history)\n\t\tawait this.runCommand(\"git\", [\"fetch\", \"--prune\", \"origin\"], { cwd: targetDir });\n\n\t\t// Reset to tracking branch. Fall back to origin/HEAD when no upstream is configured.\n\t\ttry {\n\t\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"@{upstream}\"], { cwd: targetDir });\n\t\t} catch {\n\t\t\tawait this.runCommand(\"git\", [\"remote\", \"set-head\", \"origin\", \"-a\"], { cwd: targetDir }).catch(() => {});\n\t\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"origin/HEAD\"], { cwd: targetDir });\n\t\t}\n\n\t\t// Clean untracked files (extensions should be pristine)\n\t\tawait this.runCommand(\"git\", [\"clean\", \"-fdx\"], { cwd: targetDir });\n\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runCommand(\"npm\", [\"install\"], { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async refreshTemporaryGitSource(source: GitSource, sourceStr: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.withProgress(\"pull\", sourceStr, `Refreshing ${sourceStr}...`, async () => {\n\t\t\t\tawait this.updateGit(source, \"temporary\");\n\t\t\t});\n\t\t} catch {\n\t\t\t// Keep cached temporary checkout if refresh fails.\n\t\t}\n\t}\n\n\tprivate async removeGit(source: GitSource, scope: SourceScope): Promise<void> {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) return;\n\t\trmSync(targetDir, { recursive: true, force: true });\n\t\tthis.pruneEmptyGitParents(targetDir, this.getGitInstallRoot(scope));\n\t}\n\n\tprivate pruneEmptyGitParents(targetDir: string, installRoot: string | undefined): void {\n\t\tif (!installRoot) return;\n\t\tconst resolvedRoot = resolve(installRoot);\n\t\tlet current = dirname(targetDir);\n\t\twhile (current.startsWith(resolvedRoot) && current !== resolvedRoot) {\n\t\t\tif (!existsSync(current)) {\n\t\t\t\tcurrent = dirname(current);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst entries = readdirSync(current);\n\t\t\tif (entries.length > 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trmSync(current, { recursive: true, force: true });\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent = dirname(current);\n\t\t}\n\t}\n\n\tprivate ensureNpmProject(installRoot: string): void {\n\t\tif (!existsSync(installRoot)) {\n\t\t\tmkdirSync(installRoot, { recursive: true });\n\t\t}\n\t\tthis.ensureGitIgnore(installRoot);\n\t\tconst packageJsonPath = join(installRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\tconst pkgJson = { name: \"pi-extensions\", private: true };\n\t\t\twriteFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2), \"utf-8\");\n\t\t}\n\t}\n\n\tprivate ensureGitIgnore(dir: string): void {\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\tconst ignorePath = join(dir, \".gitignore\");\n\t\tif (!existsSync(ignorePath)) {\n\t\t\twriteFileSync(ignorePath, \"*\\n!.gitignore\\n\", \"utf-8\");\n\t\t}\n\t}\n\n\tprivate getNpmInstallRoot(scope: SourceScope, temporary: boolean): string {\n\t\tif (temporary) {\n\t\t\treturn this.getTemporaryDir(\"npm\");\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\");\n\t\t}\n\t\treturn join(this.getGlobalNpmRoot(), \"..\");\n\t}\n\n\tprivate getGlobalNpmRoot(): string {\n\t\tif (this.globalNpmRoot) {\n\t\t\treturn this.globalNpmRoot;\n\t\t}\n\t\tconst result = this.runCommandSync(\"npm\", [\"root\", \"-g\"]);\n\t\tthis.globalNpmRoot = result.trim();\n\t\treturn this.globalNpmRoot;\n\t}\n\n\tprivate getNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn join(this.getTemporaryDir(\"npm\"), \"node_modules\", source.name);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\", \"node_modules\", source.name);\n\t\t}\n\t\treturn join(this.getGlobalNpmRoot(), source.name);\n\t}\n\n\tprivate getGitInstallPath(source: GitSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn this.getTemporaryDir(`git-${source.host}`, source.path);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\", source.host, source.path);\n\t\t}\n\t\treturn join(this.agentDir, \"git\", source.host, source.path);\n\t}\n\n\tprivate getGitInstallRoot(scope: SourceScope): string | undefined {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\");\n\t\t}\n\t\treturn join(this.agentDir, \"git\");\n\t}\n\n\tprivate getTemporaryDir(prefix: string, suffix?: string): string {\n\t\tconst hash = createHash(\"sha256\")\n\t\t\t.update(`${prefix}-${suffix ?? \"\"}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 8);\n\t\treturn join(tmpdir(), \"pi-extensions\", prefix, hash, suffix ?? \"\");\n\t}\n\n\tprivate getBaseDirForScope(scope: SourceScope): string {\n\t\tif (scope === \"project\") {\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME);\n\t\t}\n\t\tif (scope === \"user\") {\n\t\t\treturn this.agentDir;\n\t\t}\n\t\treturn this.cwd;\n\t}\n\n\tprivate resolvePath(input: string): string {\n\t\tconst trimmed = input.trim();\n\t\tif (trimmed === \"~\") return homedir();\n\t\tif (trimmed.startsWith(\"~/\")) return join(homedir(), trimmed.slice(2));\n\t\tif (trimmed.startsWith(\"~\")) return join(homedir(), trimmed.slice(1));\n\t\treturn resolve(this.cwd, trimmed);\n\t}\n\n\tprivate resolvePathFromBase(input: string, baseDir: string): string {\n\t\tconst trimmed = input.trim();\n\t\tif (trimmed === \"~\") return homedir();\n\t\tif (trimmed.startsWith(\"~/\")) return join(homedir(), trimmed.slice(2));\n\t\tif (trimmed.startsWith(\"~\")) return join(homedir(), trimmed.slice(1));\n\t\treturn resolve(baseDir, trimmed);\n\t}\n\n\tprivate collectPackageResources(\n\t\tpackageRoot: string,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t): boolean {\n\t\tif (filter) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst patterns = filter[resourceType as keyof PackageFilter];\n\t\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\t\tif (patterns !== undefined) {\n\t\t\t\t\tthis.applyPackageFilter(packageRoot, patterns, resourceType, target, metadata);\n\t\t\t\t} else {\n\t\t\t\t\tthis.collectDefaultResources(packageRoot, resourceType, target, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tif (manifest) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst entries = manifest[resourceType as keyof PiManifest];\n\t\t\t\tthis.addManifestEntries(\n\t\t\t\t\tentries,\n\t\t\t\t\tpackageRoot,\n\t\t\t\t\tresourceType,\n\t\t\t\t\tthis.getTargetMap(accumulator, resourceType),\n\t\t\t\t\tmetadata,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tlet hasAnyDir = false;\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst dir = join(packageRoot, resourceType);\n\t\t\tif (existsSync(dir)) {\n\t\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\t\tfor (const f of files) {\n\t\t\t\t\tthis.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true);\n\t\t\t\t}\n\t\t\t\thasAnyDir = true;\n\t\t\t}\n\t\t}\n\t\treturn hasAnyDir;\n\t}\n\n\tprivate collectDefaultResources(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries) {\n\t\t\tthis.addManifestEntries(entries, packageRoot, resourceType, target, metadata);\n\t\t\treturn;\n\t\t}\n\t\tconst dir = join(packageRoot, resourceType);\n\t\tif (existsSync(dir)) {\n\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyPackageFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\n\t\tif (userPatterns.length === 0) {\n\t\t\t// Empty array explicitly disables all resources of this type\n\t\t\tfor (const f of allFiles) {\n\t\t\t\tthis.addResource(target, f, metadata, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Apply user patterns\n\t\tconst enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot);\n\n\t\tfor (const f of allFiles) {\n\t\t\tconst enabled = enabledByUser.has(f);\n\t\t\tthis.addResource(target, f, metadata, enabled);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all files from a package for a resource type, applying manifest patterns.\n\t * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files\n\t * that pass the manifest's own patterns.\n\t */\n\tprivate collectManifestFiles(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t): { allFiles: string[]; enabledByManifest: Set<string> } {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries && entries.length > 0) {\n\t\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, packageRoot, resourceType);\n\t\t\tconst manifestPatterns = entries.filter(isPattern);\n\t\t\tconst enabledByManifest =\n\t\t\t\tmanifestPatterns.length > 0 ? applyPatterns(allFiles, manifestPatterns, packageRoot) : new Set(allFiles);\n\t\t\treturn { allFiles: Array.from(enabledByManifest), enabledByManifest };\n\t\t}\n\n\t\tconst conventionDir = join(packageRoot, resourceType);\n\t\tif (!existsSync(conventionDir)) {\n\t\t\treturn { allFiles: [], enabledByManifest: new Set() };\n\t\t}\n\t\tconst allFiles = collectResourceFiles(conventionDir, resourceType);\n\t\treturn { allFiles, enabledByManifest: new Set(allFiles) };\n\t}\n\n\tprivate readPiManifest(packageRoot: string): PiManifest | null {\n\t\tconst packageJsonPath = join(packageRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\t\treturn pkg.pi ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate addManifestEntries(\n\t\tentries: string[] | undefined,\n\t\troot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (!entries) return;\n\n\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, root, resourceType);\n\t\tconst patterns = entries.filter(isPattern);\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, root);\n\n\t\tfor (const f of allFiles) {\n\t\t\tif (enabledPaths.has(f)) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate collectFilesFromManifestEntries(entries: string[], root: string, resourceType: ResourceType): string[] {\n\t\tconst plain = entries.filter((entry) => !isPattern(entry));\n\t\tconst resolved = plain.map((entry) => resolve(root, entry));\n\t\treturn this.collectFilesFromPaths(resolved, resourceType);\n\t}\n\n\tprivate resolveLocalEntries(\n\t\tentries: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tif (entries.length === 0) return;\n\n\t\t// Collect all files from plain entries (non-pattern entries)\n\t\tconst { plain, patterns } = splitPatterns(entries);\n\t\tconst resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir));\n\t\tconst allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType);\n\n\t\t// Determine which files are enabled based on patterns\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, baseDir);\n\n\t\t// Add all files with their enabled state\n\t\tfor (const f of allFiles) {\n\t\t\tthis.addResource(target, f, metadata, enabledPaths.has(f));\n\t\t}\n\t}\n\n\tprivate addAutoDiscoveredResources(\n\t\taccumulator: ResourceAccumulator,\n\t\tglobalSettings: ReturnType<SettingsManager[\"getGlobalSettings\"]>,\n\t\tprojectSettings: ReturnType<SettingsManager[\"getProjectSettings\"]>,\n\t\tglobalBaseDir: string,\n\t\tprojectBaseDir: string,\n\t): void {\n\t\tconst userMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"user\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: globalBaseDir,\n\t\t};\n\t\tconst projectMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"project\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: projectBaseDir,\n\t\t};\n\n\t\tconst userOverrides = {\n\t\t\textensions: (globalSettings.extensions ?? []) as string[],\n\t\t\tskills: (globalSettings.skills ?? []) as string[],\n\t\t\tprompts: (globalSettings.prompts ?? []) as string[],\n\t\t\tthemes: (globalSettings.themes ?? []) as string[],\n\t\t};\n\t\tconst projectOverrides = {\n\t\t\textensions: (projectSettings.extensions ?? []) as string[],\n\t\t\tskills: (projectSettings.skills ?? []) as string[],\n\t\t\tprompts: (projectSettings.prompts ?? []) as string[],\n\t\t\tthemes: (projectSettings.themes ?? []) as string[],\n\t\t};\n\n\t\tconst userDirs = {\n\t\t\textensions: join(globalBaseDir, \"extensions\"),\n\t\t\tskills: join(globalBaseDir, \"skills\"),\n\t\t\tprompts: join(globalBaseDir, \"prompts\"),\n\t\t\tthemes: join(globalBaseDir, \"themes\"),\n\t\t};\n\t\tconst projectDirs = {\n\t\t\textensions: join(projectBaseDir, \"extensions\"),\n\t\t\tskills: join(projectBaseDir, \"skills\"),\n\t\t\tprompts: join(projectBaseDir, \"prompts\"),\n\t\t\tthemes: join(projectBaseDir, \"themes\"),\n\t\t};\n\t\tconst userAgentsSkillsDir = join(homedir(), \".agents\", \"skills\");\n\t\tconst projectAgentsSkillDirs = collectAncestorAgentsSkillDirs(this.cwd);\n\n\t\tconst addResources = (\n\t\t\tresourceType: ResourceType,\n\t\t\tpaths: string[],\n\t\t\tmetadata: PathMetadata,\n\t\t\toverrides: string[],\n\t\t\tbaseDir: string,\n\t\t) => {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst enabled = isEnabledByOverrides(path, overrides, baseDir);\n\t\t\t\tthis.addResource(target, path, metadata, enabled);\n\t\t\t}\n\t\t};\n\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(projectDirs.extensions),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.extensions,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\t[\n\t\t\t\t...collectAutoSkillEntries(projectDirs.skills),\n\t\t\t\t...projectAgentsSkillDirs.flatMap((dir) => collectAutoSkillEntries(dir)),\n\t\t\t],\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.skills,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(projectDirs.prompts),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.prompts,\n\t\t\tprojectBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(projectDirs.themes),\n\t\t\tprojectMetadata,\n\t\t\tprojectOverrides.themes,\n\t\t\tprojectBaseDir,\n\t\t);\n\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(userDirs.extensions),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.extensions,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\t[...collectAutoSkillEntries(userDirs.skills), ...collectAutoSkillEntries(userAgentsSkillsDir)],\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(userDirs.prompts),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.prompts,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(userDirs.themes),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.themes,\n\t\t\tglobalBaseDir,\n\t\t);\n\t}\n\n\tprivate collectFilesFromPaths(paths: string[], resourceType: ResourceType): string[] {\n\t\tconst files: string[] = [];\n\t\tfor (const p of paths) {\n\t\t\tif (!existsSync(p)) continue;\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(p);\n\t\t\t\tif (stats.isFile()) {\n\t\t\t\t\tfiles.push(p);\n\t\t\t\t} else if (stats.isDirectory()) {\n\t\t\t\t\tfiles.push(...collectResourceFiles(p, resourceType));\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tprivate getTargetMap(\n\t\taccumulator: ResourceAccumulator,\n\t\tresourceType: ResourceType,\n\t): Map<string, { metadata: PathMetadata; enabled: boolean }> {\n\t\tswitch (resourceType) {\n\t\t\tcase \"extensions\":\n\t\t\t\treturn accumulator.extensions;\n\t\t\tcase \"skills\":\n\t\t\t\treturn accumulator.skills;\n\t\t\tcase \"prompts\":\n\t\t\t\treturn accumulator.prompts;\n\t\t\tcase \"themes\":\n\t\t\t\treturn accumulator.themes;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown resource type: ${resourceType}`);\n\t\t}\n\t}\n\n\tprivate addResource(\n\t\tmap: Map<string, { metadata: PathMetadata; enabled: boolean }>,\n\t\tpath: string,\n\t\tmetadata: PathMetadata,\n\t\tenabled: boolean,\n\t): void {\n\t\tif (!path) return;\n\t\tif (!map.has(path)) {\n\t\t\tmap.set(path, { metadata, enabled });\n\t\t}\n\t}\n\n\tprivate createAccumulator(): ResourceAccumulator {\n\t\treturn {\n\t\t\textensions: new Map(),\n\t\t\tskills: new Map(),\n\t\t\tprompts: new Map(),\n\t\t\tthemes: new Map(),\n\t\t};\n\t}\n\n\tprivate toResolvedPaths(accumulator: ResourceAccumulator): ResolvedPaths {\n\t\tconst toResolved = (entries: Map<string, { metadata: PathMetadata; enabled: boolean }>): ResolvedResource[] => {\n\t\t\treturn Array.from(entries.entries()).map(([path, { metadata, enabled }]) => ({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t}));\n\t\t};\n\n\t\treturn {\n\t\t\textensions: toResolved(accumulator.extensions),\n\t\t\tskills: toResolved(accumulator.skills),\n\t\t\tprompts: toResolved(accumulator.prompts),\n\t\t\tthemes: toResolved(accumulator.themes),\n\t\t};\n\t}\n\n\tprivate runCommand(command: string, args: string[], options?: { cwd?: string }): Promise<void> {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = spawn(command, args, {\n\t\t\t\tcwd: options?.cwd,\n\t\t\t\tstdio: \"inherit\",\n\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t});\n\t\t\tchild.on(\"error\", reject);\n\t\t\tchild.on(\"exit\", (code) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise();\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommandSync(command: string, args: string[]): string {\n\t\tconst result = spawnSync(command, args, {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tshell: process.platform === \"win32\",\n\t\t});\n\t\tif (result.status !== 0) {\n\t\t\tthrow new Error(`Failed to run ${command} ${args.join(\" \")}: ${result.stderr || result.stdout}`);\n\t\t}\n\t\treturn (result.stdout || result.stderr || \"\").trim();\n\t}\n}\n"]}