@mariozechner/pi-coding-agent 0.50.9 → 0.51.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.
Files changed (121) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +4 -3
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +1 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/session-picker.d.ts.map +1 -1
  7. package/dist/cli/session-picker.js +3 -1
  8. package/dist/cli/session-picker.js.map +1 -1
  9. package/dist/config.d.ts.map +1 -1
  10. package/dist/config.js +9 -0
  11. package/dist/config.js.map +1 -1
  12. package/dist/core/extensions/index.d.ts +2 -2
  13. package/dist/core/extensions/index.d.ts.map +1 -1
  14. package/dist/core/extensions/index.js +1 -1
  15. package/dist/core/extensions/index.js.map +1 -1
  16. package/dist/core/extensions/types.d.ts +67 -5
  17. package/dist/core/extensions/types.d.ts.map +1 -1
  18. package/dist/core/extensions/types.js +4 -1
  19. package/dist/core/extensions/types.js.map +1 -1
  20. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  21. package/dist/core/extensions/wrapper.js +1 -1
  22. package/dist/core/extensions/wrapper.js.map +1 -1
  23. package/dist/core/keybindings.d.ts +1 -1
  24. package/dist/core/keybindings.d.ts.map +1 -1
  25. package/dist/core/keybindings.js +2 -0
  26. package/dist/core/keybindings.js.map +1 -1
  27. package/dist/core/model-registry.d.ts.map +1 -1
  28. package/dist/core/model-registry.js +19 -17
  29. package/dist/core/model-registry.js.map +1 -1
  30. package/dist/core/package-manager.d.ts.map +1 -1
  31. package/dist/core/package-manager.js +11 -9
  32. package/dist/core/package-manager.js.map +1 -1
  33. package/dist/core/skills.d.ts.map +1 -1
  34. package/dist/core/skills.js +1 -0
  35. package/dist/core/skills.js.map +1 -1
  36. package/dist/core/tools/bash.d.ts +11 -0
  37. package/dist/core/tools/bash.d.ts.map +1 -1
  38. package/dist/core/tools/bash.js +18 -3
  39. package/dist/core/tools/bash.js.map +1 -1
  40. package/dist/core/tools/edit.d.ts +2 -0
  41. package/dist/core/tools/edit.d.ts.map +1 -1
  42. package/dist/core/tools/edit.js.map +1 -1
  43. package/dist/core/tools/find.d.ts +2 -0
  44. package/dist/core/tools/find.d.ts.map +1 -1
  45. package/dist/core/tools/find.js.map +1 -1
  46. package/dist/core/tools/grep.d.ts +2 -0
  47. package/dist/core/tools/grep.d.ts.map +1 -1
  48. package/dist/core/tools/grep.js.map +1 -1
  49. package/dist/core/tools/index.d.ts +7 -7
  50. package/dist/core/tools/index.d.ts.map +1 -1
  51. package/dist/core/tools/index.js +5 -5
  52. package/dist/core/tools/index.js.map +1 -1
  53. package/dist/core/tools/ls.d.ts +2 -0
  54. package/dist/core/tools/ls.d.ts.map +1 -1
  55. package/dist/core/tools/ls.js.map +1 -1
  56. package/dist/core/tools/read.d.ts +2 -0
  57. package/dist/core/tools/read.d.ts.map +1 -1
  58. package/dist/core/tools/read.js.map +1 -1
  59. package/dist/core/tools/write.d.ts +2 -0
  60. package/dist/core/tools/write.d.ts.map +1 -1
  61. package/dist/core/tools/write.js.map +1 -1
  62. package/dist/index.d.ts +3 -3
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/modes/interactive/components/session-selector-search.d.ts +3 -1
  67. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  68. package/dist/modes/interactive/components/session-selector-search.js +13 -4
  69. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  70. package/dist/modes/interactive/components/session-selector.d.ts +11 -2
  71. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  72. package/dist/modes/interactive/components/session-selector.js +58 -12
  73. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  74. package/dist/modes/interactive/components/tree-selector.d.ts +6 -0
  75. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  76. package/dist/modes/interactive/components/tree-selector.js +43 -16
  77. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  78. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  79. package/dist/modes/interactive/interactive-mode.js +6 -15
  80. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  81. package/dist/utils/clipboard-image.d.ts.map +1 -1
  82. package/dist/utils/clipboard-image.js +6 -3
  83. package/dist/utils/clipboard-image.js.map +1 -1
  84. package/dist/utils/clipboard-native.d.ts +7 -0
  85. package/dist/utils/clipboard-native.d.ts.map +1 -0
  86. package/dist/utils/clipboard-native.js +14 -0
  87. package/dist/utils/clipboard-native.js.map +1 -0
  88. package/dist/utils/clipboard.d.ts.map +1 -1
  89. package/dist/utils/clipboard.js +10 -1
  90. package/dist/utils/clipboard.js.map +1 -1
  91. package/dist/utils/tools-manager.d.ts.map +1 -1
  92. package/dist/utils/tools-manager.js +14 -0
  93. package/dist/utils/tools-manager.js.map +1 -1
  94. package/docs/extensions.md +57 -9
  95. package/docs/keybindings.md +1 -0
  96. package/docs/models.md +43 -14
  97. package/docs/rpc.md +188 -1
  98. package/docs/termux.md +127 -0
  99. package/examples/extensions/README.md +1 -0
  100. package/examples/extensions/antigravity-image-gen.ts +1 -1
  101. package/examples/extensions/bash-spawn-hook.ts +30 -0
  102. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  103. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  104. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  105. package/examples/extensions/custom-provider-qwen-cli/package.json +1 -1
  106. package/examples/extensions/hello.ts +1 -1
  107. package/examples/extensions/question.ts +1 -1
  108. package/examples/extensions/questionnaire.ts +1 -1
  109. package/examples/extensions/rpc-demo.ts +124 -0
  110. package/examples/extensions/sandbox/index.ts +1 -1
  111. package/examples/extensions/shutdown-command.ts +2 -2
  112. package/examples/extensions/ssh.ts +4 -4
  113. package/examples/extensions/subagent/index.ts +1 -1
  114. package/examples/extensions/todo.ts +1 -1
  115. package/examples/extensions/tool-override.ts +1 -1
  116. package/examples/extensions/truncated-tool.ts +1 -1
  117. package/examples/extensions/with-deps/package-lock.json +2 -2
  118. package/examples/extensions/with-deps/package.json +1 -1
  119. package/examples/rpc-extension-ui.ts +632 -0
  120. package/examples/sdk/06-extensions.ts +1 -1
  121. package/package.json +7 -5
@@ -37,20 +37,21 @@ const OpenAICompletionsCompatSchema = Type.Object({
37
37
  const OpenAIResponsesCompatSchema = Type.Object({});
38
38
  const OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);
39
39
  // Schema for custom model definition
40
+ // Most fields are optional with sensible defaults for local models (Ollama, LM Studio, etc.)
40
41
  const ModelDefinitionSchema = Type.Object({
41
42
  id: Type.String({ minLength: 1 }),
42
- name: Type.String({ minLength: 1 }),
43
+ name: Type.Optional(Type.String({ minLength: 1 })),
43
44
  api: Type.Optional(Type.String({ minLength: 1 })),
44
- reasoning: Type.Boolean(),
45
- input: Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")])),
46
- cost: Type.Object({
45
+ reasoning: Type.Optional(Type.Boolean()),
46
+ input: Type.Optional(Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]))),
47
+ cost: Type.Optional(Type.Object({
47
48
  input: Type.Number(),
48
49
  output: Type.Number(),
49
50
  cacheRead: Type.Number(),
50
51
  cacheWrite: Type.Number(),
51
- }),
52
- contextWindow: Type.Number(),
53
- maxTokens: Type.Number(),
52
+ })),
53
+ contextWindow: Type.Optional(Type.Number()),
54
+ maxTokens: Type.Optional(Type.Number()),
54
55
  headers: Type.Optional(Type.Record(Type.String(), Type.String())),
55
56
  compat: Type.Optional(OpenAICompatSchema),
56
57
  });
@@ -271,11 +272,10 @@ export class ModelRegistry {
271
272
  }
272
273
  if (!modelDef.id)
273
274
  throw new Error(`Provider ${providerName}: model missing "id"`);
274
- if (!modelDef.name)
275
- throw new Error(`Provider ${providerName}: model missing "name"`);
276
- if (modelDef.contextWindow <= 0)
275
+ // Validate contextWindow/maxTokens only if provided (they have defaults)
276
+ if (modelDef.contextWindow !== undefined && modelDef.contextWindow <= 0)
277
277
  throw new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);
278
- if (modelDef.maxTokens <= 0)
278
+ if (modelDef.maxTokens !== undefined && modelDef.maxTokens <= 0)
279
279
  throw new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);
280
280
  }
281
281
  }
@@ -307,17 +307,19 @@ export class ModelRegistry {
307
307
  }
308
308
  }
309
309
  // baseUrl is validated to exist for providers with models
310
+ // Apply defaults for optional fields
311
+ const defaultCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
310
312
  models.push({
311
313
  id: modelDef.id,
312
- name: modelDef.name,
314
+ name: modelDef.name ?? modelDef.id,
313
315
  api: api,
314
316
  provider: providerName,
315
317
  baseUrl: providerConfig.baseUrl,
316
- reasoning: modelDef.reasoning,
317
- input: modelDef.input,
318
- cost: modelDef.cost,
319
- contextWindow: modelDef.contextWindow,
320
- maxTokens: modelDef.maxTokens,
318
+ reasoning: modelDef.reasoning ?? false,
319
+ input: (modelDef.input ?? ["text"]),
320
+ cost: modelDef.cost ?? defaultCost,
321
+ contextWindow: modelDef.contextWindow ?? 128000,
322
+ maxTokens: modelDef.maxTokens ?? 16384,
321
323
  headers,
322
324
  compat: modelDef.compat,
323
325
  });
@@ -1 +1 @@
1
- {"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAIN,SAAS,EACT,YAAY,EAIZ,mBAAmB,EACnB,qBAAqB,GAErB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C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;QACF,CAAC;aAAM,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YAC3B,4DAA4D;YAC5D,MAAM,eAAe,GAAG,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACvD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;gBACpC,IAAI,CAAC,CAAC,QAAQ,KAAK,YAAY;oBAAE,OAAO,CAAC,CAAC;gBAC1C,OAAO;oBACN,GAAG,CAAC;oBACJ,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO;oBACpC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,GAAG,eAAe,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO;iBAC3E,CAAC;YAAA,CACF,CAAC,CAAC;QACJ,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Model registry - manages built-in and custom models, provides API key resolution.\n */\n\nimport {\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\ttype Model,\n\ttype OAuthProviderInterface,\n\tregisterApiProvider,\n\tregisterOAuthProvider,\n\ttype SimpleStreamOptions,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { execSync } from \"child_process\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport type { AuthStorage } from \"./auth-storage.js\";\n\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenRouter routing preferences\nconst OpenRouterRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for Vercel AI Gateway routing preferences\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresMistralToolIds: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(Type.Union([Type.Literal(\"openai\"), Type.Literal(\"zai\"), Type.Literal(\"qwen\")])),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\t// Reserved for future use\n});\n\nconst OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);\n\n// Schema for custom model definition\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Boolean(),\n\tinput: Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")])),\n\tcost: Type.Object({\n\t\tinput: Type.Number(),\n\t\toutput: Type.Number(),\n\t\tcacheRead: Type.Number(),\n\t\tcacheWrite: Type.Number(),\n\t}),\n\tcontextWindow: Type.Number(),\n\tmaxTokens: Type.Number(),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n});\n\nconst ProviderConfigSchema = Type.Object({\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\n\ntype ModelsConfig = Static<typeof ModelsConfigSchema>;\n\n/** Provider override config (baseUrl, headers, apiKey) without custom models */\ninterface ProviderOverride {\n\tbaseUrl?: string;\n\theaders?: Record<string, string>;\n\tapiKey?: string;\n}\n\n/** Result of loading custom models from models.json */\ninterface CustomModelsResult {\n\tmodels: Model<Api>[];\n\t/** Providers with custom models (full replacement) */\n\treplacedProviders: Set<string>;\n\t/** Providers with only baseUrl/headers override (no custom models) */\n\toverrides: Map<string, ProviderOverride>;\n\terror: string | undefined;\n}\n\nfunction emptyCustomModelsResult(error?: string): CustomModelsResult {\n\treturn { models: [], replacedProviders: new Set(), overrides: new Map(), error };\n}\n\n// Cache for shell command results (persists for process lifetime)\nconst commandResultCache = new Map<string, string | undefined>();\n\n/**\n * Resolve a config value (API key, header value, etc.) to an actual value.\n * - If starts with \"!\", executes the rest as a shell command and uses stdout (cached)\n * - Otherwise checks environment variable first, then treats as literal (not cached)\n */\nfunction resolveConfigValue(config: string): string | undefined {\n\tif (config.startsWith(\"!\")) {\n\t\treturn executeCommand(config);\n\t}\n\tconst envValue = process.env[config];\n\treturn envValue || config;\n}\n\nfunction executeCommand(commandConfig: string): string | undefined {\n\tif (commandResultCache.has(commandConfig)) {\n\t\treturn commandResultCache.get(commandConfig);\n\t}\n\n\tconst command = commandConfig.slice(1);\n\tlet result: string | undefined;\n\ttry {\n\t\tconst output = execSync(command, {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tresult = output.trim() || undefined;\n\t} catch {\n\t\tresult = undefined;\n\t}\n\n\tcommandResultCache.set(commandConfig, result);\n\treturn result;\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nfunction resolveHeaders(headers: Record<string, string> | undefined): Record<string, string> | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tconst resolvedValue = resolveConfigValue(value);\n\t\tif (resolvedValue) {\n\t\t\tresolved[key] = resolvedValue;\n\t\t}\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\n/** Clear the config value command cache. Exported for testing. */\nexport function clearApiKeyCache(): void {\n\tcommandResultCache.clear();\n}\n\n/**\n * Model registry - loads and manages models, resolves API keys via AuthStorage.\n */\nexport class ModelRegistry {\n\tprivate models: Model<Api>[] = [];\n\tprivate customProviderApiKeys: Map<string, string> = new Map();\n\tprivate registeredProviders: Map<string, ProviderConfigInput> = new Map();\n\tprivate loadError: string | undefined = undefined;\n\n\tconstructor(\n\t\treadonly authStorage: AuthStorage,\n\t\tprivate modelsJsonPath: string | undefined = join(getAgentDir(), \"models.json\"),\n\t) {\n\t\t// Set up fallback resolver for custom provider API keys\n\t\tthis.authStorage.setFallbackResolver((provider) => {\n\t\t\tconst keyConfig = this.customProviderApiKeys.get(provider);\n\t\t\tif (keyConfig) {\n\t\t\t\treturn resolveConfigValue(keyConfig);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t});\n\n\t\t// Load models\n\t\tthis.loadModels();\n\t}\n\n\t/**\n\t * Reload models from disk (built-in + custom from models.json).\n\t */\n\trefresh(): void {\n\t\tthis.customProviderApiKeys.clear();\n\t\tthis.loadError = undefined;\n\t\tthis.loadModels();\n\n\t\tfor (const [providerName, config] of this.registeredProviders.entries()) {\n\t\t\tthis.applyProviderConfig(providerName, config);\n\t\t}\n\t}\n\n\t/**\n\t * Get any error from loading models.json (undefined if no error).\n\t */\n\tgetError(): string | undefined {\n\t\treturn this.loadError;\n\t}\n\n\tprivate loadModels(): void {\n\t\t// Load custom models from models.json first (to know which providers to skip/override)\n\t\tconst {\n\t\t\tmodels: customModels,\n\t\t\treplacedProviders,\n\t\t\toverrides,\n\t\t\terror,\n\t\t} = this.modelsJsonPath ? this.loadCustomModels(this.modelsJsonPath) : emptyCustomModelsResult();\n\n\t\tif (error) {\n\t\t\tthis.loadError = error;\n\t\t\t// Keep built-in models even if custom models failed to load\n\t\t}\n\n\t\tconst builtInModels = this.loadBuiltInModels(replacedProviders, overrides);\n\t\tlet combined = [...builtInModels, ...customModels];\n\n\t\t// Let OAuth providers modify their models (e.g., update baseUrl)\n\t\tfor (const oauthProvider of this.authStorage.getOAuthProviders()) {\n\t\t\tconst cred = this.authStorage.get(oauthProvider.id);\n\t\t\tif (cred?.type === \"oauth\" && oauthProvider.modifyModels) {\n\t\t\t\tcombined = oauthProvider.modifyModels(combined, cred);\n\t\t\t}\n\t\t}\n\n\t\tthis.models = combined;\n\t}\n\n\t/** Load built-in models, skipping replaced providers and applying overrides */\n\tprivate loadBuiltInModels(replacedProviders: Set<string>, overrides: Map<string, ProviderOverride>): Model<Api>[] {\n\t\treturn getProviders()\n\t\t\t.filter((provider) => !replacedProviders.has(provider))\n\t\t\t.flatMap((provider) => {\n\t\t\t\tconst models = getModels(provider as KnownProvider) as Model<Api>[];\n\t\t\t\tconst override = overrides.get(provider);\n\t\t\t\tif (!override) return models;\n\n\t\t\t\t// Apply baseUrl/headers override to all models of this provider\n\t\t\t\tconst resolvedHeaders = resolveHeaders(override.headers);\n\t\t\t\treturn models.map((m) => ({\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: override.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t}));\n\t\t\t});\n\t}\n\n\tprivate loadCustomModels(modelsJsonPath: string): CustomModelsResult {\n\t\tif (!existsSync(modelsJsonPath)) {\n\t\t\treturn emptyCustomModelsResult();\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(modelsJsonPath, \"utf-8\");\n\t\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t\t// Validate schema\n\t\t\tconst ajv = new Ajv();\n\t\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\t\tif (!validate(config)) {\n\t\t\t\tconst errors =\n\t\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\t\"Unknown schema error\";\n\t\t\t\treturn emptyCustomModelsResult(`Invalid models.json schema:\\n${errors}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\n\t\t\t// Additional validation\n\t\t\tthis.validateConfig(config);\n\n\t\t\t// Separate providers into \"full replacement\" (has models) vs \"override-only\" (no models)\n\t\t\tconst replacedProviders = new Set<string>();\n\t\t\tconst overrides = new Map<string, ProviderOverride>();\n\n\t\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\t\tif (providerConfig.models && providerConfig.models.length > 0) {\n\t\t\t\t\t// Has custom models -> full replacement\n\t\t\t\t\treplacedProviders.add(providerName);\n\t\t\t\t} else {\n\t\t\t\t\t// No models -> just override baseUrl/headers on built-in\n\t\t\t\t\toverrides.set(providerName, {\n\t\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\t\theaders: providerConfig.headers,\n\t\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\t});\n\t\t\t\t\t// Store API key for fallback resolver\n\t\t\t\t\tif (providerConfig.apiKey) {\n\t\t\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { models: this.parseModels(config), replacedProviders, overrides, error: undefined };\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\treturn emptyCustomModelsResult(`Failed to parse models.json: ${error.message}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\t\t\treturn emptyCustomModelsResult(\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${modelsJsonPath}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate validateConfig(config: ModelsConfig): void {\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst hasProviderApi = !!providerConfig.api;\n\t\t\tconst models = providerConfig.models ?? [];\n\n\t\t\tif (models.length === 0) {\n\t\t\t\t// Override-only config: just needs baseUrl (to override built-in)\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}: must specify either \"baseUrl\" (for override) or \"models\" (for replacement).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Full replacement: needs baseUrl and apiKey\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t\tif (!providerConfig.apiKey) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const modelDef of models) {\n\t\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseModels(config: ModelsConfig): Model<Api>[] {\n\t\tconst models: Model<Api>[] = [];\n\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst modelDefs = providerConfig.models ?? [];\n\t\t\tif (modelDefs.length === 0) continue; // Override-only, no custom models\n\n\t\t\t// Store API key config for fallback resolver\n\t\t\tif (providerConfig.apiKey) {\n\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t}\n\n\t\t\tfor (const modelDef of modelDefs) {\n\t\t\t\tconst api = modelDef.api || providerConfig.api;\n\t\t\t\tif (!api) continue;\n\n\t\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\t\t// Resolve env vars and shell commands in header values\n\t\t\t\tconst providerHeaders = resolveHeaders(providerConfig.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\t\tif (providerConfig.authHeader && providerConfig.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(providerConfig.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// baseUrl is validated to exist for providers with models\n\t\t\t\tmodels.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: providerConfig.baseUrl!,\n\t\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\n\t\treturn models;\n\t}\n\n\t/**\n\t * Get all models (built-in + custom).\n\t * If models.json had errors, returns only built-in models.\n\t */\n\tgetAll(): Model<Api>[] {\n\t\treturn this.models;\n\t}\n\n\t/**\n\t * Get only models that have auth configured.\n\t * This is a fast check that doesn't refresh OAuth tokens.\n\t */\n\tgetAvailable(): Model<Api>[] {\n\t\treturn this.models.filter((m) => this.authStorage.hasAuth(m.provider));\n\t}\n\n\t/**\n\t * Find a model by provider and ID.\n\t */\n\tfind(provider: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.find((m) => m.provider === provider && m.id === modelId);\n\t}\n\n\t/**\n\t * Get API key for a model.\n\t */\n\tasync getApiKey(model: Model<Api>): Promise<string | undefined> {\n\t\treturn this.authStorage.getApiKey(model.provider);\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t */\n\tasync getApiKeyForProvider(provider: string): Promise<string | undefined> {\n\t\treturn this.authStorage.getApiKey(provider);\n\t}\n\n\t/**\n\t * Check if a model is using OAuth credentials (subscription).\n\t */\n\tisUsingOAuth(model: Model<Api>): boolean {\n\t\tconst cred = this.authStorage.get(model.provider);\n\t\treturn cred?.type === \"oauth\";\n\t}\n\n\t/**\n\t * Register a provider dynamically (from extensions).\n\t *\n\t * If provider has models: replaces all existing models for this provider.\n\t * If provider has only baseUrl/headers: overrides existing models' URLs.\n\t * If provider has oauth: registers OAuth provider for /login support.\n\t */\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void {\n\t\tthis.registeredProviders.set(providerName, config);\n\t\tthis.applyProviderConfig(providerName, config);\n\t}\n\n\tprivate applyProviderConfig(providerName: string, config: ProviderConfigInput): void {\n\t\t// Register OAuth provider if provided\n\t\tif (config.oauth) {\n\t\t\t// Ensure the OAuth provider ID matches the provider name\n\t\t\tconst oauthProvider: OAuthProviderInterface = {\n\t\t\t\t...config.oauth,\n\t\t\t\tid: providerName,\n\t\t\t};\n\t\t\tregisterOAuthProvider(oauthProvider);\n\t\t}\n\n\t\tif (config.streamSimple) {\n\t\t\tif (!config.api) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"api\" is required when registering streamSimple.`);\n\t\t\t}\n\t\t\tconst streamSimple = config.streamSimple;\n\t\t\tregisterApiProvider({\n\t\t\t\tapi: config.api,\n\t\t\t\tstream: (model, context, options) => streamSimple(model, context, options as SimpleStreamOptions),\n\t\t\t\tstreamSimple,\n\t\t\t});\n\t\t}\n\n\t\t// Store API key for auth resolution\n\t\tif (config.apiKey) {\n\t\t\tthis.customProviderApiKeys.set(providerName, config.apiKey);\n\t\t}\n\n\t\tif (config.models && config.models.length > 0) {\n\t\t\t// Full replacement: remove existing models for this provider\n\t\t\tthis.models = this.models.filter((m) => m.provider !== providerName);\n\n\t\t\t// Validate required fields\n\t\t\tif (!config.baseUrl) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining models.`);\n\t\t\t}\n\t\t\tif (!config.apiKey && !config.oauth) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" or \"oauth\" is required when defining models.`);\n\t\t\t}\n\n\t\t\t// Parse and add new models\n\t\t\tfor (const modelDef of config.models) {\n\t\t\t\tconst api = modelDef.api || config.api;\n\t\t\t\tif (!api) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified.`);\n\t\t\t\t}\n\n\t\t\t\t// Merge headers\n\t\t\t\tconst providerHeaders = resolveHeaders(config.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header\n\t\t\t\tif (config.authHeader && config.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(config.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.models.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\n\t\t\t// Apply OAuth modifyModels if credentials exist (e.g., to update baseUrl)\n\t\t\tif (config.oauth?.modifyModels) {\n\t\t\t\tconst cred = this.authStorage.get(providerName);\n\t\t\t\tif (cred?.type === \"oauth\") {\n\t\t\t\t\tthis.models = config.oauth.modifyModels(this.models, cred);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (config.baseUrl) {\n\t\t\t// Override-only: update baseUrl/headers for existing models\n\t\t\tconst resolvedHeaders = resolveHeaders(config.headers);\n\t\t\tthis.models = this.models.map((m) => {\n\t\t\t\tif (m.provider !== providerName) return m;\n\t\t\t\treturn {\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: config.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * Input type for registerProvider API.\n */\nexport interface ProviderConfigInput {\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\t/** OAuth provider for /login support */\n\toauth?: Omit<OAuthProviderInterface, \"id\">;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\treasoning: boolean;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record<string, string>;\n\t\tcompat?: Model<Api>[\"compat\"];\n\t}>;\n}\n"]}
1
+ {"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAIN,SAAS,EACT,YAAY,EAIZ,mBAAmB,EACnB,qBAAqB,GAErB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAG3C,MAAM,GAAG,GAAI,SAAiB,CAAC,OAAO,IAAI,SAAS,CAAC;AAEpD,4CAA4C;AAC5C,MAAM,uBAAuB,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3C,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC9C,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;CAC/C,CAAC,CAAC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,CAAC;aAAM,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;YAC3B,4DAA4D;YAC5D,MAAM,eAAe,GAAG,cAAc,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACvD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;gBACpC,IAAI,CAAC,CAAC,QAAQ,KAAK,YAAY;oBAAE,OAAO,CAAC,CAAC;gBAC1C,OAAO;oBACN,GAAG,CAAC;oBACJ,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO;oBACpC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,GAAG,eAAe,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO;iBAC3E,CAAC;YAAA,CACF,CAAC,CAAC;QACJ,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Model registry - manages built-in and custom models, provides API key resolution.\n */\n\nimport {\n\ttype Api,\n\ttype AssistantMessageEventStream,\n\ttype Context,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\ttype Model,\n\ttype OAuthProviderInterface,\n\tregisterApiProvider,\n\tregisterOAuthProvider,\n\ttype SimpleStreamOptions,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { execSync } from \"child_process\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport type { AuthStorage } from \"./auth-storage.js\";\n\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenRouter routing preferences\nconst OpenRouterRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for Vercel AI Gateway routing preferences\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresMistralToolIds: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(Type.Union([Type.Literal(\"openai\"), Type.Literal(\"zai\"), Type.Literal(\"qwen\")])),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\t// Reserved for future use\n});\n\nconst OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);\n\n// Schema for custom model definition\n// Most fields are optional with sensible defaults for local models (Ollama, LM Studio, etc.)\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Number(),\n\t\t\toutput: Type.Number(),\n\t\t\tcacheRead: Type.Number(),\n\t\t\tcacheWrite: Type.Number(),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(OpenAICompatSchema),\n});\n\nconst ProviderConfigSchema = Type.Object({\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\n\ntype ModelsConfig = Static<typeof ModelsConfigSchema>;\n\n/** Provider override config (baseUrl, headers, apiKey) without custom models */\ninterface ProviderOverride {\n\tbaseUrl?: string;\n\theaders?: Record<string, string>;\n\tapiKey?: string;\n}\n\n/** Result of loading custom models from models.json */\ninterface CustomModelsResult {\n\tmodels: Model<Api>[];\n\t/** Providers with custom models (full replacement) */\n\treplacedProviders: Set<string>;\n\t/** Providers with only baseUrl/headers override (no custom models) */\n\toverrides: Map<string, ProviderOverride>;\n\terror: string | undefined;\n}\n\nfunction emptyCustomModelsResult(error?: string): CustomModelsResult {\n\treturn { models: [], replacedProviders: new Set(), overrides: new Map(), error };\n}\n\n// Cache for shell command results (persists for process lifetime)\nconst commandResultCache = new Map<string, string | undefined>();\n\n/**\n * Resolve a config value (API key, header value, etc.) to an actual value.\n * - If starts with \"!\", executes the rest as a shell command and uses stdout (cached)\n * - Otherwise checks environment variable first, then treats as literal (not cached)\n */\nfunction resolveConfigValue(config: string): string | undefined {\n\tif (config.startsWith(\"!\")) {\n\t\treturn executeCommand(config);\n\t}\n\tconst envValue = process.env[config];\n\treturn envValue || config;\n}\n\nfunction executeCommand(commandConfig: string): string | undefined {\n\tif (commandResultCache.has(commandConfig)) {\n\t\treturn commandResultCache.get(commandConfig);\n\t}\n\n\tconst command = commandConfig.slice(1);\n\tlet result: string | undefined;\n\ttry {\n\t\tconst output = execSync(command, {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\tresult = output.trim() || undefined;\n\t} catch {\n\t\tresult = undefined;\n\t}\n\n\tcommandResultCache.set(commandConfig, result);\n\treturn result;\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nfunction resolveHeaders(headers: Record<string, string> | undefined): Record<string, string> | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tconst resolvedValue = resolveConfigValue(value);\n\t\tif (resolvedValue) {\n\t\t\tresolved[key] = resolvedValue;\n\t\t}\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\n/** Clear the config value command cache. Exported for testing. */\nexport function clearApiKeyCache(): void {\n\tcommandResultCache.clear();\n}\n\n/**\n * Model registry - loads and manages models, resolves API keys via AuthStorage.\n */\nexport class ModelRegistry {\n\tprivate models: Model<Api>[] = [];\n\tprivate customProviderApiKeys: Map<string, string> = new Map();\n\tprivate registeredProviders: Map<string, ProviderConfigInput> = new Map();\n\tprivate loadError: string | undefined = undefined;\n\n\tconstructor(\n\t\treadonly authStorage: AuthStorage,\n\t\tprivate modelsJsonPath: string | undefined = join(getAgentDir(), \"models.json\"),\n\t) {\n\t\t// Set up fallback resolver for custom provider API keys\n\t\tthis.authStorage.setFallbackResolver((provider) => {\n\t\t\tconst keyConfig = this.customProviderApiKeys.get(provider);\n\t\t\tif (keyConfig) {\n\t\t\t\treturn resolveConfigValue(keyConfig);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t});\n\n\t\t// Load models\n\t\tthis.loadModels();\n\t}\n\n\t/**\n\t * Reload models from disk (built-in + custom from models.json).\n\t */\n\trefresh(): void {\n\t\tthis.customProviderApiKeys.clear();\n\t\tthis.loadError = undefined;\n\t\tthis.loadModels();\n\n\t\tfor (const [providerName, config] of this.registeredProviders.entries()) {\n\t\t\tthis.applyProviderConfig(providerName, config);\n\t\t}\n\t}\n\n\t/**\n\t * Get any error from loading models.json (undefined if no error).\n\t */\n\tgetError(): string | undefined {\n\t\treturn this.loadError;\n\t}\n\n\tprivate loadModels(): void {\n\t\t// Load custom models from models.json first (to know which providers to skip/override)\n\t\tconst {\n\t\t\tmodels: customModels,\n\t\t\treplacedProviders,\n\t\t\toverrides,\n\t\t\terror,\n\t\t} = this.modelsJsonPath ? this.loadCustomModels(this.modelsJsonPath) : emptyCustomModelsResult();\n\n\t\tif (error) {\n\t\t\tthis.loadError = error;\n\t\t\t// Keep built-in models even if custom models failed to load\n\t\t}\n\n\t\tconst builtInModels = this.loadBuiltInModels(replacedProviders, overrides);\n\t\tlet combined = [...builtInModels, ...customModels];\n\n\t\t// Let OAuth providers modify their models (e.g., update baseUrl)\n\t\tfor (const oauthProvider of this.authStorage.getOAuthProviders()) {\n\t\t\tconst cred = this.authStorage.get(oauthProvider.id);\n\t\t\tif (cred?.type === \"oauth\" && oauthProvider.modifyModels) {\n\t\t\t\tcombined = oauthProvider.modifyModels(combined, cred);\n\t\t\t}\n\t\t}\n\n\t\tthis.models = combined;\n\t}\n\n\t/** Load built-in models, skipping replaced providers and applying overrides */\n\tprivate loadBuiltInModels(replacedProviders: Set<string>, overrides: Map<string, ProviderOverride>): Model<Api>[] {\n\t\treturn getProviders()\n\t\t\t.filter((provider) => !replacedProviders.has(provider))\n\t\t\t.flatMap((provider) => {\n\t\t\t\tconst models = getModels(provider as KnownProvider) as Model<Api>[];\n\t\t\t\tconst override = overrides.get(provider);\n\t\t\t\tif (!override) return models;\n\n\t\t\t\t// Apply baseUrl/headers override to all models of this provider\n\t\t\t\tconst resolvedHeaders = resolveHeaders(override.headers);\n\t\t\t\treturn models.map((m) => ({\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: override.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t}));\n\t\t\t});\n\t}\n\n\tprivate loadCustomModels(modelsJsonPath: string): CustomModelsResult {\n\t\tif (!existsSync(modelsJsonPath)) {\n\t\t\treturn emptyCustomModelsResult();\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(modelsJsonPath, \"utf-8\");\n\t\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t\t// Validate schema\n\t\t\tconst ajv = new Ajv();\n\t\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\t\tif (!validate(config)) {\n\t\t\t\tconst errors =\n\t\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\t\"Unknown schema error\";\n\t\t\t\treturn emptyCustomModelsResult(`Invalid models.json schema:\\n${errors}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\n\t\t\t// Additional validation\n\t\t\tthis.validateConfig(config);\n\n\t\t\t// Separate providers into \"full replacement\" (has models) vs \"override-only\" (no models)\n\t\t\tconst replacedProviders = new Set<string>();\n\t\t\tconst overrides = new Map<string, ProviderOverride>();\n\n\t\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\t\tif (providerConfig.models && providerConfig.models.length > 0) {\n\t\t\t\t\t// Has custom models -> full replacement\n\t\t\t\t\treplacedProviders.add(providerName);\n\t\t\t\t} else {\n\t\t\t\t\t// No models -> just override baseUrl/headers on built-in\n\t\t\t\t\toverrides.set(providerName, {\n\t\t\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\t\t\theaders: providerConfig.headers,\n\t\t\t\t\t\tapiKey: providerConfig.apiKey,\n\t\t\t\t\t});\n\t\t\t\t\t// Store API key for fallback resolver\n\t\t\t\t\tif (providerConfig.apiKey) {\n\t\t\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { models: this.parseModels(config), replacedProviders, overrides, error: undefined };\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\treturn emptyCustomModelsResult(`Failed to parse models.json: ${error.message}\\n\\nFile: ${modelsJsonPath}`);\n\t\t\t}\n\t\t\treturn emptyCustomModelsResult(\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${modelsJsonPath}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate validateConfig(config: ModelsConfig): void {\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst hasProviderApi = !!providerConfig.api;\n\t\t\tconst models = providerConfig.models ?? [];\n\n\t\t\tif (models.length === 0) {\n\t\t\t\t// Override-only config: just needs baseUrl (to override built-in)\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}: must specify either \"baseUrl\" (for override) or \"models\" (for replacement).`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Full replacement: needs baseUrl and apiKey\n\t\t\t\tif (!providerConfig.baseUrl) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t\tif (!providerConfig.apiKey) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" is required when defining custom models.`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const modelDef of models) {\n\t\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\t\t// Validate contextWindow/maxTokens only if provided (they have defaults)\n\t\t\t\tif (modelDef.contextWindow !== undefined && modelDef.contextWindow <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\t\tif (modelDef.maxTokens !== undefined && modelDef.maxTokens <= 0)\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate parseModels(config: ModelsConfig): Model<Api>[] {\n\t\tconst models: Model<Api>[] = [];\n\n\t\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t\tconst modelDefs = providerConfig.models ?? [];\n\t\t\tif (modelDefs.length === 0) continue; // Override-only, no custom models\n\n\t\t\t// Store API key config for fallback resolver\n\t\t\tif (providerConfig.apiKey) {\n\t\t\t\tthis.customProviderApiKeys.set(providerName, providerConfig.apiKey);\n\t\t\t}\n\n\t\t\tfor (const modelDef of modelDefs) {\n\t\t\t\tconst api = modelDef.api || providerConfig.api;\n\t\t\t\tif (!api) continue;\n\n\t\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\t\t// Resolve env vars and shell commands in header values\n\t\t\t\tconst providerHeaders = resolveHeaders(providerConfig.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\t\tif (providerConfig.authHeader && providerConfig.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(providerConfig.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// baseUrl is validated to exist for providers with models\n\t\t\t\t// Apply defaults for optional fields\n\t\t\t\tconst defaultCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n\t\t\t\tmodels.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name ?? modelDef.id,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: providerConfig.baseUrl!,\n\t\t\t\t\treasoning: modelDef.reasoning ?? false,\n\t\t\t\t\tinput: (modelDef.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost ?? defaultCost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow ?? 128000,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens ?? 16384,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\t\t}\n\n\t\treturn models;\n\t}\n\n\t/**\n\t * Get all models (built-in + custom).\n\t * If models.json had errors, returns only built-in models.\n\t */\n\tgetAll(): Model<Api>[] {\n\t\treturn this.models;\n\t}\n\n\t/**\n\t * Get only models that have auth configured.\n\t * This is a fast check that doesn't refresh OAuth tokens.\n\t */\n\tgetAvailable(): Model<Api>[] {\n\t\treturn this.models.filter((m) => this.authStorage.hasAuth(m.provider));\n\t}\n\n\t/**\n\t * Find a model by provider and ID.\n\t */\n\tfind(provider: string, modelId: string): Model<Api> | undefined {\n\t\treturn this.models.find((m) => m.provider === provider && m.id === modelId);\n\t}\n\n\t/**\n\t * Get API key for a model.\n\t */\n\tasync getApiKey(model: Model<Api>): Promise<string | undefined> {\n\t\treturn this.authStorage.getApiKey(model.provider);\n\t}\n\n\t/**\n\t * Get API key for a provider.\n\t */\n\tasync getApiKeyForProvider(provider: string): Promise<string | undefined> {\n\t\treturn this.authStorage.getApiKey(provider);\n\t}\n\n\t/**\n\t * Check if a model is using OAuth credentials (subscription).\n\t */\n\tisUsingOAuth(model: Model<Api>): boolean {\n\t\tconst cred = this.authStorage.get(model.provider);\n\t\treturn cred?.type === \"oauth\";\n\t}\n\n\t/**\n\t * Register a provider dynamically (from extensions).\n\t *\n\t * If provider has models: replaces all existing models for this provider.\n\t * If provider has only baseUrl/headers: overrides existing models' URLs.\n\t * If provider has oauth: registers OAuth provider for /login support.\n\t */\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void {\n\t\tthis.registeredProviders.set(providerName, config);\n\t\tthis.applyProviderConfig(providerName, config);\n\t}\n\n\tprivate applyProviderConfig(providerName: string, config: ProviderConfigInput): void {\n\t\t// Register OAuth provider if provided\n\t\tif (config.oauth) {\n\t\t\t// Ensure the OAuth provider ID matches the provider name\n\t\t\tconst oauthProvider: OAuthProviderInterface = {\n\t\t\t\t...config.oauth,\n\t\t\t\tid: providerName,\n\t\t\t};\n\t\t\tregisterOAuthProvider(oauthProvider);\n\t\t}\n\n\t\tif (config.streamSimple) {\n\t\t\tif (!config.api) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"api\" is required when registering streamSimple.`);\n\t\t\t}\n\t\t\tconst streamSimple = config.streamSimple;\n\t\t\tregisterApiProvider({\n\t\t\t\tapi: config.api,\n\t\t\t\tstream: (model, context, options) => streamSimple(model, context, options as SimpleStreamOptions),\n\t\t\t\tstreamSimple,\n\t\t\t});\n\t\t}\n\n\t\t// Store API key for auth resolution\n\t\tif (config.apiKey) {\n\t\t\tthis.customProviderApiKeys.set(providerName, config.apiKey);\n\t\t}\n\n\t\tif (config.models && config.models.length > 0) {\n\t\t\t// Full replacement: remove existing models for this provider\n\t\t\tthis.models = this.models.filter((m) => m.provider !== providerName);\n\n\t\t\t// Validate required fields\n\t\t\tif (!config.baseUrl) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"baseUrl\" is required when defining models.`);\n\t\t\t}\n\t\t\tif (!config.apiKey && !config.oauth) {\n\t\t\t\tthrow new Error(`Provider ${providerName}: \"apiKey\" or \"oauth\" is required when defining models.`);\n\t\t\t}\n\n\t\t\t// Parse and add new models\n\t\t\tfor (const modelDef of config.models) {\n\t\t\t\tconst api = modelDef.api || config.api;\n\t\t\t\tif (!api) {\n\t\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified.`);\n\t\t\t\t}\n\n\t\t\t\t// Merge headers\n\t\t\t\tconst providerHeaders = resolveHeaders(config.headers);\n\t\t\t\tconst modelHeaders = resolveHeaders(modelDef.headers);\n\t\t\t\tlet headers = providerHeaders || modelHeaders ? { ...providerHeaders, ...modelHeaders } : undefined;\n\n\t\t\t\t// If authHeader is true, add Authorization header\n\t\t\t\tif (config.authHeader && config.apiKey) {\n\t\t\t\t\tconst resolvedKey = resolveConfigValue(config.apiKey);\n\t\t\t\t\tif (resolvedKey) {\n\t\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.models.push({\n\t\t\t\t\tid: modelDef.id,\n\t\t\t\t\tname: modelDef.name,\n\t\t\t\t\tapi: api as Api,\n\t\t\t\t\tprovider: providerName,\n\t\t\t\t\tbaseUrl: config.baseUrl,\n\t\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\t\tcost: modelDef.cost,\n\t\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\t\theaders,\n\t\t\t\t\tcompat: modelDef.compat,\n\t\t\t\t} as Model<Api>);\n\t\t\t}\n\n\t\t\t// Apply OAuth modifyModels if credentials exist (e.g., to update baseUrl)\n\t\t\tif (config.oauth?.modifyModels) {\n\t\t\t\tconst cred = this.authStorage.get(providerName);\n\t\t\t\tif (cred?.type === \"oauth\") {\n\t\t\t\t\tthis.models = config.oauth.modifyModels(this.models, cred);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (config.baseUrl) {\n\t\t\t// Override-only: update baseUrl/headers for existing models\n\t\t\tconst resolvedHeaders = resolveHeaders(config.headers);\n\t\t\tthis.models = this.models.map((m) => {\n\t\t\t\tif (m.provider !== providerName) return m;\n\t\t\t\treturn {\n\t\t\t\t\t...m,\n\t\t\t\t\tbaseUrl: config.baseUrl ?? m.baseUrl,\n\t\t\t\t\theaders: resolvedHeaders ? { ...m.headers, ...resolvedHeaders } : m.headers,\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * Input type for registerProvider API.\n */\nexport interface ProviderConfigInput {\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model<Api>, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record<string, string>;\n\tauthHeader?: boolean;\n\t/** OAuth provider for /login support */\n\toauth?: Omit<OAuthProviderInterface, \"id\">;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\treasoning: boolean;\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number };\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record<string, string>;\n\t\tcompat?: Model<Api>[\"compat\"];\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;IAC7B,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,MAAM,EAAE,gBAAgB,EAAE,CAAC;IAC3B,OAAO,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IAiBlB,OAAO,CAAC,cAAc;CAOtB","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 { looksLikeGitUrl } 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\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 GitSource = {\n\ttype: \"git\";\n\trepo: string;\n\thost: string;\n\tpath: string;\n\tref?: 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 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\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\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 path = this.resolvePath(parsed.path);\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\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\tthrow new Error(`Unsupported remove source: ${source}`);\n\t\t});\n\t}\n\n\tasync update(source?: string): Promise<void> {\n\t\tif (source) {\n\t\t\tawait this.updateSourceForScope(source, \"user\");\n\t\t\tawait this.updateSourceForScope(source, \"project\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tfor (const extension of globalSettings.extensions ?? []) {\n\t\t\tawait this.updateSourceForScope(extension, \"user\");\n\t\t}\n\t\tfor (const extension of projectSettings.extensions ?? []) {\n\t\t\tawait this.updateSourceForScope(extension, \"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\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata);\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}\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): void {\n\t\tconst resolved = this.resolvePath(source.path);\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 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\tif (source.startsWith(\"git:\") || looksLikeGitUrl(source)) {\n\t\t\tconst repoSpec = source.startsWith(\"git:\") ? source.slice(\"git:\".length).trim() : source;\n\t\t\tconst [repo, ref] = repoSpec.split(\"@\");\n\t\t\tconst normalized = repo.replace(/^https?:\\/\\//, \"\").replace(/\\.git$/, \"\");\n\t\t\tconst parts = normalized.split(\"/\");\n\t\t\tconst host = parts.shift() ?? \"\";\n\t\t\tconst repoPath = parts.join(\"/\");\n\t\t\treturn {\n\t\t\t\ttype: \"git\",\n\t\t\t\trepo: normalized,\n\t\t\t\thost,\n\t\t\t\tpath: repoPath,\n\t\t\t\tref,\n\t\t\t\tpinned: Boolean(ref),\n\t\t\t};\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 */\n\tprivate getPackageIdentity(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.repo}`;\n\t\t}\n\t\t// For local paths, use the absolute resolved path\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);\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\t\tconst cloneUrl = source.repo.startsWith(\"http\") ? source.repo : `https://${source.repo}`;\n\t\tawait this.runCommand(\"git\", [\"clone\", cloneUrl, 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 upstream tracking branch (handles force-push gracefully)\n\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"@{upstream}\"], { cwd: targetDir });\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 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 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\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\tcollectAutoSkillEntries(userDirs.skills),\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\tcollectAutoSkillEntries(projectDirs.skills),\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});\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, { stdio: [\"ignore\", \"pipe\", \"pipe\"], encoding: \"utf-8\" });\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;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAA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3B,OAAO,CAAC,0BAA0B;IAuHlC,OAAO,CAAC,qBAAqB;IAmB7B,OAAO,CAAC,YAAY;IAkBpB,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,UAAU;IAiBlB,OAAO,CAAC,cAAc;CAOtB","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 { looksLikeGitUrl } 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\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 GitSource = {\n\ttype: \"git\";\n\trepo: string;\n\thost: string;\n\tpath: string;\n\tref?: 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 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\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\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 path = this.resolvePath(parsed.path);\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\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\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) !== 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) !== 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\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata);\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}\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): void {\n\t\tconst resolved = this.resolvePath(source.path);\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 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\tif (source.startsWith(\"git:\") || looksLikeGitUrl(source)) {\n\t\t\tconst repoSpec = source.startsWith(\"git:\") ? source.slice(\"git:\".length).trim() : source;\n\t\t\tconst [repo, ref] = repoSpec.split(\"@\");\n\t\t\tconst normalized = repo.replace(/^https?:\\/\\//, \"\").replace(/\\.git$/, \"\");\n\t\t\tconst parts = normalized.split(\"/\");\n\t\t\tconst host = parts.shift() ?? \"\";\n\t\t\tconst repoPath = parts.join(\"/\");\n\t\t\treturn {\n\t\t\t\ttype: \"git\",\n\t\t\t\trepo: normalized,\n\t\t\t\thost,\n\t\t\t\tpath: repoPath,\n\t\t\t\tref,\n\t\t\t\tpinned: Boolean(ref),\n\t\t\t};\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 */\n\tprivate getPackageIdentity(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.repo}`;\n\t\t}\n\t\t// For local paths, use the absolute resolved path\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);\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\t\tconst cloneUrl = source.repo.startsWith(\"http\") ? source.repo : `https://${source.repo}`;\n\t\tawait this.runCommand(\"git\", [\"clone\", cloneUrl, 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 upstream tracking branch (handles force-push gracefully)\n\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", \"@{upstream}\"], { cwd: targetDir });\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 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 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\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\tcollectAutoSkillEntries(userDirs.skills),\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\tcollectAutoSkillEntries(projectDirs.skills),\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});\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, { stdio: [\"ignore\", \"pipe\", \"pipe\"], encoding: \"utf-8\" });\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"]}
@@ -569,18 +569,20 @@ export class DefaultPackageManager {
569
569
  });
570
570
  }
571
571
  async update(source) {
572
- if (source) {
573
- await this.updateSourceForScope(source, "user");
574
- await this.updateSourceForScope(source, "project");
575
- return;
576
- }
577
572
  const globalSettings = this.settingsManager.getGlobalSettings();
578
573
  const projectSettings = this.settingsManager.getProjectSettings();
579
- for (const extension of globalSettings.extensions ?? []) {
580
- await this.updateSourceForScope(extension, "user");
574
+ const identity = source ? this.getPackageIdentity(source) : undefined;
575
+ for (const pkg of globalSettings.packages ?? []) {
576
+ const sourceStr = typeof pkg === "string" ? pkg : pkg.source;
577
+ if (identity && this.getPackageIdentity(sourceStr) !== identity)
578
+ continue;
579
+ await this.updateSourceForScope(sourceStr, "user");
581
580
  }
582
- for (const extension of projectSettings.extensions ?? []) {
583
- await this.updateSourceForScope(extension, "project");
581
+ for (const pkg of projectSettings.packages ?? []) {
582
+ const sourceStr = typeof pkg === "string" ? pkg : pkg.source;
583
+ if (identity && this.getPackageIdentity(sourceStr) !== identity)
584
+ continue;
585
+ await this.updateSourceForScope(sourceStr, "project");
584
586
  }
585
587
  }
586
588
  async updateSourceForScope(source, scope) {