@sagmans/dsh-provider-extra 0.8.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,9 +9,9 @@
9
9
  *
10
10
  * @module dsh-provider-extra/login-attempt
11
11
  */
12
- import { renderEvent } from "./codex-login.js";
13
- import { StoredCredentialError } from "./login-contract.js";
14
- import { answerLabels, answerText } from "./login-choice.js";
12
+ import { renderEvent } from './codex-login.js';
13
+ import { answerLabels, answerText } from './login-choice.js';
14
+ import { StoredCredentialError } from './login-contract.js';
15
15
  /** Question ids belong to the caller; the answer echoes them back. */
16
16
  const PROMPT_QUESTION_ID = 'prompt';
17
17
  const NOTICE_QUESTION_ID = 'notice';
@@ -72,13 +72,15 @@ function openWait(host, invocation, choice, attempt) {
72
72
  const abort = new AbortController();
73
73
  const asked = host.ask({
74
74
  agent: invocation.agent,
75
- questions: [{
75
+ questions: [
76
+ {
76
77
  id: NOTICE_QUESTION_ID,
77
78
  header: choice.providerName,
78
79
  question: 'Finish signing in',
79
80
  detail: [...attempt.notices, WAIT_DETAIL].join('\n'),
80
81
  options: [{ label: DONE_LABEL }, { label: CANCEL_LABEL }],
81
- }],
82
+ },
83
+ ],
82
84
  signal: AbortSignal.any([attempt.signal, abort.signal]),
83
85
  });
84
86
  const settled = asked.then((answer) => {
@@ -101,9 +103,9 @@ function promptQuestion(prompt, choice) {
101
103
  id: PROMPT_QUESTION_ID,
102
104
  header,
103
105
  question: prompt.message,
104
- options: prompt.options.map(option => ({
106
+ options: prompt.options.map((option) => ({
105
107
  label: option.label,
106
- ...option.description === undefined ? {} : { description: option.description },
108
+ ...(option.description === undefined ? {} : { description: option.description }),
107
109
  })),
108
110
  };
109
111
  case 'secret':
@@ -111,22 +113,22 @@ function promptQuestion(prompt, choice) {
111
113
  id: SECRET_PROMPT_QUESTION_ID,
112
114
  header,
113
115
  question: prompt.message,
114
- detail: SECRET_DETAIL + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
116
+ detail: SECRET_DETAIL + (prompt.placeholder === undefined ? '' : ` ${prompt.placeholder}`),
115
117
  };
116
118
  case 'manual_code':
117
119
  return {
118
120
  id: PROMPT_QUESTION_ID,
119
121
  header,
120
122
  question: prompt.message,
121
- detail: 'Answer here only if the browser did not finish the sign-in.'
122
- + (prompt.placeholder === undefined ? '' : ' ' + prompt.placeholder),
123
+ detail: 'Answer here only if the browser did not finish the sign-in.' +
124
+ (prompt.placeholder === undefined ? '' : ` ${prompt.placeholder}`),
123
125
  };
124
126
  case 'text':
125
127
  return {
126
128
  id: PROMPT_QUESTION_ID,
127
129
  header,
128
130
  question: prompt.message,
129
- ...prompt.placeholder === undefined ? {} : { detail: prompt.placeholder },
131
+ ...(prompt.placeholder === undefined ? {} : { detail: prompt.placeholder }),
130
132
  };
131
133
  }
132
134
  }
@@ -146,14 +148,14 @@ async function askPrompt(host, invocation, prompt, choice, attempt) {
146
148
  const options = prompt.options;
147
149
  const answer = await ask;
148
150
  for (const label of answerLabels(answer, questionId)) {
149
- const hit = options.find(option => option.label === label);
151
+ const hit = options.find((option) => option.label === label);
150
152
  if (hit !== undefined)
151
153
  return hit.id;
152
154
  }
153
155
  // A select answers with an option id, never a position: an answer that
154
156
  // names neither is echoed back only when it is an id pi-ai offered.
155
157
  const typed = answerText(answer, questionId);
156
- const byId = options.find(option => option.id === typed);
158
+ const byId = options.find((option) => option.id === typed);
157
159
  if (byId !== undefined)
158
160
  return byId.id;
159
161
  throw new Error('dsh-provider-extra: answer the sign-in question by choosing one of its options');
@@ -164,7 +166,9 @@ async function askPrompt(host, invocation, prompt, choice, attempt) {
164
166
  // the withdrawal instead of demanding a code keeps the callback able to
165
167
  // finish the sign-in on its own.
166
168
  const withdrawn = new Promise((_, reject) => {
167
- const lose = () => { reject(new Error('dsh-provider-extra: the browser completed the sign-in')); };
169
+ const lose = () => {
170
+ reject(new Error('dsh-provider-extra: the browser completed the sign-in'));
171
+ };
168
172
  if (prompt.signal?.aborted === true) {
169
173
  lose();
170
174
  return;
@@ -200,7 +204,7 @@ function attemptInteraction(host, invocation, choice, attempt) {
200
204
  }
201
205
  /** What one finished sign-in means, said in terms of whether its models can be reached. */
202
206
  function successText(choice, route) {
203
- const signedIn = 'Signed in to ' + choice.providerName + ' (' + choice.methodLabel + ').';
207
+ const signedIn = `Signed in to ${choice.providerName} (${choice.methodLabel}).`;
204
208
  if (route === 'declared')
205
209
  return signedIn + DECLARED_ROUTE_NOTICE;
206
210
  if (route === 'unavailable')
@@ -212,11 +216,11 @@ function describeFailure(error, attempt, choice) {
212
216
  if (error instanceof StoredCredentialError)
213
217
  return error.message;
214
218
  if (attempt.declined || (attempt.signal.aborted && !attempt.expired))
215
- return 'The ' + choice.providerName + ' sign-in was cancelled.';
219
+ return `The ${choice.providerName} sign-in was cancelled.`;
216
220
  if (attempt.expired)
217
- return 'The ' + choice.providerName + ' sign-in timed out; start it again to get a fresh code.';
221
+ return `The ${choice.providerName} sign-in timed out; start it again to get a fresh code.`;
218
222
  const message = error instanceof Error ? error.message : String(error);
219
- return 'The ' + choice.providerName + ' sign-in failed: ' + message;
223
+ return `The ${choice.providerName} sign-in failed: ${message}`;
220
224
  }
221
225
  /** Run one sign-in end to end: the conversation plus the stored-credential check. */
222
226
  export async function runChoice(host, invocation, choice) {
@@ -254,7 +258,9 @@ export async function runChoice(host, invocation, choice) {
254
258
  if (stored === undefined) {
255
259
  return {
256
260
  kind: 'error',
257
- text: 'The ' + choice.providerName + ' sign-in reported success but stored no credential; nothing changed.',
261
+ text: 'The ' +
262
+ choice.providerName +
263
+ ' sign-in reported success but stored no credential; nothing changed.',
258
264
  };
259
265
  }
260
266
  return { kind: 'success', text: successText(choice, route) };
@@ -16,7 +16,10 @@ export const OAUTH_WORD = 'oauth';
16
16
  const PICKER_QUESTION_ID = 'provider';
17
17
  /** Route identity can be case-sensitive even when method words are not. */
18
18
  export function words(rawInput) {
19
- return rawInput.trim().split(/\s+/u).filter(word => word.length > 0);
19
+ return rawInput
20
+ .trim()
21
+ .split(/\s+/u)
22
+ .filter((word) => word.length > 0);
20
23
  }
21
24
  /** The label one choice shows: its provider alone when that provider has a single method. */
22
25
  function choiceLabel(choice, shared) {
@@ -26,7 +29,7 @@ function choiceLabel(choice, shared) {
26
29
  // the name onto it again reads as a stutter to the human choosing from it.
27
30
  return choice.methodLabel.toLowerCase().includes(choice.providerName.toLowerCase())
28
31
  ? choice.methodLabel
29
- : choice.providerName + ' (' + choice.methodLabel + ')';
32
+ : `${choice.providerName} (${choice.methodLabel})`;
30
33
  }
31
34
  /** The option label for one choice; method labels disambiguate multi-auth providers. */
32
35
  function optionLabels(choices) {
@@ -34,9 +37,13 @@ function optionLabels(choices) {
34
37
  for (const choice of choices) {
35
38
  perProvider.set(choice.providerId, (perProvider.get(choice.providerId) ?? 0) + 1);
36
39
  }
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);
40
+ const labelled = choices.map((choice) => ({
41
+ choice,
42
+ label: choiceLabel(choice, (perProvider.get(choice.providerId) ?? 0) > 1),
43
+ }));
44
+ return labelled.map(({ choice, label }) => labelled.filter((candidate) => candidate.label === label).length > 1
45
+ ? `${label} · ${choice.providerId} · ${choice.authType}`
46
+ : label);
40
47
  }
41
48
  /** The question the picker asks, one option per provider-method pair. */
42
49
  export function pickerQuestion(choices) {
@@ -47,19 +54,19 @@ export function pickerQuestion(choices) {
47
54
  question: 'Which provider do you want to sign in to?',
48
55
  options: choices.map((choice, index) => ({
49
56
  label: labels[index] ?? choice.providerName,
50
- description: choice.methodLabel + ' · ' + choice.providerId,
57
+ description: `${choice.methodLabel} · ${choice.providerId}`,
51
58
  })),
52
59
  };
53
60
  }
54
61
  /** The free text a single-question answer carries, if any. */
55
62
  export function answerText(answer, questionId) {
56
- const item = answer.answers.find(entry => entry.id === questionId);
63
+ const item = answer.answers.find((entry) => entry.id === questionId);
57
64
  const custom = item?.custom?.trim();
58
65
  return custom === undefined || custom.length === 0 ? undefined : custom;
59
66
  }
60
67
  /** The option labels a single-question answer carries. */
61
68
  export function answerLabels(answer, questionId) {
62
- return answer.answers.find(entry => entry.id === questionId)?.selected ?? [];
69
+ return answer.answers.find((entry) => entry.id === questionId)?.selected ?? [];
63
70
  }
64
71
  /**
65
72
  * Resolve what the picker's answer names: a label first, then free text as a
@@ -80,11 +87,14 @@ export function resolveChoice(choices, answer) {
80
87
  const named = choiceByWords(choices, input);
81
88
  if (named !== undefined)
82
89
  return named;
83
- // A bare method is useful only when it identifies exactly one credential owner.
90
+ return choiceByBareMethod(choices, input);
91
+ }
92
+ /** A bare method is useful only when it identifies exactly one credential owner. */
93
+ function choiceByBareMethod(choices, input) {
84
94
  const method = input.length === 1 ? input[0].toLowerCase() : undefined;
85
95
  if (method !== KEY_WORD && method !== OAUTH_WORD)
86
96
  return undefined;
87
- const matches = choices.filter(choice => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'));
97
+ const matches = choices.filter((choice) => choice.authType === (method === KEY_WORD ? 'api_key' : 'oauth'));
88
98
  return matches.length === 1 ? matches[0] : undefined;
89
99
  }
90
100
  /** The choice a provider id (and optional method word) names. */
@@ -92,10 +102,10 @@ export function choiceByWords(choices, input) {
92
102
  const providerId = input[0];
93
103
  if (providerId === undefined || input.length > 2)
94
104
  return undefined;
95
- let named = choices.filter(choice => choice.providerId === providerId);
105
+ let named = choices.filter((choice) => choice.providerId === providerId);
96
106
  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)
107
+ named = choices.filter((choice) => choice.providerId.toLowerCase() === providerId.toLowerCase());
108
+ if (new Set(named.map((choice) => choice.providerId)).size !== 1)
99
109
  return undefined;
100
110
  }
101
111
  const method = input[1]?.toLowerCase();
@@ -104,5 +114,5 @@ export function choiceByWords(choices, input) {
104
114
  if (method !== KEY_WORD && method !== OAUTH_WORD)
105
115
  return undefined;
106
116
  const authType = method === KEY_WORD ? 'api_key' : 'oauth';
107
- return named.find(choice => choice.authType === authType);
117
+ return named.find((choice) => choice.authType === authType);
108
118
  }
package/dist/login-cli.js CHANGED
@@ -21,8 +21,8 @@ import { createInterface } from 'node:readline/promises';
21
21
  import { Context } from '@deepseek-ai/cordis';
22
22
  import LocalCredentialProvider, { resolveSpec } from '@deepseek-ai/dsh-credentials-local';
23
23
  import { createModels } from '@earendil-works/pi-ai';
24
- import { catalogCodex, codexAuth } from "./codex.js";
25
- import { readlineTerminal, runCodexLogin } from "./codex-login.js";
24
+ import { catalogCodex, codexAuth } from './codex.js';
25
+ import { readlineTerminal, runCodexLogin } from './codex-login.js';
26
26
  /** Flag naming an explicit credentials document. */
27
27
  const PATH_FLAG = '--credentials-path';
28
28
  /** The explicit document override from argv, if the server overrides its own. */
@@ -30,7 +30,7 @@ function credentialsPath(argv) {
30
30
  const at = argv.indexOf(PATH_FLAG);
31
31
  const value = at === -1 ? undefined : argv[at + 1];
32
32
  if (at !== -1 && (value === undefined || value.startsWith('--'))) {
33
- throw new Error('dsh-provider-extra: ' + PATH_FLAG + ' needs a file path');
33
+ throw new Error(`dsh-provider-extra: ${PATH_FLAG} needs a file path`);
34
34
  }
35
35
  return value;
36
36
  }
@@ -41,9 +41,11 @@ async function main(argv) {
41
41
  ...(path === undefined ? {} : { path }),
42
42
  watch: false,
43
43
  });
44
- console.log('Credentials: ' + resolveSpec(path === undefined ? {} : { path }).filename);
44
+ console.log(`Credentials: ${resolveSpec(path === undefined ? {} : { path }).filename}`);
45
45
  const controller = new AbortController();
46
- process.on('SIGINT', () => { controller.abort(); });
46
+ process.on('SIGINT', () => {
47
+ controller.abort();
48
+ });
47
49
  const rl = createInterface({ input, output });
48
50
  try {
49
51
  const models = createModels(codexAuth(() => ctx.get('credentials')));
@@ -19,9 +19,9 @@
19
19
  *
20
20
  * @module dsh-provider-extra/login-command
21
21
  */
22
- import { KEY_WORD, OAUTH_WORD, answerText, choiceByWords, pickerQuestion, resolveChoice, words } from "./login-choice.js";
23
- import { runChoice } from "./login-attempt.js";
24
- import { statusOf } from "./login-status.js";
22
+ import { runChoice } from './login-attempt.js';
23
+ import { answerText, choiceByWords, KEY_WORD, OAUTH_WORD, pickerQuestion, resolveChoice, words, } from './login-choice.js';
24
+ import { statusOf } from './login-status.js';
25
25
  /** Command name a profile gets unless it renames the command. */
26
26
  export const DEFAULT_LOGIN_COMMAND_NAME = 'dsh-provider-extra-login';
27
27
  /** Input word showing what is already stored instead of starting a sign-in. */
@@ -34,11 +34,19 @@ const STATUS_WORD = 'status';
34
34
  * @returns the registry definition, valid until the profile unloads it.
35
35
  */
36
36
  export function createLoginCommand(host, commandName) {
37
- const usage = 'Usage: /' + commandName + ' [<provider-id> [' + OAUTH_WORD + '|' + KEY_WORD + '] | ' + STATUS_WORD + ']';
37
+ const usage = 'Usage: /' +
38
+ commandName +
39
+ ' [<provider-id> [' +
40
+ OAUTH_WORD +
41
+ '|' +
42
+ KEY_WORD +
43
+ '] | ' +
44
+ STATUS_WORD +
45
+ ']';
38
46
  return {
39
47
  name: commandName,
40
48
  description: 'Sign in to a model provider (subscription or API key)',
41
- input: { hint: 'no input picks a provider, ' + STATUS_WORD + ' lists what is signed in' },
49
+ input: { hint: `no input picks a provider, ${STATUS_WORD} lists what is signed in` },
42
50
  // The input is a provider id in normal use, but this command is also the
43
51
  // one place a human might paste a key: keep the session log out of it.
44
52
  recordInput: false,
@@ -47,14 +55,25 @@ export function createLoginCommand(host, commandName) {
47
55
  if (input.length === 1 && input[0]?.toLowerCase() === STATUS_WORD)
48
56
  return await statusOf(host);
49
57
  if (input.length > 2)
50
- return { kind: 'error', text: 'dsh-provider-extra: too many arguments. ' + usage };
58
+ return { kind: 'error', text: `dsh-provider-extra: too many arguments. ${usage}` };
51
59
  const choices = host.choices();
52
60
  if (choices.length === 0) {
53
- return { kind: 'error', text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in' };
61
+ return {
62
+ kind: 'error',
63
+ text: 'dsh-provider-extra: this composition mounts no provider with an interactive sign-in',
64
+ };
54
65
  }
55
66
  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 };
67
+ const known = [...new Set(choices.map((entry) => entry.providerId))].join(', ');
68
+ return {
69
+ kind: 'error',
70
+ text: 'dsh-provider-extra: no sign-in named "' +
71
+ input.join(' ') +
72
+ '". Known providers: ' +
73
+ known +
74
+ '. ' +
75
+ usage,
76
+ };
58
77
  };
59
78
  let choice;
60
79
  if (input.length === 0) {
@@ -72,10 +91,13 @@ export function createLoginCommand(host, commandName) {
72
91
  }
73
92
  catch (error) {
74
93
  const message = error instanceof Error ? error.message : String(error);
75
- return { kind: 'error', text: 'dsh-provider-extra: no provider was picked (' + message + '). ' + usage };
94
+ return {
95
+ kind: 'error',
96
+ text: `dsh-provider-extra: no provider was picked (${message}). ${usage}`,
97
+ };
76
98
  }
77
99
  if (choice === undefined)
78
- return { kind: 'error', text: 'dsh-provider-extra: no provider was picked. ' + usage };
100
+ return { kind: 'error', text: `dsh-provider-extra: no provider was picked. ${usage}` };
79
101
  }
80
102
  else {
81
103
  choice = choiceByWords(choices, input);
@@ -1,15 +1,19 @@
1
1
  import { credentialRef } from '@deepseek-ai/dsh-credentials';
2
- import { LlmError, assertUsableApiKey } from '@deepseek-ai/dsh-llm';
2
+ import { assertUsableApiKey, LlmError } from '@deepseek-ai/dsh-llm';
3
3
  import { createModels } from '@earendil-works/pi-ai';
4
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, legacySettings } from "./login-route.js";
9
- import { PendingCredentialStore, proveApiKey } from "./login-verify.js";
5
+ import { codexAuth, recordKeyFor } from './codex.js';
6
+ import { createLoginCommand } from './login-command.js';
7
+ import { StoredCredentialError } from './login-contract.js';
8
+ import { declaredCredentialRef, declareProviderRoute, legacySettings } from './login-route.js';
9
+ import { PendingCredentialStore, proveApiKey } from './login-verify.js';
10
+ import { pluginLlmError } from './plugin-error.js';
10
11
  const PLUGIN_NAME = 'dsh-provider-extra';
11
12
  const GO_SOURCE = 'opencode-go';
12
13
  const CODEX_SOURCE = 'openai-codex';
14
+ const ROUTE_NOT_LOADED = 'The configured sign-in route has no loaded provider';
15
+ const ROUTE_NOT_LOADED_CODE = 'LOGIN_ROUTE_NOT_LOADED';
16
+ const NO_OAUTH_FLOW = 'This route has no sign-in flow';
13
17
  const MISSING_STORE = 'This composition has no writable credentials service; mount dsh-credentials-local before signing in.';
14
18
  const READ_ONLY = 'The configured credential is read-only; change its supplying source before signing in.';
15
19
  /** Profile headers are adapter-owned defaults, so direct proof must carry them too. */
@@ -17,42 +21,75 @@ function loginProvider(profile, fallback) {
17
21
  const provider = profile?.piProvider ?? fallback;
18
22
  if (profile?.headers === undefined)
19
23
  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 } }), };
24
+ return {
25
+ ...provider,
26
+ stream: (model, context, options) => provider.stream(model, context, {
27
+ ...options,
28
+ headers: { ...profile.headers, ...options?.headers },
29
+ }),
30
+ streamSimple: (model, context, options) => provider.streamSimple(model, context, {
31
+ ...options,
32
+ headers: { ...profile.headers, ...options?.headers },
33
+ }),
34
+ };
23
35
  }
24
36
  /** Managed membership and legacy catalog discovery deliberately choose different target sets. */
25
37
  function loginTargets(ctx, config, routes) {
26
38
  const profiles = routes.profiles();
27
39
  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
- }));
40
+ return [...routes.catalog.providers.values()].map((route) => {
41
+ const provider = profiles.get(route.id)?.piProvider;
42
+ // A named refusal beats a TypeError when a catalog route has no loaded provider.
43
+ if (provider === undefined)
44
+ throw pluginLlmError(`${ROUTE_NOT_LOADED}: ${route.id}`, ROUTE_NOT_LOADED_CODE);
45
+ return { id: route.id, provider, auth: route.auth, served: true };
46
+ });
31
47
  }
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;
48
+ return builtinProviders().map((source) => {
49
+ const profile = source.id === GO_SOURCE
50
+ ? profiles.get(config.routeId)
51
+ : source.id === CODEX_SOURCE
52
+ ? profiles.get(config.codexRouteId)
53
+ : undefined;
35
54
  // 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(legacySettings(ctx.get('settings')), source.id);
55
+ const ref = source.id === GO_SOURCE
56
+ ? config.apiKeyEnv
57
+ : source.id === CODEX_SOURCE && profile !== undefined
58
+ ? undefined
59
+ : declaredCredentialRef(legacySettings(ctx.get('settings')), source.id);
38
60
  // Legacy Codex aliases intentionally own a separate record; their command must use that same address.
39
61
  const credentialProvider = source.id === CODEX_SOURCE && profile !== undefined ? profile.provider : source.id;
40
- return { id: source.id, provider: loginProvider(profile, source), served: profile !== undefined,
62
+ return {
63
+ id: source.id,
64
+ provider: loginProvider(profile, source),
65
+ served: profile !== undefined,
41
66
  auth: ref === undefined ? { credentialProvider } : { apiKeyRef: ref },
42
67
  };
43
68
  });
44
69
  }
45
70
  /** A named reference can hold only one API key, never an OAuth grant. */
46
71
  function choicesFor(targets) {
47
- return targets.flatMap(target => {
72
+ return targets.flatMap((target) => {
48
73
  const choices = [];
49
74
  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 });
75
+ if (target.auth !== undefined &&
76
+ 'credentialProvider' in target.auth &&
77
+ oauth?.login !== undefined) {
78
+ choices.push({
79
+ providerId: target.id,
80
+ providerName: target.provider.name,
81
+ authType: 'oauth',
82
+ methodLabel: oauth.loginLabel ?? oauth.name,
83
+ });
52
84
  }
53
85
  const apiKey = target.provider.auth?.apiKey;
54
86
  if (apiKey?.login !== undefined) {
55
- choices.push({ providerId: target.id, providerName: target.provider.name, authType: 'api_key', methodLabel: apiKey.name });
87
+ choices.push({
88
+ providerId: target.id,
89
+ providerName: target.provider.name,
90
+ authType: 'api_key',
91
+ methodLabel: apiKey.name,
92
+ });
56
93
  }
57
94
  return choices;
58
95
  });
@@ -63,21 +100,22 @@ async function writableStore(ctx, target) {
63
100
  if (credentials === undefined)
64
101
  throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
65
102
  if (target.auth === undefined)
66
- throw new LlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
103
+ throw pluginLlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
67
104
  if ('apiKeyRef' in target.auth) {
68
105
  if (typeof credentials.set !== 'function' || typeof credentials.describe !== 'function') {
69
106
  throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
70
107
  }
71
108
  if (!(await credentials.describe(target.auth.apiKeyRef)).writable)
72
- throw new LlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
109
+ throw pluginLlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
73
110
  }
74
111
  else {
75
- if (typeof credentials.modifyRecord !== 'function' || typeof credentials.readRecord !== 'function') {
112
+ if (typeof credentials.modifyRecord !== 'function' ||
113
+ typeof credentials.readRecord !== 'function') {
76
114
  throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
77
115
  }
78
116
  const info = await credentials.describeRecord?.(recordKeyFor(target.auth.credentialProvider));
79
117
  if (info?.writable === false)
80
- throw new LlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
118
+ throw pluginLlmError(READ_ONLY, 'READ_ONLY_CREDENTIAL');
81
119
  }
82
120
  return credentials;
83
121
  }
@@ -88,12 +126,19 @@ async function authenticate(target, method, credentials, interaction, guard) {
88
126
  signal.throwIfAborted();
89
127
  guard();
90
128
  if (method === 'oauth' && target.auth !== undefined && 'credentialProvider' in target.auth) {
129
+ const oauth = target.provider.auth.oauth;
130
+ // The picker offers only routes with this flow, but a route can change after that read.
131
+ if (oauth?.login === undefined)
132
+ throw pluginLlmError(`${NO_OAUTH_FLOW}: ${target.id}`, 'UNSUPPORTED_CREDENTIAL');
91
133
  // The flow owns cancellation until it returns a grant; then persistence owns completion.
92
- const grant = await target.provider.auth.oauth.login({ ...interaction, signal });
134
+ const grant = await oauth.login({ ...interaction, signal });
93
135
  await auth.credentials.modify(target.auth.credentialProvider, async () => grant);
94
136
  return;
95
137
  }
96
- const pending = createModels({ credentials: new PendingCredentialStore(), authContext: auth.authContext });
138
+ const pending = createModels({
139
+ credentials: new PendingCredentialStore(),
140
+ authContext: auth.authContext,
141
+ });
97
142
  pending.setProvider(target.provider);
98
143
  const credential = await pending.login(target.provider.id, 'api_key', interaction);
99
144
  guard();
@@ -102,24 +147,28 @@ async function authenticate(target, method, credentials, interaction, guard) {
102
147
  guard();
103
148
  if (target.auth !== undefined && 'apiKeyRef' in target.auth) {
104
149
  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');
150
+ throw pluginLlmError(`This login did not return a single API key for ${target.auth.apiKeyRef}`, 'UNSUPPORTED_CREDENTIAL');
106
151
  }
107
152
  const ref = credentialRef(target.auth.apiKeyRef);
108
153
  const key = assertUsableApiKey(credential.key, PLUGIN_NAME, ref);
154
+ // A store can lose set() after the earlier check; the proven key must not look saved.
155
+ if (typeof credentials.set !== 'function')
156
+ throw new LlmError(MISSING_STORE, 'NO_CREDENTIAL_STORE');
109
157
  // set() is atomic but not cancellable; once it starts, report the resulting durable state.
110
158
  await credentials.set(ref, key);
111
159
  try {
112
160
  if ((await credentials.resolve(ref))?.value !== key) {
113
- throw new Error(ref + ' does not resolve to the saved key.');
161
+ throw new Error(`${ref} does not resolve to the saved key.`);
114
162
  }
115
163
  }
116
164
  catch (error) {
117
- throw new StoredCredentialError('The credential was stored, but readback failed: ' + (error instanceof Error ? error.message : String(error)));
165
+ throw new StoredCredentialError('The credential was stored, but readback failed: ' +
166
+ (error instanceof Error ? error.message : String(error)));
118
167
  }
119
168
  }
120
169
  else {
121
170
  if (target.auth === undefined)
122
- throw new LlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
171
+ throw pluginLlmError('This route names no credential to store', 'UNSUPPORTED_CREDENTIAL');
123
172
  await auth.credentials.modify(target.auth.credentialProvider, async () => {
124
173
  // A queued record update can still stop before its locked mutation begins.
125
174
  signal.throwIfAborted();
@@ -132,12 +181,12 @@ async function authenticate(target, method, credentials, interaction, guard) {
132
181
  export function mountLoginCommand(ctx, config, routes) {
133
182
  if (!config.loginCommandEnabled)
134
183
  return;
135
- ctx.inject(['commands'], commandCtx => {
184
+ ctx.inject(['commands'], (commandCtx) => {
136
185
  const targets = () => loginTargets(ctx, config, routes);
137
186
  const targetFor = (id) => {
138
- const target = targets().find(target => target.id === id);
187
+ const target = targets().find((target) => target.id === id);
139
188
  if (target === undefined)
140
- throw new Error('The configured sign-in route is no longer available: ' + id);
189
+ throw new Error(`The configured sign-in route is no longer available: ${id}`);
141
190
  return target;
142
191
  };
143
192
  const guard = routes.requireOwnership ?? (() => { });
@@ -152,7 +201,8 @@ export function mountLoginCommand(ctx, config, routes) {
152
201
  guard();
153
202
  }
154
203
  catch (error) {
155
- throw new StoredCredentialError('The credential was stored, but the route is unavailable: ' + (error instanceof Error ? error.message : String(error)));
204
+ throw new StoredCredentialError('The credential was stored, but the route is unavailable: ' +
205
+ (error instanceof Error ? error.message : String(error)));
156
206
  }
157
207
  if (routes.catalog !== undefined || target.served)
158
208
  return 'present';
@@ -166,7 +216,9 @@ export function mountLoginCommand(ctx, config, routes) {
166
216
  if (target.auth === undefined)
167
217
  return undefined;
168
218
  if ('apiKeyRef' in target.auth) {
169
- return (await credentials?.resolve(target.auth.apiKeyRef)) === undefined ? undefined : 'api_key';
219
+ return (await credentials?.resolve(target.auth.apiKeyRef)) === undefined
220
+ ? undefined
221
+ : 'api_key';
170
222
  }
171
223
  const record = await credentials?.readRecord(recordKeyFor(target.auth.credentialProvider));
172
224
  return record === undefined ? undefined : record.kind === 'api-key' ? 'api_key' : 'oauth';
@@ -180,17 +232,23 @@ export function mountLoginCommand(ctx, config, routes) {
180
232
  if (credentials === undefined)
181
233
  return { ref, ...(process.env[ref] ? { source: 'env' } : {}) };
182
234
  const info = await credentials.describe(ref);
183
- return { ref, ...(info.configured && info.source !== undefined ? { source: info.source } : {}) };
235
+ return {
236
+ ref,
237
+ ...(info.configured && info.source !== undefined ? { source: info.source } : {}),
238
+ };
184
239
  },
185
240
  ask: async (request) => {
186
241
  const userQuestions = ctx.get('userQuestions');
187
242
  if (userQuestions === undefined)
188
243
  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 }) });
244
+ return userQuestions.ask({
245
+ questions: [...request.questions],
246
+ agent: request.agent,
247
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
248
+ });
191
249
  },
192
250
  };
193
251
  commandCtx.commands.register(createLoginCommand(host, config.loginCommandName));
194
- ctx.logger.info('dsh-provider-extra: /' + config.loginCommandName + ' signs in configured credentials');
252
+ ctx.logger.info(`dsh-provider-extra: /${config.loginCommandName} signs in configured credentials`);
195
253
  });
196
254
  }
@@ -38,7 +38,9 @@ const CATALOG_ROUTE_OVERRIDES = {};
38
38
  */
39
39
  export function legacySettings(service) {
40
40
  const settings = service;
41
- return settings !== undefined && typeof settings.get === 'function' && typeof settings.update === 'function'
41
+ return settings !== undefined &&
42
+ typeof settings.get === 'function' &&
43
+ typeof settings.update === 'function'
42
44
  ? settings
43
45
  : undefined;
44
46
  }
@@ -47,7 +49,9 @@ function configuredProviders(value) {
47
49
  if (typeof value !== 'object' || value === null)
48
50
  return undefined;
49
51
  const providers = value[PROVIDERS_FIELD];
50
- return typeof providers === 'object' && providers !== null ? providers : undefined;
52
+ return typeof providers === 'object' && providers !== null
53
+ ? providers
54
+ : undefined;
51
55
  }
52
56
  /**
53
57
  * The credential reference one declared route resolves, when its entry names
@@ -88,6 +92,8 @@ export async function declareProviderRoute(settings, providerId) {
88
92
  return 'unavailable';
89
93
  if (providers[providerId] !== undefined)
90
94
  return 'present';
91
- await settings.update(PI_AI_SETTINGS_NAMESPACE, { [PROVIDERS_FIELD]: { [providerId]: CATALOG_ROUTE_OVERRIDES } });
95
+ await settings.update(PI_AI_SETTINGS_NAMESPACE, {
96
+ [PROVIDERS_FIELD]: { [providerId]: CATALOG_ROUTE_OVERRIDES },
97
+ });
92
98
  return 'declared';
93
99
  }