dsh-plugin-subscriptions 0.5.0 → 0.5.2

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