dsh-plugin-subscriptions 0.5.0 → 0.5.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/README.md +15 -6
- package/README.zh.md +14 -6
- package/lib/auth/device-flow.d.ts +64 -0
- package/lib/auth/device-flow.js +176 -0
- package/lib/auth/oauth-flow.js +1 -1
- package/lib/auth/rpc.d.ts +3 -1
- package/lib/auth/store.d.ts +20 -2
- package/lib/auth/store.js +45 -9
- package/lib/client/SubscriptionsSection.d.ts +1 -1
- package/lib/client/SubscriptionsSection.js +46 -4
- package/lib/client/locales.d.ts +8 -0
- package/lib/client/locales.js +8 -0
- package/lib/client.js +94 -4
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +3 -2
- package/lib/index.js +1770 -156
- package/lib/providers/catalog-store.js +15 -0
- package/lib/providers/claude.d.ts +20 -1
- package/lib/providers/claude.js +44 -27
- package/lib/providers/codex.js +52 -8
- package/lib/providers/common.d.ts +32 -1
- package/lib/providers/common.js +48 -1
- package/lib/providers/copilot.d.ts +315 -0
- package/lib/providers/copilot.js +786 -0
- package/lib/providers/grok.d.ts +7 -2
- package/lib/providers/grok.js +46 -18
- package/lib/translate/anthropic.d.ts +47 -6
- package/lib/translate/anthropic.js +135 -20
- package/lib/translate/chat-completions.d.ts +120 -0
- package/lib/translate/chat-completions.js +363 -0
- package/lib/translate/responses.d.ts +49 -5
- package/lib/translate/responses.js +40 -7
- package/package.json +9 -10
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot subscription provider: OAuth device-authorization flow with
|
|
3
|
+
* the VS Code Copilot Chat client id, a GitHub-token → Copilot-token exchange
|
|
4
|
+
* against `copilot_internal/v2/token`, and streaming against two upstream
|
|
5
|
+
* protocols chosen per model: the OpenAI-compatible chat completions endpoint
|
|
6
|
+
* for models whose catalog entry lists `/chat/completions`, and the Responses
|
|
7
|
+
* endpoint for the newer model families (gpt-5.5/5.6, …) that only list
|
|
8
|
+
* `/responses`. Both upstreams are stream-only.
|
|
9
|
+
*
|
|
10
|
+
* Two token generations are in play: the long-lived GitHub OAuth token (kept
|
|
11
|
+
* as the session's `refreshToken`) and the ~30-minute Copilot API token it
|
|
12
|
+
* exchanges into (the session's `accessToken`). A TokenManager "refresh" is a
|
|
13
|
+
* fresh exchange, so the standard preempt/401-retry machinery applies
|
|
14
|
+
* unchanged.
|
|
15
|
+
*/
|
|
16
|
+
import { EMPTY_RESPONSE_CODE, errorChain, LlmAdapter, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
|
|
17
|
+
import { resolveImages } from '../translate/resolved.js';
|
|
18
|
+
import { streamChatCompletions, toChatMessages, toChatTools, } from '../translate/chat-completions.js';
|
|
19
|
+
import { streamResponses, toResponsesInput, toResponsesTools } from '../translate/responses.js';
|
|
20
|
+
import { httpLlmError, idleWatchdog, mapFetchFailure, ModelCatalogCache, discoverOrRetryAuth, isMissingOrInvalidCredential, oauthEndpointError, OAuthEndpointError, TokenManager, } from './common.js';
|
|
21
|
+
/**
|
|
22
|
+
* Client id of the VS Code Copilot Chat GitHub App (pi-mono and
|
|
23
|
+
* copilot2api-go use the same value): the app is pre-authorized for the
|
|
24
|
+
* Copilot internal token exchange, a self-registered OAuth App is not.
|
|
25
|
+
*/
|
|
26
|
+
export const COPILOT_CLIENT_ID = 'Iv1.b507a08c87ecfe98';
|
|
27
|
+
export const COPILOT_DEVICE_CODE_URL = 'https://github.com/login/device/code';
|
|
28
|
+
export const COPILOT_DEVICE_TOKEN_URL = 'https://github.com/login/oauth/access_token';
|
|
29
|
+
export const COPILOT_TOKEN_URL = 'https://api.github.com/copilot_internal/v2/token';
|
|
30
|
+
export const GITHUB_USER_URL = 'https://api.github.com/user';
|
|
31
|
+
export const COPILOT_API_URL = 'https://api.githubcopilot.com/chat/completions';
|
|
32
|
+
/** Responses endpoint for models whose catalog entry only lists `/responses`. */
|
|
33
|
+
export const COPILOT_RESPONSES_URL = 'https://api.githubcopilot.com/responses';
|
|
34
|
+
export const COPILOT_MODELS_URL = 'https://api.githubcopilot.com/models';
|
|
35
|
+
const COPILOT_SCOPE = 'read:user';
|
|
36
|
+
const COPILOT_CONTEXT_WINDOW = 128_000;
|
|
37
|
+
const COPILOT_DEFAULT_MAX_TOKENS = 16_000;
|
|
38
|
+
/** Refresh when the Copilot API token has less than this much life left. */
|
|
39
|
+
export const COPILOT_PREEMPT_MS = 5 * 60_000;
|
|
40
|
+
/**
|
|
41
|
+
* The VS Code update feed answers a JSON array of version strings, latest
|
|
42
|
+
* stable first. The Copilot API rejects requests whose Editor-Version is too
|
|
43
|
+
* old with `401 IDE token expired`, so the version is resolved live (cached
|
|
44
|
+
* for a day) instead of hardcoded — a stale hardcode bricks every request.
|
|
45
|
+
*/
|
|
46
|
+
export const VSCODE_RELEASES_URL = 'https://update.code.visualstudio.com/api/releases/stable';
|
|
47
|
+
/** Last-known-good VS Code version when the feed is unreachable. */
|
|
48
|
+
export const FALLBACK_VSCODE_VERSION = '1.107.0';
|
|
49
|
+
const VSCODE_VERSION_TTL_MS = 24 * 3_600_000;
|
|
50
|
+
let vscodeVersionCache;
|
|
51
|
+
let vscodeVersionInflight;
|
|
52
|
+
/**
|
|
53
|
+
* Resolve the VS Code version presented as Editor-Version: the latest stable
|
|
54
|
+
* from the update feed, cached for a day, falling back to a pinned version
|
|
55
|
+
* when the feed fails. Concurrent resolves coalesce behind one fetch.
|
|
56
|
+
* @param fetchFn - fetch implementation (injectable for tests).
|
|
57
|
+
* @param forceRefresh - bypass the cache (a 401 `IDE token expired` retry).
|
|
58
|
+
* @returns a `major.minor.patch` version string.
|
|
59
|
+
*/
|
|
60
|
+
export async function latestVsCodeVersion(fetchFn = fetch, forceRefresh = false) {
|
|
61
|
+
if (!forceRefresh && vscodeVersionCache !== undefined
|
|
62
|
+
&& Date.now() - vscodeVersionCache.at < VSCODE_VERSION_TTL_MS) {
|
|
63
|
+
return vscodeVersionCache.version;
|
|
64
|
+
}
|
|
65
|
+
vscodeVersionInflight ??= (async () => {
|
|
66
|
+
try {
|
|
67
|
+
const response = await fetchFn(VSCODE_RELEASES_URL, { headers: { accept: 'application/json' } });
|
|
68
|
+
if (!response.ok)
|
|
69
|
+
throw new Error(`HTTP ${String(response.status)}`);
|
|
70
|
+
const releases = await response.json();
|
|
71
|
+
const version = Array.isArray(releases)
|
|
72
|
+
? releases.find(entry => typeof entry === 'string' && /^\d+\.\d+\.\d+$/.test(entry))
|
|
73
|
+
: undefined;
|
|
74
|
+
if (version === undefined)
|
|
75
|
+
throw new Error('no version string in the feed');
|
|
76
|
+
vscodeVersionCache = { version: version, at: Date.now() };
|
|
77
|
+
return version;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// A feed failure must never break provider traffic: serve the stale
|
|
81
|
+
// cache, else the pinned fallback.
|
|
82
|
+
return vscodeVersionCache?.version ?? FALLBACK_VSCODE_VERSION;
|
|
83
|
+
}
|
|
84
|
+
})().finally(() => { vscodeVersionInflight = undefined; });
|
|
85
|
+
return vscodeVersionInflight;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The device-flow facts for the auth controller's DeviceFlowManager.
|
|
89
|
+
* @returns the flow spec for one attempt.
|
|
90
|
+
*/
|
|
91
|
+
export function copilotDeviceFlow() {
|
|
92
|
+
return {
|
|
93
|
+
clientId: COPILOT_CLIENT_ID,
|
|
94
|
+
scope: COPILOT_SCOPE,
|
|
95
|
+
deviceCodeUrl: COPILOT_DEVICE_CODE_URL,
|
|
96
|
+
tokenUrl: COPILOT_DEVICE_TOKEN_URL,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Header set presenting requests as the VS Code Copilot Chat extension; the
|
|
101
|
+
* Copilot API rejects traffic without an editor identity.
|
|
102
|
+
* @param hasVision - whether the request carries image input.
|
|
103
|
+
* @param vscodeVersion - Editor-Version value from {@link latestVsCodeVersion}.
|
|
104
|
+
* @returns headers to merge into Copilot API requests.
|
|
105
|
+
*/
|
|
106
|
+
export function copilotHeaders(hasVision = false, vscodeVersion = FALLBACK_VSCODE_VERSION) {
|
|
107
|
+
return {
|
|
108
|
+
'user-agent': 'GitHubCopilotChat/0.35.0',
|
|
109
|
+
'editor-version': `vscode/${vscodeVersion}`,
|
|
110
|
+
'editor-plugin-version': 'copilot-chat/0.35.0',
|
|
111
|
+
'copilot-integration-id': 'vscode-chat',
|
|
112
|
+
'openai-intent': 'conversation-edits',
|
|
113
|
+
'x-github-api-version': '2026-06-01',
|
|
114
|
+
...hasVision ? { 'copilot-vision-request': 'true' } : {},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Exchange a long-lived GitHub OAuth token for a short-lived Copilot API
|
|
119
|
+
* token. A 401/403 means the GitHub token is revoked or the account lost its
|
|
120
|
+
* Copilot subscription — permanent, re-login required.
|
|
121
|
+
* @param githubToken - the GitHub OAuth token from the device flow.
|
|
122
|
+
* @param fetchFn - fetch implementation (injectable for tests).
|
|
123
|
+
* @returns the Copilot API token and its expiry.
|
|
124
|
+
*/
|
|
125
|
+
export async function exchangeCopilotToken(githubToken, fetchFn = fetch) {
|
|
126
|
+
const response = await fetchFn(COPILOT_TOKEN_URL, {
|
|
127
|
+
headers: {
|
|
128
|
+
'authorization': `Bearer ${githubToken}`,
|
|
129
|
+
'accept': 'application/json',
|
|
130
|
+
...copilotHeaders(false, await latestVsCodeVersion(fetchFn)),
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
if (!response.ok)
|
|
134
|
+
throw await oauthEndpointError(response, 'copilot');
|
|
135
|
+
const wire = await response.json();
|
|
136
|
+
if (typeof wire.token !== 'string' || wire.token.length === 0) {
|
|
137
|
+
throw new Error('copilot token endpoint returned no token');
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
accessToken: wire.token,
|
|
141
|
+
// A missing expiry falls back to a conservative 25 minutes (the tokens
|
|
142
|
+
// typically live ~30).
|
|
143
|
+
expiresAt: typeof wire.expires_at === 'number' && wire.expires_at > 0
|
|
144
|
+
? wire.expires_at * 1000
|
|
145
|
+
: Date.now() + 25 * 60_000,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Complete a device-flow login: exchange the GitHub token for a Copilot API
|
|
150
|
+
* token and read the GitHub login name for the status display.
|
|
151
|
+
* @param githubToken - the GitHub OAuth token the device flow released.
|
|
152
|
+
* @param fetchFn - fetch implementation (injectable for tests).
|
|
153
|
+
* @returns the session to store.
|
|
154
|
+
*/
|
|
155
|
+
export async function completeCopilotLogin(githubToken, fetchFn = fetch) {
|
|
156
|
+
const pair = await exchangeCopilotToken(githubToken, fetchFn);
|
|
157
|
+
let account;
|
|
158
|
+
try {
|
|
159
|
+
const response = await fetchFn(GITHUB_USER_URL, {
|
|
160
|
+
headers: {
|
|
161
|
+
'authorization': `Bearer ${githubToken}`,
|
|
162
|
+
'accept': 'application/json',
|
|
163
|
+
// api.github.com only demands a user agent; no editor disguise needed.
|
|
164
|
+
'user-agent': 'GitHubCopilotChat/0.35.0',
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
if (response.ok) {
|
|
168
|
+
const profile = await response.json();
|
|
169
|
+
if (typeof profile.login === 'string' && profile.login.length > 0)
|
|
170
|
+
account = profile.login;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// A profile lookup failure must not fail the login; the session works without a display name.
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
accessToken: pair.accessToken,
|
|
178
|
+
refreshToken: githubToken,
|
|
179
|
+
expiresAt: pair.expiresAt,
|
|
180
|
+
...account === undefined ? {} : { account },
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Refresh a copilot session: re-exchange the long-lived GitHub token for a
|
|
185
|
+
* fresh Copilot API token.
|
|
186
|
+
* @param session - the stored session.
|
|
187
|
+
* @param fetchFn - fetch implementation (injectable for tests).
|
|
188
|
+
* @returns the fresh session to store.
|
|
189
|
+
*/
|
|
190
|
+
export async function refreshCopilot(session, fetchFn = fetch) {
|
|
191
|
+
const pair = await exchangeCopilotToken(session.refreshToken, fetchFn);
|
|
192
|
+
return {
|
|
193
|
+
accessToken: pair.accessToken,
|
|
194
|
+
refreshToken: session.refreshToken,
|
|
195
|
+
expiresAt: pair.expiresAt,
|
|
196
|
+
...session.account === undefined ? {} : { account: session.account },
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Whether a copilot refresh failure means the login is permanently gone.
|
|
201
|
+
* @param error - the thrown refresh error.
|
|
202
|
+
* @returns true when re-login is the only fix (GitHub token revoked or the subscription lost).
|
|
203
|
+
*/
|
|
204
|
+
export function isCopilotPermanentRefreshError(error) {
|
|
205
|
+
return error instanceof OAuthEndpointError && (error.status === 401 || error.status === 403);
|
|
206
|
+
}
|
|
207
|
+
/** Display name for one Copilot wire reasoning-effort value. */
|
|
208
|
+
function copilotEffortName(effort) {
|
|
209
|
+
return effort === 'xhigh' ? 'Extra High' : effort.charAt(0).toUpperCase() + effort.slice(1);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Map a catalog entry's `supports.reasoning_effort` array into selectable
|
|
213
|
+
* efforts. The endpoint discloses no default effort, so none is claimed
|
|
214
|
+
* (absence preserves the provider's own default). Duplicates and non-string
|
|
215
|
+
* entries are dropped: the harness rejects duplicate effort ids outright.
|
|
216
|
+
*/
|
|
217
|
+
function copilotReasoning(entry) {
|
|
218
|
+
const wire = entry.capabilities?.supports?.reasoning_effort;
|
|
219
|
+
if (!Array.isArray(wire))
|
|
220
|
+
return undefined;
|
|
221
|
+
const seen = new Set();
|
|
222
|
+
const efforts = [];
|
|
223
|
+
for (const value of wire) {
|
|
224
|
+
if (typeof value !== 'string' || value.length === 0 || seen.has(value))
|
|
225
|
+
continue;
|
|
226
|
+
seen.add(value);
|
|
227
|
+
efforts.push({ id: ReasoningEffortId(value), name: copilotEffortName(value) });
|
|
228
|
+
}
|
|
229
|
+
return efforts.length > 0 ? { efforts } : undefined;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Fetch the live Copilot model list. Models hidden from the picker or
|
|
233
|
+
* disabled by policy are excluded, as are models able to speak neither
|
|
234
|
+
* protocol this adapter knows: an entry listing `/chat/completions` speaks
|
|
235
|
+
* the chat wire, one listing only `/responses` (the newer GPT families,
|
|
236
|
+
* e.g. gpt-5.6) speaks the Responses wire, and the choice is recorded on the
|
|
237
|
+
* discovered entry so requests pick the matching endpoint; an entry listing
|
|
238
|
+
* BOTH endpoints additionally records `/responses` availability, which
|
|
239
|
+
* {@link copilotRequestWire} uses to reroute tools+effort requests. Vision
|
|
240
|
+
* support from the catalog becomes the model's input modalities, and a
|
|
241
|
+
* non-empty `supports.reasoning_effort` array becomes the model's selectable
|
|
242
|
+
* reasoning efforts (the endpoint discloses no default, so none is claimed).
|
|
243
|
+
* @param session - the stored session (used as-is; never refreshed here).
|
|
244
|
+
* @param fetchFn - fetch implementation (injectable for tests).
|
|
245
|
+
* @returns discovered chat models in endpoint order.
|
|
246
|
+
*/
|
|
247
|
+
export async function fetchCopilotModels(session, fetchFn = fetch) {
|
|
248
|
+
const response = await fetchFn(COPILOT_MODELS_URL, {
|
|
249
|
+
headers: {
|
|
250
|
+
'authorization': `Bearer ${session.accessToken}`,
|
|
251
|
+
'accept': 'application/json',
|
|
252
|
+
...copilotHeaders(false, await latestVsCodeVersion(fetchFn)),
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
if (!response.ok)
|
|
256
|
+
throw await oauthEndpointError(response, 'copilot models');
|
|
257
|
+
const payload = await response.json();
|
|
258
|
+
if (!Array.isArray(payload.data))
|
|
259
|
+
throw new Error('copilot models endpoint returned no data array');
|
|
260
|
+
const seen = new Set();
|
|
261
|
+
const discovered = [];
|
|
262
|
+
for (const entry of payload.data) {
|
|
263
|
+
if (typeof entry.id !== 'string' || entry.id.length === 0 || seen.has(entry.id))
|
|
264
|
+
continue;
|
|
265
|
+
if (entry.model_picker_enabled !== true || entry.policy?.state === 'disabled')
|
|
266
|
+
continue;
|
|
267
|
+
let wire;
|
|
268
|
+
let responsesSupported = false;
|
|
269
|
+
if (Array.isArray(entry.supported_endpoints)) {
|
|
270
|
+
responsesSupported = entry.supported_endpoints.includes('/responses');
|
|
271
|
+
if (entry.supported_endpoints.includes('/chat/completions'))
|
|
272
|
+
wire = 'chat-completions';
|
|
273
|
+
else if (responsesSupported)
|
|
274
|
+
wire = 'responses';
|
|
275
|
+
else
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
seen.add(entry.id);
|
|
279
|
+
const reasoning = copilotReasoning(entry);
|
|
280
|
+
discovered.push({
|
|
281
|
+
id: entry.id,
|
|
282
|
+
name: typeof entry.name === 'string' && entry.name.length > 0 ? entry.name : entry.id,
|
|
283
|
+
...typeof entry.capabilities?.limits?.max_context_window_tokens === 'number'
|
|
284
|
+
&& entry.capabilities.limits.max_context_window_tokens > 0
|
|
285
|
+
? { contextWindow: entry.capabilities.limits.max_context_window_tokens }
|
|
286
|
+
: {},
|
|
287
|
+
inputModalities: entry.capabilities?.supports?.vision === true ? ['text', 'image'] : ['text'],
|
|
288
|
+
...reasoning === undefined ? {} : { reasoning },
|
|
289
|
+
...wire === undefined ? {} : { copilotWire: wire },
|
|
290
|
+
...responsesSupported ? { copilotResponses: true } : {},
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
// An empty catalog from a 200 response is treated as a discovery failure so
|
|
294
|
+
// the adapter falls back to the static catalog instead of vanishing from
|
|
295
|
+
// the picker.
|
|
296
|
+
if (discovered.length === 0)
|
|
297
|
+
throw new Error('copilot models endpoint returned an empty catalog');
|
|
298
|
+
return discovered;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The wire protocol for one model: the discovered catalog entry's recorded
|
|
302
|
+
* choice, defaulting to chat completions for unknown models (static-catalog
|
|
303
|
+
* and no-discovery configurations, and models listing both endpoints).
|
|
304
|
+
* @param entry - the discovered catalog entry, when known.
|
|
305
|
+
* @returns the protocol the request for this model must speak.
|
|
306
|
+
*/
|
|
307
|
+
export function copilotWireFor(entry) {
|
|
308
|
+
return entry?.copilotWire === 'responses' ? 'responses' : 'chat-completions';
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* The upstream protocol for ONE REQUEST: the model's default wire, except
|
|
312
|
+
* that a dual-protocol model defaulting to chat completions must reroute to
|
|
313
|
+
* Responses when the request combines function tools with a reasoning effort
|
|
314
|
+
* — Copilot rejects exactly that combination on /chat/completions with
|
|
315
|
+
* HTTP 400 invalid_request_body ("Function tools with reasoning_effort are
|
|
316
|
+
* not supported … use /v1/responses or set reasoning_effort to 'none'",
|
|
317
|
+
* observed on gpt-5.4) while /responses serves it. Effort 'none' stays on
|
|
318
|
+
* the chat wire (the API allows the combination there), and models not
|
|
319
|
+
* listing /responses never reroute.
|
|
320
|
+
* @param entry - the discovered catalog entry, when known.
|
|
321
|
+
* @param options - the harness generate options (tools + effort only).
|
|
322
|
+
* @returns the protocol the request for this model must speak.
|
|
323
|
+
*/
|
|
324
|
+
export function copilotRequestWire(entry, options) {
|
|
325
|
+
const wire = copilotWireFor(entry);
|
|
326
|
+
if (wire !== 'chat-completions')
|
|
327
|
+
return wire;
|
|
328
|
+
if (entry?.copilotResponses !== true)
|
|
329
|
+
return wire;
|
|
330
|
+
if (options.tools === undefined || options.tools.length === 0)
|
|
331
|
+
return wire;
|
|
332
|
+
if (options.reasoningEffort === undefined || options.reasoningEffort === 'none')
|
|
333
|
+
return wire;
|
|
334
|
+
return 'responses';
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* The chat completions request body for one generation. The output cap rides
|
|
338
|
+
* `max_completion_tokens` — the newer OpenAI-family models on Copilot reject
|
|
339
|
+
* the legacy `max_tokens` parameter outright (HTTP 400 "Unsupported
|
|
340
|
+
* parameter"), and the rest of the catalog accepts the new spelling.
|
|
341
|
+
* @param options - the harness generate options.
|
|
342
|
+
* @param messages - translated wire messages (images pre-resolved).
|
|
343
|
+
* @returns the JSON body.
|
|
344
|
+
*/
|
|
345
|
+
export function copilotChatRequestBody(options, messages) {
|
|
346
|
+
return {
|
|
347
|
+
model: options.model,
|
|
348
|
+
messages,
|
|
349
|
+
...options.tools !== undefined && options.tools.length > 0
|
|
350
|
+
? { tools: toChatTools(options.tools), tool_choice: 'auto' }
|
|
351
|
+
: {},
|
|
352
|
+
...options.maxTokens !== undefined ? { max_completion_tokens: options.maxTokens } : {},
|
|
353
|
+
// The harness only passes an effort the resolved model advertised (the
|
|
354
|
+
// catalog's reasoning_effort array), and copilotRequestWire keeps the
|
|
355
|
+
// tools+effort combination off this wire for models that reject it.
|
|
356
|
+
...options.reasoningEffort !== undefined
|
|
357
|
+
? { reasoning_effort: String(options.reasoningEffort) }
|
|
358
|
+
: {},
|
|
359
|
+
// The upstream is stream-only; usage arrives on the terminal chunk.
|
|
360
|
+
stream: true,
|
|
361
|
+
stream_options: { include_usage: true },
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* The Responses request body for one generation (the wire the `/responses`-
|
|
366
|
+
* only model families speak). Usage arrives on `response.completed`.
|
|
367
|
+
* @param options - the harness generate options.
|
|
368
|
+
* @param resolved - translated instructions + input (images pre-resolved).
|
|
369
|
+
* @returns the JSON body.
|
|
370
|
+
*/
|
|
371
|
+
export function copilotResponsesRequestBody(options, resolved) {
|
|
372
|
+
return {
|
|
373
|
+
model: options.model,
|
|
374
|
+
...resolved.instructions !== undefined ? { instructions: resolved.instructions } : {},
|
|
375
|
+
input: resolved.input,
|
|
376
|
+
...options.tools !== undefined && options.tools.length > 0
|
|
377
|
+
? { tools: toResponsesTools(options.tools), tool_choice: 'auto' }
|
|
378
|
+
: {},
|
|
379
|
+
...options.maxTokens !== undefined ? { max_output_tokens: options.maxTokens } : {},
|
|
380
|
+
// The Responses wire spells the effort nested; only advertised efforts
|
|
381
|
+
// ever reach this branch (see copilotChatRequestBody).
|
|
382
|
+
...options.reasoningEffort !== undefined
|
|
383
|
+
? { reasoning: { effort: String(options.reasoningEffort) } }
|
|
384
|
+
: {},
|
|
385
|
+
// [2026-08-23]-[a reasoning model continuing a tool chain must replay its
|
|
386
|
+
// encrypted reasoning on the next request, and the blobs only arrive when
|
|
387
|
+
// asked for; for non-reasoning models the include is a no-op]
|
|
388
|
+
include: ['reasoning.encrypted_content'],
|
|
389
|
+
stream: true,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* The replayable form of one completed reasoning item: the COMPLETE item as
|
|
394
|
+
* the gateway delivered it on `response.output_item.done` — its ORIGINAL id
|
|
395
|
+
* (captured before the stable-key rewrite), summary parts, status, and the
|
|
396
|
+
* encrypted payload. A reasoning item's `id` and `summary` are not optional
|
|
397
|
+
* in the Responses input schema, so an item missing its id or its blob is
|
|
398
|
+
* not replayable and degrades to the no-replay path instead of risking an
|
|
399
|
+
* invalid input item.
|
|
400
|
+
*/
|
|
401
|
+
function completedReasoningItem(item) {
|
|
402
|
+
if (typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0)
|
|
403
|
+
return undefined;
|
|
404
|
+
if (typeof item.id !== 'string' || item.id.length === 0)
|
|
405
|
+
return undefined;
|
|
406
|
+
return {
|
|
407
|
+
type: 'reasoning',
|
|
408
|
+
id: item.id,
|
|
409
|
+
...Array.isArray(item.summary) ? { summary: item.summary } : {},
|
|
410
|
+
...typeof item.status === 'string' && item.status.length > 0 ? { status: item.status } : {},
|
|
411
|
+
encrypted_content: item.encrypted_content,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Rewrite Copilot's Responses-gateway item ids into stable per-item keys.
|
|
416
|
+
* Unlike chatgpt.com's Responses backend, the Copilot gateway mints a FRESH
|
|
417
|
+
* opaque `item.id`/`item_id` on every event of one response (the `added`,
|
|
418
|
+
* each delta, and the `done` all differ), which defeats id-keyed block
|
|
419
|
+
* assembly in the shared translator: text fragments would each open their
|
|
420
|
+
* own block, `done` would synthesize duplicates, and a function call whose
|
|
421
|
+
* arguments arrive whole only on `done` (the deltas carry empty strings)
|
|
422
|
+
* would close empty. The stable key derives from the event's `output_index`
|
|
423
|
+
* — the item's position in the response's output array, which survives the
|
|
424
|
+
* gateway's per-event id churn even when two items' events interleave on
|
|
425
|
+
* the wire (parallel tool calls do exactly that). Events without an
|
|
426
|
+
* `output_index` fall back to the key of the last `output_item.added`, which
|
|
427
|
+
* is only correct while one item's events stay contiguous — the pre-
|
|
428
|
+
* interleaving behavior, kept for gateways that omit the field; with no
|
|
429
|
+
* `added` seen yet they key to `copilot-item-0` as before. Function-call
|
|
430
|
+
* identity additionally rides the gateway-stable `call_id`.
|
|
431
|
+
*/
|
|
432
|
+
export class CopilotResponsesItemNormalizer {
|
|
433
|
+
onCaptured;
|
|
434
|
+
adds = 0;
|
|
435
|
+
lastKey = 'copilot-item-0';
|
|
436
|
+
/** Call ids and completed reasoning items collected for the open response. */
|
|
437
|
+
capturedCallIds = [];
|
|
438
|
+
capturedReasoning = [];
|
|
439
|
+
/**
|
|
440
|
+
* @param onCaptured - fired at each `response.completed` that produced BOTH
|
|
441
|
+
* function calls and completed reasoning items, receiving the response's
|
|
442
|
+
* call ids and replayable reasoning items so the adapter can replay them
|
|
443
|
+
* on the next request.
|
|
444
|
+
*/
|
|
445
|
+
constructor(onCaptured) {
|
|
446
|
+
this.onCaptured = onCaptured;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* [2026-08-23]-[a single arrival-order ordinal mis-buckets every event after
|
|
450
|
+
* a second item's `added`, mangling interleaved parallel tool calls;
|
|
451
|
+
* output_index is the only correlator the gateway keeps stable]-[changes
|
|
452
|
+
* keys only for streams that carry output_index; no-index streams keep the
|
|
453
|
+
* old last-added-key behavior byte for byte]
|
|
454
|
+
*/
|
|
455
|
+
keyFor(event) {
|
|
456
|
+
return event.output_index !== undefined
|
|
457
|
+
? `copilot-item-${String(event.output_index)}`
|
|
458
|
+
: this.lastKey;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Rewrite one parsed Responses event.
|
|
462
|
+
* @param event - the event as parsed off the wire.
|
|
463
|
+
* @returns the event with a stable item key.
|
|
464
|
+
*/
|
|
465
|
+
push(event) {
|
|
466
|
+
if (event.type === 'response.output_item.added') {
|
|
467
|
+
this.adds += 1;
|
|
468
|
+
const key = event.output_index !== undefined
|
|
469
|
+
? `copilot-item-${String(event.output_index)}`
|
|
470
|
+
: `copilot-item-${String(this.adds)}`;
|
|
471
|
+
this.lastKey = key;
|
|
472
|
+
const item = event.item;
|
|
473
|
+
if (item?.type === 'function_call' && typeof item.call_id === 'string' && item.call_id.length > 0) {
|
|
474
|
+
this.capturedCallIds.push(item.call_id);
|
|
475
|
+
}
|
|
476
|
+
return item === undefined
|
|
477
|
+
? event
|
|
478
|
+
: { ...event, item: { ...item, id: key } };
|
|
479
|
+
}
|
|
480
|
+
if (event.type === 'response.output_item.done') {
|
|
481
|
+
const item = event.item;
|
|
482
|
+
if (item?.type === 'reasoning') {
|
|
483
|
+
// Capture runs BEFORE the stable-key rewrite: the replay item must
|
|
484
|
+
// carry the item's original gateway id, not the translator key.
|
|
485
|
+
const captured = completedReasoningItem(item);
|
|
486
|
+
if (captured !== undefined)
|
|
487
|
+
this.capturedReasoning.push(captured);
|
|
488
|
+
}
|
|
489
|
+
return item === undefined
|
|
490
|
+
? event
|
|
491
|
+
: { ...event, item: { ...item, id: this.keyFor(event) } };
|
|
492
|
+
}
|
|
493
|
+
if (event.type === 'response.completed') {
|
|
494
|
+
// Both sides present is the only replayable response; clear either way —
|
|
495
|
+
// one SSE stream may carry multiple responses.
|
|
496
|
+
if (this.capturedCallIds.length > 0 && this.capturedReasoning.length > 0) {
|
|
497
|
+
this.onCaptured?.(this.capturedCallIds, this.capturedReasoning);
|
|
498
|
+
}
|
|
499
|
+
this.capturedCallIds = [];
|
|
500
|
+
this.capturedReasoning = [];
|
|
501
|
+
return event;
|
|
502
|
+
}
|
|
503
|
+
if (event.item_id === undefined)
|
|
504
|
+
return event;
|
|
505
|
+
return { ...event, item_id: this.keyFor(event) };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Copilot wire adapter: one instance serves the `copilot` provider route. */
|
|
509
|
+
export class CopilotAdapter extends LlmAdapter {
|
|
510
|
+
options;
|
|
511
|
+
catalog;
|
|
512
|
+
/**
|
|
513
|
+
* [2026-08-23]-[a reasoning model continuing a tool chain must get its
|
|
514
|
+
* reasoning back or it restarts from scratch every tool round trip; the
|
|
515
|
+
* items live in ADAPTER memory because dsh-llm's reasoning ContentBlock is
|
|
516
|
+
* a closed shape that cannot carry them through the harness]-[entries are
|
|
517
|
+
* namespaced per ACCOUNT × CONVERSATION × MODEL, idle out via a sliding
|
|
518
|
+
* TTL, and the whole store is dropped on auth transitions, so replay
|
|
519
|
+
* degrades to the old behavior instead of leaking across contexts]
|
|
520
|
+
*/
|
|
521
|
+
replayByScope = new Map();
|
|
522
|
+
/** Call-id entries kept per scope; see {@link captureReasoning}. */
|
|
523
|
+
static REPLAY_CALL_LIMIT = 64;
|
|
524
|
+
/** Conversation scopes kept at once; bounds memory when many sessions interleave. */
|
|
525
|
+
static REPLAY_SCOPE_LIMIT = 32;
|
|
526
|
+
/** How long a captured entry stays replayable; tool round trips take minutes, not hours. */
|
|
527
|
+
static REPLAY_TTL_MS = 30 * 60_000;
|
|
528
|
+
constructor(options) {
|
|
529
|
+
super();
|
|
530
|
+
this.options = options;
|
|
531
|
+
this.catalog = new ModelCatalogCache(options.catalogStore);
|
|
532
|
+
}
|
|
533
|
+
/** Discovery fetcher: resolves the session through the refresh-aware path. */
|
|
534
|
+
async fetchCatalog() {
|
|
535
|
+
return fetchCopilotModels(await this.options.tokens.session(), this.options.fetchFn);
|
|
536
|
+
}
|
|
537
|
+
providerInfo(provider) {
|
|
538
|
+
return { id: provider, name: 'GitHub Copilot' };
|
|
539
|
+
}
|
|
540
|
+
staticModels(provider) {
|
|
541
|
+
return this.options.models.map(model => ({
|
|
542
|
+
provider,
|
|
543
|
+
id: model.id,
|
|
544
|
+
name: model.name ?? model.id,
|
|
545
|
+
inputModalities: model.inputModalities ?? ['text'],
|
|
546
|
+
}));
|
|
547
|
+
}
|
|
548
|
+
async listModels(provider) {
|
|
549
|
+
// Not logged in → empty catalog, so the web picker drops the provider.
|
|
550
|
+
const session = await this.options.tokens.peek();
|
|
551
|
+
if (session === undefined)
|
|
552
|
+
return [];
|
|
553
|
+
if (!this.options.discovery)
|
|
554
|
+
return this.staticModels(provider);
|
|
555
|
+
try {
|
|
556
|
+
// The fetcher runs only on a cache miss, and resolves the session
|
|
557
|
+
// through the refresh-aware path so an expired access token renews here
|
|
558
|
+
// instead of failing discovery into the static fallback.
|
|
559
|
+
const discovered = await discoverOrRetryAuth(force => this.options.tokens.session(force), this.catalog, () => this.catalog.get(() => this.fetchCatalog()));
|
|
560
|
+
return discovered.map(model => ({
|
|
561
|
+
provider,
|
|
562
|
+
id: model.id,
|
|
563
|
+
name: model.name,
|
|
564
|
+
...model.description === undefined ? {} : { description: model.description },
|
|
565
|
+
...model.inputModalities === undefined ? {} : { inputModalities: model.inputModalities },
|
|
566
|
+
}));
|
|
567
|
+
}
|
|
568
|
+
catch (error) {
|
|
569
|
+
// A permanent refresh failure deletes the stored session: the provider
|
|
570
|
+
// is logged out, so hide it instead of showing a stale static catalog.
|
|
571
|
+
if (isMissingOrInvalidCredential(error))
|
|
572
|
+
return [];
|
|
573
|
+
this.options.onWarn?.(`copilot model discovery failed; using the built-in catalog (${errorChain(error)})`);
|
|
574
|
+
return this.staticModels(provider);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* The discovered entry for one model. Resolved through the cache's
|
|
579
|
+
* stale-while-revalidate path: capability metadata must stay stable across
|
|
580
|
+
* a long conversation — a mid-turn refetch must neither block nor fail the
|
|
581
|
+
* call before provider I/O.
|
|
582
|
+
*/
|
|
583
|
+
async discovered(model) {
|
|
584
|
+
if (!this.options.discovery)
|
|
585
|
+
return undefined;
|
|
586
|
+
const models = await this.catalog.resolve(() => this.fetchCatalog());
|
|
587
|
+
return models?.find(entry => entry.id === model);
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* [2026-08-23]-[a manually configured responses-only model combined with
|
|
591
|
+
* `discovery:false` left discovered() undefined, so copilotRequestWire
|
|
592
|
+
* silently defaulted to /chat/completions and the request 404/400'd at the
|
|
593
|
+
* gateway; an explicit config wire must win over catalog inference]-[config
|
|
594
|
+
* `models[].wire` now routes the request even without discovery]
|
|
595
|
+
*/
|
|
596
|
+
configuredWireEntry(model) {
|
|
597
|
+
const configured = this.options.models.find(entry => entry.id === model);
|
|
598
|
+
return configured?.wire === undefined
|
|
599
|
+
? undefined
|
|
600
|
+
: { id: configured.id, name: configured.name ?? configured.id, copilotWire: configured.wire };
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* The replay scope isolating one ACCOUNT × CONVERSATION × MODEL. The
|
|
604
|
+
* account identity is the session's long-lived GitHub token (stable across
|
|
605
|
+
* Copilot-token refreshes, different per GitHub login); the conversation is
|
|
606
|
+
* the loop-stamped `sessionId`, falling back to the first message's id
|
|
607
|
+
* when a hand-built request carries no session stamp; the model separates
|
|
608
|
+
* wire families. A call id captured in one scope is invisible to every
|
|
609
|
+
* other scope, so reused ids cannot leak reasoning across accounts,
|
|
610
|
+
* conversations, or models.
|
|
611
|
+
*/
|
|
612
|
+
replayScope(tokenKey, options) {
|
|
613
|
+
const conversation = options.sessionId !== undefined
|
|
614
|
+
? `session:${String(options.sessionId)}`
|
|
615
|
+
: options.messages[0] !== undefined
|
|
616
|
+
? `anchor:${String(options.messages[0].id)}`
|
|
617
|
+
: 'conversation:none';
|
|
618
|
+
return `${tokenKey}\u0000${conversation}\u0000${options.model}`;
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Store one response's completed reasoning items behind every call id it
|
|
622
|
+
* produced, inside one replay scope. Retention: a CONSUMED entry is kept —
|
|
623
|
+
* every later round of the same conversation replays ALL its earlier
|
|
624
|
+
* function_calls — until it idles out of the TTL (see {@link replayFor})
|
|
625
|
+
* or the per-scope entry cap evicts it oldest-first. All calls of one
|
|
626
|
+
* response share ONE entry object: toResponsesInput dedupes replays by
|
|
627
|
+
* array reference, so parallel calls replay the items once instead of once
|
|
628
|
+
* per call.
|
|
629
|
+
*/
|
|
630
|
+
captureReasoning(scope, callIds, items) {
|
|
631
|
+
let entries = this.replayByScope.get(scope);
|
|
632
|
+
if (entries === undefined) {
|
|
633
|
+
entries = new Map();
|
|
634
|
+
this.replayByScope.set(scope, entries);
|
|
635
|
+
}
|
|
636
|
+
else {
|
|
637
|
+
// Refresh the scope's recency so an active conversation is never the
|
|
638
|
+
// scope-cap eviction victim.
|
|
639
|
+
this.replayByScope.delete(scope);
|
|
640
|
+
this.replayByScope.set(scope, entries);
|
|
641
|
+
}
|
|
642
|
+
const now = Date.now();
|
|
643
|
+
for (const [callId, entry] of entries) {
|
|
644
|
+
if (now - entry.at >= CopilotAdapter.REPLAY_TTL_MS)
|
|
645
|
+
entries.delete(callId);
|
|
646
|
+
}
|
|
647
|
+
const entry = { items: [...items], at: now };
|
|
648
|
+
for (const callId of callIds)
|
|
649
|
+
entries.set(callId, entry);
|
|
650
|
+
// Blobs reach tens of kilobytes; cap the ENTRY count and evict the oldest
|
|
651
|
+
// by insertion order rather than tracking bytes — eviction merely degrades
|
|
652
|
+
// ancient calls to the pre-capture behavior.
|
|
653
|
+
while (entries.size > CopilotAdapter.REPLAY_CALL_LIMIT) {
|
|
654
|
+
const oldest = entries.keys().next().value;
|
|
655
|
+
if (oldest === undefined)
|
|
656
|
+
break;
|
|
657
|
+
entries.delete(oldest);
|
|
658
|
+
}
|
|
659
|
+
while (this.replayByScope.size > CopilotAdapter.REPLAY_SCOPE_LIMIT) {
|
|
660
|
+
const oldest = this.replayByScope.keys().next().value;
|
|
661
|
+
if (oldest === undefined)
|
|
662
|
+
break;
|
|
663
|
+
this.replayByScope.delete(oldest);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* The replay items for one call id in one scope, when still fresh. The TTL
|
|
668
|
+
* bounds IDLE time, not total age: a hit refreshes the entry (and its
|
|
669
|
+
* eviction recency), so an ongoing conversation keeps its chain alive
|
|
670
|
+
* while a conversation that stopped asking forgets within the TTL. An
|
|
671
|
+
* absent or aged-out entry answers `undefined` — the no-replay
|
|
672
|
+
* degradation, never an error.
|
|
673
|
+
*/
|
|
674
|
+
replayFor(scope, callId) {
|
|
675
|
+
const entries = this.replayByScope.get(scope);
|
|
676
|
+
const entry = entries?.get(callId);
|
|
677
|
+
if (entries === undefined || entry === undefined)
|
|
678
|
+
return undefined;
|
|
679
|
+
const now = Date.now();
|
|
680
|
+
if (now - entry.at >= CopilotAdapter.REPLAY_TTL_MS)
|
|
681
|
+
return undefined;
|
|
682
|
+
entry.at = now;
|
|
683
|
+
entries.delete(callId);
|
|
684
|
+
entries.set(callId, entry);
|
|
685
|
+
this.replayByScope.delete(scope);
|
|
686
|
+
this.replayByScope.set(scope, entries);
|
|
687
|
+
return entry.items;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Drop every captured replay entry. Lookup correctness never depends on
|
|
691
|
+
* the call — the scope already carries the account identity — but the host
|
|
692
|
+
* wiring invokes this on every copilot auth transition (login, logout,
|
|
693
|
+
* credential death) so a switched account's memory never holds the
|
|
694
|
+
* previous account's encrypted reasoning at all; conversation teardown is
|
|
695
|
+
* bounded by the TTL and the caps.
|
|
696
|
+
*/
|
|
697
|
+
clearReplayState() {
|
|
698
|
+
this.replayByScope.clear();
|
|
699
|
+
}
|
|
700
|
+
async resolveModel(provider, model) {
|
|
701
|
+
const discovered = await this.discovered(model);
|
|
702
|
+
const configured = this.options.models.find(entry => entry.id === model);
|
|
703
|
+
return {
|
|
704
|
+
provider,
|
|
705
|
+
id: model,
|
|
706
|
+
name: discovered?.name ?? configured?.name ?? model,
|
|
707
|
+
...discovered?.description === undefined ? {} : { description: discovered.description },
|
|
708
|
+
inputModalities: discovered?.inputModalities ?? configured?.inputModalities ?? ['text'],
|
|
709
|
+
context: { contextWindow: discovered?.contextWindow ?? configured?.contextWindow ?? COPILOT_CONTEXT_WINDOW },
|
|
710
|
+
defaultMaxTokens: configured?.maxTokens ?? COPILOT_DEFAULT_MAX_TOKENS,
|
|
711
|
+
// Efforts come from the discovered catalog's reasoning_effort array; a
|
|
712
|
+
// model that did not advertise one exposes none, so the harness rejects
|
|
713
|
+
// an explicit effort before provider I/O instead of the API 400ing
|
|
714
|
+
// (Copilot returns invalid_request_body for models that cannot reason).
|
|
715
|
+
...discovered?.reasoning === undefined ? {} : { reasoning: discovered.reasoning },
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
async *stream(options) {
|
|
719
|
+
const watchdog = idleWatchdog(options.signal, this.options.streamIdleTimeoutMs);
|
|
720
|
+
try {
|
|
721
|
+
// The discovered catalog decides the protocol: `/responses`-only model
|
|
722
|
+
// families (gpt-5.5/5.6, …) reject /chat/completions outright, and
|
|
723
|
+
// dual-protocol models reroute there once the request combines function
|
|
724
|
+
// tools with a reasoning effort (gpt-5.4 400s on the chat wire then).
|
|
725
|
+
// A configured `wire` outranks the catalog (see configuredWireEntry).
|
|
726
|
+
const wire = copilotRequestWire(this.configuredWireEntry(options.model) ?? await this.discovered(options.model), options);
|
|
727
|
+
let session = await this.options.tokens.session();
|
|
728
|
+
// Replay scope: account identity × conversation × model (see
|
|
729
|
+
// replayScope); a Copilot-token refresh preserves the GitHub token, so
|
|
730
|
+
// the 401 retry below reuses it too.
|
|
731
|
+
const scope = this.replayScope(session.refreshToken, options);
|
|
732
|
+
let response = await this.request(options, session, watchdog.signal, wire, scope);
|
|
733
|
+
if (response.status === 401) {
|
|
734
|
+
// One forced refresh + retry on an unexpired-but-rejected token. The
|
|
735
|
+
// editor version is force-refreshed too: a 401 `IDE token expired`
|
|
736
|
+
// means GitHub raised its minimum VS Code version, and only a fresh
|
|
737
|
+
// Editor-Version header fixes that (a new token does not).
|
|
738
|
+
await latestVsCodeVersion(this.options.fetchFn ?? fetch, true);
|
|
739
|
+
session = await this.options.tokens.session(true);
|
|
740
|
+
response = await this.request(options, session, watchdog.signal, wire, scope);
|
|
741
|
+
}
|
|
742
|
+
if (!response.ok)
|
|
743
|
+
throw await httpLlmError(response, 'copilot API');
|
|
744
|
+
if (response.body === null) {
|
|
745
|
+
throw new LlmError('copilot API returned no response body', EMPTY_RESPONSE_CODE);
|
|
746
|
+
}
|
|
747
|
+
const pulse = () => { watchdog.pulse(); };
|
|
748
|
+
if (wire === 'responses') {
|
|
749
|
+
// The normalizer doubles as the capture point for completed reasoning.
|
|
750
|
+
const normalizer = new CopilotResponsesItemNormalizer((callIds, items) => {
|
|
751
|
+
this.captureReasoning(scope, callIds, items);
|
|
752
|
+
});
|
|
753
|
+
yield* streamResponses(response.body, pulse, event => normalizer.push(event));
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
yield* streamChatCompletions(response.body, pulse);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
throw mapFetchFailure('copilot API', error, watchdog, options.signal);
|
|
761
|
+
}
|
|
762
|
+
finally {
|
|
763
|
+
watchdog.stop();
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
async request(options, session, signal, wire, replayScopeKey) {
|
|
767
|
+
const messages = await resolveImages(options.messages, this.options.resolveAttachments?.(), signal);
|
|
768
|
+
const hasVision = messages.some(message => message.content.some(block => block.type === 'image'));
|
|
769
|
+
const body = wire === 'responses'
|
|
770
|
+
? copilotResponsesRequestBody(options, toResponsesInput(messages, options.system,
|
|
771
|
+
// Captured completed reasoning replays ahead of its tool call.
|
|
772
|
+
callId => this.replayFor(replayScopeKey, callId)))
|
|
773
|
+
: copilotChatRequestBody(options, toChatMessages(messages, options.system));
|
|
774
|
+
return fetch(wire === 'responses' ? COPILOT_RESPONSES_URL : COPILOT_API_URL, {
|
|
775
|
+
method: 'POST',
|
|
776
|
+
headers: {
|
|
777
|
+
'authorization': `Bearer ${session.accessToken}`,
|
|
778
|
+
'accept': 'text/event-stream',
|
|
779
|
+
'content-type': 'application/json',
|
|
780
|
+
...copilotHeaders(hasVision, await latestVsCodeVersion(this.options.fetchFn ?? fetch)),
|
|
781
|
+
},
|
|
782
|
+
body: JSON.stringify(body),
|
|
783
|
+
signal,
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
}
|