@bastani/atomic 0.8.30 → 0.8.31-alpha.1
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/CHANGELOG.md +4 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +4 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +4 -0
- package/dist/builtin/mcp/package.json +3 -3
- package/dist/builtin/subagents/CHANGELOG.md +4 -0
- package/dist/builtin/subagents/package.json +4 -4
- package/dist/builtin/web-access/CHANGELOG.md +4 -0
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/workflows/CHANGELOG.md +10 -0
- package/dist/builtin/workflows/builtin/deep-research-codebase.ts +1 -1
- package/dist/builtin/workflows/builtin/goal.ts +2 -2
- package/dist/builtin/workflows/builtin/open-claude-design.ts +1 -1
- package/dist/builtin/workflows/builtin/ralph.ts +61 -11
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/src/extension/workflow-schema.ts +3 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner.ts +5 -0
- package/dist/builtin/workflows/src/runs/shared/model-fallback.ts +95 -8
- package/dist/builtin/workflows/src/shared/authoring-contract.d.ts +11 -0
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +20 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +2 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +2 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +17 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +161 -18
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +20 -5
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/context-compaction.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction.js +14 -3
- package/dist/core/compaction/context-compaction.js.map +1 -1
- package/dist/core/context-window.d.ts +29 -0
- package/dist/core/context-window.d.ts.map +1 -0
- package/dist/core/context-window.js +86 -0
- package/dist/core/context-window.js.map +1 -0
- package/dist/core/copilot-errors.d.ts +9 -0
- package/dist/core/copilot-errors.d.ts.map +1 -0
- package/dist/core/copilot-errors.js +32 -0
- package/dist/core/copilot-errors.js.map +1 -0
- package/dist/core/copilot-model-catalog.d.ts +132 -0
- package/dist/core/copilot-model-catalog.d.ts.map +1 -0
- package/dist/core/copilot-model-catalog.js +254 -0
- package/dist/core/copilot-model-catalog.js.map +1 -0
- package/dist/core/export-html/template.js +10 -1
- package/dist/core/extensions/types.d.ts +3 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/model-registry.d.ts +10 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +107 -4
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +4 -0
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-attribution.d.ts.map +1 -1
- package/dist/core/provider-attribution.js +17 -7
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/sdk.d.ts +8 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +47 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +8 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +19 -3
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +6 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +69 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +24 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/index.d.ts +1 -1
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/components/context-window-selector.d.ts +53 -0
- package/dist/modes/interactive/components/context-window-selector.d.ts.map +1 -0
- package/dist/modes/interactive/components/context-window-selector.js +136 -0
- package/dist/modes/interactive/components/context-window-selector.js.map +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +7 -0
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +91 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +14 -2
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +23 -3
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +30 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +23 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/custom-provider.md +4 -1
- package/docs/json.md +3 -1
- package/docs/models.md +78 -2
- package/docs/providers.md +3 -0
- package/docs/rpc.md +80 -1
- package/docs/sdk.md +23 -3
- package/docs/session-format.md +15 -1
- package/docs/sessions.md +1 -1
- package/docs/settings.md +7 -2
- package/docs/workflows.md +26 -4
- package/package.json +5 -5
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
declare module "@earendil-works/pi-ai" {
|
|
3
|
+
interface Model<TApi extends Api> {
|
|
4
|
+
/** Selectable context-window sizes for this model. The scalar contextWindow remains the default/effective value. */
|
|
5
|
+
contextWindowOptions?: readonly number[];
|
|
6
|
+
/** Original/default scalar context window, preserved when contextWindow is overridden for a session. */
|
|
7
|
+
defaultContextWindow?: number;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export interface ContextWindowParseResult {
|
|
11
|
+
value?: number;
|
|
12
|
+
error?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ContextWindowSelection<TApi extends Api = Api> {
|
|
15
|
+
model: Model<TApi>;
|
|
16
|
+
contextWindow: number;
|
|
17
|
+
}
|
|
18
|
+
export interface ContextWindowSelectionError {
|
|
19
|
+
error: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function validateContextWindowValue(value: number): string | undefined;
|
|
22
|
+
export declare function parseContextWindowValue(input: string): ContextWindowParseResult;
|
|
23
|
+
export declare function formatContextWindow(value: number): string;
|
|
24
|
+
export declare function normalizeContextWindowOptions(values: readonly number[] | undefined): number[];
|
|
25
|
+
export declare function getModelDefaultContextWindow(model: Model<Api>): number;
|
|
26
|
+
export declare function getSupportedContextWindows(model: Model<Api>): number[];
|
|
27
|
+
export declare function withContextWindowOptions<TApi extends Api>(model: Model<TApi>, contextWindowOptions: readonly number[]): Model<TApi>;
|
|
28
|
+
export declare function selectContextWindow<TApi extends Api>(model: Model<TApi>, contextWindow: number): ContextWindowSelection<TApi> | ContextWindowSelectionError;
|
|
29
|
+
//# sourceMappingURL=context-window.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-window.d.ts","sourceRoot":"","sources":["../../src/core/context-window.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,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mB,CAAC,IAAI,SAAS,GAAG,EACnD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,aAAa,EAAE,MAAM,GACnB,sBAAsB,CAAC,IAAI,CAAC,GAAG,2BAA2B,CAsB5D","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\n\ndeclare module \"@earendil-works/pi-ai\" {\n\tinterface Model<TApi extends Api> {\n\t\t/** Selectable context-window sizes for this model. The scalar contextWindow remains the default/effective value. */\n\t\tcontextWindowOptions?: readonly number[];\n\t\t/** Original/default scalar context window, preserved when contextWindow is overridden for a session. */\n\t\tdefaultContextWindow?: number;\n\t}\n}\n\nexport interface ContextWindowParseResult {\n\tvalue?: number;\n\terror?: string;\n}\n\nexport interface ContextWindowSelection<TApi extends Api = Api> {\n\tmodel: Model<TApi>;\n\tcontextWindow: number;\n}\n\nexport interface ContextWindowSelectionError {\n\terror: string;\n}\n\nconst CONTEXT_WINDOW_UNITS: Record<string, number> = {\n\tk: 1_000,\n\tm: 1_000_000,\n};\n\nfunction isPositiveInteger(value: number): boolean {\n\treturn Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\n\nexport function validateContextWindowValue(value: number): string | undefined {\n\treturn isPositiveInteger(value) ? undefined : \"Context window must be a positive integer token count\";\n}\n\nexport function parseContextWindowValue(input: string): ContextWindowParseResult {\n\tconst trimmed = input.trim();\n\tif (!trimmed) {\n\t\treturn { error: \"Context window requires a value\" };\n\t}\n\n\tconst match = /^(\\d+(?:\\.\\d+)?)([kKmM])?$/.exec(trimmed);\n\tif (!match) {\n\t\treturn { error: `Invalid context window \"${input}\". Use a positive number, or a compact value like 400k or 1m.` };\n\t}\n\n\tconst numericValue = Number(match[1]);\n\tconst unit = match[2]?.toLowerCase();\n\tconst multiplier = unit ? CONTEXT_WINDOW_UNITS[unit] : 1;\n\tconst tokens = numericValue * multiplier;\n\tconst validationError = validateContextWindowValue(tokens);\n\tif (validationError) {\n\t\treturn { error: `Invalid context window \"${input}\". ${validationError}.` };\n\t}\n\n\treturn { value: tokens };\n}\n\nexport function formatContextWindow(value: number): string {\n\tif (value >= 1_000_000) {\n\t\tconst millions = value / 1_000_000;\n\t\treturn millions % 1 === 0 ? `${millions}m` : `${millions.toFixed(1)}m`;\n\t}\n\tif (value >= 1_000) {\n\t\tconst thousands = value / 1_000;\n\t\treturn thousands % 1 === 0 ? `${thousands}k` : `${thousands.toFixed(1)}k`;\n\t}\n\treturn String(value);\n}\n\nexport function normalizeContextWindowOptions(values: readonly number[] | undefined): number[] {\n\tconst seen = new Set<number>();\n\tconst normalized: number[] = [];\n\tfor (const value of values ?? []) {\n\t\tif (!isPositiveInteger(value) || seen.has(value)) continue;\n\t\tseen.add(value);\n\t\tnormalized.push(value);\n\t}\n\treturn normalized.sort((a, b) => a - b);\n}\n\nexport function getModelDefaultContextWindow(model: Model<Api>): number {\n\treturn isPositiveInteger(model.defaultContextWindow ?? 0) ? model.defaultContextWindow! : model.contextWindow;\n}\n\nexport function getSupportedContextWindows(model: Model<Api>): number[] {\n\treturn normalizeContextWindowOptions([getModelDefaultContextWindow(model), ...(model.contextWindowOptions ?? [])]);\n}\n\nexport function withContextWindowOptions<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontextWindowOptions: readonly number[],\n): Model<TApi> {\n\treturn {\n\t\t...model,\n\t\tdefaultContextWindow: getModelDefaultContextWindow(model as Model<Api>),\n\t\tcontextWindowOptions: normalizeContextWindowOptions(contextWindowOptions),\n\t};\n}\n\nexport function selectContextWindow<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontextWindow: number,\n): ContextWindowSelection<TApi> | ContextWindowSelectionError {\n\tconst validationError = validateContextWindowValue(contextWindow);\n\tif (validationError) {\n\t\treturn { error: validationError };\n\t}\n\n\tconst supported = getSupportedContextWindows(model as Model<Api>);\n\tif (!supported.includes(contextWindow)) {\n\t\treturn {\n\t\t\terror: `Context window ${formatContextWindow(contextWindow)} is not supported by ${model.provider}/${model.id}. Supported values: ${supported.map(formatContextWindow).join(\", \")}.`,\n\t\t};\n\t}\n\n\treturn {\n\t\tmodel: {\n\t\t\t...model,\n\t\t\tdefaultContextWindow: getModelDefaultContextWindow(model as Model<Api>),\n\t\t\tcontextWindow,\n\t\t\tcontextWindowOptions: supported,\n\t\t},\n\t\tcontextWindow,\n\t};\n}\n"]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
const CONTEXT_WINDOW_UNITS = {
|
|
2
|
+
k: 1_000,
|
|
3
|
+
m: 1_000_000,
|
|
4
|
+
};
|
|
5
|
+
function isPositiveInteger(value) {
|
|
6
|
+
return Number.isFinite(value) && Number.isInteger(value) && value > 0;
|
|
7
|
+
}
|
|
8
|
+
export function validateContextWindowValue(value) {
|
|
9
|
+
return isPositiveInteger(value) ? undefined : "Context window must be a positive integer token count";
|
|
10
|
+
}
|
|
11
|
+
export function parseContextWindowValue(input) {
|
|
12
|
+
const trimmed = input.trim();
|
|
13
|
+
if (!trimmed) {
|
|
14
|
+
return { error: "Context window requires a value" };
|
|
15
|
+
}
|
|
16
|
+
const match = /^(\d+(?:\.\d+)?)([kKmM])?$/.exec(trimmed);
|
|
17
|
+
if (!match) {
|
|
18
|
+
return { error: `Invalid context window "${input}". Use a positive number, or a compact value like 400k or 1m.` };
|
|
19
|
+
}
|
|
20
|
+
const numericValue = Number(match[1]);
|
|
21
|
+
const unit = match[2]?.toLowerCase();
|
|
22
|
+
const multiplier = unit ? CONTEXT_WINDOW_UNITS[unit] : 1;
|
|
23
|
+
const tokens = numericValue * multiplier;
|
|
24
|
+
const validationError = validateContextWindowValue(tokens);
|
|
25
|
+
if (validationError) {
|
|
26
|
+
return { error: `Invalid context window "${input}". ${validationError}.` };
|
|
27
|
+
}
|
|
28
|
+
return { value: tokens };
|
|
29
|
+
}
|
|
30
|
+
export function formatContextWindow(value) {
|
|
31
|
+
if (value >= 1_000_000) {
|
|
32
|
+
const millions = value / 1_000_000;
|
|
33
|
+
return millions % 1 === 0 ? `${millions}m` : `${millions.toFixed(1)}m`;
|
|
34
|
+
}
|
|
35
|
+
if (value >= 1_000) {
|
|
36
|
+
const thousands = value / 1_000;
|
|
37
|
+
return thousands % 1 === 0 ? `${thousands}k` : `${thousands.toFixed(1)}k`;
|
|
38
|
+
}
|
|
39
|
+
return String(value);
|
|
40
|
+
}
|
|
41
|
+
export function normalizeContextWindowOptions(values) {
|
|
42
|
+
const seen = new Set();
|
|
43
|
+
const normalized = [];
|
|
44
|
+
for (const value of values ?? []) {
|
|
45
|
+
if (!isPositiveInteger(value) || seen.has(value))
|
|
46
|
+
continue;
|
|
47
|
+
seen.add(value);
|
|
48
|
+
normalized.push(value);
|
|
49
|
+
}
|
|
50
|
+
return normalized.sort((a, b) => a - b);
|
|
51
|
+
}
|
|
52
|
+
export function getModelDefaultContextWindow(model) {
|
|
53
|
+
return isPositiveInteger(model.defaultContextWindow ?? 0) ? model.defaultContextWindow : model.contextWindow;
|
|
54
|
+
}
|
|
55
|
+
export function getSupportedContextWindows(model) {
|
|
56
|
+
return normalizeContextWindowOptions([getModelDefaultContextWindow(model), ...(model.contextWindowOptions ?? [])]);
|
|
57
|
+
}
|
|
58
|
+
export function withContextWindowOptions(model, contextWindowOptions) {
|
|
59
|
+
return {
|
|
60
|
+
...model,
|
|
61
|
+
defaultContextWindow: getModelDefaultContextWindow(model),
|
|
62
|
+
contextWindowOptions: normalizeContextWindowOptions(contextWindowOptions),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export function selectContextWindow(model, contextWindow) {
|
|
66
|
+
const validationError = validateContextWindowValue(contextWindow);
|
|
67
|
+
if (validationError) {
|
|
68
|
+
return { error: validationError };
|
|
69
|
+
}
|
|
70
|
+
const supported = getSupportedContextWindows(model);
|
|
71
|
+
if (!supported.includes(contextWindow)) {
|
|
72
|
+
return {
|
|
73
|
+
error: `Context window ${formatContextWindow(contextWindow)} is not supported by ${model.provider}/${model.id}. Supported values: ${supported.map(formatContextWindow).join(", ")}.`,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
model: {
|
|
78
|
+
...model,
|
|
79
|
+
defaultContextWindow: getModelDefaultContextWindow(model),
|
|
80
|
+
contextWindow,
|
|
81
|
+
contextWindowOptions: supported,
|
|
82
|
+
},
|
|
83
|
+
contextWindow,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=context-window.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-window.js","sourceRoot":"","sources":["../../src/core/context-window.ts"],"names":[],"mappings":"AAyBA,MAAM,oBAAoB,GAA2B;IACpD,CAAC,EAAE,KAAK;IACR,CAAC,EAAE,SAAS;CACZ,CAAC;AAEF,SAAS,iBAAiB,CAAC,KAAa;IACvC,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAC,KAAa;IACvD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,uDAAuD,CAAC;AACvG,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,KAAa;IACpD,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO,EAAE,KAAK,EAAE,iCAAiC,EAAE,CAAC;IACrD,CAAC;IAED,MAAM,KAAK,GAAG,4BAA4B,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzD,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,OAAO,EAAE,KAAK,EAAE,2BAA2B,KAAK,+DAA+D,EAAE,CAAC;IACnH,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,EAA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B,mBAAmB,CAAC,aAAa,CAAC,wBAAwB,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,uBAAuB,SAAS,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;SACpL,CAAC;IACH,CAAC;IAED,OAAO;QACN,KAAK,EAAE;YACN,GAAG,KAAK;YACR,oBAAoB,EAAE,4BAA4B,CAAC,KAAmB,CAAC;YACvE,aAAa;YACb,oBAAoB,EAAE,SAAS;SAC/B;QACD,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\n\ndeclare module \"@earendil-works/pi-ai\" {\n\tinterface Model<TApi extends Api> {\n\t\t/** Selectable context-window sizes for this model. The scalar contextWindow remains the default/effective value. */\n\t\tcontextWindowOptions?: readonly number[];\n\t\t/** Original/default scalar context window, preserved when contextWindow is overridden for a session. */\n\t\tdefaultContextWindow?: number;\n\t}\n}\n\nexport interface ContextWindowParseResult {\n\tvalue?: number;\n\terror?: string;\n}\n\nexport interface ContextWindowSelection<TApi extends Api = Api> {\n\tmodel: Model<TApi>;\n\tcontextWindow: number;\n}\n\nexport interface ContextWindowSelectionError {\n\terror: string;\n}\n\nconst CONTEXT_WINDOW_UNITS: Record<string, number> = {\n\tk: 1_000,\n\tm: 1_000_000,\n};\n\nfunction isPositiveInteger(value: number): boolean {\n\treturn Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\n\nexport function validateContextWindowValue(value: number): string | undefined {\n\treturn isPositiveInteger(value) ? undefined : \"Context window must be a positive integer token count\";\n}\n\nexport function parseContextWindowValue(input: string): ContextWindowParseResult {\n\tconst trimmed = input.trim();\n\tif (!trimmed) {\n\t\treturn { error: \"Context window requires a value\" };\n\t}\n\n\tconst match = /^(\\d+(?:\\.\\d+)?)([kKmM])?$/.exec(trimmed);\n\tif (!match) {\n\t\treturn { error: `Invalid context window \"${input}\". Use a positive number, or a compact value like 400k or 1m.` };\n\t}\n\n\tconst numericValue = Number(match[1]);\n\tconst unit = match[2]?.toLowerCase();\n\tconst multiplier = unit ? CONTEXT_WINDOW_UNITS[unit] : 1;\n\tconst tokens = numericValue * multiplier;\n\tconst validationError = validateContextWindowValue(tokens);\n\tif (validationError) {\n\t\treturn { error: `Invalid context window \"${input}\". ${validationError}.` };\n\t}\n\n\treturn { value: tokens };\n}\n\nexport function formatContextWindow(value: number): string {\n\tif (value >= 1_000_000) {\n\t\tconst millions = value / 1_000_000;\n\t\treturn millions % 1 === 0 ? `${millions}m` : `${millions.toFixed(1)}m`;\n\t}\n\tif (value >= 1_000) {\n\t\tconst thousands = value / 1_000;\n\t\treturn thousands % 1 === 0 ? `${thousands}k` : `${thousands.toFixed(1)}k`;\n\t}\n\treturn String(value);\n}\n\nexport function normalizeContextWindowOptions(values: readonly number[] | undefined): number[] {\n\tconst seen = new Set<number>();\n\tconst normalized: number[] = [];\n\tfor (const value of values ?? []) {\n\t\tif (!isPositiveInteger(value) || seen.has(value)) continue;\n\t\tseen.add(value);\n\t\tnormalized.push(value);\n\t}\n\treturn normalized.sort((a, b) => a - b);\n}\n\nexport function getModelDefaultContextWindow(model: Model<Api>): number {\n\treturn isPositiveInteger(model.defaultContextWindow ?? 0) ? model.defaultContextWindow! : model.contextWindow;\n}\n\nexport function getSupportedContextWindows(model: Model<Api>): number[] {\n\treturn normalizeContextWindowOptions([getModelDefaultContextWindow(model), ...(model.contextWindowOptions ?? [])]);\n}\n\nexport function withContextWindowOptions<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontextWindowOptions: readonly number[],\n): Model<TApi> {\n\treturn {\n\t\t...model,\n\t\tdefaultContextWindow: getModelDefaultContextWindow(model as Model<Api>),\n\t\tcontextWindowOptions: normalizeContextWindowOptions(contextWindowOptions),\n\t};\n}\n\nexport function selectContextWindow<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontextWindow: number,\n): ContextWindowSelection<TApi> | ContextWindowSelectionError {\n\tconst validationError = validateContextWindowValue(contextWindow);\n\tif (validationError) {\n\t\treturn { error: validationError };\n\t}\n\n\tconst supported = getSupportedContextWindows(model as Model<Api>);\n\tif (!supported.includes(contextWindow)) {\n\t\treturn {\n\t\t\terror: `Context window ${formatContextWindow(contextWindow)} is not supported by ${model.provider}/${model.id}. Supported values: ${supported.map(formatContextWindow).join(\", \")}.`,\n\t\t};\n\t}\n\n\treturn {\n\t\tmodel: {\n\t\t\t...model,\n\t\t\tdefaultContextWindow: getModelDefaultContextWindow(model as Model<Api>),\n\t\t\tcontextWindow,\n\t\t\tcontextWindowOptions: supported,\n\t\t},\n\t\tcontextWindow,\n\t};\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface CopilotPromptLimitError {
|
|
2
|
+
promptTokens: number;
|
|
3
|
+
limitTokens: number;
|
|
4
|
+
}
|
|
5
|
+
export declare function parseCopilotPromptLimitError(errorMessage: string): CopilotPromptLimitError | undefined;
|
|
6
|
+
export declare function isCopilotPromptLimitError(errorMessage: string): boolean;
|
|
7
|
+
export declare function formatCopilotPromptLimitError(errorMessage: string): string;
|
|
8
|
+
export declare function formatCopilotProviderError(modelProvider: string, errorMessage: string): string;
|
|
9
|
+
//# sourceMappingURL=copilot-errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-errors.d.ts","sourceRoot":"","sources":["../../src/core/copilot-errors.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,uBAAuB;IACvC,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;CACpB;AAMD,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAUtG;AAED,wBAAgB,yBAAyB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAEvE;AAED,wBAAgB,6BAA6B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAM1E;AAED,wBAAgB,0BAA0B,CAAC,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAE9F","sourcesContent":["const COPILOT_PROMPT_LIMIT_PATTERN = /\\bprompt token count of ([\\d,]+) exceeds the limit of ([\\d,]+)/i;\nconst COPILOT_LONG_CONTEXT_GUIDANCE_MARKER = \"Copilot long-context/usage-based billing\";\n\nexport interface CopilotPromptLimitError {\n\tpromptTokens: number;\n\tlimitTokens: number;\n}\n\nfunction parseTokenCount(value: string): number {\n\treturn Number(value.replace(/,/g, \"\"));\n}\n\nexport function parseCopilotPromptLimitError(errorMessage: string): CopilotPromptLimitError | undefined {\n\tconst match = COPILOT_PROMPT_LIMIT_PATTERN.exec(errorMessage);\n\tif (!match) return undefined;\n\tconst promptTokenText = match[1];\n\tconst limitTokenText = match[2];\n\tif (!promptTokenText || !limitTokenText) return undefined;\n\tconst promptTokens = parseTokenCount(promptTokenText);\n\tconst limitTokens = parseTokenCount(limitTokenText);\n\tif (!Number.isFinite(promptTokens) || !Number.isFinite(limitTokens)) return undefined;\n\treturn { promptTokens, limitTokens };\n}\n\nexport function isCopilotPromptLimitError(errorMessage: string): boolean {\n\treturn parseCopilotPromptLimitError(errorMessage) !== undefined;\n}\n\nexport function formatCopilotPromptLimitError(errorMessage: string): string {\n\tif (!isCopilotPromptLimitError(errorMessage) || errorMessage.includes(COPILOT_LONG_CONTEXT_GUIDANCE_MARKER)) {\n\t\treturn errorMessage;\n\t}\n\n\treturn `${errorMessage}\\n\\nGitHub Copilot rejected this prompt at the API/server context cap. Atomic raises the local token budget for selected larger context windows and sends X-GitHub-Api-Version: 2026-06-01 so Copilot can choose its long-context tier server-side by prompt token count, but GitHub still requires the account to have Copilot long-context/usage-based billing entitlement enabled. Long-context Copilot requests consume higher-cost AI credits. Reduce the session context, choose a smaller context window/model, or enable the required Copilot long-context/usage-based billing entitlement for this account.`;\n}\n\nexport function formatCopilotProviderError(modelProvider: string, errorMessage: string): string {\n\treturn modelProvider === \"github-copilot\" ? formatCopilotPromptLimitError(errorMessage) : errorMessage;\n}\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const COPILOT_PROMPT_LIMIT_PATTERN = /\bprompt token count of ([\d,]+) exceeds the limit of ([\d,]+)/i;
|
|
2
|
+
const COPILOT_LONG_CONTEXT_GUIDANCE_MARKER = "Copilot long-context/usage-based billing";
|
|
3
|
+
function parseTokenCount(value) {
|
|
4
|
+
return Number(value.replace(/,/g, ""));
|
|
5
|
+
}
|
|
6
|
+
export function parseCopilotPromptLimitError(errorMessage) {
|
|
7
|
+
const match = COPILOT_PROMPT_LIMIT_PATTERN.exec(errorMessage);
|
|
8
|
+
if (!match)
|
|
9
|
+
return undefined;
|
|
10
|
+
const promptTokenText = match[1];
|
|
11
|
+
const limitTokenText = match[2];
|
|
12
|
+
if (!promptTokenText || !limitTokenText)
|
|
13
|
+
return undefined;
|
|
14
|
+
const promptTokens = parseTokenCount(promptTokenText);
|
|
15
|
+
const limitTokens = parseTokenCount(limitTokenText);
|
|
16
|
+
if (!Number.isFinite(promptTokens) || !Number.isFinite(limitTokens))
|
|
17
|
+
return undefined;
|
|
18
|
+
return { promptTokens, limitTokens };
|
|
19
|
+
}
|
|
20
|
+
export function isCopilotPromptLimitError(errorMessage) {
|
|
21
|
+
return parseCopilotPromptLimitError(errorMessage) !== undefined;
|
|
22
|
+
}
|
|
23
|
+
export function formatCopilotPromptLimitError(errorMessage) {
|
|
24
|
+
if (!isCopilotPromptLimitError(errorMessage) || errorMessage.includes(COPILOT_LONG_CONTEXT_GUIDANCE_MARKER)) {
|
|
25
|
+
return errorMessage;
|
|
26
|
+
}
|
|
27
|
+
return `${errorMessage}\n\nGitHub Copilot rejected this prompt at the API/server context cap. Atomic raises the local token budget for selected larger context windows and sends X-GitHub-Api-Version: 2026-06-01 so Copilot can choose its long-context tier server-side by prompt token count, but GitHub still requires the account to have Copilot long-context/usage-based billing entitlement enabled. Long-context Copilot requests consume higher-cost AI credits. Reduce the session context, choose a smaller context window/model, or enable the required Copilot long-context/usage-based billing entitlement for this account.`;
|
|
28
|
+
}
|
|
29
|
+
export function formatCopilotProviderError(modelProvider, errorMessage) {
|
|
30
|
+
return modelProvider === "github-copilot" ? formatCopilotPromptLimitError(errorMessage) : errorMessage;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=copilot-errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-errors.js","sourceRoot":"","sources":["../../src/core/copilot-errors.ts"],"names":[],"mappings":"AAAA,MAAM,4BAA4B,GAAG,iEAAiE,CAAC;AACvG,MAAM,oCAAoC,GAAG,0CAA0C,CAAC;AAOxF,SAAS,eAAe,CAAC,KAAa;IACrC,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,YAAoB;IAChE,MAAM,KAAK,GAAG,4BAA4B,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,MAAM,eAAe,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACjC,MAAM,cAAc,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAChC,IAAI,CAAC,eAAe,IAAI,CAAC,cAAc;QAAE,OAAO,SAAS,CAAC;IAC1D,MAAM,YAAY,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;IACtD,MAAM,WAAW,GAAG,eAAe,CAAC,cAAc,CAAC,CAAC;IACpD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC;QAAE,OAAO,SAAS,CAAC;IACtF,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,YAAoB;IAC7D,OAAO,4BAA4B,CAAC,YAAY,CAAC,KAAK,SAAS,CAAC;AACjE,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,YAAoB;IACjE,IAAI,CAAC,yBAAyB,CAAC,YAAY,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC,oCAAoC,CAAC,EAAE,CAAC;QAC7G,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,OAAO,GAAG,YAAY,slBAAslB,CAAC;AAC9mB,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAC,aAAqB,EAAE,YAAoB;IACrF,OAAO,aAAa,KAAK,gBAAgB,CAAC,CAAC,CAAC,6BAA6B,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;AACxG,CAAC","sourcesContent":["const COPILOT_PROMPT_LIMIT_PATTERN = /\\bprompt token count of ([\\d,]+) exceeds the limit of ([\\d,]+)/i;\nconst COPILOT_LONG_CONTEXT_GUIDANCE_MARKER = \"Copilot long-context/usage-based billing\";\n\nexport interface CopilotPromptLimitError {\n\tpromptTokens: number;\n\tlimitTokens: number;\n}\n\nfunction parseTokenCount(value: string): number {\n\treturn Number(value.replace(/,/g, \"\"));\n}\n\nexport function parseCopilotPromptLimitError(errorMessage: string): CopilotPromptLimitError | undefined {\n\tconst match = COPILOT_PROMPT_LIMIT_PATTERN.exec(errorMessage);\n\tif (!match) return undefined;\n\tconst promptTokenText = match[1];\n\tconst limitTokenText = match[2];\n\tif (!promptTokenText || !limitTokenText) return undefined;\n\tconst promptTokens = parseTokenCount(promptTokenText);\n\tconst limitTokens = parseTokenCount(limitTokenText);\n\tif (!Number.isFinite(promptTokens) || !Number.isFinite(limitTokens)) return undefined;\n\treturn { promptTokens, limitTokens };\n}\n\nexport function isCopilotPromptLimitError(errorMessage: string): boolean {\n\treturn parseCopilotPromptLimitError(errorMessage) !== undefined;\n}\n\nexport function formatCopilotPromptLimitError(errorMessage: string): string {\n\tif (!isCopilotPromptLimitError(errorMessage) || errorMessage.includes(COPILOT_LONG_CONTEXT_GUIDANCE_MARKER)) {\n\t\treturn errorMessage;\n\t}\n\n\treturn `${errorMessage}\\n\\nGitHub Copilot rejected this prompt at the API/server context cap. Atomic raises the local token budget for selected larger context windows and sends X-GitHub-Api-Version: 2026-06-01 so Copilot can choose its long-context tier server-side by prompt token count, but GitHub still requires the account to have Copilot long-context/usage-based billing entitlement enabled. Long-context Copilot requests consume higher-cost AI credits. Reduce the session context, choose a smaller context window/model, or enable the required Copilot long-context/usage-based billing entitlement for this account.`;\n}\n\nexport function formatCopilotProviderError(modelProvider: string, errorMessage: string): string {\n\treturn modelProvider === \"github-copilot\" ? formatCopilotPromptLimitError(errorMessage) : errorMessage;\n}\n"]}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot model catalog (CAPI) — dynamic, input-token context windows.
|
|
3
|
+
*
|
|
4
|
+
* GitHub's Copilot API (CAPI) exposes per-model limits via `GET {baseUrl}/models`. Every window
|
|
5
|
+
* Atomic shows for a Copilot model is measured in INPUT (prompt) tokens, exactly like every other
|
|
6
|
+
* provider's `contextWindow`, so GitHub models read consistently across the UI:
|
|
7
|
+
*
|
|
8
|
+
* - A model's input budget = `capabilities.limits.max_prompt_tokens`
|
|
9
|
+
* ?? `capabilities.limits.max_context_window_tokens`
|
|
10
|
+
* ?? 128_000 (the two fallbacks are safeties real CAPI entries never hit).
|
|
11
|
+
* - Models with tiered pricing expose per-tier input budgets via
|
|
12
|
+
* `billing.token_prices.<tier>.context_max`. The `default` tier is the base context window
|
|
13
|
+
* (e.g. gpt-5.5 272k, Claude 200k); a `long_context` tier adds a selectable larger input
|
|
14
|
+
* window (e.g. gpt-5.5 922k, Claude 936k) the user can switch to via the `/model` picker.
|
|
15
|
+
*
|
|
16
|
+
* This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers
|
|
17
|
+
* windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes
|
|
18
|
+
* stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot
|
|
19
|
+
* provider) and cached on disk for a short TTL, exactly like the Copilot CLI.
|
|
20
|
+
*/
|
|
21
|
+
/** Resolved input-token context window(s) for a single Copilot model. */
|
|
22
|
+
export interface CopilotModelContext {
|
|
23
|
+
/**
|
|
24
|
+
* Base context window in INPUT tokens — shown in the footer and used for compaction. The
|
|
25
|
+
* default tier's `context_max`, or the model-level `max_prompt_tokens` fallback otherwise.
|
|
26
|
+
*/
|
|
27
|
+
contextWindow: number;
|
|
28
|
+
/**
|
|
29
|
+
* Selectable input-token windows (`[default, long]`) when the model exposes a `long_context`
|
|
30
|
+
* tier larger than its default; absent for single-window models.
|
|
31
|
+
*/
|
|
32
|
+
contextWindowOptions?: readonly number[];
|
|
33
|
+
}
|
|
34
|
+
/** Map of model id → resolved input-token context window(s). */
|
|
35
|
+
export type CopilotModelCatalog = ReadonlyMap<string, CopilotModelContext>;
|
|
36
|
+
/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */
|
|
37
|
+
export declare const COPILOT_CONTEXT_WINDOW_FALLBACK = 128000;
|
|
38
|
+
export declare const COPILOT_CATALOG_API_VERSION = "2026-06-01";
|
|
39
|
+
/**
|
|
40
|
+
* Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends
|
|
41
|
+
* for Copilot token refresh and model-policy calls, plus the dated API version.
|
|
42
|
+
*/
|
|
43
|
+
export declare const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>>;
|
|
44
|
+
/** Default (non-enterprise) Copilot CAPI base URL when the token has no resolvable `proxy-ep`. */
|
|
45
|
+
export declare const DEFAULT_COPILOT_API_BASE_URL = "https://api.individual.githubcopilot.com";
|
|
46
|
+
/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */
|
|
47
|
+
export declare const COPILOT_CATALOG_CACHE_TTL_MS: number;
|
|
48
|
+
/** Current on-disk cache schema version. */
|
|
49
|
+
export declare const COPILOT_CATALOG_CACHE_VERSION: 2;
|
|
50
|
+
/**
|
|
51
|
+
* Resolve the Copilot CAPI base URL.
|
|
52
|
+
*
|
|
53
|
+
* Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with
|
|
54
|
+
* `proxy.` swapped for `api.`. Falls back to the enterprise host or the individual default. (pi-ai
|
|
55
|
+
* exposes an equivalent helper, but its published `dist` mangles the export name, so the small,
|
|
56
|
+
* stable parsing logic is reimplemented here.)
|
|
57
|
+
*/
|
|
58
|
+
export declare function copilotApiBaseUrlFromToken(token: string | undefined, enterpriseDomain?: string): string;
|
|
59
|
+
/** Raw input-token limits parsed from a CAPI model entry. */
|
|
60
|
+
export interface CopilotModelLimits {
|
|
61
|
+
/** `capabilities.limits.max_prompt_tokens`. */
|
|
62
|
+
maxPromptTokens?: number;
|
|
63
|
+
/** `capabilities.limits.max_context_window_tokens`. */
|
|
64
|
+
maxContextWindowTokens?: number;
|
|
65
|
+
/** `billing.token_prices.default.context_max`. */
|
|
66
|
+
defaultContextMax?: number;
|
|
67
|
+
/** `billing.token_prices.long_context.context_max`. */
|
|
68
|
+
longContextMax?: number;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Resolve a model's input-token context window(s) from its CAPI limits.
|
|
72
|
+
*
|
|
73
|
+
* `contextWindow` is the model's base input budget — the default tier's `context_max` when tiered,
|
|
74
|
+
* otherwise `max_prompt_tokens ?? max_context_window_tokens ?? 128_000`. A `long_context` tier that
|
|
75
|
+
* is larger than the base adds a second selectable window. Returns `undefined` when the entry
|
|
76
|
+
* carries no usable limit signal at all.
|
|
77
|
+
*/
|
|
78
|
+
export declare function resolveCopilotModelContext(limits: CopilotModelLimits): CopilotModelContext | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Parse a raw CAPI `/models` response body into an input-token context-window catalog.
|
|
81
|
+
*/
|
|
82
|
+
export declare function parseCopilotModelCatalog(body: unknown): CopilotModelCatalog;
|
|
83
|
+
export interface FetchCopilotModelCatalogOptions {
|
|
84
|
+
/** Valid Copilot CAPI bearer token (e.g. from `modelRegistry.getApiKeyForProvider`). */
|
|
85
|
+
token: string;
|
|
86
|
+
/** Override the resolved base URL; defaults to one derived from the token. */
|
|
87
|
+
baseUrl?: string;
|
|
88
|
+
/** Enterprise domain, used for base-URL resolution when the token lacks a `proxy-ep`. */
|
|
89
|
+
enterpriseDomain?: string;
|
|
90
|
+
/** Extra/override request headers. */
|
|
91
|
+
headers?: Record<string, string>;
|
|
92
|
+
/** Injectable `fetch` for testing. */
|
|
93
|
+
fetchImpl?: typeof fetch;
|
|
94
|
+
/** Abort signal. */
|
|
95
|
+
signal?: AbortSignal;
|
|
96
|
+
}
|
|
97
|
+
/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */
|
|
98
|
+
export declare function fetchCopilotModelCatalog(options: FetchCopilotModelCatalogOptions): Promise<CopilotModelCatalog>;
|
|
99
|
+
/** Replace the active catalog the registry derives context windows from. */
|
|
100
|
+
export declare function setActiveCopilotModelCatalog(catalog: CopilotModelCatalog): void;
|
|
101
|
+
/** The active catalog (empty until a successful auth-gated fetch/cache load). */
|
|
102
|
+
export declare function getActiveCopilotModelCatalog(): CopilotModelCatalog;
|
|
103
|
+
/** Reset the active catalog (primarily for tests). */
|
|
104
|
+
export declare function clearActiveCopilotModelCatalog(): void;
|
|
105
|
+
export interface ReadCopilotCatalogCacheOptions {
|
|
106
|
+
/** Expected CAPI host; a cached file from a different host is ignored. */
|
|
107
|
+
host: string;
|
|
108
|
+
/** Current epoch ms (injectable for tests). */
|
|
109
|
+
now?: number;
|
|
110
|
+
/** Freshness window; defaults to {@link COPILOT_CATALOG_CACHE_TTL_MS}. */
|
|
111
|
+
ttlMs?: number;
|
|
112
|
+
}
|
|
113
|
+
/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */
|
|
114
|
+
export declare function readCopilotCatalogCache(path: string, options: ReadCopilotCatalogCacheOptions): CopilotModelCatalog | undefined;
|
|
115
|
+
/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */
|
|
116
|
+
export declare function writeCopilotCatalogCache(path: string, baseUrl: string, catalog: CopilotModelCatalog, now?: number): void;
|
|
117
|
+
/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */
|
|
118
|
+
export declare function copilotCatalogCacheHost(baseUrl: string): string;
|
|
119
|
+
/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */
|
|
120
|
+
export declare function copilotCatalogCachePath(agentDir: string): string;
|
|
121
|
+
/**
|
|
122
|
+
* Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.
|
|
123
|
+
*
|
|
124
|
+
* Called at model-registry construction so a returning user's previously selected long-context
|
|
125
|
+
* window is recognized before startup validation runs — otherwise the persisted choice would warn
|
|
126
|
+
* ("context window 936k is not supported…") and reset until the async refresh completes. The cache
|
|
127
|
+
* TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and
|
|
128
|
+
* the async loader independently refetches on its own freshness window. Returns true when a catalog
|
|
129
|
+
* was applied. No-op (returns false) without a token or a host-matching cached catalog.
|
|
130
|
+
*/
|
|
131
|
+
export declare function seedActiveCopilotModelCatalogFromCache(accessToken: string | undefined, cachePath: string, now?: number): boolean;
|
|
132
|
+
//# sourceMappingURL=copilot-model-catalog.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"copilot-model-catalog.d.ts","sourceRoot":"","sources":["../../src/core/copilot-model-catalog.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAKH,yEAAyE;AACzE,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACzC;AAED,gEAAgE;AAChE,MAAM,MAAM,mBAAmB,GAAG,WAAW,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;AAE3E,wGAAwG;AACxG,eAAO,MAAM,+BAA+B,SAAU,CAAC;AAEvD,eAAO,MAAM,2B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AED,uFAAuF;AACvF,wBAAsB,wBAAwB,CAAC,OAAO,EAAE,+BAA+B,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAiBrH;AAWD,4EAA4E;AAC5E,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,mBAAmB,GAAG,IAAI,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;AAcD,wGAAwG;AACxG,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,8BAA8B,GACrC,mBAAmB,GAAG,SAAS,CAsBjC;AAED,6FAA6F;AAC7F,wBAAgB,wBAAwB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,mBAAmB,EAC5B,GAAG,CAAC,EAAE,MAAM,GACV,IAAI,CAaN;AAED,yFAAyF;AACzF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED,0FAA0F;AAC1F,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":["/**\n * GitHub Copilot model catalog (CAPI) — dynamic, input-token context windows.\n *\n * GitHub's Copilot API (CAPI) exposes per-model limits via `GET {baseUrl}/models`. Every window\n * Atomic shows for a Copilot model is measured in INPUT (prompt) tokens, exactly like every other\n * provider's `contextWindow`, so GitHub models read consistently across the UI:\n *\n * - A model's input budget = `capabilities.limits.max_prompt_tokens`\n * ?? `capabilities.limits.max_context_window_tokens`\n * ?? 128_000 (the two fallbacks are safeties real CAPI entries never hit).\n * - Models with tiered pricing expose per-tier input budgets via\n * `billing.token_prices.<tier>.context_max`. The `default` tier is the base context window\n * (e.g. gpt-5.5 272k, Claude 200k); a `long_context` tier adds a selectable larger input\n * window (e.g. gpt-5.5 922k, Claude 936k) the user can switch to via the `/model` picker.\n *\n * This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers\n * windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes\n * stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot\n * provider) and cached on disk for a short TTL, exactly like the Copilot CLI.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Resolved input-token context window(s) for a single Copilot model. */\nexport interface CopilotModelContext {\n\t/**\n\t * Base context window in INPUT tokens — shown in the footer and used for compaction. The\n\t * default tier's `context_max`, or the model-level `max_prompt_tokens` fallback otherwise.\n\t */\n\tcontextWindow: number;\n\t/**\n\t * Selectable input-token windows (`[default, long]`) when the model exposes a `long_context`\n\t * tier larger than its default; absent for single-window models.\n\t */\n\tcontextWindowOptions?: readonly number[];\n}\n\n/** Map of model id → resolved input-token context window(s). */\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 (non-enterprise) Copilot CAPI base URL when the token has no resolvable `proxy-ep`. */\nexport const DEFAULT_COPILOT_API_BASE_URL = \"https://api.individual.githubcopilot.com\";\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 = 2 as const;\n\n/**\n * Resolve the Copilot CAPI base URL.\n *\n * Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with\n * `proxy.` swapped for `api.`. Falls back to the enterprise host or the individual default. (pi-ai\n * exposes an equivalent helper, but its published `dist` mangles the export name, so the small,\n * stable parsing logic is reimplemented here.)\n */\nexport function copilotApiBaseUrlFromToken(token: string | undefined, enterpriseDomain?: string): string {\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\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\n/** Raw input-token limits parsed from a CAPI model entry. */\nexport interface CopilotModelLimits {\n\t/** `capabilities.limits.max_prompt_tokens`. */\n\tmaxPromptTokens?: number;\n\t/** `capabilities.limits.max_context_window_tokens`. */\n\tmaxContextWindowTokens?: number;\n\t/** `billing.token_prices.default.context_max`. */\n\tdefaultContextMax?: number;\n\t/** `billing.token_prices.long_context.context_max`. */\n\tlongContextMax?: number;\n}\n\n/**\n * Resolve a model's input-token context window(s) from its CAPI limits.\n *\n * `contextWindow` is the model's base input budget — the default tier's `context_max` when tiered,\n * otherwise `max_prompt_tokens ?? max_context_window_tokens ?? 128_000`. A `long_context` tier that\n * is larger than the base adds a second selectable window. Returns `undefined` when the entry\n * carries no usable limit signal at all.\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\treturn { contextWindow: base, contextWindowOptions: [base, limits.longContextMax] };\n\t}\n\treturn { 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 limits = asRecord(asRecord(record.capabilities)?.limits);\n\t\tconst prices = asRecord(asRecord(record.billing)?.token_prices);\n\t\tconst context = resolveCopilotModelContext({\n\t\t\tmaxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),\n\t\t\tmaxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),\n\t\t\tdefaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),\n\t\t\tlongContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),\n\t\t});\n\t\tif (context) catalog.set(id, context);\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 sanitizeCachedContext(value: unknown): CopilotModelContext | undefined {\n\tconst record = asRecord(value);\n\tconst contextWindow = toPositiveInt(record?.contextWindow);\n\tif (contextWindow === undefined) return undefined;\n\tconst rawOptions = record?.contextWindowOptions;\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) return { contextWindow, contextWindowOptions: options };\n\t}\n\treturn { contextWindow };\n}\n\n/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */\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\n/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */\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\n/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */\nexport function copilotCatalogCacheHost(baseUrl: string): string {\n\treturn hostFromBaseUrl(baseUrl);\n}\n\n/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */\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"]}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot model catalog (CAPI) — dynamic, input-token context windows.
|
|
3
|
+
*
|
|
4
|
+
* GitHub's Copilot API (CAPI) exposes per-model limits via `GET {baseUrl}/models`. Every window
|
|
5
|
+
* Atomic shows for a Copilot model is measured in INPUT (prompt) tokens, exactly like every other
|
|
6
|
+
* provider's `contextWindow`, so GitHub models read consistently across the UI:
|
|
7
|
+
*
|
|
8
|
+
* - A model's input budget = `capabilities.limits.max_prompt_tokens`
|
|
9
|
+
* ?? `capabilities.limits.max_context_window_tokens`
|
|
10
|
+
* ?? 128_000 (the two fallbacks are safeties real CAPI entries never hit).
|
|
11
|
+
* - Models with tiered pricing expose per-tier input budgets via
|
|
12
|
+
* `billing.token_prices.<tier>.context_max`. The `default` tier is the base context window
|
|
13
|
+
* (e.g. gpt-5.5 272k, Claude 200k); a `long_context` tier adds a selectable larger input
|
|
14
|
+
* window (e.g. gpt-5.5 922k, Claude 936k) the user can switch to via the `/model` picker.
|
|
15
|
+
*
|
|
16
|
+
* This data is intentionally NOT baked into a static map: GitHub adds/removes models and retiers
|
|
17
|
+
* windows over time (e.g. a model that disappears from the catalog), so a hardcoded snapshot goes
|
|
18
|
+
* stale. Instead the catalog is fetched live (gated on the user actually having the GitHub Copilot
|
|
19
|
+
* provider) and cached on disk for a short TTL, exactly like the Copilot CLI.
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
22
|
+
import { dirname, join } from "node:path";
|
|
23
|
+
/** Safety fallback when a model reports neither `max_prompt_tokens` nor `max_context_window_tokens`. */
|
|
24
|
+
export const COPILOT_CONTEXT_WINDOW_FALLBACK = 128_000;
|
|
25
|
+
export const COPILOT_CATALOG_API_VERSION = "2026-06-01";
|
|
26
|
+
/**
|
|
27
|
+
* Headers GitHub's CAPI expects for catalog reads. Mirrors the editor headers pi-ai already sends
|
|
28
|
+
* for Copilot token refresh and model-policy calls, plus the dated API version.
|
|
29
|
+
*/
|
|
30
|
+
export const COPILOT_CATALOG_HEADERS = {
|
|
31
|
+
"User-Agent": "GitHubCopilotChat/0.35.0",
|
|
32
|
+
"Editor-Version": "vscode/1.107.0",
|
|
33
|
+
"Editor-Plugin-Version": "copilot-chat/0.35.0",
|
|
34
|
+
"Copilot-Integration-Id": "vscode-chat",
|
|
35
|
+
"X-GitHub-Api-Version": COPILOT_CATALOG_API_VERSION,
|
|
36
|
+
};
|
|
37
|
+
/** Default (non-enterprise) Copilot CAPI base URL when the token has no resolvable `proxy-ep`. */
|
|
38
|
+
export const DEFAULT_COPILOT_API_BASE_URL = "https://api.individual.githubcopilot.com";
|
|
39
|
+
/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */
|
|
40
|
+
export const COPILOT_CATALOG_CACHE_TTL_MS = 30 * 60 * 1000;
|
|
41
|
+
/** Current on-disk cache schema version. */
|
|
42
|
+
export const COPILOT_CATALOG_CACHE_VERSION = 2;
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the Copilot CAPI base URL.
|
|
45
|
+
*
|
|
46
|
+
* Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with
|
|
47
|
+
* `proxy.` swapped for `api.`. Falls back to the enterprise host or the individual default. (pi-ai
|
|
48
|
+
* exposes an equivalent helper, but its published `dist` mangles the export name, so the small,
|
|
49
|
+
* stable parsing logic is reimplemented here.)
|
|
50
|
+
*/
|
|
51
|
+
export function copilotApiBaseUrlFromToken(token, enterpriseDomain) {
|
|
52
|
+
if (token) {
|
|
53
|
+
const match = token.match(/proxy-ep=([^;]+)/);
|
|
54
|
+
if (match) {
|
|
55
|
+
return `https://${match[1].replace(/^proxy\./, "api.")}`;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (enterpriseDomain)
|
|
59
|
+
return `https://copilot-api.${enterpriseDomain}`;
|
|
60
|
+
return DEFAULT_COPILOT_API_BASE_URL;
|
|
61
|
+
}
|
|
62
|
+
function trimTrailingSlash(url) {
|
|
63
|
+
return url.replace(/\/+$/, "");
|
|
64
|
+
}
|
|
65
|
+
function asRecord(value) {
|
|
66
|
+
return value && typeof value === "object" ? value : undefined;
|
|
67
|
+
}
|
|
68
|
+
function toPositiveInt(value) {
|
|
69
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Resolve a model's input-token context window(s) from its CAPI limits.
|
|
73
|
+
*
|
|
74
|
+
* `contextWindow` is the model's base input budget — the default tier's `context_max` when tiered,
|
|
75
|
+
* otherwise `max_prompt_tokens ?? max_context_window_tokens ?? 128_000`. A `long_context` tier that
|
|
76
|
+
* is larger than the base adds a second selectable window. Returns `undefined` when the entry
|
|
77
|
+
* carries no usable limit signal at all.
|
|
78
|
+
*/
|
|
79
|
+
export function resolveCopilotModelContext(limits) {
|
|
80
|
+
const hasSignal = limits.maxPromptTokens !== undefined ||
|
|
81
|
+
limits.maxContextWindowTokens !== undefined ||
|
|
82
|
+
limits.defaultContextMax !== undefined ||
|
|
83
|
+
limits.longContextMax !== undefined;
|
|
84
|
+
if (!hasSignal)
|
|
85
|
+
return undefined;
|
|
86
|
+
const maxInput = limits.maxPromptTokens ?? limits.maxContextWindowTokens ?? COPILOT_CONTEXT_WINDOW_FALLBACK;
|
|
87
|
+
const base = limits.defaultContextMax ?? maxInput;
|
|
88
|
+
if (limits.longContextMax !== undefined && limits.longContextMax > base) {
|
|
89
|
+
return { contextWindow: base, contextWindowOptions: [base, limits.longContextMax] };
|
|
90
|
+
}
|
|
91
|
+
return { contextWindow: base };
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Parse a raw CAPI `/models` response body into an input-token context-window catalog.
|
|
95
|
+
*/
|
|
96
|
+
export function parseCopilotModelCatalog(body) {
|
|
97
|
+
const catalog = new Map();
|
|
98
|
+
const data = asRecord(body)?.data;
|
|
99
|
+
if (!Array.isArray(data))
|
|
100
|
+
return catalog;
|
|
101
|
+
for (const entry of data) {
|
|
102
|
+
const record = asRecord(entry);
|
|
103
|
+
if (!record)
|
|
104
|
+
continue;
|
|
105
|
+
const id = record.id;
|
|
106
|
+
if (typeof id !== "string" || id.length === 0)
|
|
107
|
+
continue;
|
|
108
|
+
const limits = asRecord(asRecord(record.capabilities)?.limits);
|
|
109
|
+
const prices = asRecord(asRecord(record.billing)?.token_prices);
|
|
110
|
+
const context = resolveCopilotModelContext({
|
|
111
|
+
maxPromptTokens: toPositiveInt(limits?.max_prompt_tokens),
|
|
112
|
+
maxContextWindowTokens: toPositiveInt(limits?.max_context_window_tokens),
|
|
113
|
+
defaultContextMax: toPositiveInt(asRecord(prices?.default)?.context_max),
|
|
114
|
+
longContextMax: toPositiveInt(asRecord(prices?.long_context)?.context_max),
|
|
115
|
+
});
|
|
116
|
+
if (context)
|
|
117
|
+
catalog.set(id, context);
|
|
118
|
+
}
|
|
119
|
+
return catalog;
|
|
120
|
+
}
|
|
121
|
+
/** Fetch and parse the live Copilot model catalog from CAPI `GET {baseUrl}/models`. */
|
|
122
|
+
export async function fetchCopilotModelCatalog(options) {
|
|
123
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
124
|
+
const baseUrl = options.baseUrl ?? copilotApiBaseUrlFromToken(options.token, options.enterpriseDomain);
|
|
125
|
+
const response = await fetchImpl(`${trimTrailingSlash(baseUrl)}/models`, {
|
|
126
|
+
method: "GET",
|
|
127
|
+
headers: {
|
|
128
|
+
Accept: "application/json",
|
|
129
|
+
Authorization: `Bearer ${options.token}`,
|
|
130
|
+
...COPILOT_CATALOG_HEADERS,
|
|
131
|
+
...options.headers,
|
|
132
|
+
},
|
|
133
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
134
|
+
});
|
|
135
|
+
if (!response.ok) {
|
|
136
|
+
throw new Error(`GitHub Copilot /models request failed: ${response.status} ${response.statusText}`);
|
|
137
|
+
}
|
|
138
|
+
return parseCopilotModelCatalog(await response.json());
|
|
139
|
+
}
|
|
140
|
+
// ----------------------------------------------------------------------------
|
|
141
|
+
// Active in-memory catalog (consulted by the model registry).
|
|
142
|
+
//
|
|
143
|
+
// Empty by default, so with no Copilot auth / no successful fetch the registry leaves Copilot
|
|
144
|
+
// model context windows untouched and the picker never appears.
|
|
145
|
+
// ----------------------------------------------------------------------------
|
|
146
|
+
let activeCatalog = new Map();
|
|
147
|
+
/** Replace the active catalog the registry derives context windows from. */
|
|
148
|
+
export function setActiveCopilotModelCatalog(catalog) {
|
|
149
|
+
activeCatalog = catalog;
|
|
150
|
+
}
|
|
151
|
+
/** The active catalog (empty until a successful auth-gated fetch/cache load). */
|
|
152
|
+
export function getActiveCopilotModelCatalog() {
|
|
153
|
+
return activeCatalog;
|
|
154
|
+
}
|
|
155
|
+
/** Reset the active catalog (primarily for tests). */
|
|
156
|
+
export function clearActiveCopilotModelCatalog() {
|
|
157
|
+
activeCatalog = new Map();
|
|
158
|
+
}
|
|
159
|
+
function hostFromBaseUrl(baseUrl) {
|
|
160
|
+
try {
|
|
161
|
+
return new URL(baseUrl).host;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return baseUrl;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function sanitizeCachedContext(value) {
|
|
168
|
+
const record = asRecord(value);
|
|
169
|
+
const contextWindow = toPositiveInt(record?.contextWindow);
|
|
170
|
+
if (contextWindow === undefined)
|
|
171
|
+
return undefined;
|
|
172
|
+
const rawOptions = record?.contextWindowOptions;
|
|
173
|
+
if (Array.isArray(rawOptions)) {
|
|
174
|
+
const options = rawOptions.map(toPositiveInt).filter((n) => n !== undefined);
|
|
175
|
+
if (options.length > 1)
|
|
176
|
+
return { contextWindow, contextWindowOptions: options };
|
|
177
|
+
}
|
|
178
|
+
return { contextWindow };
|
|
179
|
+
}
|
|
180
|
+
/** Read a fresh, host-matching catalog from the cache file, or `undefined` if missing/stale/invalid. */
|
|
181
|
+
export function readCopilotCatalogCache(path, options) {
|
|
182
|
+
let parsed;
|
|
183
|
+
try {
|
|
184
|
+
if (!existsSync(path))
|
|
185
|
+
return undefined;
|
|
186
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
if (!parsed || parsed.version !== COPILOT_CATALOG_CACHE_VERSION)
|
|
192
|
+
return undefined;
|
|
193
|
+
if (parsed.host !== options.host)
|
|
194
|
+
return undefined;
|
|
195
|
+
const now = options.now ?? Date.now();
|
|
196
|
+
const ttlMs = options.ttlMs ?? COPILOT_CATALOG_CACHE_TTL_MS;
|
|
197
|
+
if (typeof parsed.fetchedAt !== "number" || now - parsed.fetchedAt >= ttlMs)
|
|
198
|
+
return undefined;
|
|
199
|
+
const models = asRecord(parsed.models);
|
|
200
|
+
if (!models)
|
|
201
|
+
return undefined;
|
|
202
|
+
const catalog = new Map();
|
|
203
|
+
for (const [id, value] of Object.entries(models)) {
|
|
204
|
+
const context = sanitizeCachedContext(value);
|
|
205
|
+
if (context)
|
|
206
|
+
catalog.set(id, context);
|
|
207
|
+
}
|
|
208
|
+
return catalog;
|
|
209
|
+
}
|
|
210
|
+
/** Write the catalog to the cache file (creating parent dirs). Best-effort; never throws. */
|
|
211
|
+
export function writeCopilotCatalogCache(path, baseUrl, catalog, now) {
|
|
212
|
+
const payload = {
|
|
213
|
+
version: COPILOT_CATALOG_CACHE_VERSION,
|
|
214
|
+
host: hostFromBaseUrl(baseUrl),
|
|
215
|
+
fetchedAt: now ?? Date.now(),
|
|
216
|
+
models: Object.fromEntries(catalog),
|
|
217
|
+
};
|
|
218
|
+
try {
|
|
219
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
220
|
+
writeFileSync(path, JSON.stringify(payload), "utf8");
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
// best-effort cache; ignore write failures
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/** Host component of a base URL, for matching {@link readCopilotCatalogCache} `host`. */
|
|
227
|
+
export function copilotCatalogCacheHost(baseUrl) {
|
|
228
|
+
return hostFromBaseUrl(baseUrl);
|
|
229
|
+
}
|
|
230
|
+
/** Standard on-disk cache path for the Copilot model catalog under an agent directory. */
|
|
231
|
+
export function copilotCatalogCachePath(agentDir) {
|
|
232
|
+
return join(agentDir, "cache", "copilot-models.json");
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Seed the active catalog synchronously from the on-disk cache, gated on a Copilot access token.
|
|
236
|
+
*
|
|
237
|
+
* Called at model-registry construction so a returning user's previously selected long-context
|
|
238
|
+
* window is recognized before startup validation runs — otherwise the persisted choice would warn
|
|
239
|
+
* ("context window 936k is not supported…") and reset until the async refresh completes. The cache
|
|
240
|
+
* TTL is intentionally ignored here: stale-but-present windows are still valid for selection, and
|
|
241
|
+
* the async loader independently refetches on its own freshness window. Returns true when a catalog
|
|
242
|
+
* was applied. No-op (returns false) without a token or a host-matching cached catalog.
|
|
243
|
+
*/
|
|
244
|
+
export function seedActiveCopilotModelCatalogFromCache(accessToken, cachePath, now) {
|
|
245
|
+
if (typeof accessToken !== "string" || accessToken.length === 0)
|
|
246
|
+
return false;
|
|
247
|
+
const host = copilotCatalogCacheHost(copilotApiBaseUrlFromToken(accessToken));
|
|
248
|
+
const cached = readCopilotCatalogCache(cachePath, { host, now, ttlMs: Number.POSITIVE_INFINITY });
|
|
249
|
+
if (!cached)
|
|
250
|
+
return false;
|
|
251
|
+
setActiveCopilotModelCatalog(cached);
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
//# sourceMappingURL=copilot-model-catalog.js.map
|