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.
@@ -0,0 +1,315 @@
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 { LlmAdapter } from '@deepseek-ai/dsh-llm';
17
+ import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo, StreamChunk } from '@deepseek-ai/dsh-llm';
18
+ import type { DeviceFlowSpec } from '../auth/device-flow.js';
19
+ import type { CopilotSession } from '../auth/store.js';
20
+ import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
21
+ import type { ReasoningReplayItem, ResponsesRequestInput, ResponsesStreamEvent } from '../translate/responses.js';
22
+ import { TokenManager } from './common.js';
23
+ import type { CatalogPersistence, DiscoveredModel, FetchFn, ModelEntry } from './common.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 declare const COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
30
+ export declare const COPILOT_DEVICE_CODE_URL = "https://github.com/login/device/code";
31
+ export declare const COPILOT_DEVICE_TOKEN_URL = "https://github.com/login/oauth/access_token";
32
+ export declare const COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token";
33
+ export declare const GITHUB_USER_URL = "https://api.github.com/user";
34
+ export declare const COPILOT_API_URL = "https://api.githubcopilot.com/chat/completions";
35
+ /** Responses endpoint for models whose catalog entry only lists `/responses`. */
36
+ export declare const COPILOT_RESPONSES_URL = "https://api.githubcopilot.com/responses";
37
+ export declare const COPILOT_MODELS_URL = "https://api.githubcopilot.com/models";
38
+ /** Refresh when the Copilot API token has less than this much life left. */
39
+ export declare const COPILOT_PREEMPT_MS: number;
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 declare 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 declare const FALLBACK_VSCODE_VERSION = "1.107.0";
49
+ /**
50
+ * Resolve the VS Code version presented as Editor-Version: the latest stable
51
+ * from the update feed, cached for a day, falling back to a pinned version
52
+ * when the feed fails. Concurrent resolves coalesce behind one fetch.
53
+ * @param fetchFn - fetch implementation (injectable for tests).
54
+ * @param forceRefresh - bypass the cache (a 401 `IDE token expired` retry).
55
+ * @returns a `major.minor.patch` version string.
56
+ */
57
+ export declare function latestVsCodeVersion(fetchFn?: FetchFn, forceRefresh?: boolean): Promise<string>;
58
+ /**
59
+ * The device-flow facts for the auth controller's DeviceFlowManager.
60
+ * @returns the flow spec for one attempt.
61
+ */
62
+ export declare function copilotDeviceFlow(): DeviceFlowSpec;
63
+ /**
64
+ * Header set presenting requests as the VS Code Copilot Chat extension; the
65
+ * Copilot API rejects traffic without an editor identity.
66
+ * @param hasVision - whether the request carries image input.
67
+ * @param vscodeVersion - Editor-Version value from {@link latestVsCodeVersion}.
68
+ * @returns headers to merge into Copilot API requests.
69
+ */
70
+ export declare function copilotHeaders(hasVision?: boolean, vscodeVersion?: string): Record<string, string>;
71
+ /** The freshly exchanged Copilot API token half of a session. */
72
+ interface CopilotTokenPair {
73
+ accessToken: string;
74
+ expiresAt: number;
75
+ }
76
+ /**
77
+ * Exchange a long-lived GitHub OAuth token for a short-lived Copilot API
78
+ * token. A 401/403 means the GitHub token is revoked or the account lost its
79
+ * Copilot subscription — permanent, re-login required.
80
+ * @param githubToken - the GitHub OAuth token from the device flow.
81
+ * @param fetchFn - fetch implementation (injectable for tests).
82
+ * @returns the Copilot API token and its expiry.
83
+ */
84
+ export declare function exchangeCopilotToken(githubToken: string, fetchFn?: FetchFn): Promise<CopilotTokenPair>;
85
+ /**
86
+ * Complete a device-flow login: exchange the GitHub token for a Copilot API
87
+ * token and read the GitHub login name for the status display.
88
+ * @param githubToken - the GitHub OAuth token the device flow released.
89
+ * @param fetchFn - fetch implementation (injectable for tests).
90
+ * @returns the session to store.
91
+ */
92
+ export declare function completeCopilotLogin(githubToken: string, fetchFn?: FetchFn): Promise<CopilotSession>;
93
+ /**
94
+ * Refresh a copilot session: re-exchange the long-lived GitHub token for a
95
+ * fresh Copilot API token.
96
+ * @param session - the stored session.
97
+ * @param fetchFn - fetch implementation (injectable for tests).
98
+ * @returns the fresh session to store.
99
+ */
100
+ export declare function refreshCopilot(session: CopilotSession, fetchFn?: FetchFn): Promise<CopilotSession>;
101
+ /**
102
+ * Whether a copilot refresh failure means the login is permanently gone.
103
+ * @param error - the thrown refresh error.
104
+ * @returns true when re-login is the only fix (GitHub token revoked or the subscription lost).
105
+ */
106
+ export declare function isCopilotPermanentRefreshError(error: unknown): boolean;
107
+ /**
108
+ * Fetch the live Copilot model list. Models hidden from the picker or
109
+ * disabled by policy are excluded, as are models able to speak neither
110
+ * protocol this adapter knows: an entry listing `/chat/completions` speaks
111
+ * the chat wire, one listing only `/responses` (the newer GPT families,
112
+ * e.g. gpt-5.6) speaks the Responses wire, and the choice is recorded on the
113
+ * discovered entry so requests pick the matching endpoint; an entry listing
114
+ * BOTH endpoints additionally records `/responses` availability, which
115
+ * {@link copilotRequestWire} uses to reroute tools+effort requests. Vision
116
+ * support from the catalog becomes the model's input modalities, and a
117
+ * non-empty `supports.reasoning_effort` array becomes the model's selectable
118
+ * reasoning efforts (the endpoint discloses no default, so none is claimed).
119
+ * @param session - the stored session (used as-is; never refreshed here).
120
+ * @param fetchFn - fetch implementation (injectable for tests).
121
+ * @returns discovered chat models in endpoint order.
122
+ */
123
+ export declare function fetchCopilotModels(session: CopilotSession, fetchFn?: FetchFn): Promise<DiscoveredModel[]>;
124
+ /** Which upstream protocol one Copilot model speaks. */
125
+ export type CopilotWire = 'chat-completions' | 'responses';
126
+ /**
127
+ * The wire protocol for one model: the discovered catalog entry's recorded
128
+ * choice, defaulting to chat completions for unknown models (static-catalog
129
+ * and no-discovery configurations, and models listing both endpoints).
130
+ * @param entry - the discovered catalog entry, when known.
131
+ * @returns the protocol the request for this model must speak.
132
+ */
133
+ export declare function copilotWireFor(entry: DiscoveredModel | undefined): CopilotWire;
134
+ /**
135
+ * The upstream protocol for ONE REQUEST: the model's default wire, except
136
+ * that a dual-protocol model defaulting to chat completions must reroute to
137
+ * Responses when the request combines function tools with a reasoning effort
138
+ * — Copilot rejects exactly that combination on /chat/completions with
139
+ * HTTP 400 invalid_request_body ("Function tools with reasoning_effort are
140
+ * not supported … use /v1/responses or set reasoning_effort to 'none'",
141
+ * observed on gpt-5.4) while /responses serves it. Effort 'none' stays on
142
+ * the chat wire (the API allows the combination there), and models not
143
+ * listing /responses never reroute.
144
+ * @param entry - the discovered catalog entry, when known.
145
+ * @param options - the harness generate options (tools + effort only).
146
+ * @returns the protocol the request for this model must speak.
147
+ */
148
+ export declare function copilotRequestWire(entry: DiscoveredModel | undefined, options: Pick<GenerateOptions, 'tools' | 'reasoningEffort'>): CopilotWire;
149
+ /**
150
+ * The chat completions request body for one generation. The output cap rides
151
+ * `max_completion_tokens` — the newer OpenAI-family models on Copilot reject
152
+ * the legacy `max_tokens` parameter outright (HTTP 400 "Unsupported
153
+ * parameter"), and the rest of the catalog accepts the new spelling.
154
+ * @param options - the harness generate options.
155
+ * @param messages - translated wire messages (images pre-resolved).
156
+ * @returns the JSON body.
157
+ */
158
+ export declare function copilotChatRequestBody(options: GenerateOptions, messages: Record<string, unknown>[]): Record<string, unknown>;
159
+ /**
160
+ * The Responses request body for one generation (the wire the `/responses`-
161
+ * only model families speak). Usage arrives on `response.completed`.
162
+ * @param options - the harness generate options.
163
+ * @param resolved - translated instructions + input (images pre-resolved).
164
+ * @returns the JSON body.
165
+ */
166
+ export declare function copilotResponsesRequestBody(options: GenerateOptions, resolved: ResponsesRequestInput): Record<string, unknown>;
167
+ /**
168
+ * Rewrite Copilot's Responses-gateway item ids into stable per-item keys.
169
+ * Unlike chatgpt.com's Responses backend, the Copilot gateway mints a FRESH
170
+ * opaque `item.id`/`item_id` on every event of one response (the `added`,
171
+ * each delta, and the `done` all differ), which defeats id-keyed block
172
+ * assembly in the shared translator: text fragments would each open their
173
+ * own block, `done` would synthesize duplicates, and a function call whose
174
+ * arguments arrive whole only on `done` (the deltas carry empty strings)
175
+ * would close empty. The stable key derives from the event's `output_index`
176
+ * — the item's position in the response's output array, which survives the
177
+ * gateway's per-event id churn even when two items' events interleave on
178
+ * the wire (parallel tool calls do exactly that). Events without an
179
+ * `output_index` fall back to the key of the last `output_item.added`, which
180
+ * is only correct while one item's events stay contiguous — the pre-
181
+ * interleaving behavior, kept for gateways that omit the field; with no
182
+ * `added` seen yet they key to `copilot-item-0` as before. Function-call
183
+ * identity additionally rides the gateway-stable `call_id`.
184
+ */
185
+ export declare class CopilotResponsesItemNormalizer {
186
+ private readonly onCaptured?;
187
+ private adds;
188
+ private lastKey;
189
+ /** Call ids and completed reasoning items collected for the open response. */
190
+ private capturedCallIds;
191
+ private capturedReasoning;
192
+ /**
193
+ * @param onCaptured - fired at each `response.completed` that produced BOTH
194
+ * function calls and completed reasoning items, receiving the response's
195
+ * call ids and replayable reasoning items so the adapter can replay them
196
+ * on the next request.
197
+ */
198
+ constructor(onCaptured?: ((callIds: string[], items: ReasoningReplayItem[]) => void) | undefined);
199
+ /**
200
+ * [2026-08-23]-[a single arrival-order ordinal mis-buckets every event after
201
+ * a second item's `added`, mangling interleaved parallel tool calls;
202
+ * output_index is the only correlator the gateway keeps stable]-[changes
203
+ * keys only for streams that carry output_index; no-index streams keep the
204
+ * old last-added-key behavior byte for byte]
205
+ */
206
+ private keyFor;
207
+ /**
208
+ * Rewrite one parsed Responses event.
209
+ * @param event - the event as parsed off the wire.
210
+ * @returns the event with a stable item key.
211
+ */
212
+ push(event: ResponsesStreamEvent): ResponsesStreamEvent;
213
+ }
214
+ /** Constructor dependencies for {@link CopilotAdapter}. */
215
+ export interface CopilotAdapterOptions {
216
+ models: readonly ModelEntry[];
217
+ streamIdleTimeoutMs: number;
218
+ tokens: TokenManager<CopilotSession>;
219
+ /** Whether to fetch the live catalog when logged in (false when config `models` overrides). */
220
+ discovery: boolean;
221
+ /** Warning sink for discovery failures that fall back to the static catalog. */
222
+ onWarn?: (message: string) => void;
223
+ /** Fetch implementation for discovery (defaults to global fetch). */
224
+ fetchFn?: FetchFn;
225
+ /** Resolve the attachment service per request; absent means image requests fail loudly. */
226
+ resolveAttachments?: () => AttachmentStore | undefined;
227
+ /** Durable catalog store seeding capability metadata across restarts. */
228
+ catalogStore?: CatalogPersistence;
229
+ }
230
+ /** Copilot wire adapter: one instance serves the `copilot` provider route. */
231
+ export declare class CopilotAdapter extends LlmAdapter {
232
+ private readonly options;
233
+ private readonly catalog;
234
+ /**
235
+ * [2026-08-23]-[a reasoning model continuing a tool chain must get its
236
+ * reasoning back or it restarts from scratch every tool round trip; the
237
+ * items live in ADAPTER memory because dsh-llm's reasoning ContentBlock is
238
+ * a closed shape that cannot carry them through the harness]-[entries are
239
+ * namespaced per ACCOUNT × CONVERSATION × MODEL, idle out via a sliding
240
+ * TTL, and the whole store is dropped on auth transitions, so replay
241
+ * degrades to the old behavior instead of leaking across contexts]
242
+ */
243
+ private readonly replayByScope;
244
+ /** Call-id entries kept per scope; see {@link captureReasoning}. */
245
+ private static readonly REPLAY_CALL_LIMIT;
246
+ /** Conversation scopes kept at once; bounds memory when many sessions interleave. */
247
+ private static readonly REPLAY_SCOPE_LIMIT;
248
+ /** How long a captured entry stays replayable; tool round trips take minutes, not hours. */
249
+ private static readonly REPLAY_TTL_MS;
250
+ constructor(options: CopilotAdapterOptions);
251
+ /** Discovery fetcher: resolves the session through the refresh-aware path. */
252
+ private fetchCatalog;
253
+ providerInfo(provider: string): LlmProviderInfo;
254
+ private staticModels;
255
+ listModels(provider: string): Promise<readonly LlmModelInfo[]>;
256
+ /**
257
+ * The discovered entry for one model. Resolved through the cache's
258
+ * stale-while-revalidate path: capability metadata must stay stable across
259
+ * a long conversation — a mid-turn refetch must neither block nor fail the
260
+ * call before provider I/O.
261
+ */
262
+ private discovered;
263
+ /**
264
+ * [2026-08-23]-[a manually configured responses-only model combined with
265
+ * `discovery:false` left discovered() undefined, so copilotRequestWire
266
+ * silently defaulted to /chat/completions and the request 404/400'd at the
267
+ * gateway; an explicit config wire must win over catalog inference]-[config
268
+ * `models[].wire` now routes the request even without discovery]
269
+ */
270
+ private configuredWireEntry;
271
+ /**
272
+ * The replay scope isolating one ACCOUNT × CONVERSATION × MODEL. The
273
+ * account identity is the session's long-lived GitHub token (stable across
274
+ * Copilot-token refreshes, different per GitHub login); the conversation is
275
+ * the loop-stamped `sessionId`, falling back to the first message's id
276
+ * when a hand-built request carries no session stamp; the model separates
277
+ * wire families. A call id captured in one scope is invisible to every
278
+ * other scope, so reused ids cannot leak reasoning across accounts,
279
+ * conversations, or models.
280
+ */
281
+ private replayScope;
282
+ /**
283
+ * Store one response's completed reasoning items behind every call id it
284
+ * produced, inside one replay scope. Retention: a CONSUMED entry is kept —
285
+ * every later round of the same conversation replays ALL its earlier
286
+ * function_calls — until it idles out of the TTL (see {@link replayFor})
287
+ * or the per-scope entry cap evicts it oldest-first. All calls of one
288
+ * response share ONE entry object: toResponsesInput dedupes replays by
289
+ * array reference, so parallel calls replay the items once instead of once
290
+ * per call.
291
+ */
292
+ private captureReasoning;
293
+ /**
294
+ * The replay items for one call id in one scope, when still fresh. The TTL
295
+ * bounds IDLE time, not total age: a hit refreshes the entry (and its
296
+ * eviction recency), so an ongoing conversation keeps its chain alive
297
+ * while a conversation that stopped asking forgets within the TTL. An
298
+ * absent or aged-out entry answers `undefined` — the no-replay
299
+ * degradation, never an error.
300
+ */
301
+ private replayFor;
302
+ /**
303
+ * Drop every captured replay entry. Lookup correctness never depends on
304
+ * the call — the scope already carries the account identity — but the host
305
+ * wiring invokes this on every copilot auth transition (login, logout,
306
+ * credential death) so a switched account's memory never holds the
307
+ * previous account's encrypted reasoning at all; conversation teardown is
308
+ * bounded by the TTL and the caps.
309
+ */
310
+ clearReplayState(): void;
311
+ resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
312
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
313
+ private request;
314
+ }
315
+ export {};