dsh-plugin-subscriptions 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -6
- package/README.zh.md +14 -6
- package/lib/auth/device-flow.d.ts +64 -0
- package/lib/auth/device-flow.js +176 -0
- package/lib/auth/oauth-flow.js +1 -1
- package/lib/auth/rpc.d.ts +3 -1
- package/lib/auth/store.d.ts +20 -2
- package/lib/auth/store.js +45 -9
- package/lib/client/SubscriptionsSection.d.ts +1 -1
- package/lib/client/SubscriptionsSection.js +46 -4
- package/lib/client/locales.d.ts +8 -0
- package/lib/client/locales.js +8 -0
- package/lib/client.js +94 -4
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +3 -2
- package/lib/index.js +1770 -156
- package/lib/providers/catalog-store.js +15 -0
- package/lib/providers/claude.d.ts +20 -1
- package/lib/providers/claude.js +44 -27
- package/lib/providers/codex.js +52 -8
- package/lib/providers/common.d.ts +32 -1
- package/lib/providers/common.js +48 -1
- package/lib/providers/copilot.d.ts +315 -0
- package/lib/providers/copilot.js +786 -0
- package/lib/providers/grok.d.ts +7 -2
- package/lib/providers/grok.js +46 -18
- package/lib/translate/anthropic.d.ts +47 -6
- package/lib/translate/anthropic.js +135 -20
- package/lib/translate/chat-completions.d.ts +120 -0
- package/lib/translate/chat-completions.js +363 -0
- package/lib/translate/responses.d.ts +49 -5
- package/lib/translate/responses.js +40 -7
- package/package.json +9 -10
|
@@ -77,6 +77,18 @@ function sanitizeModel(value) {
|
|
|
77
77
|
const fastTier = raw.fastTier;
|
|
78
78
|
if (fastTier !== undefined && typeof fastTier !== 'boolean')
|
|
79
79
|
return undefined;
|
|
80
|
+
const copilotWire = raw.copilotWire;
|
|
81
|
+
if (copilotWire !== undefined && copilotWire !== 'chat-completions' && copilotWire !== 'responses') {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
const copilotResponses = raw.copilotResponses;
|
|
85
|
+
if (copilotResponses !== undefined && typeof copilotResponses !== 'boolean')
|
|
86
|
+
return undefined;
|
|
87
|
+
const inputModalities = raw.inputModalities;
|
|
88
|
+
if (inputModalities !== undefined
|
|
89
|
+
&& (!Array.isArray(inputModalities) || inputModalities.length === 0
|
|
90
|
+
|| inputModalities.some(modality => modality !== 'text' && modality !== 'image')))
|
|
91
|
+
return undefined;
|
|
80
92
|
return {
|
|
81
93
|
id: raw.id,
|
|
82
94
|
name: raw.name,
|
|
@@ -86,6 +98,9 @@ function sanitizeModel(value) {
|
|
|
86
98
|
...reasoning === undefined ? {} : { reasoning },
|
|
87
99
|
...thinkingType === undefined ? {} : { thinkingType: thinkingType },
|
|
88
100
|
...fastTier === undefined ? {} : { fastTier },
|
|
101
|
+
...copilotWire === undefined ? {} : { copilotWire: copilotWire },
|
|
102
|
+
...copilotResponses === undefined ? {} : { copilotResponses },
|
|
103
|
+
...inputModalities === undefined ? {} : { inputModalities: [...inputModalities] },
|
|
89
104
|
};
|
|
90
105
|
}
|
|
91
106
|
/**
|
|
@@ -8,14 +8,17 @@ import type { GenerateOptions, LlmModelInfo, LlmProviderInfo, LlmResolvedModelIn
|
|
|
8
8
|
import type { FlowSpec } from '../auth/oauth-flow.js';
|
|
9
9
|
import type { ClaudeSession } from '../auth/store.js';
|
|
10
10
|
import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
|
|
11
|
+
import type { TranslatableMessage } from '../translate/resolved.js';
|
|
11
12
|
import { TokenManager } from './common.js';
|
|
12
13
|
import type { CatalogPersistence, DiscoveredModel, FetchFn, ModelEntry, ProviderUsage } from './common.js';
|
|
13
14
|
export declare const CLAUDE_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
|
|
14
|
-
export declare const CLAUDE_AUTHORIZE_URL = "https://claude.
|
|
15
|
+
export declare const CLAUDE_AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
|
|
15
16
|
export declare const CLAUDE_TOKEN_URL = "https://claude.ai/v1/oauth/token";
|
|
16
17
|
export declare const CLAUDE_API_URL = "https://api.anthropic.com/v1/messages?beta=true";
|
|
17
18
|
export declare const CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile";
|
|
18
19
|
export declare const CLAUDE_MODELS_URL = "https://api.anthropic.com/v1/models?beta=true";
|
|
20
|
+
export declare const CLAUDE_SCOPE = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
|
|
21
|
+
export declare const CLAUDE_CALLBACK_PATH = "/callback";
|
|
19
22
|
/** Refresh when the access token has less than this much life left. */
|
|
20
23
|
export declare const CLAUDE_PREEMPT_MS: number;
|
|
21
24
|
/**
|
|
@@ -79,6 +82,22 @@ export interface ClaudeAdapterOptions {
|
|
|
79
82
|
/** Durable catalog store seeding capability metadata across restarts. */
|
|
80
83
|
catalogStore?: CatalogPersistence;
|
|
81
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* Assemble the Anthropic request body.
|
|
87
|
+
*
|
|
88
|
+
* Extracted from the adapter so the wire shape — cache breakpoints above all —
|
|
89
|
+
* is testable without a network round trip. The message array is marked before
|
|
90
|
+
* it is placed so the breakpoints land on the blocks the body ships: one on the
|
|
91
|
+
* last `system` block (covering `tools` + `system`, which render ahead of it)
|
|
92
|
+
* and up to three across the history, Anthropic's four-slot maximum.
|
|
93
|
+
* @param options - the generate request.
|
|
94
|
+
* @param messages - conversation messages with images already resolved.
|
|
95
|
+
* @param maxTokens - the resolved output cap.
|
|
96
|
+
* @param thinking - the thinking parameter, when the model takes one.
|
|
97
|
+
* @param effort - the reasoning effort, when the model advertises efforts.
|
|
98
|
+
* @returns the JSON body to POST.
|
|
99
|
+
*/
|
|
100
|
+
export declare function claudeRequestBody(options: GenerateOptions, messages: readonly TranslatableMessage[], maxTokens: number, thinking?: Record<string, unknown>, effort?: string): Record<string, unknown>;
|
|
82
101
|
/** Claude wire adapter: one instance serves the `claude` provider route. */
|
|
83
102
|
export declare class ClaudeAdapter extends LlmAdapter {
|
|
84
103
|
private readonly options;
|
package/lib/providers/claude.js
CHANGED
|
@@ -6,16 +6,16 @@
|
|
|
6
6
|
import { execFileSync } from 'node:child_process';
|
|
7
7
|
import { EMPTY_RESPONSE_CODE, errorChain, LlmAdapter, LlmError, ReasoningEffortId, resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
8
8
|
import { resolveImages } from '../translate/resolved.js';
|
|
9
|
-
import { streamAnthropic, toAnthropicMessages, toAnthropicSystem, toAnthropicTools, } from '../translate/anthropic.js';
|
|
10
|
-
import { httpLlmError, idleWatchdog, mapFetchFailure, ModelCatalogCache, oauthEndpointError, OAuthEndpointError, TokenManager, } from './common.js';
|
|
9
|
+
import { markMessageCache, streamAnthropic, toAnthropicMessages, toAnthropicSystem, toAnthropicTools, } from '../translate/anthropic.js';
|
|
10
|
+
import { httpLlmError, idleWatchdog, mapFetchFailure, ModelCatalogCache, discoverOrRetryAuth, isMissingOrInvalidCredential, oauthEndpointError, OAuthEndpointError, TokenManager, } from './common.js';
|
|
11
11
|
export const CLAUDE_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
|
|
12
|
-
export const CLAUDE_AUTHORIZE_URL = 'https://claude.
|
|
12
|
+
export const CLAUDE_AUTHORIZE_URL = 'https://claude.ai/oauth/authorize';
|
|
13
13
|
export const CLAUDE_TOKEN_URL = 'https://claude.ai/v1/oauth/token';
|
|
14
14
|
export const CLAUDE_API_URL = 'https://api.anthropic.com/v1/messages?beta=true';
|
|
15
15
|
export const CLAUDE_PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile';
|
|
16
16
|
export const CLAUDE_MODELS_URL = 'https://api.anthropic.com/v1/models?beta=true';
|
|
17
|
-
const CLAUDE_SCOPE = 'org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload';
|
|
18
|
-
const CLAUDE_CALLBACK_PATH = '/callback';
|
|
17
|
+
export const CLAUDE_SCOPE = 'org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload';
|
|
18
|
+
export const CLAUDE_CALLBACK_PATH = '/callback';
|
|
19
19
|
const CLAUDE_CONTEXT_WINDOW = 200_000;
|
|
20
20
|
const CLAUDE_DEFAULT_MAX_TOKENS = 32_000;
|
|
21
21
|
/** Refresh when the access token has less than this much life left. */
|
|
@@ -61,13 +61,13 @@ const CLAUDE_BETA_FLAGS = CLAUDE_BETA_FALLBACK;
|
|
|
61
61
|
export const claudeFlow = {
|
|
62
62
|
callbackPath: CLAUDE_CALLBACK_PATH,
|
|
63
63
|
// The redirect URI embeds the port, so it must be an ephemeral one.
|
|
64
|
-
listen: { host: '
|
|
64
|
+
listen: { host: 'localhost', ports: [0] },
|
|
65
65
|
buildAuthorizeUrl({ redirectUri, state, pkce }) {
|
|
66
66
|
const params = new URLSearchParams({
|
|
67
67
|
code: 'true',
|
|
68
68
|
client_id: CLAUDE_CLIENT_ID,
|
|
69
69
|
response_type: 'code',
|
|
70
|
-
redirect_uri:
|
|
70
|
+
redirect_uri: redirectUri,
|
|
71
71
|
scope: CLAUDE_SCOPE,
|
|
72
72
|
code_challenge: pkce.challenge,
|
|
73
73
|
code_challenge_method: 'S256',
|
|
@@ -331,6 +331,38 @@ const CLAUDE_RETRY_MAX_DELAY_MS = 60_000;
|
|
|
331
331
|
const CLAUDE_RETRY_JITTER_RATIO = 0.2;
|
|
332
332
|
/** The Claude 4.5 family accepts image input. */
|
|
333
333
|
const CLAUDE_MODALITIES = ['text', 'image'];
|
|
334
|
+
/**
|
|
335
|
+
* Assemble the Anthropic request body.
|
|
336
|
+
*
|
|
337
|
+
* Extracted from the adapter so the wire shape — cache breakpoints above all —
|
|
338
|
+
* is testable without a network round trip. The message array is marked before
|
|
339
|
+
* it is placed so the breakpoints land on the blocks the body ships: one on the
|
|
340
|
+
* last `system` block (covering `tools` + `system`, which render ahead of it)
|
|
341
|
+
* and up to three across the history, Anthropic's four-slot maximum.
|
|
342
|
+
* @param options - the generate request.
|
|
343
|
+
* @param messages - conversation messages with images already resolved.
|
|
344
|
+
* @param maxTokens - the resolved output cap.
|
|
345
|
+
* @param thinking - the thinking parameter, when the model takes one.
|
|
346
|
+
* @param effort - the reasoning effort, when the model advertises efforts.
|
|
347
|
+
* @returns the JSON body to POST.
|
|
348
|
+
*/
|
|
349
|
+
export function claudeRequestBody(options, messages, maxTokens, thinking, effort) {
|
|
350
|
+
const anthropicMessages = toAnthropicMessages(messages);
|
|
351
|
+
markMessageCache(anthropicMessages);
|
|
352
|
+
return {
|
|
353
|
+
model: options.model,
|
|
354
|
+
max_tokens: maxTokens,
|
|
355
|
+
system: toAnthropicSystem(options.system, messages),
|
|
356
|
+
messages: anthropicMessages,
|
|
357
|
+
...options.tools !== undefined && options.tools.length > 0
|
|
358
|
+
? { tools: toAnthropicTools(options.tools) }
|
|
359
|
+
: {},
|
|
360
|
+
...thinking === undefined ? {} : { thinking },
|
|
361
|
+
...effort === undefined ? {} : { output_config: { effort } },
|
|
362
|
+
stream: true,
|
|
363
|
+
...options.sessionId !== undefined ? { metadata: { user_id: String(options.sessionId) } } : {},
|
|
364
|
+
};
|
|
365
|
+
}
|
|
334
366
|
/** Claude wire adapter: one instance serves the `claude` provider route. */
|
|
335
367
|
export class ClaudeAdapter extends LlmAdapter {
|
|
336
368
|
options;
|
|
@@ -379,7 +411,7 @@ export class ClaudeAdapter extends LlmAdapter {
|
|
|
379
411
|
if (!this.options.discovery)
|
|
380
412
|
return this.staticModels(provider);
|
|
381
413
|
try {
|
|
382
|
-
const models = await this.catalog.get(() => this.fetchCatalog());
|
|
414
|
+
const models = await discoverOrRetryAuth(force => this.options.tokens.session(force), this.catalog, () => this.catalog.get(() => this.fetchCatalog()));
|
|
383
415
|
return models.map(model => ({
|
|
384
416
|
provider,
|
|
385
417
|
id: model.id,
|
|
@@ -388,11 +420,8 @@ export class ClaudeAdapter extends LlmAdapter {
|
|
|
388
420
|
}));
|
|
389
421
|
}
|
|
390
422
|
catch (error) {
|
|
391
|
-
if (error
|
|
392
|
-
&& (error.code === 'MISSING_CREDENTIAL' || error.code === 'INVALID_CREDENTIAL'))
|
|
423
|
+
if (isMissingOrInvalidCredential(error))
|
|
393
424
|
return [];
|
|
394
|
-
if (error instanceof LlmError && error.code === 'AUTH')
|
|
395
|
-
this.catalog.invalidate();
|
|
396
425
|
this.options.onWarn?.(`claude model discovery failed; using the built-in catalog (${errorChain(error)})`);
|
|
397
426
|
return this.staticModels(provider);
|
|
398
427
|
}
|
|
@@ -462,21 +491,9 @@ export class ClaudeAdapter extends LlmAdapter {
|
|
|
462
491
|
const disc = await this.discovered(options.model);
|
|
463
492
|
const thinking = this.thinkingParam(disc?.thinkingType, maxTokens);
|
|
464
493
|
const effort = options.reasoningEffort !== undefined && disc?.reasoning !== undefined
|
|
465
|
-
?
|
|
466
|
-
:
|
|
467
|
-
const body =
|
|
468
|
-
model: options.model,
|
|
469
|
-
max_tokens: maxTokens,
|
|
470
|
-
system: toAnthropicSystem(options.system, messages),
|
|
471
|
-
messages: toAnthropicMessages(messages),
|
|
472
|
-
...options.tools !== undefined && options.tools.length > 0
|
|
473
|
-
? { tools: toAnthropicTools(options.tools) }
|
|
474
|
-
: {},
|
|
475
|
-
...thinking === undefined ? {} : { thinking },
|
|
476
|
-
...effort,
|
|
477
|
-
stream: true,
|
|
478
|
-
...options.sessionId !== undefined ? { metadata: { user_id: String(options.sessionId) } } : {},
|
|
479
|
-
};
|
|
494
|
+
? String(options.reasoningEffort)
|
|
495
|
+
: undefined;
|
|
496
|
+
const body = claudeRequestBody(options, messages, maxTokens, thinking, effort);
|
|
480
497
|
return fetch(CLAUDE_API_URL, {
|
|
481
498
|
method: 'POST',
|
|
482
499
|
headers: {
|
package/lib/providers/codex.js
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
* Codex CLI client id, and streaming against the ChatGPT backend Responses
|
|
4
4
|
* endpoint.
|
|
5
5
|
*/
|
|
6
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
7
|
import { attributionHeaders, EMPTY_RESPONSE_CODE, errorChain, LlmAdapter, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
|
|
8
8
|
import { decodeJwtPayload } from '../auth/jwt.js';
|
|
9
9
|
import { resolveImages } from '../translate/resolved.js';
|
|
10
10
|
import { streamResponses, toResponsesInput, toResponsesTools } from '../translate/responses.js';
|
|
11
|
-
import { httpLlmError, idleWatchdog, mapFetchFailure, ModelCatalogCache, oauthEndpointError, OAuthEndpointError, TokenManager, } from './common.js';
|
|
11
|
+
import { httpLlmError, idleWatchdog, mapFetchFailure, ModelCatalogCache, discoverOrRetryAuth, isMissingOrInvalidCredential, oauthEndpointError, OAuthEndpointError, TokenManager, } from './common.js';
|
|
12
12
|
export const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
|
13
13
|
export const CODEX_AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize';
|
|
14
14
|
export const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
|
|
@@ -373,6 +373,53 @@ export async function fetchCodexModels(session, fetchFn = fetch) {
|
|
|
373
373
|
}
|
|
374
374
|
return discovered;
|
|
375
375
|
}
|
|
376
|
+
const CODEX_CALL_ID_MAX_LENGTH = 64;
|
|
377
|
+
const CODEX_CALL_ID_PREFIX = 'call_';
|
|
378
|
+
/**
|
|
379
|
+
* Bound tool-call ids at the Codex wire boundary without changing the shared
|
|
380
|
+
* Responses translation used by Grok. Short ids stay verbatim. Oversized ids
|
|
381
|
+
* become deterministic hashes, and every id already present in this request
|
|
382
|
+
* is reserved first so a generated id cannot collide with a legitimate short
|
|
383
|
+
* one (or another oversized id).
|
|
384
|
+
*/
|
|
385
|
+
function normalizeCodexCallIds(input) {
|
|
386
|
+
const mapping = new Map();
|
|
387
|
+
const used = new Set();
|
|
388
|
+
const callId = (item) => (item.type === 'function_call' || item.type === 'function_call_output') && typeof item.call_id === 'string'
|
|
389
|
+
? item.call_id
|
|
390
|
+
: undefined;
|
|
391
|
+
for (const item of input) {
|
|
392
|
+
const id = callId(item);
|
|
393
|
+
if (id !== undefined && id.length <= CODEX_CALL_ID_MAX_LENGTH) {
|
|
394
|
+
mapping.set(id, id);
|
|
395
|
+
used.add(id);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
for (const item of input) {
|
|
399
|
+
const id = callId(item);
|
|
400
|
+
if (id === undefined || mapping.has(id))
|
|
401
|
+
continue;
|
|
402
|
+
let attempt = 0;
|
|
403
|
+
let normalized;
|
|
404
|
+
do {
|
|
405
|
+
const hash = createHash('sha256');
|
|
406
|
+
if (attempt > 0)
|
|
407
|
+
hash.update(String(attempt)).update('\0');
|
|
408
|
+
const digest = hash.update(id).digest('hex');
|
|
409
|
+
normalized = `${CODEX_CALL_ID_PREFIX}${digest.slice(0, CODEX_CALL_ID_MAX_LENGTH - CODEX_CALL_ID_PREFIX.length)}`;
|
|
410
|
+
attempt += 1;
|
|
411
|
+
} while (used.has(normalized));
|
|
412
|
+
mapping.set(id, normalized);
|
|
413
|
+
used.add(normalized);
|
|
414
|
+
}
|
|
415
|
+
return input.map((item) => {
|
|
416
|
+
const id = callId(item);
|
|
417
|
+
if (id === undefined)
|
|
418
|
+
return item;
|
|
419
|
+
const normalized = mapping.get(id) ?? id;
|
|
420
|
+
return normalized === id ? item : { ...item, call_id: normalized };
|
|
421
|
+
});
|
|
422
|
+
}
|
|
376
423
|
/**
|
|
377
424
|
* The Responses request body for one generation. A fast-tier request (the
|
|
378
425
|
* composer Speed toggle, the codex CLI's fast mode) carries
|
|
@@ -383,7 +430,7 @@ export function codexRequestBody(options, resolved, fast) {
|
|
|
383
430
|
return {
|
|
384
431
|
model: options.model,
|
|
385
432
|
instructions: resolved.instructions ?? DEFAULT_CODEX_INSTRUCTIONS,
|
|
386
|
-
input: resolved.input,
|
|
433
|
+
input: normalizeCodexCallIds(resolved.input),
|
|
387
434
|
...options.tools !== undefined && options.tools.length > 0
|
|
388
435
|
? { tools: toResponsesTools(options.tools) }
|
|
389
436
|
: {},
|
|
@@ -434,7 +481,7 @@ export class CodexAdapter extends LlmAdapter {
|
|
|
434
481
|
// The fetcher runs only on a cache miss, and resolves the session
|
|
435
482
|
// through the refresh-aware path so an expired access token renews here
|
|
436
483
|
// instead of failing discovery into the static fallback.
|
|
437
|
-
const discovered = await this.catalog.get(() => this.fetchCatalog());
|
|
484
|
+
const discovered = await discoverOrRetryAuth(force => this.options.tokens.session(force), this.catalog, () => this.catalog.get(() => this.fetchCatalog()));
|
|
438
485
|
return discovered.map(model => ({
|
|
439
486
|
provider,
|
|
440
487
|
id: model.id,
|
|
@@ -446,11 +493,8 @@ export class CodexAdapter extends LlmAdapter {
|
|
|
446
493
|
catch (error) {
|
|
447
494
|
// A permanent refresh failure deletes the stored session: the provider
|
|
448
495
|
// is logged out, so hide it instead of showing a stale static catalog.
|
|
449
|
-
if (error
|
|
450
|
-
&& (error.code === 'MISSING_CREDENTIAL' || error.code === 'INVALID_CREDENTIAL'))
|
|
496
|
+
if (isMissingOrInvalidCredential(error))
|
|
451
497
|
return [];
|
|
452
|
-
if (error instanceof OAuthEndpointError && error.status === 401)
|
|
453
|
-
this.catalog.invalidate();
|
|
454
498
|
this.options.onWarn?.(`codex model discovery failed; using the built-in catalog (${errorChain(error)})`);
|
|
455
499
|
return this.staticModels(provider);
|
|
456
500
|
}
|
|
@@ -19,6 +19,12 @@ export interface ModelEntry {
|
|
|
19
19
|
maxTokens?: number;
|
|
20
20
|
/** Accepted request modalities; when set, wins over the provider default. */
|
|
21
21
|
inputModalities?: ('text' | 'image')[];
|
|
22
|
+
/**
|
|
23
|
+
* Force this model's upstream protocol. Only the copilot adapter consumes
|
|
24
|
+
* the semantics; the union is inlined here to avoid a circular import of
|
|
25
|
+
* the copilot module's `CopilotWire`.
|
|
26
|
+
*/
|
|
27
|
+
wire?: 'chat-completions' | 'responses';
|
|
22
28
|
}
|
|
23
29
|
/**
|
|
24
30
|
* Validate a configured model catalog (mirrors llm-deepseek's resolveModels).
|
|
@@ -175,10 +181,20 @@ export interface DiscoveredModel {
|
|
|
175
181
|
}[];
|
|
176
182
|
defaultEffort?: ReasoningEffortId;
|
|
177
183
|
};
|
|
184
|
+
/** Accepted request modalities the endpoint advertised (e.g. Copilot's vision support flag). */
|
|
185
|
+
inputModalities?: ('text' | 'image')[];
|
|
178
186
|
/** Claude-specific: which extended-thinking wire shape this model accepts. */
|
|
179
187
|
thinkingType?: 'enabled' | 'adaptive';
|
|
180
188
|
/** Codex-specific: the catalog advertises a fast (priority) service tier. */
|
|
181
189
|
fastTier?: boolean;
|
|
190
|
+
/** Copilot-specific: which upstream protocol the model's endpoints speak. */
|
|
191
|
+
copilotWire?: 'chat-completions' | 'responses';
|
|
192
|
+
/**
|
|
193
|
+
* Copilot-specific: the catalog also lists `/responses` for this model
|
|
194
|
+
* (dual-protocol entries, e.g. gpt-5.4), so a chat-wire request may reroute
|
|
195
|
+
* there when it combines function tools with a reasoning effort.
|
|
196
|
+
*/
|
|
197
|
+
copilotResponses?: boolean;
|
|
182
198
|
}
|
|
183
199
|
/** How long a discovered catalog is trusted before re-fetching. */
|
|
184
200
|
export declare const DISCOVERY_TTL_MS: number;
|
|
@@ -207,7 +223,7 @@ export interface CatalogPersistence {
|
|
|
207
223
|
* while a stale entry refreshes in the background, and only awaits the fetch
|
|
208
224
|
* when nothing is known yet. An optional {@link CatalogPersistence} seeds the
|
|
209
225
|
* last-known state across restarts and receives every successful fetch. A 401
|
|
210
|
-
*
|
|
226
|
+
* that still fails after a forced token refresh must call {@link invalidate}.
|
|
211
227
|
*/
|
|
212
228
|
export declare class ModelCatalogCache {
|
|
213
229
|
private readonly persistence?;
|
|
@@ -224,6 +240,12 @@ export declare class ModelCatalogCache {
|
|
|
224
240
|
* @returns the cached models, or `undefined` when absent or stale.
|
|
225
241
|
*/
|
|
226
242
|
cached(): readonly DiscoveredModel[] | undefined;
|
|
243
|
+
/**
|
|
244
|
+
* The last successfully fetched catalog, ignoring TTL. Used to carry
|
|
245
|
+
* capability metadata forward when a later fetch cannot re-enrich.
|
|
246
|
+
* @returns the last-known models, or `undefined` when nothing has been stored.
|
|
247
|
+
*/
|
|
248
|
+
lastKnown(): readonly DiscoveredModel[] | undefined;
|
|
227
249
|
/** Load the persisted snapshot once; a fetch or invalidate that landed first wins. */
|
|
228
250
|
private ensureSeeded;
|
|
229
251
|
/** Run (or join) the single in-flight fetch, updating memory and disk on success. */
|
|
@@ -248,4 +270,13 @@ export declare class ModelCatalogCache {
|
|
|
248
270
|
/** Drop the cached catalog (e.g. after a 401 proved the credential changed). */
|
|
249
271
|
invalidate(): void;
|
|
250
272
|
}
|
|
273
|
+
/** Whether discovery failed because the stored login is gone. */
|
|
274
|
+
export declare function isMissingOrInvalidCredential(error: unknown): boolean;
|
|
275
|
+
/**
|
|
276
|
+
* Run a catalog fetch, retrying once after a forced token refresh when the
|
|
277
|
+
* first attempt is a 401/AUTH. Only {@link ModelCatalogCache.invalidate}s
|
|
278
|
+
* when the retry is also an auth failure, so a refresh race cannot erase
|
|
279
|
+
* last-known capability metadata.
|
|
280
|
+
*/
|
|
281
|
+
export declare function discoverOrRetryAuth<T>(session: (forceRefresh?: boolean) => Promise<unknown>, catalog: ModelCatalogCache, run: () => Promise<T>): Promise<T>;
|
|
251
282
|
export {};
|
package/lib/providers/common.js
CHANGED
|
@@ -32,6 +32,9 @@ export function validateModels(models, label) {
|
|
|
32
32
|
|| model.inputModalities.some(modality => modality !== 'text' && modality !== 'image'))) {
|
|
33
33
|
throw new Error(`${label}: catalog model "${model.id}" inputModalities must be a non-empty list of "text"/"image"`);
|
|
34
34
|
}
|
|
35
|
+
if (model.wire !== undefined && model.wire !== 'chat-completions' && model.wire !== 'responses') {
|
|
36
|
+
throw new Error(`${label}: catalog model "${model.id}" wire must be "chat-completions" or "responses"`);
|
|
37
|
+
}
|
|
35
38
|
if (seen.has(model.id))
|
|
36
39
|
throw new Error(`${label}: duplicate catalog model "${model.id}"`);
|
|
37
40
|
seen.add(model.id);
|
|
@@ -41,6 +44,7 @@ export function validateModels(models, label) {
|
|
|
41
44
|
...model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow },
|
|
42
45
|
...model.maxTokens === undefined ? {} : { maxTokens: model.maxTokens },
|
|
43
46
|
...model.inputModalities === undefined ? {} : { inputModalities: [...model.inputModalities] },
|
|
47
|
+
...model.wire === undefined ? {} : { wire: model.wire },
|
|
44
48
|
};
|
|
45
49
|
});
|
|
46
50
|
}
|
|
@@ -271,7 +275,7 @@ export const DISCOVERY_TTL_MS = 5 * 60_000;
|
|
|
271
275
|
* while a stale entry refreshes in the background, and only awaits the fetch
|
|
272
276
|
* when nothing is known yet. An optional {@link CatalogPersistence} seeds the
|
|
273
277
|
* last-known state across restarts and receives every successful fetch. A 401
|
|
274
|
-
*
|
|
278
|
+
* that still fails after a forced token refresh must call {@link invalidate}.
|
|
275
279
|
*/
|
|
276
280
|
export class ModelCatalogCache {
|
|
277
281
|
persistence;
|
|
@@ -295,6 +299,14 @@ export class ModelCatalogCache {
|
|
|
295
299
|
return undefined;
|
|
296
300
|
return this.entry.models;
|
|
297
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* The last successfully fetched catalog, ignoring TTL. Used to carry
|
|
304
|
+
* capability metadata forward when a later fetch cannot re-enrich.
|
|
305
|
+
* @returns the last-known models, or `undefined` when nothing has been stored.
|
|
306
|
+
*/
|
|
307
|
+
lastKnown() {
|
|
308
|
+
return this.entry?.models;
|
|
309
|
+
}
|
|
298
310
|
/** Load the persisted snapshot once; a fetch or invalidate that landed first wins. */
|
|
299
311
|
ensureSeeded() {
|
|
300
312
|
if (this.persistence === undefined)
|
|
@@ -363,3 +375,38 @@ export class ModelCatalogCache {
|
|
|
363
375
|
void this.persistence?.clear().catch(() => undefined);
|
|
364
376
|
}
|
|
365
377
|
}
|
|
378
|
+
/** Whether discovery failed because the stored login is gone. */
|
|
379
|
+
export function isMissingOrInvalidCredential(error) {
|
|
380
|
+
return error instanceof LlmError
|
|
381
|
+
&& (error.code === 'MISSING_CREDENTIAL' || error.code === 'INVALID_CREDENTIAL');
|
|
382
|
+
}
|
|
383
|
+
/** Whether discovery failed because the access token was rejected. */
|
|
384
|
+
function isDiscoveryAuthFailure(error) {
|
|
385
|
+
return (error instanceof OAuthEndpointError && error.status === 401)
|
|
386
|
+
|| (error instanceof LlmError && error.code === 'AUTH');
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Run a catalog fetch, retrying once after a forced token refresh when the
|
|
390
|
+
* first attempt is a 401/AUTH. Only {@link ModelCatalogCache.invalidate}s
|
|
391
|
+
* when the retry is also an auth failure, so a refresh race cannot erase
|
|
392
|
+
* last-known capability metadata.
|
|
393
|
+
*/
|
|
394
|
+
export async function discoverOrRetryAuth(session, catalog, run) {
|
|
395
|
+
try {
|
|
396
|
+
return await run();
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
if (isMissingOrInvalidCredential(error) || !isDiscoveryAuthFailure(error))
|
|
400
|
+
throw error;
|
|
401
|
+
try {
|
|
402
|
+
await session(true);
|
|
403
|
+
return await run();
|
|
404
|
+
}
|
|
405
|
+
catch (retryError) {
|
|
406
|
+
if (!isMissingOrInvalidCredential(retryError) && isDiscoveryAuthFailure(retryError)) {
|
|
407
|
+
catalog.invalidate();
|
|
408
|
+
}
|
|
409
|
+
throw retryError;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|