@bastani/atomic 0.9.5-alpha.6 → 0.9.5-alpha.7
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.
- package/CHANGELOG.md +18 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/bun/split-loader.d.ts +2 -0
- package/dist/bun/split-loader.d.ts.map +1 -0
- package/dist/bun/split-loader.js +37 -0
- package/dist/bun/split-loader.js.map +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +6 -4
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts +5 -4
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +15 -9
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +1 -1
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +1 -1
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/builtin-packages.d.ts.map +1 -1
- package/dist/core/builtin-packages.js +8 -4
- package/dist/core/builtin-packages.js.map +1 -1
- package/dist/core/copilot-model-catalog.d.ts.map +1 -1
- package/dist/core/copilot-model-catalog.js +3 -2
- package/dist/core/copilot-model-catalog.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +8 -3
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/openai-responses-payload-sanitizer.d.ts +6 -0
- package/dist/core/openai-responses-payload-sanitizer.d.ts.map +1 -0
- package/dist/core/openai-responses-payload-sanitizer.js +59 -0
- package/dist/core/openai-responses-payload-sanitizer.js.map +1 -0
- package/dist/core/package-manager-auto-resources.d.ts +2 -2
- package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
- package/dist/core/package-manager-auto-resources.js +32 -52
- package/dist/core/package-manager-auto-resources.js.map +1 -1
- package/dist/core/package-manager-resolver.d.ts.map +1 -1
- package/dist/core/package-manager-resolver.js +23 -14
- package/dist/core/package-manager-resolver.js.map +1 -1
- package/dist/core/package-manager-resource-collector.d.ts +3 -3
- package/dist/core/package-manager-resource-collector.d.ts.map +1 -1
- package/dist/core/package-manager-resource-collector.js +76 -73
- package/dist/core/package-manager-resource-collector.js.map +1 -1
- package/dist/core/package-manager-resource-files.d.ts +9 -8
- package/dist/core/package-manager-resource-files.d.ts.map +1 -1
- package/dist/core/package-manager-resource-files.js +92 -81
- package/dist/core/package-manager-resource-files.js.map +1 -1
- package/dist/core/prompt-templates-async.d.ts +3 -0
- package/dist/core/prompt-templates-async.d.ts.map +1 -0
- package/dist/core/prompt-templates-async.js +118 -0
- package/dist/core/prompt-templates-async.js.map +1 -0
- package/dist/core/provider-context-usage.d.ts +11 -0
- package/dist/core/provider-context-usage.d.ts.map +1 -0
- package/dist/core/provider-context-usage.js +58 -0
- package/dist/core/provider-context-usage.js.map +1 -0
- package/dist/core/resource-loader-assets.d.ts +3 -3
- package/dist/core/resource-loader-assets.d.ts.map +1 -1
- package/dist/core/resource-loader-assets.js +66 -83
- package/dist/core/resource-loader-assets.js.map +1 -1
- package/dist/core/resource-loader-core.d.ts +1 -1
- package/dist/core/resource-loader-core.d.ts.map +1 -1
- package/dist/core/resource-loader-core.js +5 -5
- package/dist/core/resource-loader-core.js.map +1 -1
- package/dist/core/resource-loader-reload.d.ts.map +1 -1
- package/dist/core/resource-loader-reload.js +43 -7
- package/dist/core/resource-loader-reload.js.map +1 -1
- package/dist/core/resource-loader-types.d.ts +7 -1
- package/dist/core/resource-loader-types.d.ts.map +1 -1
- package/dist/core/resource-loader-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +6 -4
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/skills-async.d.ts +3 -0
- package/dist/core/skills-async.d.ts.map +1 -0
- package/dist/core/skills-async.js +269 -0
- package/dist/core/skills-async.js.map +1 -0
- package/dist/main-deferred-startup.d.ts +2 -0
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +2 -0
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -4
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +10 -1
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.d.ts +6 -0
- package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +27 -13
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-editor-actions.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-editor-actions.js +13 -13
- package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-extension-runtime.js +16 -0
- package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +48 -0
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +5 -0
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +18 -6
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +3 -3
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-onboarding.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-onboarding.js +1 -0
- package/dist/modes/interactive/interactive-onboarding.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +43 -6
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +57 -0
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-resource-disclosure.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-resource-disclosure.js +3 -2
- package/dist/modes/interactive/interactive-resource-disclosure.js.map +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.js +10 -8
- package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.js +1 -1
- package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +59 -52
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/theme/theme-loading.d.ts +1 -0
- package/dist/modes/interactive/theme/theme-loading.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-loading.js +3 -0
- package/dist/modes/interactive/theme/theme-loading.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -1
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/utils/module-require.d.ts +11 -0
- package/dist/utils/module-require.d.ts.map +1 -1
- package/dist/utils/module-require.js +14 -1
- package/dist/utils/module-require.js.map +1 -1
- package/dist/utils/split-launcher.d.ts +38 -0
- package/dist/utils/split-launcher.d.ts.map +1 -0
- package/dist/utils/split-launcher.js +63 -0
- package/dist/utils/split-launcher.js.map +1 -0
- package/docs/compaction.md +3 -0
- package/docs/keybindings.md +2 -2
- package/docs/providers.md +1 -1
- package/docs/settings.md +2 -2
- package/docs/usage.md +1 -1
- package/npm-shrinkwrap.json +23 -23
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin-packages.js","sourceRoot":"","sources":["../../src/core/builtin-packages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"builtin-packages.js","sourceRoot":"","sources":["../../src/core/builtin-packages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAsBlE,MAAM,kBAAkB,GAAoC;IAC3D;QACC,WAAW,EAAE,oBAAoB;QACjC,gBAAgB,EAAE,WAAW;QAC7B,WAAW,EAAE,WAAW;QACxB,aAAa,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,EAAE,UAAU,CAAC;KACnD;IACD;QACC,WAAW,EAAE,oBAAoB;QACjC,gBAAgB,EAAE,WAAW;QAC7B,WAAW,EAAE,WAAW;QACxB,aAAa,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,EAAE,UAAU,CAAC;KACnD;IAC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EAAE,oBAAoB,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC;QAC3C,UAAU;QACV,gBAAgB,EAAE,KAAK;KACvB,CAAC;IACF,OAAO;QACN,GAAG,OAAO;QACV,gBAAgB,EAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;KACxE,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,sBAAsB;IACrC,MAAM,OAAO,GAAG,iCAAiC,EAAE,CAAC;IAEpD,OAAO,gBAAgB,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QAC9C,MAAM,UAAU,GAAG,uBAAuB,CACzC,CAAC,GAAG,UAAU,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,GAAG,cAAc,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC,EACjF,UAAU,CACV,CAAC;QACF,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACvC,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { getPackageDir } from \"../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../utils/split-launcher.ts\";\n\ninterface BuiltinPackageDescriptor {\n\treadonly packageName: string;\n\treadonly distDirName: string;\n\treadonly requiredEntry: string;\n\treadonly sourceCandidates: (context: BuiltinPackageCandidateContext) => string[];\n}\n\ninterface BuiltinPackageCandidateContext {\n\treadonly here: string;\n\treadonly packageDir: string;\n\treadonly isSourceCheckout: boolean;\n}\n\ninterface WorkspaceBuiltinSpec {\n\treadonly packageName: string;\n\treadonly workspaceDirName: string;\n\treadonly distDirName: string;\n\treadonly requiredEntry: string;\n}\n\nconst WORKSPACE_BUILTINS: readonly WorkspaceBuiltinSpec[] = [\n\t{\n\t\tpackageName: \"@bastani/workflows\",\n\t\tworkspaceDirName: \"workflows\",\n\t\tdistDirName: \"workflows\",\n\t\trequiredEntry: join(\"src\", \"extension\", \"index.ts\"),\n\t},\n\t{\n\t\tpackageName: \"@bastani/subagents\",\n\t\tworkspaceDirName: \"subagents\",\n\t\tdistDirName: \"subagents\",\n\t\trequiredEntry: join(\"src\", \"extension\", \"index.ts\"),\n\t},\n\t{\n\t\tpackageName: \"@bastani/mcp\",\n\t\tworkspaceDirName: \"mcp\",\n\t\tdistDirName: \"mcp\",\n\t\trequiredEntry: \"index.ts\",\n\t},\n\t{\n\t\tpackageName: \"@bastani/web-access\",\n\t\tworkspaceDirName: \"web-access\",\n\t\tdistDirName: \"web-access\",\n\t\trequiredEntry: \"index.ts\",\n\t},\n\t{\n\t\tpackageName: \"@bastani/intercom\",\n\t\tworkspaceDirName: \"intercom\",\n\t\tdistDirName: \"intercom\",\n\t\trequiredEntry: \"index.ts\",\n\t},\n\t{\n\t\tpackageName: \"@bastani/cursor\",\n\t\tworkspaceDirName: \"cursor\",\n\t\tdistDirName: \"cursor\",\n\t\trequiredEntry: \"index.ts\",\n\t},\n];\n\nconst BUILTIN_PACKAGES: readonly BuiltinPackageDescriptor[] = WORKSPACE_BUILTINS.map(\n\t(spec): BuiltinPackageDescriptor => ({\n\t\tpackageName: spec.packageName,\n\t\tdistDirName: spec.distDirName,\n\t\trequiredEntry: spec.requiredEntry,\n\t\tsourceCandidates: ({ here, packageDir, isSourceCheckout }) =>\n\t\t\tisSourceCheckout\n\t\t\t\t? [\n\t\t\t\t\t\tjoin(packageDir, \"..\", spec.workspaceDirName),\n\t\t\t\t\t\tjoin(here, \"..\", \"..\", \"..\", spec.workspaceDirName),\n\t\t\t\t\t]\n\t\t\t\t: [],\n\t}),\n);\n\nfunction readPackageName(packageJsonPath: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as { name?: string };\n\t\treturn pkg.name;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isPackageDir(dir: string, descriptor: BuiltinPackageDescriptor): boolean {\n\treturn (\n\t\texistsSync(join(dir, descriptor.requiredEntry)) &&\n\t\treadPackageName(join(dir, \"package.json\")) === descriptor.packageName\n\t);\n}\n\nfunction firstExistingPackageDir(candidates: string[], descriptor: BuiltinPackageDescriptor): string | undefined {\n\tconst seen = new Set<string>();\n\n\tfor (const candidate of candidates) {\n\t\tconst resolved = resolve(candidate);\n\t\tif (seen.has(resolved)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(resolved);\n\t\tif (isPackageDir(resolved, descriptor)) {\n\t\t\treturn resolved;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction distCandidates(context: BuiltinPackageCandidateContext, descriptor: BuiltinPackageDescriptor): string[] {\n\tconst { here, packageDir } = context;\n\treturn [\n\t\tjoin(here, \"..\", \"builtin\", descriptor.distDirName),\n\t\tjoin(packageDir, \"builtin\", descriptor.distDirName),\n\t\tjoin(packageDir, \"dist\", \"builtin\", descriptor.distDirName),\n\t];\n}\nfunction getBuiltinPackageCandidateContext(): BuiltinPackageCandidateContext {\n\tconst packageDir = getPackageDir();\n\t// In the split launcher the bundled import.meta.url is a foreign-OS build\n\t// path; fall back to the package dir (the executable dir), where `builtin/`\n\t// sits, so distCandidates still resolves.\n\tconst context: BuiltinPackageCandidateContext = {\n\t\there: moduleDirFromMetaUrl(import.meta.url),\n\t\tpackageDir,\n\t\tisSourceCheckout: false,\n\t};\n\treturn {\n\t\t...context,\n\t\tisSourceCheckout: existsSync(join(context.packageDir, \"src\", \"main.ts\")),\n\t};\n}\n\n/**\n * Built-in pi package roots shipped with this Atomic distribution.\n *\n * Development layout:\n * packages/coding-agent/src/core -> packages/<builtin>\n *\n * npm/dist layout:\n * packages/coding-agent/dist/core -> packages/coding-agent/dist/builtin/<package>\n *\n * Bun binary layout:\n * process executable dir -> builtin/<package>\n */\nexport function getBuiltinPackagePaths(): string[] {\n\tconst context = getBuiltinPackageCandidateContext();\n\n\treturn BUILTIN_PACKAGES.flatMap((descriptor) => {\n\t\tconst packageDir = firstExistingPackageDir(\n\t\t\t[...descriptor.sourceCandidates(context), ...distCandidates(context, descriptor)],\n\t\t\tdescriptor,\n\t\t);\n\t\treturn packageDir ? [packageDir] : [];\n\t});\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-model-catalog.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAK/E,yGAAyG;AACzG,MAAM,WAAW,mBAAmB;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IAC5B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,oBAAoB;IACpC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,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AM,EACf,OAAO,EAAE,mBAAmB,EAC5B,GAAG,CAAC,EAAE,MAAM,GACV,IAAI,CAaN;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;;;;;;;;;GASG;AACH,wBAAgB,sCAAsC,CACrD,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,EAAE,MAAM,GACV,OAAO,CAOT","sourcesContent":["/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"copilot-model-catalog.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAK/E,yGAAyG;AACzG,MAAM,WAAW,mBAAmB;IACnC,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,MAAM,CAAC,EAAE,kBAAkB,CAAC;IAC5B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,WAAW,CAAC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,CAE/E;AAED,iFAAiF;AACjF,wBAAgB,4BAA4B,IAAI,mBAAmB,CAElE;AAED,sDAAsD;AACtD,wBAAgB,8BAA8B,IAAI,IAAI,CAErD;AAuBD,MAAM,WAAW,8BAA8B;IAC9C,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,+CAA+C;IAC/C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AA+DD,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,8BAA8B,GACrC,mBAAmB,GAAG,SAAS,CAsBjC;AAED,wBAAgB,wBAAwB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,mBAAmB,EAC5B,GAAG,CAAC,EAAE,MAAM,GACV,IAAI,CAaN;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED;;;;;;;;;GASG;AACH,wBAAgB,sCAAsC,CACrD,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,EAAE,MAAM,GACV,OAAO,CAOT","sourcesContent":["/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\nconst GHE_COPILOT_API_HOST_PREFIX = [\"copilot\", \"api\"].join(\"-\");\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://${GHE_COPILOT_API_HOST_PREFIX}.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://${GHE_COPILOT_API_HOST_PREFIX}.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
@@ -21,6 +21,7 @@ export const DEFAULT_COPILOT_API_BASE_URL = "https://api.individual.githubcopilo
|
|
|
21
21
|
export const COPILOT_PUBLIC_API_BASE_URL = "https://api.githubcopilot.com";
|
|
22
22
|
/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */
|
|
23
23
|
export const COPILOT_ENTERPRISE_API_BASE_URL = "https://api.enterprise.githubcopilot.com";
|
|
24
|
+
const GHE_COPILOT_API_HOST_PREFIX = ["copilot", "api"].join("-");
|
|
24
25
|
export const COPILOT_GITHUB_TOKEN_ENV = "COPILOT_GITHUB_TOKEN";
|
|
25
26
|
export const COPILOT_API_TARGET_ENV = "COPILOT_API_TARGET";
|
|
26
27
|
export const GITHUB_COPILOT_BASE_URL_ENV = "GITHUB_COPILOT_BASE_URL";
|
|
@@ -51,7 +52,7 @@ function copilotApiBaseUrlFromServerUrl(serverUrl) {
|
|
|
51
52
|
if (!host || host === "github.com")
|
|
52
53
|
return undefined;
|
|
53
54
|
if (host.endsWith(".ghe.com"))
|
|
54
|
-
return `https
|
|
55
|
+
return `https://${GHE_COPILOT_API_HOST_PREFIX}.${host}`;
|
|
55
56
|
return COPILOT_ENTERPRISE_API_BASE_URL;
|
|
56
57
|
}
|
|
57
58
|
catch {
|
|
@@ -81,7 +82,7 @@ export function copilotApiBaseUrlFromToken(token, enterpriseDomain, env = proces
|
|
|
81
82
|
}
|
|
82
83
|
}
|
|
83
84
|
if (enterpriseDomain)
|
|
84
|
-
return `https
|
|
85
|
+
return `https://${GHE_COPILOT_API_HOST_PREFIX}.${enterpriseDomain}`;
|
|
85
86
|
const serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);
|
|
86
87
|
if (serverUrlOverride)
|
|
87
88
|
return serverUrlOverride;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-model-catalog.js","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAA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Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\n\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://copilot-api.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://copilot-api.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"copilot-model-catalog.js","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAkC1C,wGAAwG;AACxG,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD,MAAM,CAAC,MAAM,2BAA2B,GAAG,YAAY,CAAC;AAExD;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAqC;IACxE,YAAY,EAAE,0BAA0B;IACxC,gBAAgB,EAAE,gBAAgB;IAClC,uBAAuB,EAAE,qBAAqB;IAC9C,wBAAwB,EAAE,aAAa;IACvC,sBAAsB,EAAE,2BAA2B;CACnD,CAAC;AAEF,oFAAoF;AACpF,MAAM,CAAC,MAAM,4BAA4B,GAAG,0CAA0C,CAAC;AAEvF,mFAAmF;AACnF,MAAM,CAAC,MAAM,2BAA2B,GAAG,+BAA+B,CAAC;AAE3E,wEAAwE;AACxE,MAAM,CAAC,MAAM,+BAA+B,GAAG,0CAA0C,CAAC;AAC1F,MAAM,2BAA2B,GAAG,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjE,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC;AAC/D,M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AAM,UAAU,sCAAsC,CACrD,WAA+B,EAC/B,SAAiB,EACjB,GAAY;IAEZ,IAAI,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,IAAI,GAAG,uBAAuB,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,CAAC;IAC9E,MAAM,MAAM,GAAG,uBAAuB,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,iBAAiB,EAAE,CAAC,CAAC;IAClG,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,4BAA4B,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/** GitHub Copilot CAPI model catalog parsing, active state, and disk cache. */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) and optional synthesis metadata for a single Copilot model. */\nexport interface CopilotModelContext {\n\tcontextWindow: number;\n\tcontextWindowOptions?: readonly number[];\n\tmaxInputTokens?: number;\n\tmaxTokens?: number;\n\tdisplayName?: string;\n\tvendor?: string;\n\tsupportedEndpoints?: readonly string[];\n\tsupports?: CopilotModelSupports;\n\tlimits?: CopilotModelLimits;\n\tmodelPickerEnabled?: boolean;\n\tpolicyState?: string;\n\ttype?: string;\n}\n\nexport interface CopilotModelSupports {\n\tadaptiveThinking?: boolean;\n\tmaxThinkingBudget?: boolean;\n\tminThinkingBudget?: boolean;\n\tparallelToolCalls?: boolean;\n\treasoningEffort?: boolean;\n\treasoningEffortLevels?: readonly string[];\n\tstreaming?: boolean;\n\tstructuredOutputs?: boolean;\n\ttoolCalls?: boolean;\n\tvision?: boolean;\n}\n\n/** Map of model id → resolved context window(s) plus optional synthesis metadata. */\nexport type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;\n\n/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */\nexport const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;\n\nexport const COPILOT_CATALOG_API_VERSION = \"2026-06-01\";\n\n/**\n * Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends\n * for Copilot token refresh and model-policy calls, plus the dated API version.\n */\nexport const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>> = {\n\t\"User-Agent\": \"GitHubCopilotChat/0.35.0\",\n\t\"Editor-Version\": \"vscode/1.107.0\",\n\t\"Editor-Plugin-Version\": \"copilot-chat/0.35.0\",\n\t\"Copilot-Integration-Id\": \"vscode-chat\",\n\t\"X-GitHub-Api-Version\": COPILOT_CATALOG_API_VERSION,\n};\n\n/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\n\n/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */\nexport const COPILOT_PUBLIC_API_BASE_URL = \"https://api.githubcopilot.com\";\n\n/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */\nexport const COPILOT_ENTERPRISE_API_BASE_URL = \"https://api.enterprise.githubcopilot.com\";\nconst GHE_COPILOT_API_HOST_PREFIX = [\"copilot\", \"api\"].join(\"-\");\nexport const COPILOT_GITHUB_TOKEN_ENV = \"COPILOT_GITHUB_TOKEN\";\nexport const COPILOT_API_TARGET_ENV = \"COPILOT_API_TARGET\";\nexport const GITHUB_COPILOT_BASE_URL_ENV = \"GITHUB_COPILOT_BASE_URL\";\nexport const GITHUB_SERVER_URL_ENV = \"GITHUB_SERVER_URL\";\n\ntype CopilotEnvironment = Record<string, string | undefined>;\n\nfunction normalizeCopilotApiBaseUrl(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\tif (!trimmed) return undefined;\n\tconst withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`;\n\ttry {\n\t\tnew URL(withScheme);\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn withScheme.replace(/\\/+$/, \"\");\n}\n\nfunction explicitCopilotApiBaseUrlFromEnvironment(env: CopilotEnvironment): string | undefined {\n\treturn normalizeCopilotApiBaseUrl(env[COPILOT_API_TARGET_ENV]) ?? normalizeCopilotApiBaseUrl(env[GITHUB_COPILOT_BASE_URL_ENV]);\n}\n\nfunction copilotApiBaseUrlFromServerUrl(serverUrl: string | undefined): string | undefined {\n\tconst trimmed = serverUrl?.trim();\n\tif (!trimmed) return undefined;\n\ttry {\n\t\tconst parsed = new URL(trimmed.includes(\"://\") ? trimmed : `https://${trimmed}`);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (!host || host === \"github.com\") return undefined;\n\t\tif (host.endsWith(\".ghe.com\")) return `https://${GHE_COPILOT_API_HOST_PREFIX}.${host}`;\n\t\treturn COPILOT_ENTERPRISE_API_BASE_URL;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isCopilotEnvironmentToken(token: string | undefined, env: CopilotEnvironment): boolean {\n\tconst environmentToken = copilotTokenFromEnvironment(env);\n\treturn environmentToken !== undefined && token === environmentToken;\n}\n\nexport function copilotTokenFromEnvironment(env: CopilotEnvironment = process.env): string | undefined {\n\tconst token = env[COPILOT_GITHUB_TOKEN_ENV]?.trim();\n\treturn token ? token : undefined;\n}\n\n/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */\nexport const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;\n\n/** Current on-disk cache schema version. */\nexport const COPILOT_CATALOG_CACHE_VERSION = 5 as const;\n\nexport function copilotApiBaseUrlFromToken(\n\ttoken: string | undefined,\n\tenterpriseDomain?: string,\n\tenv: CopilotEnvironment = process.env,\n): string {\n\tconst explicitOverride = explicitCopilotApiBaseUrlFromEnvironment(env);\n\tif (explicitOverride) return explicitOverride;\n\tif (token) {\n\t\tconst match = token.match(/proxy-ep=([^;]+)/);\n\t\tif (match) {\n\t\t\treturn `https://${match[1].replace(/^proxy\\./, \"api.\")}`;\n\t\t}\n\t}\n\tif (enterpriseDomain) return `https://${GHE_COPILOT_API_HOST_PREFIX}.${enterpriseDomain}`;\n\tconst serverUrlOverride = copilotApiBaseUrlFromServerUrl(env[GITHUB_SERVER_URL_ENV]);\n\tif (serverUrlOverride) return serverUrlOverride;\n\tif (isCopilotEnvironmentToken(token, env)) return COPILOT_PUBLIC_API_BASE_URL;\n\treturn DEFAULT_COPILOT_API_BASE_URL;\n}\n\nfunction trimTrailingSlash(url: string): string {\n\treturn url.replace(/\\/+$/, \"\");\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n\treturn value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction toPositiveInt(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nexport interface CopilotModelLimits {\n\tmaxPromptTokens?: number;\n\tmaxContextWindowTokens?: number;\n\tmaxOutputTokens?: number;\n\tdefaultContextMax?: number;\n\tlongContextMax?: number;\n}\n\nfunction stringArray(value: unknown): readonly string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\tconst strings = value.filter((item): item is string => typeof item === \"string\" && item.length > 0);\n\treturn strings.length > 0 ? strings : undefined;\n}\n\nfunction supportedFlag(record: Record<string, unknown> | undefined, key: string): boolean | undefined {\n\tconst value = record?.[key];\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return Number.isFinite(value) && value > 0;\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn undefined;\n}\n\nfunction parseCopilotSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptive_thinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"max_thinking_budget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"min_thinking_budget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallel_tool_calls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoning_effort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoning_effort),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structured_outputs\"),\n\t\ttoolCalls: supportedFlag(record, \"tool_calls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction parseCopilotLimits(limits: Record<string, unknown> | undefined, prices: Record<string, unknown> | undefined): CopilotModelLimits {\n\treturn {\n\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\tmaxOutputTokens: toPositiveInt(limits?.max_output_tokens),\n\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t};\n}\n\nexport function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined {\n\tconst hasSignal =\n\t\tlimits.maxPromptTokens !== undefined ||\n\t\tlimits.maxContextWindowTokens !== undefined ||\n\t\tlimits.defaultContextMax !== undefined ||\n\t\tlimits.longContextMax !== undefined;\n\tif (!hasSignal) return undefined;\n\n\tconst maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;\n\tconst base = limits.defaultContextMax ?? maxInput;\n\tif (limits.longContextMax !== undefined && limits.longContextMax > base) {\n\t\t// Display the model's full context window as the long tier (matching openai/* and anthropic/*)\n\t\t// when CAPI advertises it; otherwise fall back to the long-context prompt threshold for\n\t\t// older/sparse payloads.\n\t\tconst longWindow = limits.maxContextWindowTokens ?? limits.longContextMax;\n\t\t// The hard prompt/input cap GitHub enforces server-side: prefer max_prompt_tokens, else derive\n\t\t// it from total − output reserve, else fall back to the long-context prompt threshold.\n\t\tconst derivedInputCap =\n\t\t\tlimits.maxContextWindowTokens !== undefined && limits.maxOutputTokens !== undefined\n\t\t\t\t? limits.maxContextWindowTokens - limits.maxOutputTokens\n\t\t\t\t: undefined;\n\t\tconst inputCap =\n\t\t\tlimits.maxPromptTokens ??\n\t\t\t(derivedInputCap !== undefined && derivedInputCap > 0 ? derivedInputCap : undefined) ??\n\t\t\tlimits.longContextMax;\n\t\t// Only carry the cap when the displayed long window actually exceeds it (the branded-total\n\t\t// case); when they coincide there is no gap and the input budget is just the window.\n\t\tconst resolved: CopilotModelContext = longWindow > inputCap\n\t\t\t? { contextWindow: base, contextWindowOptions: [base, longWindow], maxInputTokens: inputCap }\n\t\t\t: { contextWindow: base, contextWindowOptions: [base, longWindow] };\n\t\treturn limits.maxOutputTokens !== undefined ? { ...resolved, maxTokens: limits.maxOutputTokens } : resolved;\n\t}\n\treturn limits.maxOutputTokens !== undefined ? { contextWindow: base, maxTokens: limits.maxOutputTokens } : { contextWindow: base };\n}\n\n/**\n * Parse a raw CAPI `/models` response body into an input-token context-window catalog.\n */\nexport function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog {\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tconst data = asRecord(body)?.data;\n\tif (!Array.isArray(data)) return catalog;\n\n\tfor (const entry of data) {\n\t\tconst record = asRecord(entry);\n\t\tif (!record) continue;\n\t\tconst id = record.id;\n\t\tif (typeof id !== \"string\" || id.length === 0) continue;\n\n\t\tconst capabilities = asRecord(record.capabilities);\n\t\tconst limitsRecord = asRecord(capabilities?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst limits = parseCopilotLimits(limitsRecord, prices);\n\t\tconst context = resolveCopilotModelContext(limits);\n\t\tif (context) {\n\t\t\tconst policy = asRecord(record.policy);\n\t\t\tcatalog.set(id, {\n\t\t\t\t...context,\n\t\t\t\tdisplayName: typeof record.name === \"string\" && record.name.length > 0 ? record.name : undefined,\n\t\t\t\tvendor: typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined,\n\t\t\t\tsupportedEndpoints: stringArray(record.supported_endpoints),\n\t\t\t\tsupports: parseCopilotSupports(capabilities?.supports),\n\t\t\t\tlimits,\n\t\t\t\tmodelPickerEnabled: typeof record.model_picker_enabled === \"boolean\" ? record.model_picker_enabled : undefined,\n\t\t\t\tpolicyState: typeof policy?.state === \"string\" ? policy.state : undefined,\n\t\t\t\ttype: typeof capabilities?.type === \"string\" ? capabilities.type : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn catalog;\n}\n\nexport interface FetchCopilotModelCatalogOptions {\n\t/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */\n\ttoken: string;\n\t/** Override the resolved base URL; defaults to one derived from the token. */\n\tbaseUrl?: string;\n\t/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */\n\tenterpriseDomain?: string;\n\t/** Extra/override request headers. */\n\theaders?: Record<string, string>;\n\t/** Injectable `fetch` for testing. */\n\tfetchImpl?: typeof fetch;\n\t/** Abort signal. */\n\tsignal?: AbortSignal;\n}\n\n/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */\nexport async function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog> {\n\tconst fetchImpl = options.fetchImpl ?? fetch;\n\tconst baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);\n\tconst response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {\n\t\tmethod: \"GET\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t...COPILOT_CATALOG_HEADERS,\n\t\t\t...options.headers,\n\t\t},\n\t\t...(options.signal ? { signal: options.signal } : {}),\n\t});\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);\n\t}\n\treturn parseCopilotModelCatalog(await response.json());\n}\n\n// ----------------------------------------------------------------------------\n// Active in-memory catalog (consulted by the model registry).\n//\n// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot\n// model context windows untouched and the picker never appears.\n// ----------------------------------------------------------------------------\n\nlet activeCatalog: CopilotModelCatalog = new Map();\n\n/** Replace the active catalog the registry derives context windows from. */\nexport function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void {\n\tactiveCatalog = catalog;\n}\n\n/** The active catalog (empty until a successful auth-gated fetch/cache load). */\nexport function getActiveCopilotModelCatalog(): CopilotModelCatalog {\n\treturn activeCatalog;\n}\n\n/** Reset the active catalog (primarily for tests). */\nexport function clearActiveCopilotModelCatalog(): void {\n\tactiveCatalog = new Map();\n}\n\n// ----------------------------------------------------------------------------\n// Disk cache.\n// ----------------------------------------------------------------------------\n\ninterface CopilotCatalogCacheFile {\n\tversion: typeof COPILOT_CATALOG_CACHE_VERSION;\n\t/** CAPI host the catalog was fetched from; cache misses on host change (e.g. enterprise switch). */\n\thost: string;\n\t/** Epoch ms the catalog was fetched. */\n\tfetchedAt: number;\n\tmodels: Record<string, CopilotModelContext>;\n}\n\nfunction hostFromBaseUrl(baseUrl: string): string {\n\ttry {\n\t\treturn new URL(baseUrl).host;\n\t} catch {\n\t\treturn baseUrl;\n\t}\n}\n\nexport interface ReadCopilotCatalogCacheOptions {\n\t/** Expected CAPI host; a cached file from a different host is ignored. */\n\thost: string;\n\t/** Current epoch ms (injectable for tests). */\n\tnow?: number;\n\t/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */\n\tttlMs?: number;\n}\n\nfunction sanitizeCachedSupports(value: unknown): CopilotModelSupports | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst supports: CopilotModelSupports = {\n\t\tadaptiveThinking: supportedFlag(record, \"adaptiveThinking\"),\n\t\tmaxThinkingBudget: supportedFlag(record, \"maxThinkingBudget\"),\n\t\tminThinkingBudget: supportedFlag(record, \"minThinkingBudget\"),\n\t\tparallelToolCalls: supportedFlag(record, \"parallelToolCalls\"),\n\t\treasoningEffort: supportedFlag(record, \"reasoningEffort\"),\n\t\treasoningEffortLevels: stringArray(record.reasoningEffortLevels),\n\t\tstreaming: supportedFlag(record, \"streaming\"),\n\t\tstructuredOutputs: supportedFlag(record, \"structuredOutputs\"),\n\t\ttoolCalls: supportedFlag(record, \"toolCalls\"),\n\t\tvision: supportedFlag(record, \"vision\"),\n\t};\n\treturn Object.values(supports).some((flag) => flag !== undefined) ? supports : undefined;\n}\n\nfunction sanitizeCachedLimits(value: unknown): CopilotModelLimits | undefined {\n\tconst record = asRecord(value);\n\tif (!record) return undefined;\n\tconst limits: CopilotModelLimits = {\n\t\tmaxPromptTokens: toPositiveInt(record.maxPromptTokens),\n\t\tmaxContextWindowTokens: toPositiveInt(record.maxContextWindowTokens),\n\t\tmaxOutputTokens: toPositiveInt(record.maxOutputTokens),\n\t\tdefaultContextMax: toPositiveInt(record.defaultContextMax),\n\t\tlongContextMax: toPositiveInt(record.longContextMax),\n\t};\n\treturn Object.values(limits).some((limit) => limit !== undefined) ? limits : undefined;\n}\n\nfunction sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst maxInputTokens = toPositiveInt(record?.maxInputTokens);\n\tconst maxTokens = toPositiveInt(record?.maxTokens);\n\tconst rawOptions = record?.contextWindowOptions;\n\tconst base: CopilotModelContext = maxInputTokens !== undefined ? { contextWindow, maxInputTokens } : { contextWindow };\n\tif (maxTokens !== undefined) base.maxTokens = maxTokens;\n\tif (Array.isArray(rawOptions)) {\n\t\tconst options = rawOptions.map(toPositiveInt).filter((n): n is number => n !== undefined);\n\t\tif (options.length > 1) base.contextWindowOptions = options;\n\t}\n\tconst displayName = record && typeof record.displayName === \"string\" && record.displayName.length > 0 ? record.displayName : undefined;\n\tconst vendor = record && typeof record.vendor === \"string\" && record.vendor.length > 0 ? record.vendor : undefined;\n\tconst policyState = record && typeof record.policyState === \"string\" ? record.policyState : undefined;\n\tconst type = record && typeof record.type === \"string\" ? record.type : undefined;\n\treturn {\n\t\t...base,\n\t\tdisplayName,\n\t\tvendor,\n\t\tsupportedEndpoints: stringArray(record?.supportedEndpoints),\n\t\tsupports: sanitizeCachedSupports(record?.supports),\n\t\tlimits: sanitizeCachedLimits(record?.limits),\n\t\tmodelPickerEnabled: typeof record?.modelPickerEnabled === \"boolean\" ? record.modelPickerEnabled : undefined,\n\t\tpolicyState,\n\t\ttype,\n\t};\n}\n\nexport function readCopilotCatalogCache(\n\tpath: string,\n\toptions: ReadCopilotCatalogCacheOptions,\n): CopilotModelCatalog | undefined {\n\tlet parsed: CopilotCatalogCacheFile;\n\ttry {\n\t\tif (!existsSync(path)) return undefined;\n\t\tparsed = JSON.parse(readFileSync(path, \"utf8\")) as CopilotCatalogCacheFile;\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION) return undefined;\n\tif (parsed.host !== options.host) return undefined;\n\tconst now = options.now ?? Date.now();\n\tconst ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;\n\tif (typeof parsed.fetchedAt !== \"number\" || now - parsed.fetchedAt >= ttlMs) return undefined;\n\tconst models = asRecord(parsed.models);\n\tif (!models) return undefined;\n\n\tconst catalog = new Map<string, CopilotModelContext>();\n\tfor (const [id, value] of Object.entries(models)) {\n\t\tconst context = sanitizeCachedContext(value);\n\t\tif (context) catalog.set(id, context);\n\t}\n\treturn catalog;\n}\n\nexport function writeCopilotCatalogCache(\n\tpath: string,\n\tbaseUrl: string,\n\tcatalog: CopilotModelCatalog,\n\tnow?: number,\n): void {\n\tconst payload: CopilotCatalogCacheFile = {\n\t\tversion: COPILOT_CATALOG_CACHE_VERSION,\n\t\thost: hostFromBaseUrl(baseUrl),\n\t\tfetchedAt: now ?? Date.now(),\n\t\tmodels: Object.fromEntries(catalog),\n\t};\n\ttry {\n\t\tmkdirSync(dirname(path), { recursive: true });\n\t\twriteFileSync(path, JSON.stringify(payload), \"utf8\");\n\t} catch {\n\t\t// best-effort cache; ignore write failures\n\t}\n}\n\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\nexport function copilotCatalogCachePath(agentDir: string): string {\n\treturn join(agentDir, \"cache\", \"copilot-models.json\");\n}\n\n/**\n * Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.\n *\n * Called at model-registry construction so a returning user's previously selected long-context\n * window is recognized before startup validation runs — otherwise the persisted choice would warn\n * (\"context window 936k is not supported…\") and reset until the async refresh completes. The cache\n * TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and\n * the async loader independently refetches on its own freshness window. Returns true when a catalog\n * was applied. No-op (returns false) without a token or a host-matching cached catalog.\n */\nexport function seedActiveCopilotModelCatalogFromCache(\n\taccessToken: string | undefined,\n\tcachePath: string,\n\tnow?: number,\n): boolean {\n\tif (typeof accessToken !== \"string\" || accessToken.length === 0) return false;\n\tconst host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));\n\tconst cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });\n\tif (!cached) return false;\n\tsetActiveCopilotModelCatalog(cached);\n\treturn true;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAMnD,iBAAe,kBAAkB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAqCnE;AAoDD,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAOrE;AAiBD;;;;;;;;GAQG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAQ5E;AAED;;;GAGG;AACH,iBAAS,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoD5C;AAED,kEAAkE;AAClE,eAAO,MAAM,wBAAwB;;;;CAIpC,CAAC;AAUF,wBAAsB,mBAAmB,CACvC,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,mBAAmB,GAC/B,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAmCvC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(import.meta.url, {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAMnD,iBAAe,kBAAkB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAqCnE;AAoDD,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,mBAAmB,CAOrE;AAiBD;;;;;;;;GAQG;AACH,iBAAS,eAAe,CAAC,WAAW,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CAQ5E;AAMD;;;GAGG;AACH,iBAAS,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAoD5C;AAED,kEAAkE;AAClE,eAAO,MAAM,wBAAwB;;;;CAIpC,CAAC;AAUF,wBAAsB,mBAAmB,CACvC,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,mBAAmB,GAC/B,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAmCvC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { createJiti } from "jiti/static";
|
|
6
6
|
import { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from "../../config.js";
|
|
7
|
+
import { moduleDirFromMetaUrl } from "../../utils/split-launcher.js";
|
|
8
|
+
import { resolutionBaseUrl } from "../../utils/module-require.js";
|
|
7
9
|
import { resolvePath } from "../../utils/paths.js";
|
|
8
10
|
const require = createRequire(import.meta.url);
|
|
9
11
|
let _virtualModules = null;
|
|
@@ -128,6 +130,9 @@ function findPackageRoot(packageName, searchPaths) {
|
|
|
128
130
|
}
|
|
129
131
|
throw new Error(`Cannot locate package directory for "${packageName}"`);
|
|
130
132
|
}
|
|
133
|
+
function currentModuleDir() {
|
|
134
|
+
return moduleDirFromMetaUrl(import.meta.url, "dist", "core", "extensions");
|
|
135
|
+
}
|
|
131
136
|
/**
|
|
132
137
|
* Get aliases for jiti (used in Node.js/development mode).
|
|
133
138
|
* In Bun binary mode, virtualModules is used instead.
|
|
@@ -135,7 +140,7 @@ function findPackageRoot(packageName, searchPaths) {
|
|
|
135
140
|
function getAliases() {
|
|
136
141
|
if (_aliases)
|
|
137
142
|
return _aliases;
|
|
138
|
-
const __dirname =
|
|
143
|
+
const __dirname = currentModuleDir();
|
|
139
144
|
const packageIndex = path.resolve(__dirname, "../..", "index.js");
|
|
140
145
|
const typeboxEntry = require.resolve("typebox");
|
|
141
146
|
const typeboxCompileEntry = require.resolve("typebox/compile");
|
|
@@ -209,7 +214,7 @@ export async function loadExtensionModule(extensionPath, cacheToken) {
|
|
|
209
214
|
// skips per-launch transpilation of the extension module graph. Re-loads of
|
|
210
215
|
// the same path fall back to transformed imports for fresh evaluation.
|
|
211
216
|
const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));
|
|
212
|
-
const jiti = createJiti(import.meta.url, {
|
|
217
|
+
const jiti = createJiti(resolutionBaseUrl(import.meta.url), {
|
|
213
218
|
moduleCache: false,
|
|
214
219
|
...(forceTransformedImports
|
|
215
220
|
? { fsCache: getTranspileCacheDir(), tryNative: false }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-virtual-modules.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAGnD,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,IAAI,eAAe,GAAkC,IAAI,CAAC;AAC1D,IAAI,sBAAsB,GAA2C,IAAI,CAAC;AAE1E,KAAK,UAAU,kBAAkB;IAC/B,MAAM,CAAC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,WAAW,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,aAAa,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACpH,MAAM,CAAC,SAAS,CAAC;QACjB,MAAM,CAAC,iBAAiB,CAAC;QACzB,MAAM,CAAC,eAAe,CAAC;QACvB,MAAM,CAAC,+BAA+B,CAAC;QACvC,MAAM,CAAC,wBAAwB,CAAC;QAChC,yEAAyE;QACzE,mEAAmE;QACnE,yEAAyE;QACzE,4EAA4E;QAC5E,MAAM,CAAC,8BAA8B,CAAC;QACtC,MAAM,CAAC,6BAA6B,CAAC;QACrC,uFAAuF;QACvF,0FAA0F;QAC1F,MAAM,CAAC,gBAAgB,CAAC;KACzB,CAAC,CAAC;IAEH,OAAO;QACL,OAAO;QACP,iBAAiB,EAAE,cAAc;QACjC,eAAe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OAAO,IAAI,CAAC,GAAG,EAAE;QACvC,WAAW,EAAE,KAAK;QAClB,GAAG,CAAC,uBAAuB;YACzB,CAAC,CAAC,EAAE,OAAO,EAAE,oBAAoB,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE;YACvD,CAAC,CAAC,SAAS;gBACT,CAAC,CAAC,EAAE,OAAO,EAAE,oBAAoB,EAAE,EAAE;gBACrC,CAAC,CAAC,EAAE,CAAC;QACT,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,MAAM,iBAAiB,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;KACjG,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,aAAa,EAAE,UAAU,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACzG,IAAI,SAAS,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC1C,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,OAAO,GAAG,MAA0B,CAAC;IAC3C,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IACpD,IAAI,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACpC,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(import.meta.url, {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader-virtual-modules.js","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE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AAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC;KACjG,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,aAAa,EAAE,UAAU,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACzG,IAAI,SAAS,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC1C,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3C,CAAC;IACD,MAAM,OAAO,GAAG,MAA0B,CAAC;IAC3C,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,SAAS,CAAC;IACpD,IAAI,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACpC,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti/static\";\nimport { getExtensionTranspileCacheDir, isBunBinary, isBundledBuild } from \"../../config.ts\";\nimport { moduleDirFromMetaUrl } from \"../../utils/split-launcher.ts\";\nimport { resolutionBaseUrl } from \"../../utils/module-require.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport type { ExtensionFactory } from \"./types.ts\";\n\nconst require = createRequire(import.meta.url);\nlet _virtualModules: Record<string, object> | null = null;\nlet _virtualModulesPromise: Promise<Record<string, object>> | null = null;\n\nasync function loadVirtualModules(): Promise<Record<string, object>> {\n const [typebox, typeboxCompile, typeboxValue, piAgentCore, piTui, piAi, piAiOauth, piCodingAgent] = await Promise.all([\n import(\"typebox\"),\n import(\"typebox/compile\"),\n import(\"typebox/value\"),\n import(\"@earendil-works/pi-agent-core\"),\n import(\"@earendil-works/pi-tui\"),\n // pi 0.80.2: the old global pi-ai API moved off the root entrypoint onto\n // `/compat` (a strict superset). Extensions still `import ... from\n // \"@earendil-works/pi-ai\"`, so we load the compat module here and key it\n // under the root specifier below to keep every extension working unchanged.\n import(\"@earendil-works/pi-ai/compat\"),\n import(\"@earendil-works/pi-ai/oauth\"),\n // NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n // avoiding a circular dependency while preserving the package-name extension import path.\n import(\"../../index.ts\"),\n ]);\n\n return {\n typebox,\n \"typebox/compile\": typeboxCompile,\n \"typebox/value\": typeboxValue,\n \"@sinclair/typebox\": typebox,\n \"@sinclair/typebox/compile\": typeboxCompile,\n \"@sinclair/typebox/value\": typeboxValue,\n \"@earendil-works/pi-agent-core\": piAgentCore,\n \"@earendil-works/pi-tui\": piTui,\n \"@earendil-works/pi-ai\": piAi,\n \"@earendil-works/pi-ai/compat\": piAi,\n \"@earendil-works/pi-ai/oauth\": piAiOauth,\n \"@bastani/atomic\": piCodingAgent,\n \"@mariozechner/pi-agent-core\": piAgentCore,\n \"@mariozechner/pi-tui\": piTui,\n \"@mariozechner/pi-ai\": piAi,\n \"@mariozechner/pi-ai/compat\": piAi,\n \"@mariozechner/pi-ai/oauth\": piAiOauth,\n };\n}\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary). */\nasync function getVirtualModules(): Promise<Record<string, object>> {\n if (_virtualModules) return _virtualModules;\n _virtualModulesPromise ??= loadVirtualModules().then(\n (virtualModules) => {\n _virtualModules = virtualModules;\n return virtualModules;\n },\n (error: Error) => {\n _virtualModulesPromise = null;\n throw error;\n },\n );\n return _virtualModulesPromise;\n}\nlet _aliases: Record<string, string> | null = null;\nlet _transpileCacheDir: string | null = null;\n\n/**\n * Persistent on-disk cache for jiti-transpiled extension modules.\n * jiti keys cache entries by source-content hash, so entries self-invalidate\n * when extension sources change; stale sibling version dirs are pruned\n * in the background.\n */\nfunction getTranspileCacheDir(): string {\n if (_transpileCacheDir) return _transpileCacheDir;\n _transpileCacheDir = getExtensionTranspileCacheDir();\n pruneStaleTranspileCaches(_transpileCacheDir);\n return _transpileCacheDir;\n}\n\nfunction pruneStaleTranspileCaches(currentDir: string): void {\n const parent = path.dirname(currentDir);\n const keep = path.basename(currentDir);\n void fs.promises\n .readdir(parent)\n .then((entries) =>\n Promise.all(\n entries\n .filter((entry) => entry !== keep)\n .map((entry) => fs.promises.rm(path.join(parent, entry), { recursive: true, force: true })),\n ),\n )\n .catch(() => {});\n}\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map<string, ExtensionFactory>();\n\nexport interface ExtensionCacheToken {\n cwd: string;\n generation: number;\n}\n\nexport function clearExtensionCache(): void {\n extensionCache.clear();\n extensionCacheCwd = undefined;\n extensionCacheGeneration++;\n}\n\nexport function useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n const resolvedCwd = resolvePath(cwd);\n if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n clearExtensionCache();\n }\n extensionCacheCwd = resolvedCwd;\n return { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n return (\n cacheToken !== undefined &&\n extensionCacheCwd === cacheToken.cwd &&\n extensionCacheGeneration === cacheToken.generation\n );\n}\n\nfunction extensionImportSpecifier(extensionPath: string, cacheToken: ExtensionCacheToken | undefined): string {\n const url = pathToFileURL(extensionPath);\n const cacheKey = cacheToken ? `${cacheToken.generation}:${cacheToken.cwd}` : `${Date.now()}:${Math.random()}`;\n url.searchParams.set(\"atomicExtensionCache\", cacheKey);\n return url.href;\n}\n\n/**\n * Locate an installed package's root directory without consulting its\n * \"exports\" map: require.resolve(\"<pkg>/package.json\") throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED under Node for packages that do not export\n * \"./package.json\" (pi-ai does not), and import.meta.resolve() cannot be\n * used because its mere presence silently disables bytecode generation for\n * the compiled binary (CJS bundle). Scanning require.resolve.paths() walks\n * the same node_modules chain Node would, without exports-map encapsulation.\n */\nfunction findPackageRoot(packageName: string, searchPaths?: string[]): string {\n for (const base of searchPaths ?? require.resolve.paths(packageName) ?? []) {\n const candidate = path.join(base, packageName);\n if (fs.existsSync(path.join(candidate, \"package.json\"))) {\n return candidate;\n }\n }\n throw new Error(`Cannot locate package directory for \"${packageName}\"`);\n}\nfunction currentModuleDir(): string {\n return moduleDirFromMetaUrl(import.meta.url, \"dist\", \"core\", \"extensions\");\n}\n\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nfunction getAliases(): Record<string, string> {\n if (_aliases) return _aliases;\n\n const __dirname = currentModuleDir();\n const packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n const typeboxEntry = require.resolve(\"typebox\");\n const typeboxCompileEntry = require.resolve(\"typebox/compile\");\n const typeboxValueEntry = require.resolve(\"typebox/value\");\n\n const packagesRoot = path.resolve(__dirname, \"../../../../\");\n const resolveWorkspaceOrImport = (workspaceRelativePath: string, packageName: string): string => {\n const workspacePath = path.join(packagesRoot, workspaceRelativePath);\n if (fs.existsSync(workspacePath)) {\n return workspacePath;\n }\n const packageRoot = findPackageRoot(packageName);\n const entryRelativePath = workspaceRelativePath.split(\"/\").slice(1).join(\"/\");\n return path.join(packageRoot, entryRelativePath);\n };\n\n const piCodingAgentEntry = packageIndex;\n const piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n const piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n // The workspace path mirrors pi-ai 0.80.x's built dist layout. If an\n // upstream layout change moves these files, this join needs updating to\n // match the package's real dist paths.\n const piAiEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai\");\n const piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai\");\n\n _aliases = {\n \"@bastani/atomic\": piCodingAgentEntry,\n \"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n \"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n \"@earendil-works/pi-tui\": piTuiEntry,\n \"@earendil-works/pi-ai\": piAiEntry,\n \"@earendil-works/pi-ai/compat\": piAiEntry,\n \"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n \"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n \"@mariozechner/pi-tui\": piTuiEntry,\n \"@mariozechner/pi-ai\": piAiEntry,\n \"@mariozechner/pi-ai/compat\": piAiEntry,\n \"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n typebox: typeboxEntry,\n \"typebox/compile\": typeboxCompileEntry,\n \"typebox/value\": typeboxValueEntry,\n \"@sinclair/typebox\": typeboxEntry,\n \"@sinclair/typebox/compile\": typeboxCompileEntry,\n \"@sinclair/typebox/value\": typeboxValueEntry,\n };\n\n return _aliases;\n}\n\n/** Internal hooks for extension-loader alias regression tests. */\nexport const extensionLoaderTestHooks = {\n loadVirtualModules,\n getAliases,\n findPackageRoot,\n};\n\n/**\n * Extension paths already evaluated via native import() in this process. Bun on\n * Windows ignores the cache-busting query on file URLs, so re-loads of these\n * paths (e.g. /reload) must go through jiti's transformed-import path to get a\n * fresh module evaluation.\n */\nconst nativelyImportedPaths = new Set<string>();\n\nexport async function loadExtensionModule(\n extensionPath: string,\n cacheToken?: ExtensionCacheToken,\n): Promise<ExtensionFactory | undefined> {\n if (isCurrentCacheToken(cacheToken)) {\n const cachedFactory = extensionCache.get(extensionPath);\n if (cachedFactory) return cachedFactory;\n }\n\n const isWindows = process.platform === \"win32\";\n // Single-file builds (compiled binary or dev bundle) cannot alias host\n // package specifiers to files on disk: extensions must share the live\n // module instances baked into the build, so virtualModules is used instead\n // (which requires jiti's transformed-import path).\n const isSingleFileBuild = isBunBinary || isBundledBuild;\n // Windows first-load fast path: native import() (jiti's default tryNative)\n // skips per-launch transpilation of the extension module graph. Re-loads of\n // the same path fall back to transformed imports for fresh evaluation.\n const forceTransformedImports = isSingleFileBuild || (isWindows && nativelyImportedPaths.has(extensionPath));\n const jiti = createJiti(resolutionBaseUrl(import.meta.url), {\n moduleCache: false,\n ...(forceTransformedImports\n ? { fsCache: getTranspileCacheDir(), tryNative: false }\n : isWindows\n ? { fsCache: getTranspileCacheDir() }\n : {}),\n ...(isSingleFileBuild ? { virtualModules: await getVirtualModules() } : { alias: getAliases() }),\n });\n const module = await jiti.import(extensionImportSpecifier(extensionPath, cacheToken), { default: true });\n if (isWindows && !forceTransformedImports) {\n nativelyImportedPaths.add(extensionPath);\n }\n const factory = module as ExtensionFactory;\n if (typeof factory !== \"function\") return undefined;\n if (isCurrentCacheToken(cacheToken)) {\n extensionCache.set(extensionPath, factory);\n }\n return factory;\n}\n"]}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
export declare function isOpenAIResponsesModel(model: Pick<Model<Api>, "api">): boolean;
|
|
3
|
+
export declare function isValidResponsesFunctionCallId(id: unknown): id is string;
|
|
4
|
+
export declare function responsesFunctionCallIdForCallId(callId: unknown): string | undefined;
|
|
5
|
+
export declare function sanitizeOpenAIResponsesPayload(payload: unknown, model: Pick<Model<Api>, "api">): unknown;
|
|
6
|
+
//# sourceMappingURL=openai-responses-payload-sanitizer.d.ts.map
|