@sagmans/dsh-provider-extra 0.4.0 → 0.5.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.
@@ -10,6 +10,7 @@
10
10
  * @module dsh-provider-extra/login-attempt
11
11
  */
12
12
  import { renderEvent } from "./codex-login.js";
13
+ import { StoredCredentialError } from "./login-contract.js";
13
14
  import { answerLabels, answerText } from "./login-choice.js";
14
15
  /** Question ids belong to the caller; the answer echoes them back. */
15
16
  const PROMPT_QUESTION_ID = 'prompt';
@@ -43,6 +44,8 @@ const WAIT_DETAIL = 'Finish on that page, then choose Done. The sign-in complete
43
44
  const DECLARED_ROUTE_NOTICE = ' The provider was added to the llm-pi-ai settings, so its models work now.';
44
45
  /** Said when a configured route already carried the sign-in. */
45
46
  const PRESENT_ROUTE_NOTICE = ' The credential is stored and the route reads it on its next request.';
47
+ /** A failed confirmation cannot imply that a completed host login rolled back. */
48
+ const READBACK_FAILURE_PREFIX = 'The sign-in completed, but credential readback failed: ';
46
49
  /**
47
50
  * Said when nothing here can serve the provider. A stored credential with no
48
51
  * route is the state that later fails a turn, so the failure belongs to the
@@ -76,7 +79,7 @@ function openWait(host, invocation, choice, attempt) {
76
79
  detail: [...attempt.notices, WAIT_DETAIL].join('\n'),
77
80
  options: [{ label: DONE_LABEL }, { label: CANCEL_LABEL }],
78
81
  }],
79
- signal: abort.signal,
82
+ signal: AbortSignal.any([attempt.signal, abort.signal]),
80
83
  });
81
84
  const settled = asked.then((answer) => {
82
85
  if (answerLabels(answer, NOTICE_QUESTION_ID).includes(CANCEL_LABEL)) {
@@ -137,7 +140,7 @@ async function askPrompt(host, invocation, prompt, choice, attempt) {
137
140
  const ask = host.ask({
138
141
  agent: invocation.agent,
139
142
  questions: [promptQuestion(prompt, choice)],
140
- signal: attempt.abort.signal,
143
+ signal: attempt.signal,
141
144
  });
142
145
  if (prompt.type === 'select') {
143
146
  const options = prompt.options;
@@ -183,7 +186,7 @@ async function askPrompt(host, invocation, prompt, choice, attempt) {
183
186
  /** The interaction one attempt hands to pi-ai's login. */
184
187
  function attemptInteraction(host, invocation, choice, attempt) {
185
188
  return {
186
- signal: attempt.abort.signal,
189
+ signal: attempt.signal,
187
190
  notify: (event) => {
188
191
  attempt.notices.push(...renderEvent(event));
189
192
  if (attempt.wait === undefined)
@@ -204,9 +207,11 @@ function successText(choice, route) {
204
207
  return signedIn + UNAVAILABLE_ROUTE_NOTICE;
205
208
  return signedIn + PRESENT_ROUTE_NOTICE;
206
209
  }
207
- /** Why one attempt ended without a credential, as the human should read it. */
210
+ /** Failed attempts must distinguish cancelled work from credentials already committed. */
208
211
  function describeFailure(error, attempt, choice) {
209
- if (attempt.declined)
212
+ if (error instanceof StoredCredentialError)
213
+ return error.message;
214
+ if (attempt.declined || (attempt.signal.aborted && !attempt.expired))
210
215
  return 'The ' + choice.providerName + ' sign-in was cancelled.';
211
216
  if (attempt.expired)
212
217
  return 'The ' + choice.providerName + ' sign-in timed out; start it again to get a fresh code.';
@@ -215,7 +220,15 @@ function describeFailure(error, attempt, choice) {
215
220
  }
216
221
  /** Run one sign-in end to end: the conversation plus the stored-credential check. */
217
222
  export async function runChoice(host, invocation, choice) {
218
- const attempt = { abort: new AbortController(), notices: [], wait: undefined, declined: false, expired: false };
223
+ const abort = new AbortController();
224
+ const attempt = {
225
+ abort,
226
+ signal: AbortSignal.any([invocation.signal, abort.signal]),
227
+ notices: [],
228
+ wait: undefined,
229
+ declined: false,
230
+ expired: false,
231
+ };
219
232
  const deadline = setTimeout(() => {
220
233
  attempt.expired = true;
221
234
  attempt.abort.abort();
@@ -223,12 +236,21 @@ export async function runChoice(host, invocation, choice) {
223
236
  if (typeof deadline === 'object')
224
237
  deadline.unref();
225
238
  try {
239
+ attempt.signal.throwIfAborted();
226
240
  const route = await host.login(choice, attemptInteraction(host, invocation, choice, attempt));
241
+ // A resolved host may already have committed credentials; late cancellation cannot undo them.
227
242
  await closeWait(attempt);
228
243
  // pi-ai persists during login, so resolving is not yet proof: only a
229
244
  // record read back is. A flow that resolves without one is a catalog bug
230
245
  // the human must hear about rather than a silent no-op sign-in.
231
- const stored = await host.stored(choice.providerId);
246
+ let stored;
247
+ try {
248
+ stored = await host.stored(choice.providerId);
249
+ }
250
+ catch (error) {
251
+ const message = error instanceof Error ? error.message : String(error);
252
+ throw new StoredCredentialError(READBACK_FAILURE_PREFIX + message, { cause: error });
253
+ }
232
254
  if (stored === undefined) {
233
255
  return {
234
256
  kind: 'error',
@@ -14,9 +14,9 @@ export const KEY_WORD = 'key';
14
14
  export const OAUTH_WORD = 'oauth';
15
15
  /** Question ids belong to the caller; the answer echoes them back. */
16
16
  const PICKER_QUESTION_ID = 'provider';
17
- /** Split raw command input into lowercase words. */
17
+ /** Route identity can be case-sensitive even when method words are not. */
18
18
  export function words(rawInput) {
19
- return rawInput.trim().toLowerCase().split(/\s+/u).filter(word => word.length > 0);
19
+ return rawInput.trim().split(/\s+/u).filter(word => word.length > 0);
20
20
  }
21
21
  /** The label one choice shows: its provider alone when that provider has a single method. */
22
22
  function choiceLabel(choice, shared) {
@@ -34,7 +34,9 @@ function optionLabels(choices) {
34
34
  for (const choice of choices) {
35
35
  perProvider.set(choice.providerId, (perProvider.get(choice.providerId) ?? 0) + 1);
36
36
  }
37
- return choices.map(choice => choiceLabel(choice, (perProvider.get(choice.providerId) ?? 0) > 1));
37
+ const labels = choices.map(choice => choiceLabel(choice, (perProvider.get(choice.providerId) ?? 0) > 1));
38
+ return labels.map((label, index) => labels.filter(candidate => candidate === label).length > 1
39
+ ? label + ' · ' + choices[index].providerId + ' · ' + choices[index].authType : label);
38
40
  }
39
41
  /** The question the picker asks, one option per provider-method pair. */
40
42
  export function pickerQuestion(choices) {
@@ -74,24 +76,33 @@ export function resolveChoice(choices, answer) {
74
76
  const text = answerText(answer, PICKER_QUESTION_ID);
75
77
  if (text === undefined)
76
78
  return undefined;
77
- const named = choices.filter(choice => choice.providerId === text.toLowerCase());
78
- if (named.length === 1)
79
- return named[0];
80
- const method = text.toLowerCase().split(/\s+/u)[1] ?? text.toLowerCase();
81
- return named.find(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'))
82
- ?? choices.find(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'));
79
+ const input = words(text);
80
+ const named = choiceByWords(choices, input);
81
+ if (named !== undefined)
82
+ return named;
83
+ // A bare method is useful only when it identifies exactly one credential owner.
84
+ const method = input.length === 1 ? input[0].toLowerCase() : undefined;
85
+ if (method !== KEY_WORD && method !== OAUTH_WORD)
86
+ return undefined;
87
+ const matches = choices.filter(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'));
88
+ return matches.length === 1 ? matches[0] : undefined;
83
89
  }
84
90
  /** The choice a provider id (and optional method word) names. */
85
91
  export function choiceByWords(choices, input) {
86
92
  const providerId = input[0];
87
- if (providerId === undefined)
88
- return undefined;
89
- const named = choices.filter(choice => choice.providerId === providerId);
90
- if (named.length === 0)
93
+ if (providerId === undefined || input.length > 2)
91
94
  return undefined;
92
- const method = input[1];
95
+ let named = choices.filter(choice => choice.providerId === providerId);
96
+ if (named.length === 0) {
97
+ named = choices.filter(choice => choice.providerId.toLowerCase() === providerId.toLowerCase());
98
+ if (new Set(named.map(choice => choice.providerId)).size !== 1)
99
+ return undefined;
100
+ }
101
+ const method = input[1]?.toLowerCase();
93
102
  if (method === undefined)
94
103
  return named[0];
104
+ if (method !== KEY_WORD && method !== OAUTH_WORD)
105
+ return undefined;
95
106
  const authType = method === KEY_WORD ? 'api_key' : 'oauth';
96
107
  return named.find(choice => choice.authType === authType);
97
108
  }
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * @module dsh-provider-extra/login-command
21
21
  */
22
- import { KEY_WORD, OAUTH_WORD, choiceByWords, pickerQuestion, resolveChoice, words } from "./login-choice.js";
22
+ import { KEY_WORD, OAUTH_WORD, answerText, choiceByWords, pickerQuestion, resolveChoice, words } from "./login-choice.js";
23
23
  import { runChoice } from "./login-attempt.js";
24
24
  import { statusOf } from "./login-status.js";
25
25
  /** Command name a profile gets unless it renames the command. */
@@ -44,7 +44,7 @@ export function createLoginCommand(host, commandName) {
44
44
  recordInput: false,
45
45
  handler: async (invocation) => {
46
46
  const input = words(invocation.rawInput);
47
- if (input.length === 1 && input[0] === STATUS_WORD)
47
+ if (input.length === 1 && input[0]?.toLowerCase() === STATUS_WORD)
48
48
  return await statusOf(host);
49
49
  if (input.length > 2)
50
50
  return { kind: 'error', text: 'dsh-provider-extra: too many arguments. ' + usage };
@@ -52,14 +52,23 @@ export function createLoginCommand(host, commandName) {
52
52
  if (choices.length === 0) {
53
53
  return { kind: 'error', text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in' };
54
54
  }
55
+ const unknownChoice = (input) => {
56
+ const known = [...new Set(choices.map(entry => entry.providerId))].join(', ');
57
+ return { kind: 'error', text: 'dsh-provider-extra: no sign-in named "' + input.join(' ') + '". Known providers: ' + known + '. ' + usage };
58
+ };
55
59
  let choice;
56
60
  if (input.length === 0) {
57
61
  try {
58
- choice = resolveChoice(choices, await host.ask({
62
+ const question = pickerQuestion(choices);
63
+ const answer = await host.ask({
59
64
  agent: invocation.agent,
60
- questions: [pickerQuestion(choices)],
65
+ questions: [question],
61
66
  signal: invocation.signal,
62
- }));
67
+ });
68
+ choice = resolveChoice(choices, answer);
69
+ const typed = answerText(answer, question.id);
70
+ if (choice === undefined && typed !== undefined)
71
+ return unknownChoice(words(typed));
63
72
  }
64
73
  catch (error) {
65
74
  const message = error instanceof Error ? error.message : String(error);
@@ -70,10 +79,8 @@ export function createLoginCommand(host, commandName) {
70
79
  }
71
80
  else {
72
81
  choice = choiceByWords(choices, input);
73
- if (choice === undefined) {
74
- const known = [...new Set(choices.map(entry => entry.providerId))].join(', ');
75
- return { kind: 'error', text: 'dsh-provider-extra: no sign-in named "' + input.join(' ') + '". Known providers: ' + known + '. ' + usage };
76
- }
82
+ if (choice === undefined)
83
+ return unknownChoice(input);
77
84
  }
78
85
  return await runChoice(host, invocation, choice);
79
86
  },
@@ -7,4 +7,6 @@
7
7
  *
8
8
  * @module dsh-provider-extra/login-contract
9
9
  */
10
- export {};
10
+ /** Post-commit facts must remain visible even when cancellation or a deadline also wins. */
11
+ export class StoredCredentialError extends Error {
12
+ }
@@ -0,0 +1,196 @@
1
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
2
+ import { LlmError, assertUsableApiKey } from '@deepseek-ai/dsh-llm';
3
+ import { createModels } from '@earendil-works/pi-ai';
4
+ import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
5
+ import { codexAuth, recordKeyFor } from "./codex.js";
6
+ import { createLoginCommand } from "./login-command.js";
7
+ import { StoredCredentialError } from "./login-contract.js";
8
+ import { declareProviderRoute, declaredCredentialRef } from "./login-route.js";
9
+ import { PendingCredentialStore, proveApiKey } from "./login-verify.js";
10
+ const PLUGIN_NAME = 'dsh-provider-extra';
11
+ const GO_SOURCE = 'opencode-go';
12
+ const CODEX_SOURCE = 'openai-codex';
13
+ const MISSING_STORE = 'This composition has no writable credentials service; mount dsh-credentials-local before signing in.';
14
+ const READ_ONLY = 'The configured credential is read-only; change its supplying source before signing in.';
15
+ /** Profile headers are adapter-owned defaults, so direct proof must carry them too. */
16
+ function loginProvider(profile, fallback) {
17
+ const provider = profile?.piProvider ?? fallback;
18
+ if (profile?.headers === undefined)
19
+ return provider;
20
+ return { ...provider,
21
+ stream: (model, context, options) => provider.stream(model, context, { ...options, headers: { ...profile.headers, ...options?.headers } }),
22
+ streamSimple: (model, context, options) => provider.streamSimple(model, context, { ...options, headers: { ...profile.headers, ...options?.headers } }), };
23
+ }
24
+ /** Managed membership and legacy catalog discovery deliberately choose different target sets. */
25
+ function loginTargets(ctx, config, routes) {
26
+ const profiles = routes.profiles();
27
+ if (routes.catalog !== undefined) {
28
+ return [...routes.catalog.providers.values()].map(route => ({
29
+ id: route.id, provider: profiles.get(route.id).piProvider, auth: route.auth, served: true,
30
+ }));
31
+ }
32
+ return builtinProviders().map(source => {
33
+ const profile = source.id === GO_SOURCE ? profiles.get(config.routeId)
34
+ : source.id === CODEX_SOURCE ? profiles.get(config.codexRouteId) : undefined;
35
+ // The plugin's Go adapter resolves its Config reference before considering any provider record.
36
+ const ref = source.id === GO_SOURCE ? config.apiKeyEnv
37
+ : source.id === CODEX_SOURCE && profile !== undefined ? undefined : declaredCredentialRef(ctx.get('settings'), source.id);
38
+ // Legacy Codex aliases intentionally own a separate record; their command must use that same address.
39
+ const credentialProvider = source.id === CODEX_SOURCE && profile !== undefined ? profile.provider : source.id;
40
+ return { id: source.id, provider: loginProvider(profile, source), served: profile !== undefined,
41
+ auth: ref === undefined ? { credentialProvider } : { apiKeyRef: ref },
42
+ };
43
+ });
44
+ }
45
+ /** A named reference can hold only one API key, never an OAuth grant. */
46
+ function choicesFor(targets) {
47
+ return targets.flatMap(target => {
48
+ const choices = [];
49
+ const oauth = target.provider.auth?.oauth;
50
+ if (target.auth !== undefined && 'credentialProvider' in target.auth && oauth?.login !== undefined) {
51
+ choices.push({ providerId: target.id, providerName: target.provider.name, authType: 'oauth', methodLabel: oauth.loginLabel ?? oauth.name });
52
+ }
53
+ const apiKey = target.provider.auth?.apiKey;
54
+ if (apiKey?.login !== undefined) {
55
+ choices.push({ providerId: target.id, providerName: target.provider.name, authType: 'api_key', methodLabel: apiKey.name });
56
+ }
57
+ return choices;
58
+ });
59
+ }
60
+ /** Checking writability before a prompt avoids obtaining grants the composition cannot retain. */
61
+ async function writableStore(ctx, target) {
62
+ const credentials = ctx.get('credentials');
63
+ if (credentials === undefined)
64
+ throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
65
+ if (target.auth === undefined)
66
+ throw new LlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
67
+ if ('apiKeyRef' in target.auth) {
68
+ if (typeof credentials.set !== 'function' || typeof credentials.describe !== 'function') {
69
+ throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
70
+ }
71
+ if (!(await credentials.describe(target.auth.apiKeyRef)).writable)
72
+ throw new LlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
73
+ }
74
+ else {
75
+ if (typeof credentials.modifyRecord !== 'function' || typeof credentials.readRecord !== 'function') {
76
+ throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
77
+ }
78
+ const info = await credentials.describeRecord?.(recordKeyFor(target.auth.credentialProvider));
79
+ if (info?.writable === false)
80
+ throw new LlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
81
+ }
82
+ return credentials;
83
+ }
84
+ /** OAuth crosses the durability boundary before any later cancellation or ownership verdict. */
85
+ async function authenticate(target, method, credentials, interaction, guard) {
86
+ const auth = codexAuth(() => credentials);
87
+ const signal = interaction.signal ?? new AbortController().signal;
88
+ signal.throwIfAborted();
89
+ guard();
90
+ if (method === 'oauth' && target.auth !== undefined && 'credentialProvider' in target.auth) {
91
+ // The flow owns cancellation until it returns a grant; then persistence owns completion.
92
+ const grant = await target.provider.auth.oauth.login({ ...interaction, signal });
93
+ await auth.credentials.modify(target.auth.credentialProvider, async () => grant);
94
+ return;
95
+ }
96
+ const pending = createModels({ credentials: new PendingCredentialStore(), authContext: auth.authContext });
97
+ pending.setProvider(target.provider);
98
+ const credential = await pending.login(target.provider.id, 'api_key', interaction);
99
+ guard();
100
+ await proveApiKey(pending, target.provider.id, signal);
101
+ signal.throwIfAborted();
102
+ guard();
103
+ if (target.auth !== undefined && 'apiKeyRef' in target.auth) {
104
+ if (credential.type !== 'api_key' || credential.key === undefined) {
105
+ throw new LlmError('This login did not return a single API key for ' + target.auth.apiKeyRef, 'UNSUPPORTED_CREDENTIAL');
106
+ }
107
+ const ref = credentialRef(target.auth.apiKeyRef);
108
+ const key = assertUsableApiKey(credential.key, PLUGIN_NAME, ref);
109
+ // set() is atomic but not cancellable; once it starts, report the resulting durable state.
110
+ await credentials.set(ref, key);
111
+ try {
112
+ if ((await credentials.resolve(ref))?.value !== key) {
113
+ throw new Error(ref + ' does not resolve to the saved key.');
114
+ }
115
+ }
116
+ catch (error) {
117
+ throw new StoredCredentialError('The credential was stored, but readback failed: ' + (error instanceof Error ? error.message : String(error)));
118
+ }
119
+ }
120
+ else {
121
+ if (target.auth === undefined)
122
+ throw new LlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
123
+ await auth.credentials.modify(target.auth.credentialProvider, async () => {
124
+ // A queued record update can still stop before its locked mutation begins.
125
+ signal.throwIfAborted();
126
+ guard();
127
+ return credential;
128
+ });
129
+ }
130
+ }
131
+ /** Both modes share the attended conversation without sharing route-declaration authority. */
132
+ export function mountLoginCommand(ctx, config, routes) {
133
+ if (!config.loginCommandEnabled)
134
+ return;
135
+ ctx.inject(['commands'], commandCtx => {
136
+ const targets = () => loginTargets(ctx, config, routes);
137
+ const targetFor = (id) => {
138
+ const target = targets().find(target => target.id === id);
139
+ if (target === undefined)
140
+ throw new Error('The configured sign-in route is no longer available: ' + id);
141
+ return target;
142
+ };
143
+ const guard = routes.requireOwnership ?? (() => { });
144
+ const host = {
145
+ choices: () => choicesFor(targets()),
146
+ login: async (choice, interaction) => {
147
+ guard();
148
+ const target = targetFor(choice.providerId);
149
+ const credentials = await writableStore(ctx, target);
150
+ await authenticate(target, choice.authType, credentials, interaction, guard);
151
+ try {
152
+ guard();
153
+ }
154
+ catch (error) {
155
+ throw new StoredCredentialError('The credential was stored, but the route is unavailable: ' + (error instanceof Error ? error.message : String(error)));
156
+ }
157
+ if (routes.catalog !== undefined || target.served)
158
+ return 'present';
159
+ if (interaction.signal?.aborted)
160
+ return 'unavailable';
161
+ return declareProviderRoute(ctx.get('settings'), target.id);
162
+ },
163
+ stored: async (id) => {
164
+ const target = targetFor(id);
165
+ const credentials = ctx.get('credentials');
166
+ if (target.auth === undefined)
167
+ return undefined;
168
+ if ('apiKeyRef' in target.auth) {
169
+ return (await credentials?.resolve(target.auth.apiKeyRef)) === undefined ? undefined : 'api_key';
170
+ }
171
+ const record = await credentials?.readRecord(recordKeyFor(target.auth.credentialProvider));
172
+ return record === undefined ? undefined : record.kind === 'api-key' ? 'api_key' : 'oauth';
173
+ },
174
+ reference: async (id) => {
175
+ const target = targetFor(id);
176
+ if (target.auth === undefined || !('apiKeyRef' in target.auth))
177
+ return undefined;
178
+ const ref = target.auth.apiKeyRef;
179
+ const credentials = ctx.get('credentials');
180
+ if (credentials === undefined)
181
+ return { ref, ...(process.env[ref] ? { source: 'env' } : {}) };
182
+ const info = await credentials.describe(ref);
183
+ return { ref, ...(info.configured && info.source !== undefined ? { source: info.source } : {}) };
184
+ },
185
+ ask: async (request) => {
186
+ const userQuestions = ctx.get('userQuestions');
187
+ if (userQuestions === undefined)
188
+ throw new Error('dsh-provider-extra: this composition mounts no session UI that can ask the sign-in questions');
189
+ return userQuestions.ask({ questions: [...request.questions], agent: request.agent,
190
+ ...(request.signal === undefined ? {} : { signal: request.signal }) });
191
+ },
192
+ };
193
+ commandCtx.commands.register(createLoginCommand(host, config.loginCommandName));
194
+ ctx.logger.info('dsh-provider-extra: /' + config.loginCommandName + ' signs in configured credentials');
195
+ });
196
+ }
@@ -7,6 +7,8 @@ const PROBE_TIMEOUT_MS = 20_000;
7
7
  const PROBE_TIMEOUT = 'the provider did not answer in time';
8
8
  /** Prefix that turns a provider's own words into the sentence a human reads. */
9
9
  const REJECTED_PREFIX = 'the provider did not accept this API key: ';
10
+ /** No model means no evidence, not a provider rejection or a successful proof. */
11
+ const NO_MODELS_PREFIX = 'cannot verify this API key: no models are available for provider ';
10
12
  /**
11
13
  * A credential store that forgets.
12
14
  *
@@ -38,13 +40,16 @@ export class PendingCredentialStore {
38
40
  * Throws the provider's own explanation when it refuses, so the human can tell
39
41
  * a mistyped key from a key that lacks a plan or a region.
40
42
  */
41
- export async function proveApiKey(models, providerId) {
43
+ export async function proveApiKey(models, providerId, signal) {
44
+ signal?.throwIfAborted();
42
45
  const model = models.getModels(providerId)[0];
43
- // A provider with no catalog model cannot be asked anything, and refusing a
44
- // key nothing has disproved would block a sign-in that may be perfectly good.
45
46
  if (model === undefined)
46
- return;
47
- const answer = await models.completeSimple(model, { messages: [{ role: 'user', content: PROBE_PROMPT, timestamp: Date.now() }] }, { maxTokens: PROBE_MAX_TOKENS, signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
47
+ throw new Error(NO_MODELS_PREFIX + providerId);
48
+ const deadline = AbortSignal.timeout(PROBE_TIMEOUT_MS);
49
+ const probeSignal = signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
50
+ const answer = await models.completeSimple(model, { messages: [{ role: 'user', content: PROBE_PROMPT, timestamp: Date.now() }] }, { maxTokens: PROBE_MAX_TOKENS, signal: probeSignal });
51
+ // A transport may finish despite cancellation; that answer must not authorize a key write.
52
+ probeSignal.throwIfAborted();
48
53
  if (answer.stopReason !== 'error' && answer.stopReason !== 'aborted')
49
54
  return;
50
55
  throw new Error(REJECTED_PREFIX + (answer.errorMessage ?? PROBE_TIMEOUT));
@@ -15,7 +15,7 @@
15
15
  import { defaultProviderAuthContext } from '@earendil-works/pi-ai';
16
16
  import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
17
17
  import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
18
- import { resolveExtraModels } from "./extra-models.js";
18
+ import { resolveExtraModels, selectWhitelistedModels } from "./extra-models.js";
19
19
  /** pi-ai catalog id of the OpenCode Go provider this route mirrors. */
20
20
  export const OPENCODE_GO_PROVIDER_ID = 'opencode-go';
21
21
  /** Routing header the OpenCode Go gateway requires on every model request. */
@@ -84,11 +84,11 @@ function withRoutingHeader(options, config) {
84
84
  * every dispatch path funnels through them with the request's own options.
85
85
  * @param config - the route configuration.
86
86
  * @param catalog - the installed catalog provider to reuse.
87
- * @param extras - resolved extra models, re-keyed here like catalog models.
87
+ * @param resolved - catalog and extra models already resolved and selected.
88
88
  * @returns the provider to register into the adapter's model collection.
89
89
  */
90
- function routeProvider(config, catalog, extras) {
91
- const models = [...catalog.getModels(), ...extras].map(model => ({
90
+ function routeProvider(config, catalog, resolved) {
91
+ const models = resolved.map(model => ({
92
92
  ...model,
93
93
  ...config.baseURL === undefined ? {} : { baseUrl: config.baseURL },
94
94
  provider: config.provider,
@@ -112,6 +112,10 @@ function routeProvider(config, catalog, extras) {
112
112
  export function buildOpenCodeGoProfile(config) {
113
113
  const catalog = catalogOpenCodeGo();
114
114
  const extras = resolveExtraModels(catalog.getModels(), [...DEFAULT_EXTRA_MODELS, ...(config.extraModels ?? [])], DEFAULT_EXTRA_MODEL_TEMPLATE);
115
+ // Selection runs last so a whitelist may name a shipped or declared extra
116
+ // exactly as it names a catalog model, and so a typo in either is refused
117
+ // here rather than served as a route quietly missing a model.
118
+ const models = selectWhitelistedModels(config.provider, [...catalog.getModels(), ...extras.models], config.models);
115
119
  return {
116
120
  provider: config.provider,
117
121
  displayName: config.displayName,
@@ -123,7 +127,7 @@ export function buildOpenCodeGoProfile(config) {
123
127
  retryPolicy: resolveRetryPolicy(undefined, 'dsh-provider-extra: opencode-go'),
124
128
  modelErrors: extras.modelErrors,
125
129
  configuredMaxTokens: new Map(),
126
- piProvider: routeProvider(config, catalog, extras.models),
130
+ piProvider: routeProvider(config, catalog, models),
127
131
  };
128
132
  }
129
133
  /**
@@ -0,0 +1,40 @@
1
+ {
2
+ "catalog": {
3
+ "version": 1,
4
+ "providers": [
5
+ {
6
+ "id": "example-route",
7
+ "name": "Example provider",
8
+ "source": "openai",
9
+ "auth": {
10
+ "apiKeyRef": "EXAMPLE_API_KEY"
11
+ },
12
+ "models": [
13
+ {
14
+ "id": "example-model",
15
+ "name": "Example model",
16
+ "metadata": {
17
+ "api": "openai-responses",
18
+ "reasoning": false,
19
+ "input": [
20
+ "text"
21
+ ],
22
+ "cost": {
23
+ "input": 0,
24
+ "output": 0,
25
+ "cacheRead": 0,
26
+ "cacheWrite": 0
27
+ },
28
+ "contextWindow": 8192,
29
+ "maxTokens": 1024
30
+ }
31
+ }
32
+ ]
33
+ }
34
+ ],
35
+ "default": {
36
+ "provider": "example-route",
37
+ "model": "example-model"
38
+ }
39
+ }
40
+ }