@mariozechner/pi-coding-agent 0.25.4 → 0.26.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 (83) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +47 -5
  3. package/dist/cli/session-picker.d.ts +2 -2
  4. package/dist/cli/session-picker.d.ts.map +1 -1
  5. package/dist/cli/session-picker.js +2 -2
  6. package/dist/cli/session-picker.js.map +1 -1
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +1 -13
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/custom-tools/loader.d.ts +3 -2
  11. package/dist/core/custom-tools/loader.d.ts.map +1 -1
  12. package/dist/core/custom-tools/loader.js +5 -4
  13. package/dist/core/custom-tools/loader.js.map +1 -1
  14. package/dist/core/hooks/loader.d.ts +2 -5
  15. package/dist/core/hooks/loader.d.ts.map +1 -1
  16. package/dist/core/hooks/loader.js +4 -7
  17. package/dist/core/hooks/loader.js.map +1 -1
  18. package/dist/core/model-config.d.ts +5 -4
  19. package/dist/core/model-config.d.ts.map +1 -1
  20. package/dist/core/model-config.js +12 -19
  21. package/dist/core/model-config.js.map +1 -1
  22. package/dist/core/sdk.d.ts +211 -0
  23. package/dist/core/sdk.d.ts.map +1 -0
  24. package/dist/core/sdk.js +462 -0
  25. package/dist/core/sdk.js.map +1 -0
  26. package/dist/core/session-manager.d.ts +31 -91
  27. package/dist/core/session-manager.d.ts.map +1 -1
  28. package/dist/core/session-manager.js +187 -352
  29. package/dist/core/session-manager.js.map +1 -1
  30. package/dist/core/settings-manager.d.ts +12 -2
  31. package/dist/core/settings-manager.d.ts.map +1 -1
  32. package/dist/core/settings-manager.js +101 -37
  33. package/dist/core/settings-manager.js.map +1 -1
  34. package/dist/core/skills.d.ts +7 -1
  35. package/dist/core/skills.d.ts.map +1 -1
  36. package/dist/core/skills.js +7 -5
  37. package/dist/core/skills.js.map +1 -1
  38. package/dist/core/slash-commands.d.ts +9 -3
  39. package/dist/core/slash-commands.d.ts.map +1 -1
  40. package/dist/core/slash-commands.js +10 -7
  41. package/dist/core/slash-commands.js.map +1 -1
  42. package/dist/core/system-prompt.d.ts +24 -2
  43. package/dist/core/system-prompt.d.ts.map +1 -1
  44. package/dist/core/system-prompt.js +18 -16
  45. package/dist/core/system-prompt.js.map +1 -1
  46. package/dist/core/tools/index.d.ts +12 -22
  47. package/dist/core/tools/index.d.ts.map +1 -1
  48. package/dist/core/tools/index.js +2 -0
  49. package/dist/core/tools/index.js.map +1 -1
  50. package/dist/index.d.ts +2 -1
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +12 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/main.d.ts +4 -1
  55. package/dist/main.d.ts.map +1 -1
  56. package/dist/main.js +142 -312
  57. package/dist/main.js.map +1 -1
  58. package/dist/modes/interactive/components/session-selector.d.ts +3 -12
  59. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  60. package/dist/modes/interactive/components/session-selector.js +1 -3
  61. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  62. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  63. package/dist/modes/interactive/interactive-mode.js +3 -2
  64. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  65. package/dist/utils/shell.d.ts.map +1 -1
  66. package/dist/utils/shell.js +1 -1
  67. package/dist/utils/shell.js.map +1 -1
  68. package/docs/sdk.md +819 -0
  69. package/examples/README.md +29 -0
  70. package/examples/sdk/01-minimal.ts +22 -0
  71. package/examples/sdk/02-custom-model.ts +36 -0
  72. package/examples/sdk/03-custom-prompt.ts +44 -0
  73. package/examples/sdk/04-skills.ts +44 -0
  74. package/examples/sdk/05-tools.ts +67 -0
  75. package/examples/sdk/06-hooks.ts +61 -0
  76. package/examples/sdk/07-context-files.ts +36 -0
  77. package/examples/sdk/08-slash-commands.ts +37 -0
  78. package/examples/sdk/09-api-keys-and-oauth.ts +45 -0
  79. package/examples/sdk/10-settings.ts +38 -0
  80. package/examples/sdk/11-sessions.ts +46 -0
  81. package/examples/sdk/12-full-control.ts +91 -0
  82. package/examples/sdk/README.md +138 -0
  83. package/package.json +4 -4
@@ -43,14 +43,11 @@ export interface LoadHooksResult {
43
43
  export declare function loadHooks(paths: string[], cwd: string): Promise<LoadHooksResult>;
44
44
  /**
45
45
  * Discover and load hooks from standard locations:
46
- * 1. ~/.pi/agent/hooks/*.ts (global)
46
+ * 1. agentDir/hooks/*.ts (global)
47
47
  * 2. cwd/.pi/hooks/*.ts (project-local)
48
48
  *
49
49
  * Plus any explicitly configured paths from settings.
50
- *
51
- * @param configuredPaths - Explicit paths from settings.json
52
- * @param cwd - Current working directory
53
50
  */
54
- export declare function discoverAndLoadHooks(configuredPaths: string[], cwd: string): Promise<LoadHooksResult>;
51
+ export declare function discoverAndLoadHooks(configuredPaths: string[], cwd: string, agentDir?: string): Promise<LoadHooksResult>;
55
52
  export {};
56
53
  //# sourceMappingURL=loader.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/hooks/loader.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AA0B9D;;GAEG;AACH,KAAK,SAAS,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAE1D;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,UAAU,EAAE,KAAK,IAAI,CAAC;AAE7E;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,6CAA6C;IAC7C,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IACnC,qDAAqD;IACrD,cAAc,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,CAAC;CAC/C;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC/B,gCAAgC;IAChC,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,wCAAwC;IACxC,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/C;AA0GD;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAkBtF;AAqBD;;;;;;;;;GASG;AACH,wBAAsB,oBAAoB,CAAC,eAAe,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CA2B3G","sourcesContent":["/**\n * Hook loader - loads TypeScript hook modules using jiti.\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Attachment } from \"@mariozechner/pi-agent-core\";\nimport { createJiti } from \"jiti\";\nimport { getAgentDir } from \"../../config.js\";\nimport type { HookAPI, HookFactory } from \"./types.js\";\n\n// Create require function to resolve module paths at runtime\nconst require = createRequire(import.meta.url);\n\n// Lazily computed aliases - resolved at runtime to handle global installs\nlet _aliases: Record<string, string> | null = null;\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\t_aliases = {\n\t\t\"@mariozechner/pi-coding-agent\": packageIndex,\n\t\t\"@mariozechner/pi-coding-agent/hooks\": path.resolve(__dirname, \"index.js\"),\n\t\t\"@mariozechner/pi-tui\": require.resolve(\"@mariozechner/pi-tui\"),\n\t\t\"@mariozechner/pi-ai\": require.resolve(\"@mariozechner/pi-ai\"),\n\t\t\"@sinclair/typebox\": require.resolve(\"@sinclair/typebox\"),\n\t};\n\treturn _aliases;\n}\n\n/**\n * Generic handler function type.\n */\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Send handler type for pi.send().\n */\nexport type SendHandler = (text: string, attachments?: Attachment[]) => void;\n\n/**\n * Registered handlers for a loaded hook.\n */\nexport interface LoadedHook {\n\t/** Original path from config */\n\tpath: string;\n\t/** Resolved absolute path */\n\tresolvedPath: string;\n\t/** Map of event type to handler functions */\n\thandlers: Map<string, HandlerFn[]>;\n\t/** Set the send handler for this hook's pi.send() */\n\tsetSendHandler: (handler: SendHandler) => void;\n}\n\n/**\n * Result of loading hooks.\n */\nexport interface LoadHooksResult {\n\t/** Successfully loaded hooks */\n\thooks: LoadedHook[];\n\t/** Errors encountered during loading */\n\terrors: Array<{ path: string; error: string }>;\n}\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nfunction normalizeUnicodeSpaces(str: string): string {\n\treturn str.replace(UNICODE_SPACES, \" \");\n}\n\nfunction expandPath(p: string): string {\n\tconst normalized = normalizeUnicodeSpaces(p);\n\tif (normalized.startsWith(\"~/\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(2));\n\t}\n\tif (normalized.startsWith(\"~\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(1));\n\t}\n\treturn normalized;\n}\n\n/**\n * Resolve hook path.\n * - Absolute paths used as-is\n * - Paths starting with ~ expanded to home directory\n * - Relative paths resolved from cwd\n */\nfunction resolveHookPath(hookPath: string, cwd: string): string {\n\tconst expanded = expandPath(hookPath);\n\n\tif (path.isAbsolute(expanded)) {\n\t\treturn expanded;\n\t}\n\n\t// Relative paths resolved from cwd\n\treturn path.resolve(cwd, expanded);\n}\n\n/**\n * Create a HookAPI instance that collects handlers.\n * Returns the API and a function to set the send handler later.\n */\nfunction createHookAPI(handlers: Map<string, HandlerFn[]>): {\n\tapi: HookAPI;\n\tsetSendHandler: (handler: SendHandler) => void;\n} {\n\tlet sendHandler: SendHandler = () => {\n\t\t// Default no-op until mode sets the handler\n\t};\n\n\tconst api: HookAPI = {\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\tconst list = handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\thandlers.set(event, list);\n\t\t},\n\t\tsend(text: string, attachments?: Attachment[]): void {\n\t\t\tsendHandler(text, attachments);\n\t\t},\n\t} as HookAPI;\n\n\treturn {\n\t\tapi,\n\t\tsetSendHandler: (handler: SendHandler) => {\n\t\t\tsendHandler = handler;\n\t\t},\n\t};\n}\n\n/**\n * Load a single hook module using jiti.\n */\nasync function loadHook(hookPath: string, cwd: string): Promise<{ hook: LoadedHook | null; error: string | null }> {\n\tconst resolvedPath = resolveHookPath(hookPath, cwd);\n\n\ttry {\n\t\t// Create jiti instance for TypeScript/ESM loading\n\t\t// Use aliases to resolve package imports since hooks are loaded from user directories\n\t\t// (e.g. ~/.pi/agent/hooks) but import from packages installed with pi-coding-agent\n\t\tconst jiti = createJiti(import.meta.url, {\n\t\t\talias: getAliases(),\n\t\t});\n\n\t\t// Import the module\n\t\tconst module = await jiti.import(resolvedPath, { default: true });\n\t\tconst factory = module as HookFactory;\n\n\t\tif (typeof factory !== \"function\") {\n\t\t\treturn { hook: null, error: \"Hook must export a default function\" };\n\t\t}\n\n\t\t// Create handlers map and API\n\t\tconst handlers = new Map<string, HandlerFn[]>();\n\t\tconst { api, setSendHandler } = createHookAPI(handlers);\n\n\t\t// Call factory to register handlers\n\t\tfactory(api);\n\n\t\treturn {\n\t\t\thook: { path: hookPath, resolvedPath, handlers, setSendHandler },\n\t\t\terror: null,\n\t\t};\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { hook: null, error: `Failed to load hook: ${message}` };\n\t}\n}\n\n/**\n * Load all hooks from configuration.\n * @param paths - Array of hook file paths\n * @param cwd - Current working directory for resolving relative paths\n */\nexport async function loadHooks(paths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst hooks: LoadedHook[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const hookPath of paths) {\n\t\tconst { hook, error } = await loadHook(hookPath, cwd);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: hookPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (hook) {\n\t\t\thooks.push(hook);\n\t\t}\n\t}\n\n\treturn { hooks, errors };\n}\n\n/**\n * Discover hook files from a directory.\n * Returns all .ts files (and symlinks to .ts files) in the directory (non-recursive).\n */\nfunction discoverHooksInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\t\treturn entries\n\t\t\t.filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(\".ts\"))\n\t\t\t.map((e) => path.join(dir, e.name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Discover and load hooks from standard locations:\n * 1. ~/.pi/agent/hooks/*.ts (global)\n * 2. cwd/.pi/hooks/*.ts (project-local)\n *\n * Plus any explicitly configured paths from settings.\n *\n * @param configuredPaths - Explicit paths from settings.json\n * @param cwd - Current working directory\n */\nexport async function discoverAndLoadHooks(configuredPaths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\t// Helper to add paths without duplicates\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Global hooks: ~/.pi/agent/hooks/\n\tconst globalHooksDir = path.join(getAgentDir(), \"hooks\");\n\taddPaths(discoverHooksInDir(globalHooksDir));\n\n\t// 2. Project-local hooks: cwd/.pi/hooks/\n\tconst localHooksDir = path.join(cwd, \".pi\", \"hooks\");\n\taddPaths(discoverHooksInDir(localHooksDir));\n\n\t// 3. Explicitly configured paths (can override/add)\n\taddPaths(configuredPaths.map((p) => resolveHookPath(p, cwd)));\n\n\treturn loadHooks(allPaths, cwd);\n}\n"]}
1
+ {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/hooks/loader.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AA0B9D;;GAEG;AACH,KAAK,SAAS,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAE1D;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,UAAU,EAAE,KAAK,IAAI,CAAC;AAE7E;;GAEG;AACH,MAAM,WAAW,UAAU;IAC1B,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,6CAA6C;IAC7C,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IACnC,qDAAqD;IACrD,cAAc,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,CAAC;CAC/C;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC/B,gCAAgC;IAChC,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,wCAAwC;IACxC,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC/C;AA0GD;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAkBtF;AAqBD;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACzC,eAAe,EAAE,MAAM,EAAE,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAsB,GAC9B,OAAO,CAAC,eAAe,CAAC,CA2B1B","sourcesContent":["/**\n * Hook loader - loads TypeScript hook modules using jiti.\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Attachment } from \"@mariozechner/pi-agent-core\";\nimport { createJiti } from \"jiti\";\nimport { getAgentDir } from \"../../config.js\";\nimport type { HookAPI, HookFactory } from \"./types.js\";\n\n// Create require function to resolve module paths at runtime\nconst require = createRequire(import.meta.url);\n\n// Lazily computed aliases - resolved at runtime to handle global installs\nlet _aliases: Record<string, string> | null = null;\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\t_aliases = {\n\t\t\"@mariozechner/pi-coding-agent\": packageIndex,\n\t\t\"@mariozechner/pi-coding-agent/hooks\": path.resolve(__dirname, \"index.js\"),\n\t\t\"@mariozechner/pi-tui\": require.resolve(\"@mariozechner/pi-tui\"),\n\t\t\"@mariozechner/pi-ai\": require.resolve(\"@mariozechner/pi-ai\"),\n\t\t\"@sinclair/typebox\": require.resolve(\"@sinclair/typebox\"),\n\t};\n\treturn _aliases;\n}\n\n/**\n * Generic handler function type.\n */\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Send handler type for pi.send().\n */\nexport type SendHandler = (text: string, attachments?: Attachment[]) => void;\n\n/**\n * Registered handlers for a loaded hook.\n */\nexport interface LoadedHook {\n\t/** Original path from config */\n\tpath: string;\n\t/** Resolved absolute path */\n\tresolvedPath: string;\n\t/** Map of event type to handler functions */\n\thandlers: Map<string, HandlerFn[]>;\n\t/** Set the send handler for this hook's pi.send() */\n\tsetSendHandler: (handler: SendHandler) => void;\n}\n\n/**\n * Result of loading hooks.\n */\nexport interface LoadHooksResult {\n\t/** Successfully loaded hooks */\n\thooks: LoadedHook[];\n\t/** Errors encountered during loading */\n\terrors: Array<{ path: string; error: string }>;\n}\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nfunction normalizeUnicodeSpaces(str: string): string {\n\treturn str.replace(UNICODE_SPACES, \" \");\n}\n\nfunction expandPath(p: string): string {\n\tconst normalized = normalizeUnicodeSpaces(p);\n\tif (normalized.startsWith(\"~/\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(2));\n\t}\n\tif (normalized.startsWith(\"~\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(1));\n\t}\n\treturn normalized;\n}\n\n/**\n * Resolve hook path.\n * - Absolute paths used as-is\n * - Paths starting with ~ expanded to home directory\n * - Relative paths resolved from cwd\n */\nfunction resolveHookPath(hookPath: string, cwd: string): string {\n\tconst expanded = expandPath(hookPath);\n\n\tif (path.isAbsolute(expanded)) {\n\t\treturn expanded;\n\t}\n\n\t// Relative paths resolved from cwd\n\treturn path.resolve(cwd, expanded);\n}\n\n/**\n * Create a HookAPI instance that collects handlers.\n * Returns the API and a function to set the send handler later.\n */\nfunction createHookAPI(handlers: Map<string, HandlerFn[]>): {\n\tapi: HookAPI;\n\tsetSendHandler: (handler: SendHandler) => void;\n} {\n\tlet sendHandler: SendHandler = () => {\n\t\t// Default no-op until mode sets the handler\n\t};\n\n\tconst api: HookAPI = {\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\tconst list = handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\thandlers.set(event, list);\n\t\t},\n\t\tsend(text: string, attachments?: Attachment[]): void {\n\t\t\tsendHandler(text, attachments);\n\t\t},\n\t} as HookAPI;\n\n\treturn {\n\t\tapi,\n\t\tsetSendHandler: (handler: SendHandler) => {\n\t\t\tsendHandler = handler;\n\t\t},\n\t};\n}\n\n/**\n * Load a single hook module using jiti.\n */\nasync function loadHook(hookPath: string, cwd: string): Promise<{ hook: LoadedHook | null; error: string | null }> {\n\tconst resolvedPath = resolveHookPath(hookPath, cwd);\n\n\ttry {\n\t\t// Create jiti instance for TypeScript/ESM loading\n\t\t// Use aliases to resolve package imports since hooks are loaded from user directories\n\t\t// (e.g. ~/.pi/agent/hooks) but import from packages installed with pi-coding-agent\n\t\tconst jiti = createJiti(import.meta.url, {\n\t\t\talias: getAliases(),\n\t\t});\n\n\t\t// Import the module\n\t\tconst module = await jiti.import(resolvedPath, { default: true });\n\t\tconst factory = module as HookFactory;\n\n\t\tif (typeof factory !== \"function\") {\n\t\t\treturn { hook: null, error: \"Hook must export a default function\" };\n\t\t}\n\n\t\t// Create handlers map and API\n\t\tconst handlers = new Map<string, HandlerFn[]>();\n\t\tconst { api, setSendHandler } = createHookAPI(handlers);\n\n\t\t// Call factory to register handlers\n\t\tfactory(api);\n\n\t\treturn {\n\t\t\thook: { path: hookPath, resolvedPath, handlers, setSendHandler },\n\t\t\terror: null,\n\t\t};\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { hook: null, error: `Failed to load hook: ${message}` };\n\t}\n}\n\n/**\n * Load all hooks from configuration.\n * @param paths - Array of hook file paths\n * @param cwd - Current working directory for resolving relative paths\n */\nexport async function loadHooks(paths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst hooks: LoadedHook[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const hookPath of paths) {\n\t\tconst { hook, error } = await loadHook(hookPath, cwd);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: hookPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (hook) {\n\t\t\thooks.push(hook);\n\t\t}\n\t}\n\n\treturn { hooks, errors };\n}\n\n/**\n * Discover hook files from a directory.\n * Returns all .ts files (and symlinks to .ts files) in the directory (non-recursive).\n */\nfunction discoverHooksInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\t\treturn entries\n\t\t\t.filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(\".ts\"))\n\t\t\t.map((e) => path.join(dir, e.name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Discover and load hooks from standard locations:\n * 1. agentDir/hooks/*.ts (global)\n * 2. cwd/.pi/hooks/*.ts (project-local)\n *\n * Plus any explicitly configured paths from settings.\n */\nexport async function discoverAndLoadHooks(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n): Promise<LoadHooksResult> {\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\t// Helper to add paths without duplicates\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Global hooks: agentDir/hooks/\n\tconst globalHooksDir = path.join(agentDir, \"hooks\");\n\taddPaths(discoverHooksInDir(globalHooksDir));\n\n\t// 2. Project-local hooks: cwd/.pi/hooks/\n\tconst localHooksDir = path.join(cwd, \".pi\", \"hooks\");\n\taddPaths(discoverHooksInDir(localHooksDir));\n\n\t// 3. Explicitly configured paths (can override/add)\n\taddPaths(configuredPaths.map((p) => resolveHookPath(p, cwd)));\n\n\treturn loadHooks(allPaths, cwd);\n}\n"]}
@@ -152,15 +152,12 @@ function discoverHooksInDir(dir) {
152
152
  }
153
153
  /**
154
154
  * Discover and load hooks from standard locations:
155
- * 1. ~/.pi/agent/hooks/*.ts (global)
155
+ * 1. agentDir/hooks/*.ts (global)
156
156
  * 2. cwd/.pi/hooks/*.ts (project-local)
157
157
  *
158
158
  * Plus any explicitly configured paths from settings.
159
- *
160
- * @param configuredPaths - Explicit paths from settings.json
161
- * @param cwd - Current working directory
162
159
  */
163
- export async function discoverAndLoadHooks(configuredPaths, cwd) {
160
+ export async function discoverAndLoadHooks(configuredPaths, cwd, agentDir = getAgentDir()) {
164
161
  const allPaths = [];
165
162
  const seen = new Set();
166
163
  // Helper to add paths without duplicates
@@ -173,8 +170,8 @@ export async function discoverAndLoadHooks(configuredPaths, cwd) {
173
170
  }
174
171
  }
175
172
  };
176
- // 1. Global hooks: ~/.pi/agent/hooks/
177
- const globalHooksDir = path.join(getAgentDir(), "hooks");
173
+ // 1. Global hooks: agentDir/hooks/
174
+ const globalHooksDir = path.join(agentDir, "hooks");
178
175
  addPaths(discoverHooksInDir(globalHooksDir));
179
176
  // 2. Project-local hooks: cwd/.pi/hooks/
180
177
  const localHooksDir = path.join(cwd, ".pi", "hooks");
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sourceRoot":"","sources":["../../../src/core/hooks/loader.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,6DAA6D;AAC7D,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAE/C,0EAA0E;AAC1E,IAAI,QAAQ,GAAkC,IAAI,CAAC;AACnD,SAAS,UAAU,GAA2B;IAC7C,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAE9B,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,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AAC,CAAC,CAAC,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACzB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACnB,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACF,CAAC;IAAA,CACD,CAAC;IAEF,sCAAsC;IACtC,MAAM,cAAc,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,OAAO,CAAC,CAAC;IACzD,QAAQ,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC,CAAC;IAE7C,yCAAyC;IACzC,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IACrD,QAAQ,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC,CAAC;IAE5C,oDAAoD;IACpD,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IAE9D,OAAO,SAAS,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAAA,CAChC","sourcesContent":["/**\n * Hook loader - loads TypeScript hook modules using jiti.\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Attachment } from \"@mariozechner/pi-agent-core\";\nimport { createJiti } from \"jiti\";\nimport { getAgentDir } from \"../../config.js\";\nimport type { HookAPI, HookFactory } from \"./types.js\";\n\n// Create require function to resolve module paths at runtime\nconst require = createRequire(import.meta.url);\n\n// Lazily computed aliases - resolved at runtime to handle global installs\nlet _aliases: Record<string, string> | null = null;\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\t_aliases = {\n\t\t\"@mariozechner/pi-coding-agent\": packageIndex,\n\t\t\"@mariozechner/pi-coding-agent/hooks\": path.resolve(__dirname, \"index.js\"),\n\t\t\"@mariozechner/pi-tui\": require.resolve(\"@mariozechner/pi-tui\"),\n\t\t\"@mariozechner/pi-ai\": require.resolve(\"@mariozechner/pi-ai\"),\n\t\t\"@sinclair/typebox\": require.resolve(\"@sinclair/typebox\"),\n\t};\n\treturn _aliases;\n}\n\n/**\n * Generic handler function type.\n */\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Send handler type for pi.send().\n */\nexport type SendHandler = (text: string, attachments?: Attachment[]) => void;\n\n/**\n * Registered handlers for a loaded hook.\n */\nexport interface LoadedHook {\n\t/** Original path from config */\n\tpath: string;\n\t/** Resolved absolute path */\n\tresolvedPath: string;\n\t/** Map of event type to handler functions */\n\thandlers: Map<string, HandlerFn[]>;\n\t/** Set the send handler for this hook's pi.send() */\n\tsetSendHandler: (handler: SendHandler) => void;\n}\n\n/**\n * Result of loading hooks.\n */\nexport interface LoadHooksResult {\n\t/** Successfully loaded hooks */\n\thooks: LoadedHook[];\n\t/** Errors encountered during loading */\n\terrors: Array<{ path: string; error: string }>;\n}\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nfunction normalizeUnicodeSpaces(str: string): string {\n\treturn str.replace(UNICODE_SPACES, \" \");\n}\n\nfunction expandPath(p: string): string {\n\tconst normalized = normalizeUnicodeSpaces(p);\n\tif (normalized.startsWith(\"~/\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(2));\n\t}\n\tif (normalized.startsWith(\"~\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(1));\n\t}\n\treturn normalized;\n}\n\n/**\n * Resolve hook path.\n * - Absolute paths used as-is\n * - Paths starting with ~ expanded to home directory\n * - Relative paths resolved from cwd\n */\nfunction resolveHookPath(hookPath: string, cwd: string): string {\n\tconst expanded = expandPath(hookPath);\n\n\tif (path.isAbsolute(expanded)) {\n\t\treturn expanded;\n\t}\n\n\t// Relative paths resolved from cwd\n\treturn path.resolve(cwd, expanded);\n}\n\n/**\n * Create a HookAPI instance that collects handlers.\n * Returns the API and a function to set the send handler later.\n */\nfunction createHookAPI(handlers: Map<string, HandlerFn[]>): {\n\tapi: HookAPI;\n\tsetSendHandler: (handler: SendHandler) => void;\n} {\n\tlet sendHandler: SendHandler = () => {\n\t\t// Default no-op until mode sets the handler\n\t};\n\n\tconst api: HookAPI = {\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\tconst list = handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\thandlers.set(event, list);\n\t\t},\n\t\tsend(text: string, attachments?: Attachment[]): void {\n\t\t\tsendHandler(text, attachments);\n\t\t},\n\t} as HookAPI;\n\n\treturn {\n\t\tapi,\n\t\tsetSendHandler: (handler: SendHandler) => {\n\t\t\tsendHandler = handler;\n\t\t},\n\t};\n}\n\n/**\n * Load a single hook module using jiti.\n */\nasync function loadHook(hookPath: string, cwd: string): Promise<{ hook: LoadedHook | null; error: string | null }> {\n\tconst resolvedPath = resolveHookPath(hookPath, cwd);\n\n\ttry {\n\t\t// Create jiti instance for TypeScript/ESM loading\n\t\t// Use aliases to resolve package imports since hooks are loaded from user directories\n\t\t// (e.g. ~/.pi/agent/hooks) but import from packages installed with pi-coding-agent\n\t\tconst jiti = createJiti(import.meta.url, {\n\t\t\talias: getAliases(),\n\t\t});\n\n\t\t// Import the module\n\t\tconst module = await jiti.import(resolvedPath, { default: true });\n\t\tconst factory = module as HookFactory;\n\n\t\tif (typeof factory !== \"function\") {\n\t\t\treturn { hook: null, error: \"Hook must export a default function\" };\n\t\t}\n\n\t\t// Create handlers map and API\n\t\tconst handlers = new Map<string, HandlerFn[]>();\n\t\tconst { api, setSendHandler } = createHookAPI(handlers);\n\n\t\t// Call factory to register handlers\n\t\tfactory(api);\n\n\t\treturn {\n\t\t\thook: { path: hookPath, resolvedPath, handlers, setSendHandler },\n\t\t\terror: null,\n\t\t};\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { hook: null, error: `Failed to load hook: ${message}` };\n\t}\n}\n\n/**\n * Load all hooks from configuration.\n * @param paths - Array of hook file paths\n * @param cwd - Current working directory for resolving relative paths\n */\nexport async function loadHooks(paths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst hooks: LoadedHook[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const hookPath of paths) {\n\t\tconst { hook, error } = await loadHook(hookPath, cwd);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: hookPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (hook) {\n\t\t\thooks.push(hook);\n\t\t}\n\t}\n\n\treturn { hooks, errors };\n}\n\n/**\n * Discover hook files from a directory.\n * Returns all .ts files (and symlinks to .ts files) in the directory (non-recursive).\n */\nfunction discoverHooksInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\t\treturn entries\n\t\t\t.filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(\".ts\"))\n\t\t\t.map((e) => path.join(dir, e.name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Discover and load hooks from standard locations:\n * 1. ~/.pi/agent/hooks/*.ts (global)\n * 2. cwd/.pi/hooks/*.ts (project-local)\n *\n * Plus any explicitly configured paths from settings.\n *\n * @param configuredPaths - Explicit paths from settings.json\n * @param cwd - Current working directory\n */\nexport async function discoverAndLoadHooks(configuredPaths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\t// Helper to add paths without duplicates\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Global hooks: ~/.pi/agent/hooks/\n\tconst globalHooksDir = path.join(getAgentDir(), \"hooks\");\n\taddPaths(discoverHooksInDir(globalHooksDir));\n\n\t// 2. Project-local hooks: cwd/.pi/hooks/\n\tconst localHooksDir = path.join(cwd, \".pi\", \"hooks\");\n\taddPaths(discoverHooksInDir(localHooksDir));\n\n\t// 3. Explicitly configured paths (can override/add)\n\taddPaths(configuredPaths.map((p) => resolveHookPath(p, cwd)));\n\n\treturn loadHooks(allPaths, cwd);\n}\n"]}
1
+ {"version":3,"file":"loader.js","sourceRoot":"","sources":["../../../src/core/hooks/loader.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,6DAA6D;AAC7D,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAE/C,0EAA0E;AAC1E,IAAI,QAAQ,GAAkC,IAAI,CAAC;AACnD,SAAS,UAAU,GAA2B;IAC7C,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAE9B,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/D,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,EAAE,UAAU,C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CAAC,QAAQ,CAAC,CAAC;gBACnB,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACF,CAAC;IAAA,CACD,CAAC;IAEF,mCAAmC;IACnC,MAAM,cAAc,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACpD,QAAQ,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC,CAAC;IAE7C,yCAAyC;IACzC,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IACrD,QAAQ,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC,CAAC;IAE5C,oDAAoD;IACpD,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IAE9D,OAAO,SAAS,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;AAAA,CAChC","sourcesContent":["/**\n * Hook loader - loads TypeScript hook modules using jiti.\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Attachment } from \"@mariozechner/pi-agent-core\";\nimport { createJiti } from \"jiti\";\nimport { getAgentDir } from \"../../config.js\";\nimport type { HookAPI, HookFactory } from \"./types.js\";\n\n// Create require function to resolve module paths at runtime\nconst require = createRequire(import.meta.url);\n\n// Lazily computed aliases - resolved at runtime to handle global installs\nlet _aliases: Record<string, string> | null = null;\nfunction getAliases(): Record<string, string> {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\t_aliases = {\n\t\t\"@mariozechner/pi-coding-agent\": packageIndex,\n\t\t\"@mariozechner/pi-coding-agent/hooks\": path.resolve(__dirname, \"index.js\"),\n\t\t\"@mariozechner/pi-tui\": require.resolve(\"@mariozechner/pi-tui\"),\n\t\t\"@mariozechner/pi-ai\": require.resolve(\"@mariozechner/pi-ai\"),\n\t\t\"@sinclair/typebox\": require.resolve(\"@sinclair/typebox\"),\n\t};\n\treturn _aliases;\n}\n\n/**\n * Generic handler function type.\n */\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Send handler type for pi.send().\n */\nexport type SendHandler = (text: string, attachments?: Attachment[]) => void;\n\n/**\n * Registered handlers for a loaded hook.\n */\nexport interface LoadedHook {\n\t/** Original path from config */\n\tpath: string;\n\t/** Resolved absolute path */\n\tresolvedPath: string;\n\t/** Map of event type to handler functions */\n\thandlers: Map<string, HandlerFn[]>;\n\t/** Set the send handler for this hook's pi.send() */\n\tsetSendHandler: (handler: SendHandler) => void;\n}\n\n/**\n * Result of loading hooks.\n */\nexport interface LoadHooksResult {\n\t/** Successfully loaded hooks */\n\thooks: LoadedHook[];\n\t/** Errors encountered during loading */\n\terrors: Array<{ path: string; error: string }>;\n}\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nfunction normalizeUnicodeSpaces(str: string): string {\n\treturn str.replace(UNICODE_SPACES, \" \");\n}\n\nfunction expandPath(p: string): string {\n\tconst normalized = normalizeUnicodeSpaces(p);\n\tif (normalized.startsWith(\"~/\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(2));\n\t}\n\tif (normalized.startsWith(\"~\")) {\n\t\treturn path.join(os.homedir(), normalized.slice(1));\n\t}\n\treturn normalized;\n}\n\n/**\n * Resolve hook path.\n * - Absolute paths used as-is\n * - Paths starting with ~ expanded to home directory\n * - Relative paths resolved from cwd\n */\nfunction resolveHookPath(hookPath: string, cwd: string): string {\n\tconst expanded = expandPath(hookPath);\n\n\tif (path.isAbsolute(expanded)) {\n\t\treturn expanded;\n\t}\n\n\t// Relative paths resolved from cwd\n\treturn path.resolve(cwd, expanded);\n}\n\n/**\n * Create a HookAPI instance that collects handlers.\n * Returns the API and a function to set the send handler later.\n */\nfunction createHookAPI(handlers: Map<string, HandlerFn[]>): {\n\tapi: HookAPI;\n\tsetSendHandler: (handler: SendHandler) => void;\n} {\n\tlet sendHandler: SendHandler = () => {\n\t\t// Default no-op until mode sets the handler\n\t};\n\n\tconst api: HookAPI = {\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\tconst list = handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\thandlers.set(event, list);\n\t\t},\n\t\tsend(text: string, attachments?: Attachment[]): void {\n\t\t\tsendHandler(text, attachments);\n\t\t},\n\t} as HookAPI;\n\n\treturn {\n\t\tapi,\n\t\tsetSendHandler: (handler: SendHandler) => {\n\t\t\tsendHandler = handler;\n\t\t},\n\t};\n}\n\n/**\n * Load a single hook module using jiti.\n */\nasync function loadHook(hookPath: string, cwd: string): Promise<{ hook: LoadedHook | null; error: string | null }> {\n\tconst resolvedPath = resolveHookPath(hookPath, cwd);\n\n\ttry {\n\t\t// Create jiti instance for TypeScript/ESM loading\n\t\t// Use aliases to resolve package imports since hooks are loaded from user directories\n\t\t// (e.g. ~/.pi/agent/hooks) but import from packages installed with pi-coding-agent\n\t\tconst jiti = createJiti(import.meta.url, {\n\t\t\talias: getAliases(),\n\t\t});\n\n\t\t// Import the module\n\t\tconst module = await jiti.import(resolvedPath, { default: true });\n\t\tconst factory = module as HookFactory;\n\n\t\tif (typeof factory !== \"function\") {\n\t\t\treturn { hook: null, error: \"Hook must export a default function\" };\n\t\t}\n\n\t\t// Create handlers map and API\n\t\tconst handlers = new Map<string, HandlerFn[]>();\n\t\tconst { api, setSendHandler } = createHookAPI(handlers);\n\n\t\t// Call factory to register handlers\n\t\tfactory(api);\n\n\t\treturn {\n\t\t\thook: { path: hookPath, resolvedPath, handlers, setSendHandler },\n\t\t\terror: null,\n\t\t};\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { hook: null, error: `Failed to load hook: ${message}` };\n\t}\n}\n\n/**\n * Load all hooks from configuration.\n * @param paths - Array of hook file paths\n * @param cwd - Current working directory for resolving relative paths\n */\nexport async function loadHooks(paths: string[], cwd: string): Promise<LoadHooksResult> {\n\tconst hooks: LoadedHook[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\n\tfor (const hookPath of paths) {\n\t\tconst { hook, error } = await loadHook(hookPath, cwd);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: hookPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (hook) {\n\t\t\thooks.push(hook);\n\t\t}\n\t}\n\n\treturn { hooks, errors };\n}\n\n/**\n * Discover hook files from a directory.\n * Returns all .ts files (and symlinks to .ts files) in the directory (non-recursive).\n */\nfunction discoverHooksInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\t\treturn entries\n\t\t\t.filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(\".ts\"))\n\t\t\t.map((e) => path.join(dir, e.name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Discover and load hooks from standard locations:\n * 1. agentDir/hooks/*.ts (global)\n * 2. cwd/.pi/hooks/*.ts (project-local)\n *\n * Plus any explicitly configured paths from settings.\n */\nexport async function discoverAndLoadHooks(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n): Promise<LoadHooksResult> {\n\tconst allPaths: string[] = [];\n\tconst seen = new Set<string>();\n\n\t// Helper to add paths without duplicates\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Global hooks: agentDir/hooks/\n\tconst globalHooksDir = path.join(agentDir, \"hooks\");\n\taddPaths(discoverHooksInDir(globalHooksDir));\n\n\t// 2. Project-local hooks: cwd/.pi/hooks/\n\tconst localHooksDir = path.join(cwd, \".pi\", \"hooks\");\n\taddPaths(discoverHooksInDir(localHooksDir));\n\n\t// 3. Explicitly configured paths (can override/add)\n\taddPaths(configuredPaths.map((p) => resolveHookPath(p, cwd)));\n\n\treturn loadHooks(allPaths, cwd);\n}\n"]}
@@ -8,20 +8,21 @@ export declare function resolveApiKey(keyConfig: string): string | undefined;
8
8
  * Get all models (built-in + custom), freshly loaded
9
9
  * Returns { models, error } - either models array or error message
10
10
  */
11
- export declare function loadAndMergeModels(): {
11
+ export declare function loadAndMergeModels(agentDir?: string): {
12
12
  models: Model<Api>[];
13
13
  error: string | null;
14
14
  };
15
15
  /**
16
16
  * Get API key for a model (checks custom providers first, then built-in)
17
- * Now async to support OAuth token refresh
17
+ * Now async to support OAuth token refresh.
18
+ * Note: OAuth storage location is configured globally via setOAuthStorage.
18
19
  */
19
20
  export declare function getApiKeyForModel(model: Model<Api>): Promise<string | undefined>;
20
21
  /**
21
22
  * Get only models that have valid API keys available
22
23
  * Returns { models, error } - either models array or error message
23
24
  */
24
- export declare function getAvailableModels(): Promise<{
25
+ export declare function getAvailableModels(agentDir?: string): Promise<{
25
26
  models: Model<Api>[];
26
27
  error: string | null;
27
28
  }>;
@@ -29,7 +30,7 @@ export declare function getAvailableModels(): Promise<{
29
30
  * Find a specific model by provider and ID
30
31
  * Returns { model, error } - either model or error message
31
32
  */
32
- export declare function findModel(provider: string, modelId: string): {
33
+ export declare function findModel(provider: string, modelId: string, agentDir?: string): {
33
34
  model: Model<Api> | null;
34
35
  error: string | null;
35
36
  };
@@ -1 +1 @@
1
- {"version":3,"file":"model-config.d.ts","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,EAOR,KAAK,KAAK,EAKV,MAAM,qBAAqB,CAAC;AAqE7B;;;GAGG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOnE;AAyID;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI;IAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CA+BnF;AAED;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAkFtF;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,CA2BlG;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAS/G;AAgBD;;;GAGG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAyB5D","sourcesContent":["import {\n\ttype Api,\n\tgetApiKey,\n\tgetGitHubCopilotBaseUrl,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\tloadOAuthCredentials,\n\ttype Model,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n\tremoveOAuthCredentials,\n\tsaveOAuthCredentials,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { getModelsPath } from \"../config.js\";\nimport { getOAuthToken, type OAuthProvider, refreshToken } from \"./oauth/index.js\";\n\n// Handle both default and named exports\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n});\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(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\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.String({ minLength: 1 }),\n\tapiKey: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: 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// Custom provider API key mappings (provider name -> apiKey config)\nconst customProviderApiKeys: Map<string, string> = new Map();\n\n/**\n * Resolve an API key config value to an actual key.\n * First checks if it's an environment variable, then treats as literal.\n */\nexport function resolveApiKey(keyConfig: string): string | undefined {\n\t// First check if it's an env var name\n\tconst envValue = process.env[keyConfig];\n\tif (envValue) return envValue;\n\n\t// Otherwise treat as literal API key\n\treturn keyConfig;\n}\n\n/**\n * Load custom models from models.json in agent config dir\n * Returns { models, error } - either models array or error message\n */\nfunction loadCustomModels(): { models: Model<Api>[]; error: string | null } {\n\tconst configPath = getModelsPath();\n\tif (!existsSync(configPath)) {\n\t\treturn { models: [], error: null };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(configPath, \"utf-8\");\n\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t// Validate schema\n\t\tconst ajv = new Ajv();\n\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\tif (!validate(config)) {\n\t\t\tconst errors =\n\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\"Unknown schema error\";\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json schema:\\n${errors}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Additional validation\n\t\ttry {\n\t\t\tvalidateConfig(config);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Parse models\n\t\treturn { models: parseModels(config), error: null };\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Failed to parse models.json: ${error.message}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodels: [],\n\t\t\terror: `Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t};\n\t}\n}\n\n/**\n * Validate config structure and requirements\n */\nfunction validateConfig(config: ModelsConfig): void {\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\tconst hasProviderApi = !!providerConfig.api;\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. ` +\n\t\t\t\t\t\t`Set at provider or model level.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate required fields\n\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t}\n\t}\n}\n\n/**\n * Parse config into Model objects\n */\nfunction parseModels(config: ModelsConfig): Model<Api>[] {\n\tconst models: Model<Api>[] = [];\n\n\t// Clear and rebuild custom provider API key mappings\n\tcustomProviderApiKeys.clear();\n\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t// Store API key config for this provider\n\t\tcustomProviderApiKeys.set(providerName, providerConfig.apiKey);\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\t// Model-level api overrides provider-level api\n\t\t\tconst api = modelDef.api || providerConfig.api;\n\n\t\t\tif (!api) {\n\t\t\t\t// This should have been caught by validateConfig, but be safe\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\tlet headers =\n\t\t\t\tproviderConfig.headers || modelDef.headers ? { ...providerConfig.headers, ...modelDef.headers } : undefined;\n\n\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\tif (providerConfig.authHeader) {\n\t\t\t\tconst resolvedKey = resolveApiKey(providerConfig.apiKey);\n\t\t\t\tif (resolvedKey) {\n\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodels.push({\n\t\t\t\tid: modelDef.id,\n\t\t\t\tname: modelDef.name,\n\t\t\t\tapi: api as Api,\n\t\t\t\tprovider: providerName,\n\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\tcost: modelDef.cost,\n\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\theaders,\n\t\t\t\tcompat: modelDef.compat,\n\t\t\t} as Model<Api>);\n\t\t}\n\t}\n\n\treturn models;\n}\n\n/**\n * Get all models (built-in + custom), freshly loaded\n * Returns { models, error } - either models array or error message\n */\nexport function loadAndMergeModels(): { models: Model<Api>[]; error: string | null } {\n\tconst builtInModels: Model<Api>[] = [];\n\tconst providers = getProviders();\n\n\t// Load all built-in models\n\tfor (const provider of providers) {\n\t\tconst providerModels = getModels(provider as KnownProvider);\n\t\tbuiltInModels.push(...(providerModels as Model<Api>[]));\n\t}\n\n\t// Load custom models\n\tconst { models: customModels, error } = loadCustomModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst combined = [...builtInModels, ...customModels];\n\n\t// Update github-copilot base URL based on OAuth token or enterprise domain\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tif (copilotCreds) {\n\t\tconst domain = copilotCreds.enterpriseUrl ? normalizeDomain(copilotCreds.enterpriseUrl) : undefined;\n\t\tconst baseUrl = getGitHubCopilotBaseUrl(copilotCreds.access, domain ?? undefined);\n\t\treturn {\n\t\t\tmodels: combined.map((m) => (m.provider === \"github-copilot\" ? { ...m, baseUrl } : m)),\n\t\t\terror: null,\n\t\t};\n\t}\n\n\treturn { models: combined, error: null };\n}\n\n/**\n * Get API key for a model (checks custom providers first, then built-in)\n * Now async to support OAuth token refresh\n */\nexport async function getApiKeyForModel(model: Model<Api>): Promise<string | undefined> {\n\t// For custom providers, check their apiKey config\n\tconst customKeyConfig = customProviderApiKeys.get(model.provider);\n\tif (customKeyConfig) {\n\t\treturn resolveApiKey(customKeyConfig);\n\t}\n\n\t// For Anthropic, check OAuth first\n\tif (model.provider === \"anthropic\") {\n\t\t// 1. Check OAuth storage (auto-refresh if needed)\n\t\tconst oauthToken = await getOAuthToken(\"anthropic\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Check ANTHROPIC_OAUTH_TOKEN env var (manual OAuth token)\n\t\tconst oauthEnv = process.env.ANTHROPIC_OAUTH_TOKEN;\n\t\tif (oauthEnv) {\n\t\t\treturn oauthEnv;\n\t\t}\n\n\t\t// 3. Fall back to ANTHROPIC_API_KEY env var\n\t}\n\n\tif (model.provider === \"github-copilot\") {\n\t\t// 1. Check OAuth storage (from device flow login)\n\t\tconst oauthToken = await getOAuthToken(\"github-copilot\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Use GitHub token directly (works with copilot scope on github.com)\n\t\tconst githubToken = process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t\tif (!githubToken) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// 3. For enterprise, exchange token for short-lived Copilot token\n\t\tconst enterpriseDomain = process.env.COPILOT_ENTERPRISE_URL\n\t\t\t? normalizeDomain(process.env.COPILOT_ENTERPRISE_URL)\n\t\t\t: undefined;\n\n\t\tif (enterpriseDomain) {\n\t\t\tconst creds = await refreshGitHubCopilotToken(githubToken, enterpriseDomain);\n\t\t\tsaveOAuthCredentials(\"github-copilot\", creds);\n\t\t\treturn creds.access;\n\t\t}\n\n\t\t// 4. For github.com, use token directly\n\t\treturn githubToken;\n\t}\n\n\t// For Google Gemini CLI and Antigravity, check OAuth and encode projectId with token\n\tif (model.provider === \"google-gemini-cli\" || model.provider === \"google-antigravity\") {\n\t\tconst oauthProvider = model.provider as \"google-gemini-cli\" | \"google-antigravity\";\n\t\tconst credentials = loadOAuthCredentials(oauthProvider);\n\t\tif (!credentials) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Check if token is expired\n\t\tif (Date.now() >= credentials.expires) {\n\t\t\ttry {\n\t\t\t\tawait refreshToken(oauthProvider);\n\t\t\t\tconst refreshedCreds = loadOAuthCredentials(oauthProvider);\n\t\t\t\tif (refreshedCreds?.projectId) {\n\t\t\t\t\treturn JSON.stringify({ token: refreshedCreds.access, projectId: refreshedCreds.projectId });\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremoveOAuthCredentials(oauthProvider);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tif (credentials.projectId) {\n\t\t\treturn JSON.stringify({ token: credentials.access, projectId: credentials.projectId });\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// For built-in providers, use getApiKey from @mariozechner/pi-ai\n\treturn getApiKey(model.provider as KnownProvider);\n}\n\n/**\n * Get only models that have valid API keys available\n * Returns { models, error } - either models array or error message\n */\nexport async function getAvailableModels(): Promise<{ models: Model<Api>[]; error: string | null }> {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst availableModels: Model<Api>[] = [];\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tconst hasCopilotEnv = !!(process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN);\n\tconst hasCopilot = !!copilotCreds || hasCopilotEnv;\n\n\tfor (const model of allModels) {\n\t\tif (model.provider === \"github-copilot\") {\n\t\t\tif (hasCopilot) {\n\t\t\t\tavailableModels.push(model);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst apiKey = await getApiKeyForModel(model);\n\t\tif (apiKey) {\n\t\t\tavailableModels.push(model);\n\t\t}\n\t}\n\n\treturn { models: availableModels, error: null };\n}\n\n/**\n * Find a specific model by provider and ID\n * Returns { model, error } - either model or error message\n */\nexport function findModel(provider: string, modelId: string): { model: Model<Api> | null; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { model: null, error };\n\t}\n\n\tconst model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;\n\treturn { model, error: null };\n}\n\n/**\n * Mapping from model provider to OAuth provider ID.\n * Only providers that support OAuth are listed here.\n */\nconst providerToOAuthProvider: Record<string, OAuthProvider> = {\n\tanthropic: \"anthropic\",\n\t\"github-copilot\": \"github-copilot\",\n\t\"google-gemini-cli\": \"google-gemini-cli\",\n\t\"google-antigravity\": \"google-antigravity\",\n};\n\n// Cache for OAuth status per provider (avoids file reads on every render)\nconst oauthStatusCache: Map<string, boolean> = new Map();\n\n/**\n * Invalidate the OAuth status cache.\n * Call this after login/logout operations.\n */\nexport function invalidateOAuthCache(): void {\n\toauthStatusCache.clear();\n}\n\n/**\n * Check if a model is using OAuth credentials (subscription).\n * This checks if OAuth credentials exist and would be used for the model,\n * without actually fetching or refreshing the token.\n * Results are cached until invalidateOAuthCache() is called.\n */\nexport function isModelUsingOAuth(model: Model<Api>): boolean {\n\tconst oauthProvider = providerToOAuthProvider[model.provider];\n\tif (!oauthProvider) {\n\t\treturn false;\n\t}\n\n\t// Check cache first\n\tif (oauthStatusCache.has(oauthProvider)) {\n\t\treturn oauthStatusCache.get(oauthProvider)!;\n\t}\n\n\t// Check if OAuth credentials exist for this provider\n\tlet usingOAuth = false;\n\tconst credentials = loadOAuthCredentials(oauthProvider);\n\tif (credentials) {\n\t\tusingOAuth = true;\n\t}\n\n\t// Also check for manual OAuth token env var (for Anthropic)\n\tif (!usingOAuth && model.provider === \"anthropic\" && process.env.ANTHROPIC_OAUTH_TOKEN) {\n\t\tusingOAuth = true;\n\t}\n\n\toauthStatusCache.set(oauthProvider, usingOAuth);\n\treturn usingOAuth;\n}\n"]}
1
+ {"version":3,"file":"model-config.d.ts","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,EAOR,KAAK,KAAK,EAKV,MAAM,qBAAqB,CAAC;AAsE7B;;;GAGG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOnE;AAyID;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,GAAE,MAAsB,GAAG;IAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CA+BnH;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAkFtF;AAED;;;GAGG;AACH,wBAAsB,kBAAkB,CACvC,QAAQ,GAAE,MAAsB,GAC9B,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,CAgBzD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CACxB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,MAAsB,GAC9B;IAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CASpD;AAgBD;;;GAGG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAyB5D","sourcesContent":["import {\n\ttype Api,\n\tgetApiKey,\n\tgetGitHubCopilotBaseUrl,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\tloadOAuthCredentials,\n\ttype Model,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n\tremoveOAuthCredentials,\n\tsaveOAuthCredentials,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport { getOAuthToken, type OAuthProvider, refreshToken } from \"./oauth/index.js\";\n\n// Handle both default and named exports\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n});\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(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\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.String({ minLength: 1 }),\n\tapiKey: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: 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// Custom provider API key mappings (provider name -> apiKey config)\nconst customProviderApiKeys: Map<string, string> = new Map();\n\n/**\n * Resolve an API key config value to an actual key.\n * First checks if it's an environment variable, then treats as literal.\n */\nexport function resolveApiKey(keyConfig: string): string | undefined {\n\t// First check if it's an env var name\n\tconst envValue = process.env[keyConfig];\n\tif (envValue) return envValue;\n\n\t// Otherwise treat as literal API key\n\treturn keyConfig;\n}\n\n/**\n * Load custom models from models.json in agent config dir\n * Returns { models, error } - either models array or error message\n */\nfunction loadCustomModels(agentDir: string = getAgentDir()): { models: Model<Api>[]; error: string | null } {\n\tconst configPath = join(agentDir, \"models.json\");\n\tif (!existsSync(configPath)) {\n\t\treturn { models: [], error: null };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(configPath, \"utf-8\");\n\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t// Validate schema\n\t\tconst ajv = new Ajv();\n\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\tif (!validate(config)) {\n\t\t\tconst errors =\n\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\"Unknown schema error\";\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json schema:\\n${errors}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Additional validation\n\t\ttry {\n\t\t\tvalidateConfig(config);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Parse models\n\t\treturn { models: parseModels(config), error: null };\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Failed to parse models.json: ${error.message}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodels: [],\n\t\t\terror: `Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t};\n\t}\n}\n\n/**\n * Validate config structure and requirements\n */\nfunction validateConfig(config: ModelsConfig): void {\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\tconst hasProviderApi = !!providerConfig.api;\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. ` +\n\t\t\t\t\t\t`Set at provider or model level.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate required fields\n\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t}\n\t}\n}\n\n/**\n * Parse config into Model objects\n */\nfunction parseModels(config: ModelsConfig): Model<Api>[] {\n\tconst models: Model<Api>[] = [];\n\n\t// Clear and rebuild custom provider API key mappings\n\tcustomProviderApiKeys.clear();\n\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t// Store API key config for this provider\n\t\tcustomProviderApiKeys.set(providerName, providerConfig.apiKey);\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\t// Model-level api overrides provider-level api\n\t\t\tconst api = modelDef.api || providerConfig.api;\n\n\t\t\tif (!api) {\n\t\t\t\t// This should have been caught by validateConfig, but be safe\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\tlet headers =\n\t\t\t\tproviderConfig.headers || modelDef.headers ? { ...providerConfig.headers, ...modelDef.headers } : undefined;\n\n\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\tif (providerConfig.authHeader) {\n\t\t\t\tconst resolvedKey = resolveApiKey(providerConfig.apiKey);\n\t\t\t\tif (resolvedKey) {\n\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodels.push({\n\t\t\t\tid: modelDef.id,\n\t\t\t\tname: modelDef.name,\n\t\t\t\tapi: api as Api,\n\t\t\t\tprovider: providerName,\n\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\tcost: modelDef.cost,\n\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\theaders,\n\t\t\t\tcompat: modelDef.compat,\n\t\t\t} as Model<Api>);\n\t\t}\n\t}\n\n\treturn models;\n}\n\n/**\n * Get all models (built-in + custom), freshly loaded\n * Returns { models, error } - either models array or error message\n */\nexport function loadAndMergeModels(agentDir: string = getAgentDir()): { models: Model<Api>[]; error: string | null } {\n\tconst builtInModels: Model<Api>[] = [];\n\tconst providers = getProviders();\n\n\t// Load all built-in models\n\tfor (const provider of providers) {\n\t\tconst providerModels = getModels(provider as KnownProvider);\n\t\tbuiltInModels.push(...(providerModels as Model<Api>[]));\n\t}\n\n\t// Load custom models\n\tconst { models: customModels, error } = loadCustomModels(agentDir);\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst combined = [...builtInModels, ...customModels];\n\n\t// Update github-copilot base URL based on OAuth token or enterprise domain\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tif (copilotCreds) {\n\t\tconst domain = copilotCreds.enterpriseUrl ? normalizeDomain(copilotCreds.enterpriseUrl) : undefined;\n\t\tconst baseUrl = getGitHubCopilotBaseUrl(copilotCreds.access, domain ?? undefined);\n\t\treturn {\n\t\t\tmodels: combined.map((m) => (m.provider === \"github-copilot\" ? { ...m, baseUrl } : m)),\n\t\t\terror: null,\n\t\t};\n\t}\n\n\treturn { models: combined, error: null };\n}\n\n/**\n * Get API key for a model (checks custom providers first, then built-in)\n * Now async to support OAuth token refresh.\n * Note: OAuth storage location is configured globally via setOAuthStorage.\n */\nexport async function getApiKeyForModel(model: Model<Api>): Promise<string | undefined> {\n\t// For custom providers, check their apiKey config\n\tconst customKeyConfig = customProviderApiKeys.get(model.provider);\n\tif (customKeyConfig) {\n\t\treturn resolveApiKey(customKeyConfig);\n\t}\n\n\t// For Anthropic, check OAuth first\n\tif (model.provider === \"anthropic\") {\n\t\t// 1. Check OAuth storage (auto-refresh if needed)\n\t\tconst oauthToken = await getOAuthToken(\"anthropic\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Check ANTHROPIC_OAUTH_TOKEN env var (manual OAuth token)\n\t\tconst oauthEnv = process.env.ANTHROPIC_OAUTH_TOKEN;\n\t\tif (oauthEnv) {\n\t\t\treturn oauthEnv;\n\t\t}\n\n\t\t// 3. Fall back to ANTHROPIC_API_KEY env var\n\t}\n\n\tif (model.provider === \"github-copilot\") {\n\t\t// 1. Check OAuth storage (from device flow login)\n\t\tconst oauthToken = await getOAuthToken(\"github-copilot\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Use GitHub token directly (works with copilot scope on github.com)\n\t\tconst githubToken = process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t\tif (!githubToken) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// 3. For enterprise, exchange token for short-lived Copilot token\n\t\tconst enterpriseDomain = process.env.COPILOT_ENTERPRISE_URL\n\t\t\t? normalizeDomain(process.env.COPILOT_ENTERPRISE_URL)\n\t\t\t: undefined;\n\n\t\tif (enterpriseDomain) {\n\t\t\tconst creds = await refreshGitHubCopilotToken(githubToken, enterpriseDomain);\n\t\t\tsaveOAuthCredentials(\"github-copilot\", creds);\n\t\t\treturn creds.access;\n\t\t}\n\n\t\t// 4. For github.com, use token directly\n\t\treturn githubToken;\n\t}\n\n\t// For Google Gemini CLI and Antigravity, check OAuth and encode projectId with token\n\tif (model.provider === \"google-gemini-cli\" || model.provider === \"google-antigravity\") {\n\t\tconst oauthProvider = model.provider as \"google-gemini-cli\" | \"google-antigravity\";\n\t\tconst credentials = loadOAuthCredentials(oauthProvider);\n\t\tif (!credentials) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Check if token is expired\n\t\tif (Date.now() >= credentials.expires) {\n\t\t\ttry {\n\t\t\t\tawait refreshToken(oauthProvider);\n\t\t\t\tconst refreshedCreds = loadOAuthCredentials(oauthProvider);\n\t\t\t\tif (refreshedCreds?.projectId) {\n\t\t\t\t\treturn JSON.stringify({ token: refreshedCreds.access, projectId: refreshedCreds.projectId });\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremoveOAuthCredentials(oauthProvider);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tif (credentials.projectId) {\n\t\t\treturn JSON.stringify({ token: credentials.access, projectId: credentials.projectId });\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// For built-in providers, use getApiKey from @mariozechner/pi-ai\n\treturn getApiKey(model.provider as KnownProvider);\n}\n\n/**\n * Get only models that have valid API keys available\n * Returns { models, error } - either models array or error message\n */\nexport async function getAvailableModels(\n\tagentDir: string = getAgentDir(),\n): Promise<{ models: Model<Api>[]; error: string | null }> {\n\tconst { models: allModels, error } = loadAndMergeModels(agentDir);\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst availableModels: Model<Api>[] = [];\n\tfor (const model of allModels) {\n\t\tconst apiKey = await getApiKeyForModel(model);\n\t\tif (apiKey) {\n\t\t\tavailableModels.push(model);\n\t\t}\n\t}\n\n\treturn { models: availableModels, error: null };\n}\n\n/**\n * Find a specific model by provider and ID\n * Returns { model, error } - either model or error message\n */\nexport function findModel(\n\tprovider: string,\n\tmodelId: string,\n\tagentDir: string = getAgentDir(),\n): { model: Model<Api> | null; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels(agentDir);\n\n\tif (error) {\n\t\treturn { model: null, error };\n\t}\n\n\tconst model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;\n\treturn { model, error: null };\n}\n\n/**\n * Mapping from model provider to OAuth provider ID.\n * Only providers that support OAuth are listed here.\n */\nconst providerToOAuthProvider: Record<string, OAuthProvider> = {\n\tanthropic: \"anthropic\",\n\t\"github-copilot\": \"github-copilot\",\n\t\"google-gemini-cli\": \"google-gemini-cli\",\n\t\"google-antigravity\": \"google-antigravity\",\n};\n\n// Cache for OAuth status per provider (avoids file reads on every render)\nconst oauthStatusCache: Map<string, boolean> = new Map();\n\n/**\n * Invalidate the OAuth status cache.\n * Call this after login/logout operations.\n */\nexport function invalidateOAuthCache(): void {\n\toauthStatusCache.clear();\n}\n\n/**\n * Check if a model is using OAuth credentials (subscription).\n * This checks if OAuth credentials exist and would be used for the model,\n * without actually fetching or refreshing the token.\n * Results are cached until invalidateOAuthCache() is called.\n */\nexport function isModelUsingOAuth(model: Model<Api>): boolean {\n\tconst oauthProvider = providerToOAuthProvider[model.provider];\n\tif (!oauthProvider) {\n\t\treturn false;\n\t}\n\n\t// Check cache first\n\tif (oauthStatusCache.has(oauthProvider)) {\n\t\treturn oauthStatusCache.get(oauthProvider)!;\n\t}\n\n\t// Check if OAuth credentials exist for this provider\n\tlet usingOAuth = false;\n\tconst credentials = loadOAuthCredentials(oauthProvider);\n\tif (credentials) {\n\t\tusingOAuth = true;\n\t}\n\n\t// Also check for manual OAuth token env var (for Anthropic)\n\tif (!usingOAuth && model.provider === \"anthropic\" && process.env.ANTHROPIC_OAUTH_TOKEN) {\n\t\tusingOAuth = true;\n\t}\n\n\toauthStatusCache.set(oauthProvider, usingOAuth);\n\treturn usingOAuth;\n}\n"]}
@@ -2,7 +2,8 @@ import { getApiKey, getGitHubCopilotBaseUrl, getModels, getProviders, loadOAuthC
2
2
  import { Type } from "@sinclair/typebox";
3
3
  import AjvModule from "ajv";
4
4
  import { existsSync, readFileSync } from "fs";
5
- import { getModelsPath } from "../config.js";
5
+ import { join } from "path";
6
+ import { getAgentDir } from "../config.js";
6
7
  import { getOAuthToken, refreshToken } from "./oauth/index.js";
7
8
  // Handle both default and named exports
8
9
  const Ajv = AjvModule.default || AjvModule;
@@ -70,8 +71,8 @@ export function resolveApiKey(keyConfig) {
70
71
  * Load custom models from models.json in agent config dir
71
72
  * Returns { models, error } - either models array or error message
72
73
  */
73
- function loadCustomModels() {
74
- const configPath = getModelsPath();
74
+ function loadCustomModels(agentDir = getAgentDir()) {
75
+ const configPath = join(agentDir, "models.json");
75
76
  if (!existsSync(configPath)) {
76
77
  return { models: [], error: null };
77
78
  }
@@ -187,7 +188,7 @@ function parseModels(config) {
187
188
  * Get all models (built-in + custom), freshly loaded
188
189
  * Returns { models, error } - either models array or error message
189
190
  */
190
- export function loadAndMergeModels() {
191
+ export function loadAndMergeModels(agentDir = getAgentDir()) {
191
192
  const builtInModels = [];
192
193
  const providers = getProviders();
193
194
  // Load all built-in models
@@ -196,7 +197,7 @@ export function loadAndMergeModels() {
196
197
  builtInModels.push(...providerModels);
197
198
  }
198
199
  // Load custom models
199
- const { models: customModels, error } = loadCustomModels();
200
+ const { models: customModels, error } = loadCustomModels(agentDir);
200
201
  if (error) {
201
202
  return { models: [], error };
202
203
  }
@@ -215,7 +216,8 @@ export function loadAndMergeModels() {
215
216
  }
216
217
  /**
217
218
  * Get API key for a model (checks custom providers first, then built-in)
218
- * Now async to support OAuth token refresh
219
+ * Now async to support OAuth token refresh.
220
+ * Note: OAuth storage location is configured globally via setOAuthStorage.
219
221
  */
220
222
  export async function getApiKeyForModel(model) {
221
223
  // For custom providers, check their apiKey config
@@ -293,22 +295,13 @@ export async function getApiKeyForModel(model) {
293
295
  * Get only models that have valid API keys available
294
296
  * Returns { models, error } - either models array or error message
295
297
  */
296
- export async function getAvailableModels() {
297
- const { models: allModels, error } = loadAndMergeModels();
298
+ export async function getAvailableModels(agentDir = getAgentDir()) {
299
+ const { models: allModels, error } = loadAndMergeModels(agentDir);
298
300
  if (error) {
299
301
  return { models: [], error };
300
302
  }
301
303
  const availableModels = [];
302
- const copilotCreds = loadOAuthCredentials("github-copilot");
303
- const hasCopilotEnv = !!(process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN);
304
- const hasCopilot = !!copilotCreds || hasCopilotEnv;
305
304
  for (const model of allModels) {
306
- if (model.provider === "github-copilot") {
307
- if (hasCopilot) {
308
- availableModels.push(model);
309
- }
310
- continue;
311
- }
312
305
  const apiKey = await getApiKeyForModel(model);
313
306
  if (apiKey) {
314
307
  availableModels.push(model);
@@ -320,8 +313,8 @@ export async function getAvailableModels() {
320
313
  * Find a specific model by provider and ID
321
314
  * Returns { model, error } - either model or error message
322
315
  */
323
- export function findModel(provider, modelId) {
324
- const { models: allModels, error } = loadAndMergeModels();
316
+ export function findModel(provider, modelId, agentDir = getAgentDir()) {
317
+ const { models: allModels, error } = loadAndMergeModels(agentDir);
325
318
  if (error) {
326
319
  return { model: null, error };
327
320
  }
@@ -1 +1 @@
1
- {"version":3,"file":"model-config.js","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,SAAS,EACT,uBAAuB,EACvB,SAAS,EACT,YAAY,EAEZ,oBAAoB,EAEpB,eAAe,EACf,yBAAyB,EACzB,sBAAsB,EACtB,oBAAoB,GACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAsB,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEnF,wCAAwC;AACxC,MAAM,GAAG,GAAI,SAAiB,CAAC,OAAO,IAAI,SAAS,CAAC;AAEpD,2CAA2C;AAC3C,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC;IACtC,aAAa,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC5C,qBAAqB,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IACpD,uBAAuB,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IACtD,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,C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AEF,0EAA0E;AAC1E,MAAM,gBAAgB,GAAyB,IAAI,GAAG,EAAE,CAAC;AAEzD;;;GAGG;AACH,MAAM,UAAU,oBAAoB,GAAS;IAC5C,gBAAgB,CAAC,KAAK,EAAE,CAAC;AAAA,CACzB;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAiB,EAAW;IAC7D,MAAM,aAAa,GAAG,uBAAuB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9D,IAAI,CAAC,aAAa,EAAE,CAAC;QACpB,OAAO,KAAK,CAAC;IACd,CAAC;IAED,oBAAoB;IACpB,IAAI,gBAAgB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;QACzC,OAAO,gBAAgB,CAAC,GAAG,CAAC,aAAa,CAAE,CAAC;IAC7C,CAAC;IAED,qDAAqD;IACrD,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,MAAM,WAAW,GAAG,oBAAoB,CAAC,aAAa,CAAC,CAAC;IACxD,IAAI,WAAW,EAAE,CAAC;QACjB,UAAU,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,4DAA4D;IAC5D,IAAI,CAAC,UAAU,IAAI,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC;QACxF,UAAU,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,gBAAgB,CAAC,GAAG,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;IAChD,OAAO,UAAU,CAAC;AAAA,CAClB","sourcesContent":["import {\n\ttype Api,\n\tgetApiKey,\n\tgetGitHubCopilotBaseUrl,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\tloadOAuthCredentials,\n\ttype Model,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n\tremoveOAuthCredentials,\n\tsaveOAuthCredentials,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { getModelsPath } from \"../config.js\";\nimport { getOAuthToken, type OAuthProvider, refreshToken } from \"./oauth/index.js\";\n\n// Handle both default and named exports\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n});\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(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\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.String({ minLength: 1 }),\n\tapiKey: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: 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// Custom provider API key mappings (provider name -> apiKey config)\nconst customProviderApiKeys: Map<string, string> = new Map();\n\n/**\n * Resolve an API key config value to an actual key.\n * First checks if it's an environment variable, then treats as literal.\n */\nexport function resolveApiKey(keyConfig: string): string | undefined {\n\t// First check if it's an env var name\n\tconst envValue = process.env[keyConfig];\n\tif (envValue) return envValue;\n\n\t// Otherwise treat as literal API key\n\treturn keyConfig;\n}\n\n/**\n * Load custom models from models.json in agent config dir\n * Returns { models, error } - either models array or error message\n */\nfunction loadCustomModels(): { models: Model<Api>[]; error: string | null } {\n\tconst configPath = getModelsPath();\n\tif (!existsSync(configPath)) {\n\t\treturn { models: [], error: null };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(configPath, \"utf-8\");\n\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t// Validate schema\n\t\tconst ajv = new Ajv();\n\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\tif (!validate(config)) {\n\t\t\tconst errors =\n\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\"Unknown schema error\";\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json schema:\\n${errors}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Additional validation\n\t\ttry {\n\t\t\tvalidateConfig(config);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Parse models\n\t\treturn { models: parseModels(config), error: null };\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Failed to parse models.json: ${error.message}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodels: [],\n\t\t\terror: `Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t};\n\t}\n}\n\n/**\n * Validate config structure and requirements\n */\nfunction validateConfig(config: ModelsConfig): void {\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\tconst hasProviderApi = !!providerConfig.api;\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. ` +\n\t\t\t\t\t\t`Set at provider or model level.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate required fields\n\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t}\n\t}\n}\n\n/**\n * Parse config into Model objects\n */\nfunction parseModels(config: ModelsConfig): Model<Api>[] {\n\tconst models: Model<Api>[] = [];\n\n\t// Clear and rebuild custom provider API key mappings\n\tcustomProviderApiKeys.clear();\n\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t// Store API key config for this provider\n\t\tcustomProviderApiKeys.set(providerName, providerConfig.apiKey);\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\t// Model-level api overrides provider-level api\n\t\t\tconst api = modelDef.api || providerConfig.api;\n\n\t\t\tif (!api) {\n\t\t\t\t// This should have been caught by validateConfig, but be safe\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\tlet headers =\n\t\t\t\tproviderConfig.headers || modelDef.headers ? { ...providerConfig.headers, ...modelDef.headers } : undefined;\n\n\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\tif (providerConfig.authHeader) {\n\t\t\t\tconst resolvedKey = resolveApiKey(providerConfig.apiKey);\n\t\t\t\tif (resolvedKey) {\n\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodels.push({\n\t\t\t\tid: modelDef.id,\n\t\t\t\tname: modelDef.name,\n\t\t\t\tapi: api as Api,\n\t\t\t\tprovider: providerName,\n\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\tcost: modelDef.cost,\n\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\theaders,\n\t\t\t\tcompat: modelDef.compat,\n\t\t\t} as Model<Api>);\n\t\t}\n\t}\n\n\treturn models;\n}\n\n/**\n * Get all models (built-in + custom), freshly loaded\n * Returns { models, error } - either models array or error message\n */\nexport function loadAndMergeModels(): { models: Model<Api>[]; error: string | null } {\n\tconst builtInModels: Model<Api>[] = [];\n\tconst providers = getProviders();\n\n\t// Load all built-in models\n\tfor (const provider of providers) {\n\t\tconst providerModels = getModels(provider as KnownProvider);\n\t\tbuiltInModels.push(...(providerModels as Model<Api>[]));\n\t}\n\n\t// Load custom models\n\tconst { models: customModels, error } = loadCustomModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst combined = [...builtInModels, ...customModels];\n\n\t// Update github-copilot base URL based on OAuth token or enterprise domain\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tif (copilotCreds) {\n\t\tconst domain = copilotCreds.enterpriseUrl ? normalizeDomain(copilotCreds.enterpriseUrl) : undefined;\n\t\tconst baseUrl = getGitHubCopilotBaseUrl(copilotCreds.access, domain ?? undefined);\n\t\treturn {\n\t\t\tmodels: combined.map((m) => (m.provider === \"github-copilot\" ? { ...m, baseUrl } : m)),\n\t\t\terror: null,\n\t\t};\n\t}\n\n\treturn { models: combined, error: null };\n}\n\n/**\n * Get API key for a model (checks custom providers first, then built-in)\n * Now async to support OAuth token refresh\n */\nexport async function getApiKeyForModel(model: Model<Api>): Promise<string | undefined> {\n\t// For custom providers, check their apiKey config\n\tconst customKeyConfig = customProviderApiKeys.get(model.provider);\n\tif (customKeyConfig) {\n\t\treturn resolveApiKey(customKeyConfig);\n\t}\n\n\t// For Anthropic, check OAuth first\n\tif (model.provider === \"anthropic\") {\n\t\t// 1. Check OAuth storage (auto-refresh if needed)\n\t\tconst oauthToken = await getOAuthToken(\"anthropic\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Check ANTHROPIC_OAUTH_TOKEN env var (manual OAuth token)\n\t\tconst oauthEnv = process.env.ANTHROPIC_OAUTH_TOKEN;\n\t\tif (oauthEnv) {\n\t\t\treturn oauthEnv;\n\t\t}\n\n\t\t// 3. Fall back to ANTHROPIC_API_KEY env var\n\t}\n\n\tif (model.provider === \"github-copilot\") {\n\t\t// 1. Check OAuth storage (from device flow login)\n\t\tconst oauthToken = await getOAuthToken(\"github-copilot\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Use GitHub token directly (works with copilot scope on github.com)\n\t\tconst githubToken = process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t\tif (!githubToken) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// 3. For enterprise, exchange token for short-lived Copilot token\n\t\tconst enterpriseDomain = process.env.COPILOT_ENTERPRISE_URL\n\t\t\t? normalizeDomain(process.env.COPILOT_ENTERPRISE_URL)\n\t\t\t: undefined;\n\n\t\tif (enterpriseDomain) {\n\t\t\tconst creds = await refreshGitHubCopilotToken(githubToken, enterpriseDomain);\n\t\t\tsaveOAuthCredentials(\"github-copilot\", creds);\n\t\t\treturn creds.access;\n\t\t}\n\n\t\t// 4. For github.com, use token directly\n\t\treturn githubToken;\n\t}\n\n\t// For Google Gemini CLI and Antigravity, check OAuth and encode projectId with token\n\tif (model.provider === \"google-gemini-cli\" || model.provider === \"google-antigravity\") {\n\t\tconst oauthProvider = model.provider as \"google-gemini-cli\" | \"google-antigravity\";\n\t\tconst credentials = loadOAuthCredentials(oauthProvider);\n\t\tif (!credentials) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Check if token is expired\n\t\tif (Date.now() >= credentials.expires) {\n\t\t\ttry {\n\t\t\t\tawait refreshToken(oauthProvider);\n\t\t\t\tconst refreshedCreds = loadOAuthCredentials(oauthProvider);\n\t\t\t\tif (refreshedCreds?.projectId) {\n\t\t\t\t\treturn JSON.stringify({ token: refreshedCreds.access, projectId: refreshedCreds.projectId });\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremoveOAuthCredentials(oauthProvider);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tif (credentials.projectId) {\n\t\t\treturn JSON.stringify({ token: credentials.access, projectId: credentials.projectId });\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// For built-in providers, use getApiKey from @mariozechner/pi-ai\n\treturn getApiKey(model.provider as KnownProvider);\n}\n\n/**\n * Get only models that have valid API keys available\n * Returns { models, error } - either models array or error message\n */\nexport async function getAvailableModels(): Promise<{ models: Model<Api>[]; error: string | null }> {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst availableModels: Model<Api>[] = [];\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tconst hasCopilotEnv = !!(process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN);\n\tconst hasCopilot = !!copilotCreds || hasCopilotEnv;\n\n\tfor (const model of allModels) {\n\t\tif (model.provider === \"github-copilot\") {\n\t\t\tif (hasCopilot) {\n\t\t\t\tavailableModels.push(model);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst apiKey = await getApiKeyForModel(model);\n\t\tif (apiKey) {\n\t\t\tavailableModels.push(model);\n\t\t}\n\t}\n\n\treturn { models: availableModels, error: null };\n}\n\n/**\n * Find a specific model by provider and ID\n * Returns { model, error } - either model or error message\n */\nexport function findModel(provider: string, modelId: string): { model: Model<Api> | null; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels();\n\n\tif (error) {\n\t\treturn { model: null, error };\n\t}\n\n\tconst model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;\n\treturn { model, error: null };\n}\n\n/**\n * Mapping from model provider to OAuth provider ID.\n * Only providers that support OAuth are listed here.\n */\nconst providerToOAuthProvider: Record<string, OAuthProvider> = {\n\tanthropic: \"anthropic\",\n\t\"github-copilot\": \"github-copilot\",\n\t\"google-gemini-cli\": \"google-gemini-cli\",\n\t\"google-antigravity\": \"google-antigravity\",\n};\n\n// Cache for OAuth status per provider (avoids file reads on every render)\nconst oauthStatusCache: Map<string, boolean> = new Map();\n\n/**\n * Invalidate the OAuth status cache.\n * Call this after login/logout operations.\n */\nexport function invalidateOAuthCache(): void {\n\toauthStatusCache.clear();\n}\n\n/**\n * Check if a model is using OAuth credentials (subscription).\n * This checks if OAuth credentials exist and would be used for the model,\n * without actually fetching or refreshing the token.\n * Results are cached until invalidateOAuthCache() is called.\n */\nexport function isModelUsingOAuth(model: Model<Api>): boolean {\n\tconst oauthProvider = providerToOAuthProvider[model.provider];\n\tif (!oauthProvider) {\n\t\treturn false;\n\t}\n\n\t// Check cache first\n\tif (oauthStatusCache.has(oauthProvider)) {\n\t\treturn oauthStatusCache.get(oauthProvider)!;\n\t}\n\n\t// Check if OAuth credentials exist for this provider\n\tlet usingOAuth = false;\n\tconst credentials = loadOAuthCredentials(oauthProvider);\n\tif (credentials) {\n\t\tusingOAuth = true;\n\t}\n\n\t// Also check for manual OAuth token env var (for Anthropic)\n\tif (!usingOAuth && model.provider === \"anthropic\" && process.env.ANTHROPIC_OAUTH_TOKEN) {\n\t\tusingOAuth = true;\n\t}\n\n\toauthStatusCache.set(oauthProvider, usingOAuth);\n\treturn usingOAuth;\n}\n"]}
1
+ {"version":3,"file":"model-config.js","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,SAAS,EACT,uBAAuB,EACvB,SAAS,EACT,YAAY,EAEZ,oBAAoB,EAEpB,eAAe,EACf,yBAAyB,EACzB,sBAAsB,EACtB,oBAAoB,GACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,SAAS,MAAM,KAAK,CAAC;AAC5B,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;AAC3C,OAAO,EAAE,aAAa,EAAsB,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEnF,wCAAwC;AACxC,MAAM,GAAG,GAAI,SAAiB,CAAC,OAAO,IAAI,SAAS,CAAC;AAEpD,2CAA2C;AAC3C,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC;IACtC,aAAa,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC5C,qBAAqB,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IACpD,uBAAuB,EAAE,IAAI,CAAC,QAAQ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CAAC;AAAA,CACzB;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAiB,EAAW;IAC7D,MAAM,aAAa,GAAG,uBAAuB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC9D,IAAI,CAAC,aAAa,EAAE,CAAC;QACpB,OAAO,KAAK,CAAC;IACd,CAAC;IAED,oBAAoB;IACpB,IAAI,gBAAgB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,CAAC;QACzC,OAAO,gBAAgB,CAAC,GAAG,CAAC,aAAa,CAAE,CAAC;IAC7C,CAAC;IAED,qDAAqD;IACrD,IAAI,UAAU,GAAG,KAAK,CAAC;IACvB,MAAM,WAAW,GAAG,oBAAoB,CAAC,aAAa,CAAC,CAAC;IACxD,IAAI,WAAW,EAAE,CAAC;QACjB,UAAU,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,4DAA4D;IAC5D,IAAI,CAAC,UAAU,IAAI,KAAK,CAAC,QAAQ,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC;QACxF,UAAU,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,gBAAgB,CAAC,GAAG,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;IAChD,OAAO,UAAU,CAAC;AAAA,CAClB","sourcesContent":["import {\n\ttype Api,\n\tgetApiKey,\n\tgetGitHubCopilotBaseUrl,\n\tgetModels,\n\tgetProviders,\n\ttype KnownProvider,\n\tloadOAuthCredentials,\n\ttype Model,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n\tremoveOAuthCredentials,\n\tsaveOAuthCredentials,\n} from \"@mariozechner/pi-ai\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport AjvModule from \"ajv\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.js\";\nimport { getOAuthToken, type OAuthProvider, refreshToken } from \"./oauth/index.js\";\n\n// Handle both default and named exports\nconst Ajv = (AjvModule as any).default || AjvModule;\n\n// Schema for OpenAI compatibility settings\nconst OpenAICompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n});\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(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\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.String({ minLength: 1 }),\n\tapiKey: Type.String({ minLength: 1 }),\n\tapi: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai-completions\"),\n\t\t\tType.Literal(\"openai-responses\"),\n\t\t\tType.Literal(\"anthropic-messages\"),\n\t\t\tType.Literal(\"google-generative-ai\"),\n\t\t]),\n\t),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: 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// Custom provider API key mappings (provider name -> apiKey config)\nconst customProviderApiKeys: Map<string, string> = new Map();\n\n/**\n * Resolve an API key config value to an actual key.\n * First checks if it's an environment variable, then treats as literal.\n */\nexport function resolveApiKey(keyConfig: string): string | undefined {\n\t// First check if it's an env var name\n\tconst envValue = process.env[keyConfig];\n\tif (envValue) return envValue;\n\n\t// Otherwise treat as literal API key\n\treturn keyConfig;\n}\n\n/**\n * Load custom models from models.json in agent config dir\n * Returns { models, error } - either models array or error message\n */\nfunction loadCustomModels(agentDir: string = getAgentDir()): { models: Model<Api>[]; error: string | null } {\n\tconst configPath = join(agentDir, \"models.json\");\n\tif (!existsSync(configPath)) {\n\t\treturn { models: [], error: null };\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(configPath, \"utf-8\");\n\t\tconst config: ModelsConfig = JSON.parse(content);\n\n\t\t// Validate schema\n\t\tconst ajv = new Ajv();\n\t\tconst validate = ajv.compile(ModelsConfigSchema);\n\t\tif (!validate(config)) {\n\t\t\tconst errors =\n\t\t\t\tvalidate.errors?.map((e: any) => ` - ${e.instancePath || \"root\"}: ${e.message}`).join(\"\\n\") ||\n\t\t\t\t\"Unknown schema error\";\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json schema:\\n${errors}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Additional validation\n\t\ttry {\n\t\t\tvalidateConfig(config);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Invalid models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\n\t\t// Parse models\n\t\treturn { models: parseModels(config), error: null };\n\t} catch (error) {\n\t\tif (error instanceof SyntaxError) {\n\t\t\treturn {\n\t\t\t\tmodels: [],\n\t\t\t\terror: `Failed to parse models.json: ${error.message}\\n\\nFile: ${configPath}`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tmodels: [],\n\t\t\terror: `Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${configPath}`,\n\t\t};\n\t}\n}\n\n/**\n * Validate config structure and requirements\n */\nfunction validateConfig(config: ModelsConfig): void {\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\tconst hasProviderApi = !!providerConfig.api;\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\tconst hasModelApi = !!modelDef.api;\n\n\t\t\tif (!hasProviderApi && !hasModelApi) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Provider ${providerName}, model ${modelDef.id}: no \"api\" specified. ` +\n\t\t\t\t\t\t`Set at provider or model level.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Validate required fields\n\t\t\tif (!modelDef.id) throw new Error(`Provider ${providerName}: model missing \"id\"`);\n\t\t\tif (!modelDef.name) throw new Error(`Provider ${providerName}: model missing \"name\"`);\n\t\t\tif (modelDef.contextWindow <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid contextWindow`);\n\t\t\tif (modelDef.maxTokens <= 0)\n\t\t\t\tthrow new Error(`Provider ${providerName}, model ${modelDef.id}: invalid maxTokens`);\n\t\t}\n\t}\n}\n\n/**\n * Parse config into Model objects\n */\nfunction parseModels(config: ModelsConfig): Model<Api>[] {\n\tconst models: Model<Api>[] = [];\n\n\t// Clear and rebuild custom provider API key mappings\n\tcustomProviderApiKeys.clear();\n\n\tfor (const [providerName, providerConfig] of Object.entries(config.providers)) {\n\t\t// Store API key config for this provider\n\t\tcustomProviderApiKeys.set(providerName, providerConfig.apiKey);\n\n\t\tfor (const modelDef of providerConfig.models) {\n\t\t\t// Model-level api overrides provider-level api\n\t\t\tconst api = modelDef.api || providerConfig.api;\n\n\t\t\tif (!api) {\n\t\t\t\t// This should have been caught by validateConfig, but be safe\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Merge headers: provider headers are base, model headers override\n\t\t\tlet headers =\n\t\t\t\tproviderConfig.headers || modelDef.headers ? { ...providerConfig.headers, ...modelDef.headers } : undefined;\n\n\t\t\t// If authHeader is true, add Authorization header with resolved API key\n\t\t\tif (providerConfig.authHeader) {\n\t\t\t\tconst resolvedKey = resolveApiKey(providerConfig.apiKey);\n\t\t\t\tif (resolvedKey) {\n\t\t\t\t\theaders = { ...headers, Authorization: `Bearer ${resolvedKey}` };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmodels.push({\n\t\t\t\tid: modelDef.id,\n\t\t\t\tname: modelDef.name,\n\t\t\t\tapi: api as Api,\n\t\t\t\tprovider: providerName,\n\t\t\t\tbaseUrl: providerConfig.baseUrl,\n\t\t\t\treasoning: modelDef.reasoning,\n\t\t\t\tinput: modelDef.input as (\"text\" | \"image\")[],\n\t\t\t\tcost: modelDef.cost,\n\t\t\t\tcontextWindow: modelDef.contextWindow,\n\t\t\t\tmaxTokens: modelDef.maxTokens,\n\t\t\t\theaders,\n\t\t\t\tcompat: modelDef.compat,\n\t\t\t} as Model<Api>);\n\t\t}\n\t}\n\n\treturn models;\n}\n\n/**\n * Get all models (built-in + custom), freshly loaded\n * Returns { models, error } - either models array or error message\n */\nexport function loadAndMergeModels(agentDir: string = getAgentDir()): { models: Model<Api>[]; error: string | null } {\n\tconst builtInModels: Model<Api>[] = [];\n\tconst providers = getProviders();\n\n\t// Load all built-in models\n\tfor (const provider of providers) {\n\t\tconst providerModels = getModels(provider as KnownProvider);\n\t\tbuiltInModels.push(...(providerModels as Model<Api>[]));\n\t}\n\n\t// Load custom models\n\tconst { models: customModels, error } = loadCustomModels(agentDir);\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst combined = [...builtInModels, ...customModels];\n\n\t// Update github-copilot base URL based on OAuth token or enterprise domain\n\tconst copilotCreds = loadOAuthCredentials(\"github-copilot\");\n\tif (copilotCreds) {\n\t\tconst domain = copilotCreds.enterpriseUrl ? normalizeDomain(copilotCreds.enterpriseUrl) : undefined;\n\t\tconst baseUrl = getGitHubCopilotBaseUrl(copilotCreds.access, domain ?? undefined);\n\t\treturn {\n\t\t\tmodels: combined.map((m) => (m.provider === \"github-copilot\" ? { ...m, baseUrl } : m)),\n\t\t\terror: null,\n\t\t};\n\t}\n\n\treturn { models: combined, error: null };\n}\n\n/**\n * Get API key for a model (checks custom providers first, then built-in)\n * Now async to support OAuth token refresh.\n * Note: OAuth storage location is configured globally via setOAuthStorage.\n */\nexport async function getApiKeyForModel(model: Model<Api>): Promise<string | undefined> {\n\t// For custom providers, check their apiKey config\n\tconst customKeyConfig = customProviderApiKeys.get(model.provider);\n\tif (customKeyConfig) {\n\t\treturn resolveApiKey(customKeyConfig);\n\t}\n\n\t// For Anthropic, check OAuth first\n\tif (model.provider === \"anthropic\") {\n\t\t// 1. Check OAuth storage (auto-refresh if needed)\n\t\tconst oauthToken = await getOAuthToken(\"anthropic\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Check ANTHROPIC_OAUTH_TOKEN env var (manual OAuth token)\n\t\tconst oauthEnv = process.env.ANTHROPIC_OAUTH_TOKEN;\n\t\tif (oauthEnv) {\n\t\t\treturn oauthEnv;\n\t\t}\n\n\t\t// 3. Fall back to ANTHROPIC_API_KEY env var\n\t}\n\n\tif (model.provider === \"github-copilot\") {\n\t\t// 1. Check OAuth storage (from device flow login)\n\t\tconst oauthToken = await getOAuthToken(\"github-copilot\");\n\t\tif (oauthToken) {\n\t\t\treturn oauthToken;\n\t\t}\n\n\t\t// 2. Use GitHub token directly (works with copilot scope on github.com)\n\t\tconst githubToken = process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;\n\t\tif (!githubToken) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// 3. For enterprise, exchange token for short-lived Copilot token\n\t\tconst enterpriseDomain = process.env.COPILOT_ENTERPRISE_URL\n\t\t\t? normalizeDomain(process.env.COPILOT_ENTERPRISE_URL)\n\t\t\t: undefined;\n\n\t\tif (enterpriseDomain) {\n\t\t\tconst creds = await refreshGitHubCopilotToken(githubToken, enterpriseDomain);\n\t\t\tsaveOAuthCredentials(\"github-copilot\", creds);\n\t\t\treturn creds.access;\n\t\t}\n\n\t\t// 4. For github.com, use token directly\n\t\treturn githubToken;\n\t}\n\n\t// For Google Gemini CLI and Antigravity, check OAuth and encode projectId with token\n\tif (model.provider === \"google-gemini-cli\" || model.provider === \"google-antigravity\") {\n\t\tconst oauthProvider = model.provider as \"google-gemini-cli\" | \"google-antigravity\";\n\t\tconst credentials = loadOAuthCredentials(oauthProvider);\n\t\tif (!credentials) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Check if token is expired\n\t\tif (Date.now() >= credentials.expires) {\n\t\t\ttry {\n\t\t\t\tawait refreshToken(oauthProvider);\n\t\t\t\tconst refreshedCreds = loadOAuthCredentials(oauthProvider);\n\t\t\t\tif (refreshedCreds?.projectId) {\n\t\t\t\t\treturn JSON.stringify({ token: refreshedCreds.access, projectId: refreshedCreds.projectId });\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tremoveOAuthCredentials(oauthProvider);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tif (credentials.projectId) {\n\t\t\treturn JSON.stringify({ token: credentials.access, projectId: credentials.projectId });\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// For built-in providers, use getApiKey from @mariozechner/pi-ai\n\treturn getApiKey(model.provider as KnownProvider);\n}\n\n/**\n * Get only models that have valid API keys available\n * Returns { models, error } - either models array or error message\n */\nexport async function getAvailableModels(\n\tagentDir: string = getAgentDir(),\n): Promise<{ models: Model<Api>[]; error: string | null }> {\n\tconst { models: allModels, error } = loadAndMergeModels(agentDir);\n\n\tif (error) {\n\t\treturn { models: [], error };\n\t}\n\n\tconst availableModels: Model<Api>[] = [];\n\tfor (const model of allModels) {\n\t\tconst apiKey = await getApiKeyForModel(model);\n\t\tif (apiKey) {\n\t\t\tavailableModels.push(model);\n\t\t}\n\t}\n\n\treturn { models: availableModels, error: null };\n}\n\n/**\n * Find a specific model by provider and ID\n * Returns { model, error } - either model or error message\n */\nexport function findModel(\n\tprovider: string,\n\tmodelId: string,\n\tagentDir: string = getAgentDir(),\n): { model: Model<Api> | null; error: string | null } {\n\tconst { models: allModels, error } = loadAndMergeModels(agentDir);\n\n\tif (error) {\n\t\treturn { model: null, error };\n\t}\n\n\tconst model = allModels.find((m) => m.provider === provider && m.id === modelId) || null;\n\treturn { model, error: null };\n}\n\n/**\n * Mapping from model provider to OAuth provider ID.\n * Only providers that support OAuth are listed here.\n */\nconst providerToOAuthProvider: Record<string, OAuthProvider> = {\n\tanthropic: \"anthropic\",\n\t\"github-copilot\": \"github-copilot\",\n\t\"google-gemini-cli\": \"google-gemini-cli\",\n\t\"google-antigravity\": \"google-antigravity\",\n};\n\n// Cache for OAuth status per provider (avoids file reads on every render)\nconst oauthStatusCache: Map<string, boolean> = new Map();\n\n/**\n * Invalidate the OAuth status cache.\n * Call this after login/logout operations.\n */\nexport function invalidateOAuthCache(): void {\n\toauthStatusCache.clear();\n}\n\n/**\n * Check if a model is using OAuth credentials (subscription).\n * This checks if OAuth credentials exist and would be used for the model,\n * without actually fetching or refreshing the token.\n * Results are cached until invalidateOAuthCache() is called.\n */\nexport function isModelUsingOAuth(model: Model<Api>): boolean {\n\tconst oauthProvider = providerToOAuthProvider[model.provider];\n\tif (!oauthProvider) {\n\t\treturn false;\n\t}\n\n\t// Check cache first\n\tif (oauthStatusCache.has(oauthProvider)) {\n\t\treturn oauthStatusCache.get(oauthProvider)!;\n\t}\n\n\t// Check if OAuth credentials exist for this provider\n\tlet usingOAuth = false;\n\tconst credentials = loadOAuthCredentials(oauthProvider);\n\tif (credentials) {\n\t\tusingOAuth = true;\n\t}\n\n\t// Also check for manual OAuth token env var (for Anthropic)\n\tif (!usingOAuth && model.provider === \"anthropic\" && process.env.ANTHROPIC_OAUTH_TOKEN) {\n\t\tusingOAuth = true;\n\t}\n\n\toauthStatusCache.set(oauthProvider, usingOAuth);\n\treturn usingOAuth;\n}\n"]}