dsh-subscriptions 0.1.0

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